How can geometry.toJSON be deserialized in Three.js? (is there a geometry.fromJSON?)

I am exploring ways to transfer some of the Geometry loading and processing tasks to a web worker. In order to send the data back to the main thread, I need to serialize the Geometry instance, and it appears that using Geometry.prototype.toJSON() is the ideal method for this.

However, I am struggling to understand how to convert the serialized object back into a Geometry instance in the main thread. What is the intended use of the output from toJSON()?

On a side note, I came across this related question, but it seems outdated as toJSON() was not yet part of the API at that time. The accepted answer seems complex and involves manual work in the main thread.

Answer №1

From what I gather, the issue is as follows:

  • You are looking to load a file as a geometry (such as obj or stl).
  • You aim to load this file within a WebWorker.
  • Once loaded, you wish to send the geometry back to the main script.
  • To achieve this, you are considering sending the file back as JSON since direct object transfer is not feasible.
  • Following this, you plan to convert the JSON data into a geometry on the main thread.

The downside of the above approach is that converting from JSON to a geometry involves another loading operation, similar to what JSONLoader does. In essence, it defeats the purpose of using a separate worker thread.

My suggested method involves loading the file into flat arrays of vertices and normals, which are then sent back to the main thread for incorporation into a BufferGeometry. Additionally, utilizing transferable objects can enhance processing speed.

// worker.js

var vertices = new Float32Array(faces * 3 * 3);
var normals = new Float32Array(faces * 3 * 3);

// Load your file into these arrays.

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);

// Perform further actions as needed.

};

Answer №2

If you need to deserialize geometry, you can utilize the JSONLoader in the following way:

let geometry = new THREE.Geometry();
let serializedGeometry = geometry.toJSON();
let jsonLoader = new THREE.JSONLoader();

let result = jsonLoader.parse(serializedGeometry.data);

let deserializedGeometry = result.geometry;

Answer №3

Have you considered utilizing the JSONLoader for this task?

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

Another option is to load a JSON file in a similar manner.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue of Access-Control-Allow-Origin restriction arises specifically when using the gmap elevation API

My attempts to retrieve the elevation of a site using latitude and longitude have been unsuccessful due to an error I encountered while making an ajax call. Regardless of whether I use HTTP or HTTPS, I receive the following error message: "No 'Access ...

Performing asynchronous requests using Ajax in a loop

I am encountering a situation in my jQuery code where I have a loop containing an AJAX call. As the loop executes, each iteration triggers an AJAX request to the server. I am curious to know whether a new thread is created for each of these calls on the ...

I am struggling to make my button hover effects to function properly despite trying out numerous suggestions to fix it

As a newcomer, this is my first real assignment. I've managed to tackle other challenges successfully, but this one seems a bit more complex and I'm struggling to pinpoint where I'm going wrong. Despite googling various solutions, none of th ...

When I attempt to conceal the filter within mat-table using *ngIf, I encounter an issue where I am unable to read the property 'value' due to it being

After creating a mat-table, I encountered an issue when trying to show and hide my input filter area using a button. If I use *ngIf="showInputFilter" to hide the filter area, I receive the error message Cannot read property 'value' of u ...

transform two series of data into a single object - JavaScript

I'm struggling to merge two arrays into a single array object. Here is the first array, referred to as "keys". Each item in this array should become an object key: ["name", "age", "gender", "status"] The second array contains values and is named "h ...

What is the best way to add all IDs to an array, except for the very first one

Is there a way to push all response IDs into the idList array, excluding the first ID? Currently, the code below pushes all IDs to the list. How can it be modified to exclude the first ID? const getAllId = async () => { let res = await axios({ m ...

Which is better: specifying a name in window.open() or using replace?

If the current window is www.myparent.com and a button labeled "a" is clicked, it triggers the following function window.open('children','same','',??). Subsequently, a new page will open as www.myparent.com/children. On the o ...

Changing the value of a nested object in React's state

In my web application, I am using React/Redux with a Description Class that allows users to edit descriptions. The Props description and propertyTypes are fetched through AJAX calls. import React, { PropTypes } from 'react'; const defaultDesc ...

Obtaining the value with JQuery's .change() function

Currently, I am in the process of setting up dynamic drop-down selectors using JQuery. Despite being new to frontend development, I have encountered a challenge with retrieving the value of a dropdown once it has been changed using JQuery. The user flow I ...

Restrict the number of dynamic form elements to a maximum of 10 entries

I am working on a feature where users can refer their friends and the data will be saved in a database. <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <script type='text/javascript' sr ...

Angular 4 Password Regular Expression Not Working

My validation regex checks for at least 8 characters, including one number, one uppercase letter, one lowercase letter, and one special character. Here is the regex I am using: '(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@$!%*?&])[A-Za-zd$@$!%*?& ...

The Google Location API allows you to access location-based services

Exploring the realm of Google Geolocation API has been an exciting journey for me. After obtaining my key, I dove into creating a straightforward form that prompts users to input a city name and then fetches the corresponding latitude and longitude using t ...

Ways to Increase jQuery Element ID

I have several instances of jPlayer (a jQuery audio player) set up: jPlayer1, jPlayer2, jPlayer3, jPlayer4. Each one is initialized and preloaded with audio files. The following function will loop through an existing array and attach a method to play the ...

JavaScript error: Property 'includes' of undefined cannot be accessed

To verify the existence of data.objectId in the array msgArr, I am utilizing the following code snippet: var exists = msgArr.some(item => item.objectId === data.objectId); if(!exists){ msgArr.push({"objectId":data.objectId,"latLont":data.latLont," ...

Tips for filtering array elements in MongoDB based on element dataIf you want to eliminate certain elements from an array in MongoDB based

Seeking guidance on writing a Mongo query to remove elements from an array based on specific data. { "_id": ObjectId("ajdi293akjf83rhfsf398"), "one": "oneData", "two": [ { "_id":ObjectId("akjf82ijikfj83jkfkj3"), "valu ...

I'm having trouble applying JavaScript to my Flask template, even though it is stored in the static directory. Any suggestions on how to fix this issue with the code provided?

I am currently working on a Flask project and attempting to create a hierarchical structure resembling a tree. However, I suspect that the JavaScript is not being correctly applied to my tree.html file, as the options cannot be expanded. The code provided ...

When using $.ajax, special characters are not rendered properly, displaying strange symbols instead of accents such as "é" or "ã"

I'm struggling to display the letter "é" using $.ajax and a JSON file. I've tried setting everything up with <meta charset="utf-8"> but all I get is an alert window showing "". Any help is appreciated, just not looking for PHP solutions. H ...

How can we pass a function to a child component in Vue 2.0?

I am facing a challenge with passing a function link to the child component in Vue. Although it is functioning correctly, the code appears in HTML format. How can I enhance this? In my Vue instance, I have: app = new Vue({ ... some code data: { ...

Hover over with your mouse to open and close the dropdown menu in React JS

Just starting out with React JS and encountering a small issue. I'm trying to make the menu disappear when the mouse leaves that area, so I used onMouseOut and onMouseLeave to close it. However, I noticed that having these options in place prevents th ...

Arrange a jQuery data table by British date format and exclude any empty cells

Is there a way to ensure the empty cell remains at the bottom when sorting dates in the dd/mm/yyyy format? I am encountering issues with this aspect in sorting the age column. Here is the link to my problem: http://jsfiddle.net/dup75/11/ $('#hr_curri ...