Skip to content

Commit

Permalink
Update 4.3.5
Browse files Browse the repository at this point in the history
  • Loading branch information
nimadez committed Aug 28, 2024
1 parent b369535 commit 278647b
Show file tree
Hide file tree
Showing 18 changed files with 664 additions and 508 deletions.
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
All notable changes to this project will be documented in this file.

## 4.3.5
- ~~Update to babylonjs 7.22.3~~
- The update was rolled back, serious bug (no mouseover on Z axis)
- New detachable floating panels!
- Review and improve menus (faster and more managable)
- Improve websockets client and server
- Standalone node.js server (Electron alternative)
- Improve three.js module (less memory, faster load time)
- Fix camera-related visual artifacts (fov 0.1 issue)
- Improve modules and pathtracer code
- Add three.js WorkerPool library (more stable)

> - You shouldn't notice a change unless you move the panel
> - The left button moves the panel, the center button hides the panel and the right button resets the panel to its original position and close it.
## 4.3.4 x1.5
- Faster startup time (avg. 2s to 0.5s - x1.5 faster)
- Change default PT material to lambert
Expand Down
21 changes: 11 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
Voxel-based 3D modeling application<br>
[https://nimadez.github.io/voxel-builder/](https://nimadez.github.io/voxel-builder/)

```Version 4.3.4 Beta```<br>
```Version 4.3.5 Beta```<br>
[Changelog](https://github.com/nimadez/voxel-builder/blob/main/CHANGELOG.md)

[Installation](https://github.com/nimadez/voxel-builder#installation)<br>
Expand Down Expand Up @@ -50,12 +50,13 @@ Voxel-based 3D modeling application<br>
- Blender importer script

**More**
- Unique handcrafted user-interface woven into the code
- Minimum dependency, portable, online and offline
- Ad-free, no miners and trackers, no logging
- Extras [?](https://github.com/nimadez/voxel-builder/wiki/Extras)

## Installation
Install [Electron](https://github.com/electron/electron/releases) for Linux or Windows
Install [Electron](https://github.com/electron/electron/releases) for Linux or Windows *(optional)*
```
electron-v*-linux-x64.zip
electron-v*-win32-x64.zip
Expand All @@ -64,7 +65,12 @@ Get and run Voxel Builder
```
git clone https://github.com/nimadez/voxel-builder.git
cd voxel-builder
# Start with Electron:
electron .
# Start with Node.js:
node server.js
```
Update to the latest version
```
Expand Down Expand Up @@ -98,17 +104,10 @@ Failed to import GLB meshes for voxelization
Multiple meshes need to have the same properties or they won't merge,
the only solution is to merge meshes before exporting to GLB.
```
Visual artifacts and Moire patterns
```
These are related to thin-instances and nothing special can be done at this time.
Reproduce: set camera FOV to 0.1 and press F to fit camera
(but usually you don't need that FOV, use orthographic mode)
```
Wacom tablet crashes randomly and throws warning on Linux (GNOME)
```
Warning: BJS - Max number of touches exceeded. Ignoring touches in excess of 2.
This is a Babylon.js and Wayland issue that needs to be fixed.
(wayland uses multiple pointers, one for each input device)
This problem is related to Babylon.js and nothing can be done.
```

## FAQ
Expand Down Expand Up @@ -141,6 +140,8 @@ How to run Blender importer script?
↑ Features and uix overhaul
↑ New SPS particles to build the world
↑ I wrote a playground for learning Babylon.js
"I don't mean to compete, GL is nostalgic for me."
```

Version 3.0.0 *(BJS 4)* to 4.2.2 *(BJS 6)*<br>
Expand Down
3 changes: 3 additions & 0 deletions electron.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

123 changes: 52 additions & 71 deletions index.html

Large diffs are not rendered by default.

102 changes: 102 additions & 0 deletions libs/addons/WorkerPool.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/**
* @author Deepkolos / https://github.com/deepkolos
*/

export class WorkerPool {

constructor( pool = 4 ) {

this.pool = pool;
this.queue = [];
this.workers = [];
this.workersResolve = [];
this.workerStatus = 0;

}

_initWorker( workerId ) {

if ( ! this.workers[ workerId ] ) {

const worker = this.workerCreator();
worker.addEventListener( 'message', this._onMessage.bind( this, workerId ) );
this.workers[ workerId ] = worker;

}

}

_getIdleWorker() {

for ( let i = 0; i < this.pool; i ++ )
if ( ! ( this.workerStatus & ( 1 << i ) ) ) return i;

return - 1;

}

_onMessage( workerId, msg ) {

const resolve = this.workersResolve[ workerId ];
resolve && resolve( msg );

if ( this.queue.length ) {

const { resolve, msg, transfer } = this.queue.shift();
this.workersResolve[ workerId ] = resolve;
this.workers[ workerId ].postMessage( msg, transfer );

} else {

this.workerStatus ^= 1 << workerId;

}

}

setWorkerCreator( workerCreator ) {

this.workerCreator = workerCreator;

}

setWorkerLimit( pool ) {

this.pool = pool;

}

postMessage( msg, transfer ) {

return new Promise( ( resolve ) => {

const workerId = this._getIdleWorker();

if ( workerId !== - 1 ) {

this._initWorker( workerId );
this.workerStatus |= 1 << workerId;
this.workersResolve[ workerId ] = resolve;
this.workers[ workerId ].postMessage( msg, transfer );

} else {

this.queue.push( { resolve, msg, transfer } );

}

} );

}

dispose() {

this.workers.forEach( ( worker ) => worker.terminate() );
this.workersResolve.length = 0;
this.workers.length = 0;
this.queue.length = 0;
this.workerStatus = 0;

}

}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "voxel-builder",
"version": "4.3.4",
"version": "4.3.5",
"description": "Voxel-based 3D modeling application",
"main": "electron.js",
"scripts": {
Expand Down
8 changes: 4 additions & 4 deletions scripts/blender-importer.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""
# Blender 4.x.x
# Run script inside Blender and select .JSON file
"""
#!/usr/bin/env python3
#
# Blender 4.x.x
# Run script inside Blender and select .JSON file

import os
import json
Expand Down
88 changes: 60 additions & 28 deletions scripts/ws-connect.py
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,48 +1,80 @@
#!/usr/bin/env python3
# Aug 2024 https://nimadez.github.io/
#
# Websockets Server
# This script can be used to connect with machine learning models
# $ python3 ws-connect.py


import os, sys, json, random, time
import asyncio
import os, sys, json, random, time, asyncio

sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '/libs')
from websockets.asyncio.server import serve
from websockets.server import serve

if __import__('platform').system == 'Windows': # fix [WinError 10054]
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())


PORT = 8014
TOTAL = 100
CLEAR = False # clear scene or add voxel
CLEAR = True # clear scene or add a voxel
POST = True # test in send mode?


def generator():
data = []
for x in range(20):
for y in range(20):
for z in range(20):
if random.randint(0,9) < 5:
hex = "#%06X" % random.randint(0, 0xFFFFFF)
data.append({
"position": { "x": x, "y": y, "z": z },
"color": hex, #.upper()
"visible": True
})
return data


class Server():
def __init__(self):
pass


async def handler(self, ws):
async for msg in ws:
msg = json.loads(msg)
if not POST:
match msg['key']:
case 'init':
print("Connection established.")
case 'get':
print(f"Received: {str(msg['voxels'])[:40]}...")
else:
voxel_data = generator()
payload = { "voxels": voxel_data, "is_clear": CLEAR }
await ws.send(json.dumps(payload))
print("Sent")
time.sleep(0.2)

time.sleep(0.1)

async def handler(ws):
while True:
data = []
for i in range(TOTAL):
hex = "#%06x" % random.randint(0, 0xFFFFFF)
data.append({
"position": { "x": random.randint(-20,20), "y": random.randint(0,20), "z": random.randint(-20,20) },
"color": hex.upper(),
"visible": True
})

payload = { "voxels": data, "is_clear": CLEAR }
async def main(self):
try:
async with serve(self.handler, "localhost", PORT, max_queue=1, max_size=2 ** 25):
print(f"Running websockets server at ws://localhost:{PORT}")
await asyncio.get_running_loop().create_future()
except Exception as err:
print(err)

await ws.send(json.dumps(payload))
print('sent')
message = await ws.recv()
print('receive', message[:40], '...')
time.sleep(0.1)

def start(self):
try:
asyncio.run(self.main())
except KeyboardInterrupt:
print('Shutdown.')
finally:
pass

async def main():
async with serve(handler, "", PORT):
print(f"Websockets server is ready on port {PORT}")
await asyncio.get_running_loop().create_future()


if __name__ == "__main__":
asyncio.run(main())
Server().start()
48 changes: 48 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#!/usr/bin/env node
// Aug 2024 https://nimadez.github.io/
// Voxel Builder Server

const http = require('http');
const url = require('url');
const fs = require('fs');

const PORT = 8011;

http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
let filePath = `.${parsedUrl.pathname}`;

if (parsedUrl.pathname == '/')
filePath = './index.html';

fs.readFile(filePath, (err, data) => {
if (err) {
console.log(`GET ${filePath} 404 NOT FOUND`)
res.writeHead(404, { 'Content-Type': 'text/html' });
return res.end("404 Not Found");
}

console.log(`GET ${filePath} 200 OK`)
res.writeHead(200, { 'Content-Type': getContentType(filePath) });
res.write(data);
return res.end();
});
}).listen(PORT, () => {
console.log('Voxel Builder')
console.log(`Server running at http://localhost:${PORT}`);
});

function getContentType(filePath) {
const extname = String(filePath).split('.').pop().toLowerCase();
const mimeTypes = {
'html': 'text/html',
'js': 'text/javascript',
'css': 'text/css',
'json': 'application/json',
'png': 'image/png',
'jpg': 'image/jpg',
'jpeg': 'image/jpeg',
'gif': 'image/gif'
};
return mimeTypes[extname] || 'application/octet-stream';
}
Loading

0 comments on commit 278647b

Please sign in to comment.