Three.js - How to deserialize geometry.toJSON ()? (where is geometry.fromJSON?)

I am trying to upload the loading and processing of Geometry into a web worker. To send it back to the main thread, the Geometry instance must be serialized, and it seems that Geometry.prototype.toJSON() intended for this type of thing.

But I can't figure out how to return this object to a Geometry instance in the main thread. How is the toJSON() output supposed to be used?

PS: I saw this related question , but it seems dated. toJSON() has not been to the API yet. The accepted answer is a bit confusing and requires me to continue to do the raw work in the main thread.

+6
source share
3 answers

If I understand correctly, the problem is this:

  • You have a file that you want to load as geometry (obj, stl, etc.).
  • You want to upload this file to WebWorker.
  • Then you want to send the geometry back to the main script.
  • So, you are thinking of sending the file back to the main stream as JSON, since sending objects is not supported.
  • Then you convert json to main stream geometry.

The problem is that converting from a JSON string to geometry is a different loading operation (which is why JSONLoader is), so at this point you can just load on the main thread.

The approach I used was to upload the file to flat arrays of vertices and normals, and then send them back to the main stream to add BufferGeometry. You can also use portable objects to get a higher speed.

 // worker.js var vertices = new Float32Array( faces * 3 * 3 ); var normals = new Float32Array( faces * 3 * 3 ); // Load your file into the arrays somehow. var message = { status:'complete', vertices: vertices, normals: normals }; postMessage(message, [message.vertices.buffer, message.normals.buffer]); 

 // app.js onmessage = function (event) { var vertices = event.data.vertices; var normals = event.data.normals; var geometry = new THREE.BufferGeometry(); geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); var material = new THREE.MeshPhongMaterial(); var mesh = new THREE.Mesh( geometry, material ); // Do something with it. }; 
+3
source

Why don't you just use JSONLoader?

 myloader = new THREE.JSONLoader() myloader.load("path/to/json", function(geometry,material){ mesh = new THREE.Mesh(geometry,material) scene.add(mesh) }) 

or upload a json file in the same way

+2
source

You can use JSONLoader unserialize geometry as follows:

 var geometry = new THREE.Geometry(); var serializedGeometry = geometry.toJSON(); var jsonLoader = new THREE.JSONLoader(); var result = jsonLoader.parse(serializedGeometry.data); var unserializedGeometry = result.geometry; 
+1
source

Source: https://habr.com/ru/post/983024/


All Articles