Skip to content Skip to sidebar Skip to footer

Three.js Merging Meshes But Keeping Separate Materials

I am working on a visualization project based through a web server and I have it working and looking how I want it but it is much slower than I was hoping. Basically, it has a huge

Solution 1:

I spot one particular performance killer: you're modifying the scene by adding and removing objects in the render() function. Instead you should create all the objects you need and turn the objects you don't need invisible or visible. Use visibility rather than transparency to make things invisible.

Another problem (not performance related) is that you're moving a directional light ... a directional light doesn't have a position, but it does have an orientation.

Lastly, as you say in your code, you should really optimise that loop and only change what you need to. As any geometry changes you make have to be delivered to the GPU on each frame which is expensive, you really don't want to make changes you don't need to make, really keep your render() loop as quick as possible.

One particular change I'd probably also make for this is to add a method which builds a material by colour. If you already have that colour it returns that, otherwise it creates that colour. It might not help much, but every little bit can help.


Solution 2:

In case if anyone is looking how to actually merge meshes with multiple materials here's my function. This will merge meshes and re-index materials so all should work fine(tested on r71).

 function mergeMeshes (meshArr) {
    var geometry = new THREE.Geometry(),
        materials = [],
        m,
        materialPointer = 0,
        reindex = 0;

    for (var i = 0; i < meshArr.length; i++) {
        m = meshArr[i];

        if (m.material.materials) {
            for (var j = 0; j < m.material.materials.length; j++) {
                materials[materialPointer++] = m.material.materials[j];
            }
        } else if (m.material) {
            materials[materialPointer++] = m.material;
        }
        geometry.merge(m.geometry, m.matrix, reindex);
        reindex = materialPointer;
    }
    return new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
};

This will definitely speed up scenes with thousands of static objects. Once objects are merged they can only be transformed as one massive mesh.


Post a Comment for "Three.js Merging Meshes But Keeping Separate Materials"