Atlaslog / Field Notes / three.js rendering
Field note · three.js rendering
InstancedMesh trees are randomly rotated and half vanish
Quick answer
The 5000 instances render, but orientation and size ignore the per-instance values, and whole stands disappear when the camera moves. The instance matrices were never flagged for upload and the bounding sphere still covers only the base geometry.
Symptom
- InstancedMesh count is 5000, yet each tree has an arbitrary orientation and scale unrelated to what was set.
- Moving the camera a few hundred metres makes an entire stand of trees disappear, and it returns when you move back.
- setColorAt colours appear only after instanceColor.needsUpdate is set.
Checklist
- Reduce count to 2 and read matrix 0 back with getMatrixAt to verify the writes.
- Check that Matrix4.compose received a Quaternion rather than Euler angles.
- Verify instanceMatrix.needsUpdate = true runs after the loop.
- Compare the bounding sphere with the 800 m instance spread.
Fix
Drive a reusable Object3D (position, rotation, scale, updateMatrix) into setMatrixAt, then set instanceMatrix.needsUpdate and call computeBoundingSphere() so frustum culling covers the instance spread.
Code
var m = new THREE.Matrix4();
mesh.getMatrixAt(0, m);
console.log('第 0 个实例平移', new THREE.Vector3().setFromMatrixPosition(m));var treeGeo = new THREE.ConeGeometry(0.6, 3, 6);
var treeMat = new THREE.MeshStandardMaterial({ color: 0x2e7d32 });
var count = 5000;
var trees = new THREE.InstancedMesh(treeGeo, treeMat, count);
var dummy = new THREE.Object3D();
for (var i = 0; i < count; i++) {
dummy.position.set(
(Math.random() - 0.5) * 800,
0,
(Math.random() - 0.5) * 800
);
dummy.rotation.y = Math.random() * Math.PI * 2;
dummy.scale.set(1, 0.8 + Math.random() * 0.6, 1);
dummy.updateMatrix();
trees.setMatrixAt(i, dummy.matrix);
}
trees.instanceMatrix.needsUpdate = true;
trees.computeBoundingSphere(); // 关键:按实例分布重算
scene.add(trees);
Watch out
- Reusing one dummy Object3D without resetting rotation and scale each iteration makes later instances inherit the previous transform.
- Calling computeBoundingSphere before writing the matrices leaves the sphere at the base geometry size.
English edition written for Atlaslog from the original Chinese field note. Code is unchanged and runs as-is.
Atlaslog (2026). InstancedMesh trees are randomly rotated and half vanish. https://www.jingweizhi.com/en/cookbook/three-instanced-transform.html (accessed 2026-11-03).