Combining several meshes in ThreeJS while maintaining distinct materials

I seem to be facing a dilemma. I am attempting to consolidate several meshes into one in order to optimize draw calls. Each mesh I have comes with its own unique material, whether it be color or texture.

Below is the snippet of code I have been working on:

        
        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 all blocks 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);
    

However, every time my render function runs, I encounter this error message: "Uncaught TypeError: Cannot read property 'visible' of undefined".

I'm puzzled as to where I might have made an error. Any insights?

Answer №1

When combining geometries into one entity, you should be aware that using MeshFaceMaterial has been renamed to MultiMaterial in version r.72.

It is illogical to merge geometries with different material indices together.

WebGLRenderer must segregate the geometry by material in order to properly render it.

Generally speaking, only merge geometries if they will be displayed using a single type of material.

Version r.72 of three.js

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Nested jQuery Plugin Selector Problems

I'm looking to have the ability to nest one plugin inside another. However, my selectors seem too broad and are capturing elements within the nested plugin as well. For instance, consider the following HTML structure: <div class="my-plugin"> ...

Changing the host in every URL within a string using node.js

I am working with a string that contains URLs with IP addresses: { "auth" : { "login" : "http://123.123.11.22:85/auth/signin", "resetpass" : "http://123.123.22.33:85/auth/resetpass", "profile" : "http://123.123.33.44:85/auth/profile" ...

Unable to access account: HTML Javascript login issue

Problem with Login Code As a newcomer to HTML, CSS, and almost unknown in Javascript, I sought help from others to create a login code. The code was working fine earlier, but now it's not functioning as expected. Despite checking everything, I can&ap ...

What is the best way to incorporate personalized events into an array using JavaScript?

Imagine we have an array called var arr = [1, 2, 3]. I am looking for a way to create a method that can observe any changes made to this array. The idea is something similar to the following: arr.on('change', function () { // perform some ac ...

Is there a way to trigger this pop-up after reaching a certain percentage of the page while scrolling?

I've been working on a WordPress site that features an "article box" which suggests another article to users after they scroll to a certain point on the page. However, the issue is that this point is not relative but absolute. This means that the box ...

The function Server.listeners is not recognized by the system

Currently, I am following a tutorial on websockets to understand how to incorporate Socket.IO into my Angular project. Despite meticulously adhering to the instructions provided, I encountered an error when attempting to run my websockets server project: ...

Which JavaScript library or template engine would be most suitable for this scenario?

I am tasked with creating an invite your Facebook friends module that will display the names and photos of your friends, allowing you to message them. It is essential that this feature seamlessly integrates into my website's design, so I need to style ...

Resolving label overlapping issue in Chart.js version 2

I am currently utilizing Chart.js 2 for a project of mine. I've successfully customized the style, but there's one persistent issue that I can't seem to resolve and it's becoming quite frustrating. Occasionally, the last label on the x ...

Tips for modifying an HTML element's attribute when a button is clicked, both in the client and server side

Context: This question delves into the fundamental concepts of AJAX. I have been studying this tutorial along with this example for the JavaScript part, and this resource (the last one on the page) for the PHP segment. Imagine a scenario where a JavaScri ...

Automatically toggle Bootstrap checkbox switch to OFF upon successful completion of AJAX script

On my Employee screen, I have an HTML Form with a Bootstrap Checkbox Switch that toggles the visibility of password change fields. Clicking it reveals or hides the fields accordingly. I'd like to set this switch to "off" when the AJAX script updates ...

What is the best way to ensure that one method waits for another method to complete before proceeding?

Below is a React method that needs completion for uploading images to cloudinary and setting the URL in state before executing the API call addStudent. The order of execution seems correct at first glance, but the last API call crashes due to base64 data n ...

Guide to inserting text into an html element upon clicking an ASP:Button

In my code, there is a DIV that holds some text. Accompanying the text is an asp:Button. When this button is clicked, I aim to access and save this particular text. Nonetheless, it seems that once the button is clicked, the content of the DIV resets - lik ...

Trouble displaying loaded JSON data with $http GET in ng-table

I have recently delved into learning angularjs and am currently experimenting with using ng-table to display the results of blast searches. Everything runs smoothly when I directly add the JSON data in the JavaScript script. However, I have been unsuccess ...

The AJAX call for fetching logged in users is coming back as undefined

Hey there! I'm currently diving into the world of AJAX and am working on enhancing the user experience on my admin system. One thing I want to achieve is to update information like online users, messages, tasks, etc. every 30 seconds or so (for testin ...

Enable compatibility with high resolution screens and enable zoom functionality

My goal is to ensure my website appears consistent on all screen sizes by default, while still allowing users to zoom in and out freely. However, I've encountered challenges with using percentages or vh/vw units, as they don't scale elements prop ...

Error occurred while retrieving JSON array using Jquery

var groupMembers = $.parseJSON(members); $.each(groupMembers, function (index, item) { $.ajax({ type: "POST", url: "'.base_url(" / panel / listNotifications ").'/'.$id.'/" + valueSelected, d ...

Make window.print() trigger the download of a PDF file

Recently, I added a new feature to my website allowing users to download the site's content by following these instructions: Printing with Javascript || Mozilla Dev. Essentially, the user can print a newly formatted site stored in a hidden iframe. Now ...

The first argument in the Node.appendChild function does not adhere to the Node interface when trying to append to a new element

Hey there, I'm new to web development and could use some help. I'm encountering an error where I am trying to add an href attribute to an image tag. Here is my code: function linkus() { var a = document.getElementsByTagName("img"); ...

Difficulty dealing with Firestore using get() followed by add()

Recently started learning Vue.js and Firestore, facing a challenge with what should be a simple task. 1) I am trying to fetch default values from an existing template document in my Firestore database. 2) The goal is to use these default values to create ...

The watermark feature in HTML may not appear when printed on every page

I'm facing an issue with adding a watermark style. The watermark displays only on the first page when attempting to print in Chrome. It works perfectly in Firefox and IE. <style type="text/css"> #watermark { color: #d0d0d0; font-size: 90pt; ...