"Encountered an issue with combining multiple meshes that share the same geometry but have

I wrote a loop that generates multiple Mesh objects with various geometries, where each mesh corresponds to a specific texture:

var geoCube = new THREE.CubeGeometry(voxelSize, voxelSize, voxelSize);
var geometry = new THREE.Geometry();

for( var i = 0; i < voxels.length; i++ ){
  var voxel = voxels[i];
  var object;
  color = voxel.color; 
  texture = almacen.textPlaneTexture(voxel.texto,color,voxelSize); 
  //Return the texture with a color and a text for each face of the geometry
  material = new THREE.MeshBasicMaterial({ map: texture });                       
  object = new THREE.Mesh(geoCube, material);

  THREE.GeometryUtils.merge( geometry, object );
}

//Add geometry merged at scene
mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial() );
mesh.geometry.computeFaceNormals();
mesh.geometry.computeVertexNormals();
mesh.geometry.computeTangents();

scene.add( mesh );

However, I encountered an error in my Three.js JavaScript code:

Uncaught TypeError: Cannot read property 'map' of undefined

This issue arises in the following function:

function bufferGuessUVType ( material ) {
}

Update:

I have decided to abandon the merging approach and utilize a single geometry for all voxels instead. Even though I believe that utilizing merged meshes would enhance the app's performance.

Answer №1

When using r53+, the code structure should resemble the following:


var geoCube = new THREE.CubeGeometry(voxelSize, voxelSize, voxelSize);
var geometry = new THREE.Geometry();
var materials = [];

for (var i = 0; i < voxels.length; i++) {

  for (var j = 0; j < geoCube.faces.length; j ++) {
    geoCube.faces[j].materialIndex = i;
  }

  var object = new THREE.Mesh(geoCube);
  // Assumption is that object positioning takes place here.
  THREE.GeometryUtils.merge(geometry, object);

  var voxel = voxels[i];
  var texture = almacen.textPlaneTexture(voxel.texto, voxel.color, voxelSize);
  materials.push(new THREE.MeshBasicMaterial({ map: texture }));

}

// Add geometry to the scene

var mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
mesh.geometry.computeFaceNormals();
mesh.geometry.computeVertexNormals();

scene.add(mesh);

Answer №2

There are some methods that require the materials array to be present in the mesh face material. For instance:

function fetchMeshMaterial( object, geometryGroup ) {

    return object.material instanceof THREE.MeshFaceMaterial
        ? object.material.materials[ geometryGroup.materialIndex ]
        : object.material;

};

To address this, you can reference the materials array in both the geometry and the mesh face material. This means that when creating the mesh, the line would be modified as follows:

mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial(geometry.materials) );

Additionally, when processing the voxels in a loop, you can add a new material to the materials array like so:

geometry.materials.push( new THREE.MeshBasicMaterial({ map: texture }));

It's crucial for each face in the geometry to have a materialIndex assigned; otherwise, an error may occur. One way to achieve this is by iterating through geometry.faces[] and assigning a materialIndex if you know how many faces each voxel has.

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

The issue of elements flickering while being hidden and shown with jQuery has been observed in both Chrome and

Having trouble with a simple animation using jQuery? While it may work smoothly in Firefox, you might be experiencing flickering in Chrome and Edge. Check out this jsfiddle for reference: HTML <div id="boxes-wrapper"> <div class="box"></ ...

Guide to deploying a React application using Material-UI and react-router

I've successfully built an application using React, Material-UI, and react-router. Below is the content of my complete package.json: { "name": "trader-ui", "version": "0.1.0", "private": true, "dependencies": { "@material-ui/core": "^3.2. ...

Troubleshooting: Issues with MongoDB Aggregation not reflecting updates in my collection

Currently, I am attempting to execute an aggregation query in Mongo utilizing their nodejs driver. The query involves aggregating some fields, calculating averages, and other operations. I constructed the aggregation in Mongo Cloud and then exported it to ...

Retrieve a JSON response from within a schema housed in MongoDB

