29 March, 2017

THREE.js merging geometries

I've had some trouble working out how to properly merge Geometries in three.js so I've created an example.

Have a look at http://qazzian.com:3000/mergeTest.html

In this example, all the blocks are using the same material.

Simple merge example:
let geom1 = new THREE.BoxGeometry(1,1,1);
let geom2 = new THREE.BoxGeometry(2,1,2);
block.translate(3,0,3);
geom1.merge(geom2);

After merging the blocks THREE needs to know that shape has changed.

// Tell THREE to recalculate various things.
this.block0.elementsNeedUpdate = true;
this.block0.verticesNeedUpdate = true;
this.block0.uvsNeedUpdate = true;
this.block0.normalsNeedUpdate = true;
this.block0.colorsNeedUpdate = true;
this.block0.lineDistancesNeedUpdate = true;
this.block0.groupsNeedUpdate = true;

THREE also needs to update the render location for the camera. Otherwise all the merged blocks disappear from the view when the first block is off camera.
this.block0.computeBoundingSphere();

See source for this example is hosted on github:
https://github.com/Qazzian/minecraft-mapper-js/blob/master/public/js/tests/mergeTest.js

The addCube function is the one that does the merging.
It uses a setTimeout to simulate data loading asynchronously.