Captainlonate
Captainlonate

Reputation: 5008

ThreeJS Merging multiple meshes with unique materials

I don't know what I'm doing wrong. I have multiple meshes that I am trying to merge into one mesh so that I can save on draw calls. Each of my meshes has a unique materials. In this example it just has a different color, but really they will have unique textures mapped.

This is my code:

        materials = [];
        blocks = [];
        var tempMat;
        var tempCube;
        var tempGeo;
        var tempvec;


        // block 1
        tempMat = new THREE.MeshLambertMaterial({ color: '0x0000ff' });
        materials.push( tempMat );
        tempGeo = new THREE.CubeGeometry(1, 1, 1);
        for (var ix=0; ix<tempGeo.faces.length; ix++) {
                tempGeo.faces[ix].materialIndex = 0;
        }
        tempCube = new THREE.Mesh( tempGeo, tempMat );
        tempCube.position.set(0, 3, -6);
        blocks.push( tempCube );


        // block 2
        tempMat = new THREE.MeshLambertMaterial({ color: '0x00ff00' });
        materials.push( tempMat );
        tempGeo = new THREE.CubeGeometry(1, 1, 1);
        for (var ix=0; ix<tempGeo.faces.length; ix++) {
                tempGeo.faces[ix].materialIndex = 1;
        }
        tempCube = new THREE.Mesh( tempGeo, tempMat );
        tempCube.position.set(1, 3, -6);
        blocks.push( tempCube );


        // Merging them all into one
        var geo = new THREE.Geometry();
        for (var i=0; i<blocks.length; i++) {
            blocks[i].updateMatrix();
            geo.merge(blocks[i].geometry, blocks[i].matrix, i);
        }
        var newmesh = new THREE.Mesh( geo, new THREE.MeshFaceMaterial( materials ) );
        scene.add(newmesh);

Basically, that gives me an error that says: Uncaught TypeError: Cannot read property 'visible' of undefined every time my render function is called.

Where did I go wrong?

Upvotes: 2

Views: 1286

Answers (1)

WestLangley
WestLangley

Reputation: 104833

You are merging geometries into one, and using MeshFaceMaterial (renamed MultiMaterial in r.72).

It does not make any sense to merge geometries having different material indices.

WebGLRenderer needs to segment the geometry by material to render it.

As a rule-of-thumb, only merge geometries if they will be rendered with a single material.

three.js r.72

Upvotes: 1

Related Questions