I have a document structure that looks like this: { "id": "someString", "servers": [ { "name": "ServerName", "bases": [ { "name": "Base 1", "status": true }, { "name": "Base 2", ...

What is the best way to apply a class to a jQuery element only if a specific condition is met, and then remove it if the condition is no longer

Is there a more concise method to accomplish the same task? const selectAllCheckbox = $("input.select_all"); const isChecked = selectAllCheckbox.prop("checked"); isChecked ? selectAllCheckbox.parent().addClass("selected") : selectAllCheckbox.parent().r ...

Strategies for avoiding text selection interference with onMouseMove event

I am in the process of adding a "resize handle" to adjust the width of my left navigation panel. This handle, represented by a div, triggers an onMouseDown() event that calculates the necessary widths and applies them to the relevant elements during subseq ...

What is the best way to create a select box in React that allows for both single and multiple selections?

I recently started utilizing a new package for generating dynamic forms, which can be found at this link. Upon reading through the documentation, I attempted to create a select box as outlined in the instructions provided here. Despite following the step ...

Please explain the concept of the Node.js event loop

I've spent countless hours poring over guides and resources on the event loop, yet I still can't grasp its essence. It's common knowledge that the libuv library is responsible for implementing the event loop, but what exactly is this entity ...

What steps do I need to take to create a custom image for a website?

I'm looking for a way to create a website image using just code, without the need for an actual image file or image tag. Is there a method to do this? Would I use CSS, Javascript, or HTML5 for this task? If using JavaScript to dynamically generate the ...

Using a .NET Web-API controller variable as a parameter in a JavaScript function

I am looking to send a "variable" from the controller to a JavaScript function. The code I have implemented is as below: <div ng-controller="faqController"> <div ng-repeat="c in categories"> <h2 onclick="toggle_visibility(&apos ...

Creating a self-chaining function in JavaScript: A guide

Currently, my goal is to create an Array.prototype function called union( array_to_union ), and then utilize it in the following manner: var a = [1,2,3]; a.union([2,3,4]).union([1,3,4]) ...... I am aiming for the outcome to be the union of these arrays. ...

Execute the function once the audio has finished loading

I need help running a function once an audio file has finished downloading. This is my JavaScript code: // https://freesound.org/people/jefftbyrd/sounds/486445/ var audioFile = "https://raw.githubusercontent.com/hitoribot/my-room/master/audio/test/test.m ...

What is the process for deducting the ordered quantity from the available quantity once an order is confirmed

Although I'm not a fan of hard coding, I've been struggling to find a solution to my problem and some explanations are just not clicking for me. The issue at hand involves three data products in the cart, product details, and placed order data f ...

Developing an SQL table for a website using JavaScript

My command is not functioning as expected and I am struggling to identify the issue. The database opens successfully, however, it fails to process the table creation. var createtable2 = 'CREATE TABLE IF NOT EXISTS offlineCabinDefects (id INTEGER PRIM ...

What is a more effective method for linking values with variables in an object?

Can you suggest a more efficient way to write this in JavaScript? let foo; if(bar) { foo = bar.value; } I am attempting to prevent a react error from occurring when `bar` is null if I were to use const foo = bar.value. ...

Invoke a method in an Angular 2 component using an HTML event

Can an angular component method be invoked using an HTML event? <shape onclick="myMethodInParentComponent()" > I am unable to use (click) as shape is not recognized by Angular. Shape also contains several unknown sub elements making it impractical ...

Place the image either above or below the text in a relative position

I have a peculiar dilemma that has been on my mind lately. As I work on designing my website, I am nearing completion of the responsive/mobile view. Currently, everything looks fine, but only because I use display: none; to hide images when the viewport is ...

Troubleshooting: Why is my Local Image not displaying in ReactJS

I am facing an issue with displaying images in my React application using an array of image paths. Below is the code snippet I have written: import React, { Component } from 'react'; class ItemsList extends Component { constructor() { ...

What method is most effective for duplicating objects in Angular 2?

Is it just me, or does Angular 1.x have methods on the global angular object like angular.copy and angular.shallowCopy that are missing in Angular 2? It seems like there is no equivalent version in Angular 2 documentation. If Angular 2 doesn't plan on ...

The function window.scrollBy seems to be causing a conflict with jjmslideshow, resulting in the page being unable to

I wrote a simple script to create a "smooth scroll" effect when a specific link is clicked: (function() { 'use strict'; // Checking for compatibility if ( 'querySelector' in document && 'addEventListener' in window ...