calling object3D children for unique styles / animations - three.js

I'm wondering how I would go about calling the individual children of cube (mesh0, mesh1) so I'm able to set different styles / animations to them both.
AFRAME.registerComponent('multi_box', {
schema: {},
update: function() {
for (var i = 0; i < 2; i++) {
var material = new THREE.MeshBasicMaterial({color: "blue"});
var geometry = new THREE.BoxGeometry(1, 1, 1);
var cube = new THREE.Mesh(geometry, material);
cube.position.x = i == 0 ? -1 : 1;
cube.position.y = 0.5;
cube.position.z = -5;
this.el.setObject3D("mesh"+i, cube); //unique name for each object
}
console.log(this.el.object3DMap)
}
});
Codepen link: https://codepen.io/ubermario/pen/wrwjVG
I can console.log them both and see that they are unique objects to each other but I'm having trouble calling them:
var meshtest = this.el.getObject3D('mesh0')
console.log(meshtest.position)
I'v tried this method but with no luck: aframe get object3d children
Any help is appreciated :)

Instancing
In your for cycle, you create
a new geometry instance
a new material instance
a new mesh that connect the previous two
Each new keyword creates a unique instance that is independent of the others. In your case mesh0 and mesh1 are fully independent of each other. If you change any property of an instance, like for example material color or position, the other(s) will not be affected by that. In fact you do that by assigning a different x position to each cube.
Storage
Your component holds a map of 3D objects. Each is identified by a unique name. You generate this name by concatenating the prefix mesh with the iteration number (value of i).
You can later access the cubes just the same way you created them. Either by name
this.el.getObject3D('mesh0')
this.el.getObject3D('mesh1')
//etc.
or by index
this.el.object3D.children[0]
this.el.object3D.children[1]
and you can manipulate them further. For example you can put his on Ln19 in your Codepen:
this.el.getObject3D('mesh0').position.y = 2;
this.el.object3D.children[1].position.z = -3;
Just for completeness: If you would omit the +i at the end, you would overwrite the same key again and again, so mesh would reference just the last cube and others would get lost.
Changing properties
Three.js has a nice API, but in javascript you always need to think what happens behind the scenes. You will see that while learning new stuff. For example:
this.el.object3D.children[1].position.z = -3;
this.el.object3D.children[1].material.color.set('#ffff00');
this.el.object3D.children[1].material.color = [1, 1, 0];
As you can see the position can be changed directly, but color needs a setter sometimes. Things get more complicated with vectors where you need to watch which methods change the current instance and which produce a new one. You could easily forget to clone it. Say you had:
var pos = new THREE.Vector3(-1, 0.5, -5)
for (var i = 0; i < 2; i++) {
var material = new THREE.MeshBasicMaterial({color: "blue"});
var geometry = new THREE.BoxGeometry(1, 1, 1);
var cube = new THREE.Mesh(geometry, material);
//wrong, since it will assign the object reference,
//i.e. always the same object.
//Thus, the cubes will be at one position in the end
cube.position = pos;
//right
cube.pos = pos.clone();
pos.x += 1;
this.el.setObject3D("mesh"+i, cube); //unique name for each object
}
The difference is a bit more moderate topic on reference and value types. You will find many tutorials for that, for example this small gist I just found.
I hope this was helpful and wish you good progress in learning!

Related

Three.js - repositioning vertices in a 'particle' mesh

