I am creating a Geometry in three.js and populating it with vertices to build a 2D terrain. I am pushing all of the Vector3s and Face3s to the geometry as soon as my terrain is created, and then modifying each vertex and face every frame.
Because I am modifying the face vertices every frame, I need to tell three.js to update the faces. I am doing this using geometry.elementsNeedUpdate = true. This works, however I have noticed it causes a substantially large amount of memory usage (my app uses an extra ~50mb of RAM every second).
The following code demonstrates what I'm trying to do:
function pushEverything(geom) {
for (var i = 0; i < 10000; i++) {
geom.vertices.push(new THREE.Vector3(...));
geom.faces.push(new THREE.Face3(...));
geom.faces.push(new THREE.Face3(...));
}
}
function rebuild(geom) {
for (var face of geom.faces) {
face.a = ...
face.b = ...
face.c = ...
}
geom.elementsNeedUpdate = true
}
var renderer = new THREE.WebGLRenderer({
canvas: document.getElementById("my-canvas")
});
var geom = new THREE.Geometry();
var camera = new THREE.PerspectiveCamera(...);
pushEverything(geom);
while (true) {
// Perform some terrain modifications
rebuild(geom);
renderer.render(geom, camera);
sleep(1000 / 30);
}
I have already followed the advice of this question, which suggested using geometry.vertices[x].copy(...) instead of geometry.vertices[x] = new Vector3(...).
My question is: why is my memory usage so high when using geometry.elementsNeedUpdate = true? Is there an alternative method to updating a Geometry's faces?
I am using three.js 0.87.1 from NPM.
I have found and solved the issue. It was not a memory leak on three.js' part, but it was a memory leak on my part.
I was creating a Geometry and allowing myself to clone it, perform modifications to the clone, and then merge it back into the original. What I didn't realise is that I should call geometry.dispose() on the cloned geometry when I was done with it. So, I was basically cloning the geometry every frame, which explains the huge memory usage.
I have fixed my issue by converting the Geometry to a BufferGeometry, and calling geometry.dispose() on the geometry when I am done with it. I now have expected memory usage.
Related
I have a three.js project where I'm adding in 100 meshes, that are divided into 10 scenes:
//add 100 meshes to 10 scenes based on an array containing 100 elements
for (var i = 0; i < data.length; i++) {
mesh = new THREE.Mesh(geometry, material);
//random positions so they don't spawn on same spot
mesh.position.x = THREE.Math.randInt(-500, 500);
mesh.position.z = THREE.Math.randInt(-500, 500);
They're added in by a loop, and all these meshes are assigned to 10 scenes:
// Assign 10 meshes per scene.
var sceneIndex = Math.floor(i/10);
scenes[sceneIndex].add(mesh);
I also wrote a functionality where I can rotate a mesh around the center of the scene.
But I don't know how to apply the rotation functionality to all meshes while still keeping them divided into their corresponding scenes. This probably sounds way too vague so I have a fiddle that holds all of the relevant code.
If you comment these two lines back in you'll see that the meshes all move to scenes[0], and they all rotate fine the way I wanted, but I still need them divided in their individual scenes.
spinningRig.add(mesh);
scenes[0].add(spinningRig);
How is the code supposed to look like? Waht is the logic to it?
The logic is fairly simple. The simplest format would be to have a separate spinningRig for each scene -- essentially a grouping of the meshes for each scene.
When you create each scene, you'll also create a spinningRig and add + assign it to that scene:
// Setup 10 scenes
for(var i=0;i<10;i++) {
scenes.push(new THREE.Scene());
// Add the spinningRig to the scene
var spinningRig = new THREE.Object3D();
scenes[i].add(spinningRig);
// Track the spinningRig on the scene, for convenience.
scenes[i].userData.spinningRig = spinningRig;
}
Then instead of adding the meshes directly to the scene, add them to the spinningRig for the scene:
var sceneIndex = Math.floor(i/10);
scenes[sceneIndex].userData.spinningRig.add(mesh);
And finally, rotate the spinningRig assigned to the currentScene:
currentScene.userData.spinningRig.rotation.y -= 0.025;
See jsFiddle: https://jsfiddle.net/712777ee/4/
Is it possible to create a dynamic animation by applying transformations to the bones of a 3D model using three.js? I tried moving and rotating the bones of a SkinnedMesh, but the mesh was not updated.
loader = new THREE.JSONLoader();
loader.load('/JS-Projects/Virtual-Jonah/Modelos/initialPose.js',function jsonReady( geometry )
{
mesh = new THREE.SkinnedMesh( geometry, new THREE.MeshNormalMaterial({skinning : true}) );
mesh.scale.set( 10, 10, 10 );
mesh.position.z = mesh.position.y = mesh.position.x = 0;
mesh.geometry.dynamic = true;
scene.add( mesh );
var index = 0;
for (var i = 0; i < mesh.bones.length; i++)
{
if (mesh.bones[i].name == "forearm_R")
{
index = i;
break;
}
}
setInterval (function ()
{
mesh.bones[index].useQuaternion = false;
mesh.bones[index].position.z += 10;
mesh.bones[index].matrixAutoUpdate = true;
mesh.bones[index].matrixWorldNeedsUpdate = true;
mesh.geometry.verticesNeedUpdate = true;
mesh.geometry.normalsNeedUpdate = true;
renderer.render(scene, camera);
}, 33);
renderer.render(scene, camera);
});
The model I am using was created with makeHuman (nightly build), exported to Collada, imported in Blender and exported to the three.js JSON model. The link to the model is the following:
https://www.dropbox.com/sh/x1606vnaoghes1y/gG_BcZcEKd/initial
Thank you!
Yes, you can!
You need to set mesh.skeleton.bones[i], both mesh.skeleton.bones[i].rotation and mesh.skeleton.bones[i].position. Rotation is of type Euler. Position is of type Vector3. I have actually tested this using my code from here https://github.com/lucasdealmeidasm/three-mm3d (that includes a working skinned mesh with bone-attachable objects) and one can indeed do that.
Note that Inateno's answer is very wrong, there are many instances where this is necessary.
For example, in a FPS, one uses both dynamic and non-dynamic animation.
When a character runs and holds a gun, the direction he points the gun at is dynamically set (one could use mesh.skeleton.bones[i].rotation where "i" is the index for bone assigned to the arm for that) while the rest of the animation, including the walking, is made in the editor and loaded. One can, in three.js, use "THREE.AnimationHandler.update(delta);" and then change single bones' position and rotation in code to solve those issues.
I know you can export a bone driven animation from Blender in JSON format, for use in THREE.js, there are a few tutorials of that around the web. I hope this helps. Good Luck.
If I understund you want to create animations yourself inside the code ?
You are note supposed to do this, in Unity you have a simple animation editor, you never manipulate bones directly in code.
It's long, boring, unperforming. To animate a model use animation directly.
Here's a result of animation with some bones manipulation but there is an animation over.
http://threejs.org/examples/webgl_animation_skinning_morph.html
Here is a tutorial about making simple animation if you need http://blog.romanliutikov.com/post/60461559240/rigging-and-skeletal-animation-in-three-js
And here a related post about animations problems just in case
Blender exports a three.js animation - bones rotate strangely
Hope this will help you :)
I am currently working on a small project using the new Babylon.js framework. One of the issues I have run into is that I basically have two meshes. One of the meshes is supposed to be the background, and the other is supposed to follow the cursor to mark where on the other mesh you are targeting. The problem is that when I move the targeting mesh to the position of the cursor, it blocks the background mesh when I use scene.pick, resulting in the other mesh having its position set on its self.
Is there any way to ignore the targeting mesh when using scene.pick so that I only pick the background mesh or is there some other method I could use? If not, what would be the steps to implement this sort of feature to essentially raycast only through certain meshes?
If you need code samples or any other forms of description, let me know. Thanks!
Ok, it's easy.
So, we have two meshes. One is called "ground", the second "cursor". If you want to pick only on the ground you have two solutions :
First:
var ground = new BABYLON.Mesh("ground",scene);
ground.isPickable = true ;
var cursor = new BABYLON.Mesh("cursor", scene);
cursor.isPickable = false;
...
var p = scene.pick(event.clientX, event.clientY); // it return only "isPickable" meshes
...
Second:
var ground = new BABYLON.Mesh("ground",scene);
var cursor = new BABYLON.Mesh("cursor", scene);
...
var p = scene.pick(event.clientX, event.clientY, function(mesh) {
return mesh.name == "ground"; // so only ground will be pickable
});
...
regards.
I'm loading a mesh from an obj file, then trying to normalize it. However, I'm getting strange results. Here is the code for loading and centering the mesh:
var manager = new THREE.LoadingManager();
var loader = new THREE.OBJLoader(manager);
loader.load('http://jamesdedge.com/threejs/bunny.obj', function(object) {
object.traverse(function(child) {
if(child instanceof THREE.Mesh)
{
var geometry = child.geometry;
var verts = geometry.vertices;
var ctr = new THREE.Vector3(0.0, 0.0, 0.0);
for(i = 0; i < verts.length; ++i)
ctr.add(verts[i]);
ctr.divideScalar(verts.length);
for(i = 0; i < verts.length; ++i)
verts[i].sub(ctr);
}
});
scene.add(object);
});
This code should just center the mesh on the average of the vertex positions, but it seems to be causing a strange effect. You can see it on my website here: http://jamesdedge.com/threejs/tjs_demo.html
I don't see what is causing this, the ctr variable is giving me a valid vector and subtracting a vector from all the vertices will only reposition it.
Many of the vertices in this model are duplicates (i.e. the same javascript object is contained in the object multiple times), so ctr gets detracted from those vertices multiple times.
One way to address this is issue is to merge the vertices at the start of your traversal function, i.e.
var geometry = child.geometry;
geometry.mergeVertices();
This will also make your code run a bit faster as it has to process a lot less vertices.
You can use GeometryUtils.center() to center your whole mesh conveniently in the middle of the scene at (0,0,0). Anyway, just look at the source code of that function
https://github.com/mrdoob/three.js/blob/master/src/extras/GeometryUtils.js
This should give you a good idea on how to conquer your problem.
I have a a question that's been bothering me for some time.
I am using the three.js webgl library to render a large scene with many textures and meshes.
This question is not necessarily bound to webgl, but more javascript arrays and memory management.
I am basically doing this:
var modelArray = [];
var model = function(geometry,db_data){
var tex = THREE.ImageUtils.loadTexture('texture.jpg');
var mat = new THREE.MeshPhongMaterial({map:tex})
this.mesh = new THREE.Mesh(geometry,mat);
this.db = db_data;
scene.add(this.mesh);
};
function loadModels(model_array){
for(i=0;i<geometry.length;i++){
modelArray.push(new model(model_array[i]['geometry'],model_array[i]['db_info']));
}
}
loadModels();
Am I being inefficient here? Am I essentially doubling up the amount of memory being used since I have the mesh loaded to the scene and an array. Or does the model (specifically the model.mesh) object in the array simply point to a singular memory block?
Should I just create an array of mesh ids and reference the scene objects, or is it ok to add the mesh to the scene and an array?
Thanks in advance and I hope I was clear enough.
The main thing that jumps out at me is this:
var tex = THREE.ImageUtils.loadTexture('texture.jpg');
var mat = new THREE.MeshPhongMaterial({map:tex})
If you are loading the same texture every time you create a new model, that could create a lot of overhead (and it can also be pretty slow). I would load the texture(s) and corresponding material(s) you need outside of your loop once.
Your modelArray is a list of plain model objects, each of which has a pointer to the corresponding mesh object (and db object). The scene has a pointer to the same mesh object so you are not exploding your memory use by cloning meshes.
It's possible that your memory use is just because your mesh geometries take up a lot of memory. Try loading your models one by one while watching memory usage; perhaps you have one that is unexpectedly detailed.