I have a basic three.js game working and I'd like to add particles. I've been searching online, including multiple questions here, and the closest I've come to getting a 'particle system' working is using a THREE.BufferGeometry, a THREE.BufferAttribute and a THREE.Points mesh. I set it up like this:
const particleMaterial = new THREE.PointsMaterial( { size: 10, map: particleTexture, blending: THREE.AdditiveBlending, transparent: true } );
const particlesGeometry = new THREE.BufferGeometry;
const particlesCount = 300;
const posArray = new Float32Array(particlesCount * 3);
for (let i = 0; i < particlesCount; i++) {
posArray[i] = Math.random() * 10;
}
const particleBufferAttribute = new THREE.BufferAttribute(posArray, 3);
particlesGeometry.setAttribute( 'position', particleBufferAttribute );
const particlesMesh = new THREE.Points(particlesGeometry, particleMaterial);
particlesMesh.counter = 0;
scene.add(particlesMesh);
This part works and displays the particles fine, at their initial positions, but of course I'd like to move them.
I have tried all manner of things, in my 'animate' function, but I am not happening upon the right combination. I'd like to move particles, ideally one vertex per frame.
The current thing I'm doing in the animate function - which does not work! - is this:
particleBufferAttribute.setXYZ( particlesMesh.counter, objects[0].position.x, objects[0].position.y, objects[0].position.z );
particlesGeometry.setAttribute( 'position', particleBufferAttribute );
//posArray[particlesMesh.counter] = objects[0].position;
particlesMesh.counter ++;
if (particlesMesh.counter > particlesCount) {
particlesMesh.counter = 0;
}
If anyone has any pointers about how to move Points mesh vertices, that would be great.
Alternatively, if this is not at all the right approach, please let me know.
I did find Stemkoski's ShaderParticleEngine, but I could not find any information about how to make it work (the docs are very minimal and do not seem to include examples).
You don't need to re-set the attribute, but you do need to tell the renderer that the attribute has changed.
particleBufferAttribute.setXYZ( particlesMesh.counter, objects[0].position.x, objects[0].position.y, objects[0].position.z );
particleBufferAttribute.needsUpdate = true; // This is the kicker!
By setting needsUpdate to true, the renderer knows to re-upload that attribute to the GPU.
This might not be concern for you, but just know that moving particles in this way is expensive, because you re-upload the position attribute every single frame, which includes all the position data for every particle you aren't moving.

object.updateWorldMatrix is not a function

As documentation of Three.js said, after changing the position of the camera, we must call the updateProjectionMatrix() method.
I'm doing the same. But it gives me an error like this:
TypeError: object.updateWorldMatrix is not a function
at Box3.expandByObject (three.module.js:6329)
at Box3.setFromObject (three.module.js:6233)
at index.js:66
at GLTFLoader.js:147
at GLTFLoader.js:1639
My goal is to put my loaded GLTF object, in the center of the screen.
And this is the code I'm using for it:
this.gltfLoader.load("/corolla.gltf", (object) => {
const box = new THREE.Box3().setFromObject(object);
const size = box.getSize(new THREE.Vector3()).length();
const center = box.getCenter(new THREE.Vector3());
// reset OrbitControl
this.controls.reset();
object.position.x += (object.position.x - center.x);
object.position.y += (object.position.y - center.y);
object.position.z += (object.position.z - center.z);
this.controls.maxDistance = size * 10;
this.camera.near = size / 100;
this.camera.far = size * 100;
this.camera.updateProjectionMatrix();
this.camera.position.copy(center);
this.camera.position.x += size / 2.0;
this.camera.position.y += size / 5.0;
this.camera.position.z += size / 2.0;
this.camera.lookAt(center);
this.gltf = object.scene;
this.scene.add(this.gltf);
},
this.manageLoading,
this.gltfLoadErr);
For the record, I'm using the last version of Three.js, it's 0.110.0;
It looks like the errors is occurring here:
const box = new THREE.Box3().setFromObject(object);
Where object is the object coming back from the call to GLTFLoader.load.
According to the docs, object is not an Object3D (which is what Box3.setFromObject expects).
Instead, object is a JSON structure containing information about the GLTF data. The three.js example suggests object.scene would be a renderable entity (if it exists).
Take a look at the code for the GLTFLoader example, here. Compare it against your implementation. You can also debug your code to see exactly what is object contains. Once you have a handle on that, if you're still having problems, come back and ask more questions!
Short solution:
var hollowCylinderGeom = new THREE.LatheBufferGeometry([
new THREE.Vector2(1, 0),
new THREE.Vector2(2, 0),
new THREE.Vector2(2, 2),
new THREE.Vector2(1, 2),
new THREE.Vector2(1, 0)
], 90).toNonIndexed();
var mesh = new THREE.Mesh(hollowCylinderGeom);
console.log(new THREE.Box3().setFromObject(mesh));

How can an AnimationAction stop at the last frame without looping in three.js?

I'd like to stop an AnimationAction at the last frame that I've created with morph targets.
https://threejs.org/docs/#api/en/animation/AnimationAction
I've tried animationAction.clampWhenFinished = true; but that doesn't seem to work.
I've looked at older stackoverflow questions and searched through forums but the solutions didn't work.
var cubeTarget1 = new THREE.BoxGeometry(20, 10, 10);
var cubeTarget2 = new THREE.BoxGeometry(20, 10, 50);
var cubeTarget3 = new THREE.BoxGeometry(60, 10, 10);
cubeGeometry.morphTargets[0] = {name: 't1', vertices: cubeTarget1.vertices};
cubeGeometry.morphTargets[1] = {name: 't2', vertices: cubeTarget2.vertices};
cubeGeometry.morphTargets[2] = {name: 't3', vertices: cubeTarget3.vertices};
Is there a way I can do something like: (this doesn't work, it loops back to the first morphTarget)
var clip1 = THREE.AnimationClip.CreateFromMorphTargetSequence('run', [cubeGeometry.morphTargets[0],cubeGeometry.morphTargets[1]], 30);
var action1 = mixer.clipAction(clip1);
action1.play(); // starts at cubeTarget1 ends at cubeTarget2 (animating between them, without a loop)
// and at a later point I'd like to do
var clip2 = THREE.AnimationClip.CreateFromMorphTargetSequence('run', [cubeGeometry.morphTargets[1],cubeGeometry.morphTargets[2]], 30);
var action2 = mixer.clipAction(clip2);
action2.play(); // starts at cubeTarget2 ends at cubeTarget3 (animating between them, without a loop)
Here's my fiddle:
https://jsfiddle.net/foreyez/uy8abk6v/
This is my approach that I used with an enemy bot gltf model on my three.js prototype first person shooter. The robot has a single track animation with many frames. I had to split the frames up into sub clips with the following code then applied clampwhenfinished.
var EnemyHeavyBotFallBackClip = THREE.AnimationUtils.subclip(gltf.animations[0], “Take_001”, 1300, 1355);
actionEnemyHeavyBotFallBackMixer = mixer.clipAction(EnemyHeavyBotFallBackClip);
actionEnemyHeavyBotFallBackMixer.clampWhenFinished = true;
actionEnemyHeavyBotFallBackMixer.setLoop(THREE.LoopOnce);
actionEnemyHeavyBotFallBackMixer.play();
https://www.shanebrumback.com/super-soldier-battle-intro.html
Disclaimer: This is my website.
I looked at the three.js code. And inside LoopOnce the section involving clampWhenFinished doesn't get hit at all.
For now I'll do it in a very crude way until I find a better solution:
action.setDuration(5).play();
setTimeout(function()
{
action.paused = true;
},2500); // half of the duration
Another way I've been doing is to use morphTargetInfluences and just increment it on an animation loop:
function animate() {
if (cube.morphTargetInfluences[0] < 1)
cube.morphTargetInfluences[0] += 0.01;
controls.update();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
Use Tween.js if you need more functionality.
It took me a while to get this working, a lot of the online examples seem to be outdated and/or non-working. Try:
var clips = THREE.AnimationClip.CreateClipsFromMorphTargetSequences(geometry.morphAttributes.position, 60, true);
mixer = new THREE.AnimationMixer(points);
var action = mixer.clipAction(clips[0]).setDuration(10);
action.clampWhenFinished = true;
action.setLoop(THREE.LoopOnce);
action.play();
Note the "noLoop" parameter of CreateClipsFromMorphTargetSequences(name: String, morphTargetSequence: Array, fps: Number, noLoop: Boolean) needs to be "true" along with clampWhenFinished = true and setLoop(THREE.LoopOnce).
Full example here https://jsfiddle.net/jm4ersoq/

THREE.js Reusing geometry does not seem to work efficiently

I am loading several models into scene using the same geometry like so (pseudo code):
var geoCache = [];
function parseJSONGeometry(json_geo){
// this code is the three.js model parser from the jsonloader
return geometry;
}
function loadCachedGeo(data){
if( !geoCache[data.id] ){
geoCache[json.id] = parseJSONGeometry(data);
}
return geoCache[json.id];
}
function loadObjects(json){
var mats = [];
combined = new THREE.Geometry();
for(i=0<i<json.geometries.length;i++){
data = json.geometries[i];
geo = loadCachedGeo(data.id);
mats.push(new THREE.MeshBasicMaterial(map:THREE.imageUtils.loadTexture(data.src)));
mesh = new THREE.Mesh(geo);
mesh.position.set(data.x,data.y,data.z);
combined = THREE.GeometryUtils.mergeGeometry(combined,mesh);
}
mesh = new THREE.Mesh(combined,new THREE.MeshFaceMaterial(mats));
scene.add(mesh);
}
I also cache the textures, however I omitted that for the sake of simplicity.
When I call:
renderer.info.render.faces
renderer.info.memory.textures
renderer.info.memory.programs
renderer.info.memory.geometries;
renderer.info.render.calls
I notice when one object is on the screen the poly count is say 1000, textures: 1, calls: 1, shaders: 1 and geometries: 1. When two objects are on the screen 2000 faces are reported, 1 texture, 1 shader, 2 calls, and 2 geometries.
I thought that reusing geometry in this fashion only loads the geometry once into the gpu. Am I missing something, can someone PLEASE explain this behavior?
Three.js r59
You need to inspect
renderer.info.memory.geometries
There is also
renderer.info.memory.textures
renderer.info.memory.programs
three.js r.59

How to dynamically add mesh from Object3D to new Object in THREE.js

I am a complete newbie to 3d programming and have been working with three.js just over a week now. I have managed to load multiple collada and obj files, and managed to get perspectives, trackballs, everything working from examples. However, now I am stuck and need some help. For reference you can see the file i'm posting about at the following url:
http://shaman-labz.appspot.com/webgl_loader_obj_mtl.html
This page is basically straight from the examples, except that i am loading up an obj file, which has all these objects as meshes. what i am working on now is after loading the obj, i am going to iterate through all the geometries in the object and extract them so that i can drop them in the scene one a time when i need them, or have them float around like bubbles or something. I was thinking to maybe try to use the fresnel example, but this is where i'm hitting up against the boundaries of my understanding, and some terminology escapes me.
My question is, when this runs, the object that returns and is added to the scene after load has all these gems in it together.
So instead of the following lines:
var loader = new THREE.OBJMTLLoader();
loader.addEventListener( 'load', function ( event ) {
var object = event.content;
object.position.y = - 100;
scene.add( object );
});
loader.load( 'obj/gems/24.obj', 'obj/gems/24.mtl' );
So what i'm doing is when the object returns, i look at the internals in debug/break mode, and i see that it's an object3D and object.children is an array of 25 meshes...and each of those meshes would be one of my 'gems' that i want to work with individually.
So here's where i get lost...when i grab the 'mesh' do i need to strip out the underlying geometry and create a new mesh?
on this page, you can see what i tried to accomplish:
http://shaman-labz.appspot.com/webgl_loader_obj_mtl2.html
the only major difference is in this section of code:
var loader = new THREE.OBJMTLLoader();
loader.addEventListener( 'load', function ( event ) {
var object = event.content;
var pos=0;
for(var i=0; i< object.children.length; i++){
var m = object.children[i];
var gem = new THREE.Object3D();
gem.name=m.name;
gem.add(m);
gem.position.x = -10;
gem.position.y = -10;
gem.position.z = pos;
scene.add( gem );
pos = pos - 10;
}
});
loader.load( 'obj/gems/24.obj', 'obj/gems/24.mtl' );
notice that only 13 of the 25 gems show up from the collection, and also note how they are scattered, indicating that they are somehow still linked to some higher-order relationships that i am unable to set with position properly (it's like each mesh is somehow offset relative to it's original positioning in the original object loaded...thinking this has to do with world matrix?

Resources