"Efficiently rendering a variety of textures using a single draw

Hey there, I am interested in creating multiple cubes with unique textures for each cube. In order to optimize performance, I've combined the geometries into a single mesh. However, I've encountered an issue with textures as I currently require a draw call per texture. Is there a way to merge textures similar to how I merged the geometries, so I can create a single texturized mesh with just one draw call?

Here is my current code snippet:

var geometry = new THREE.Geometry();
    var materials = [];

    for(var p = 0; p < 1000; p++){
        var height = Math.floor((Math.random() * 100) + 50);

        var box = new THREE.BoxGeometry(10, 5, 10);        
        box.translate(
           Math.floor((Math.random() * 100) + 50), 
           Math.floor((Math.random() * 100) + 50), 
           Math.floor((Math.random() * 100) + 50));

        var texture = new THREE.MeshLambertMaterial({ map: new THREE.TextureLoader().load(textures[p])});
        texture.needsUpdate = true;

        geometry.merge(box);
        materials.push(texture);                         
     }

      var mesh = new THREE.Mesh(geometry, materials);        
      el.setObject3D("mesh", mesh);  

I believe the solution may be to associate a texture per geometry or to combine different textures into a single texture. Any advice on this matter would be greatly appreciated. Thank you in advance.

I am using A-Frame v.0.7.1, but I believe this issue pertains more to Three.js.

Answer №1

To simplify your workflow, consider consolidating all your texture images into a single texture atlas. Then adjust the UV coordinates for each geometry to reference the appropriate texture.

Excerpt from the mentioned resource:

var texture = new THREE.MeshLambertMaterial({ map: new THREE.TextureLoader().load('textureatlas.png')});

var bricks = [
  new THREE.Vector2(0, .666),
  new THREE.Vector2(.5, .666),
  new THREE.Vector2(.5, 1),
  new THREE.Vector2(0, 1)
];

geometry.faceVertexUvs[0] = [];
geometry.faceVertexUvs[0][0] = [ bricks[0], bricks[1], bricks[3] ];
geometry.faceVertexUvs[0][1] = [ bricks[1], bricks[2], bricks[3] ];

When merging geometries, ensure that the UV coordinates are properly transferred (this may happen automatically).

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

Zod vow denial: ZodError consistently delivers an empty array

My goal is to validate data received from the backend following a specific TypeScript structure. export interface Booking { locationId: string; bookingId: number; spotId: string; from: string; to: string; status: "pending" | "con ...

Take away the attention from the span element

I have been experimenting with the following jsfiddle and attempted various methods suggested in this Stack Overflow thread, but I am struggling to remove the focus from the "feedback" span after clicking on the cancel button in jQuery confirm dialog. Her ...

Placing pins on Google Maps

I'm attempting to display two separate markers on two individual maps positioned next to each other on my website. <script type="text/javascript"> var map, map2; function initialize(condition) { // setting up the maps var myOptions = { zoo ...

What is the best way to update a collection item while maintaining non-existing values in the query?

Consider this straightforward example, where an item is saved as: { "test": { "a1": "a1" } } When collection.updateOne is called with $set and the following object: await collection.updateOne(doc, {$set: {"test&q ...

Does the arrangement of props matter in JSX?

Assuming the o object has a key/value pair of: foo: 'bar', can I expect these results to hold true?: // foo will be 'bar' <MyComponent foo='should not override' {...o} /> // foo will be 'overridden' ...

Node-RED experiences crashes while attempting to make HTTP requests to access a web service

I'm currently facing a challenge in creating a node that can make web service calls. The tools I'm using are: Node-RED version: v0.17.5 Node.js version: v8.4.0 An exception is being thrown, and here's the error message: node-red_1 ...

Unexpected error: JSON data at line 1 column 1 of the JSON data is incomplete

I've encountered an issue with my script related to a JSON response error. Below is the code snippet in question: $(document).ready(function() { $('#btndouble').click(function(){ var address = $('#btcaddress').val(); ...

Difficulty with info window within a for loop

I am currently working on implementing multiple info windows for markers. I found an example on Stack Overflow that I am trying to follow. Despite not encountering any errors in the console, the info windows do not appear as expected when clicking on the m ...

How to use ngModel directive in Angular to select/unselect dynamically generated checkboxes and retrieve their values

Currently, I am working with a dataset retrieved from an API and dynamically creating checkboxes in my HTML page using the DataView component from PrimeNG. My objective is to implement a feature where users can select or deselect all checkboxes with a cli ...

changing the elements' classes by using a carousel

Having trouble with a custom carousel and unable to use the standard Bootstrap carousel. This is how my code is structured: Images: <img src="1.img"/> <img src="2.img"/> <img src="3.img"/> Prev / Next buttons: <div class="left ...

How can I utilize VeeValidate 3's locale message JSON files without the need for Node.js or an HTTP server?

With VeeValidate 2, the locale message files are in javascript format, making it possible to use them by including <script src='./vee-validate/dist/locale/ja.js'> without needing Node.js or an Http Server. However, with VeeValidate 3, the ...

Changes have been made to the Vue object, however, it does not trigger a re-render

Whenever I hit the right arrow key, it adjusts the object without re-rendering it : <div class="map"> <div class="map-page" tabindex="0" @keyup.arrow-keys="show" ref="mapPage"> <template v-for="mapRow in mapMatrix"> < ...

Is it possible to pass a variable to a text constant in Angular?

In my constant file, I keep track of all global values. Here is the content of the file: module.exports = { PORT: process.env.PORT || 4000, SERVER: "http://localhost:4200", FAIL_RESULT: "NOK", SUCCESSFUL_RESULT: "OK ...

React JS - Building a dynamic multi-tiered dropdown navigation system

Link to view the illustrative example: here. Could anyone advise on a solution for ensuring only one submenu is open at a time? For instance, when "menu 3" is opened, I would like "menu 2" to be automatically closed. ...

The successful loading of tab favicons in the DOM of an angular chrome extension is a triumph, however, explicit XHR requests are unfortunately

I've been immersed in developing a Chrome extension with Angular 5. Successfully, I managed to extract favIconUrls from the tabs API and link them to my popup.html's DOM. The icons are retrieved and displayed without any hiccups. See an example ...

Pass data to all routes in ExpressJS

After logging in, I am setting req.session variables as follows: req.session.loggedin = true req.session.firstname = loginDetails.firstName; I would like to streamline this process and pass this information to ALL routes without manually adding them to ea ...

Ways to implement the don't repeat yourself (DRY) principle in React JS with condition-based logic

https://i.stack.imgur.com/xkrEV.gif Here is a sample way to use the component: import React from "react"; import MyAvatars from "../../components/MyAvatar/MyAvatars"; const About = () => { return ( <MyAvatars ...

The Vimeo player JavaScript API is experiencing issues on iOS devices

I am facing an issue where the API for playing a video only works on iOS after the play button is clicked in the player. However, it works fine on desktop and Chrome for Android. http://codepen.io/bdougherty/pen/JgDfm $(function() { var iframe = $(&a ...

jQuery Validation is not functioning correctly

I am facing an issue with implementing jQuery.Validation. I have written a script and included all JS files below, but for some unknown reason, the validation always returns that the form is valid. Below is the JavaScript code I am using: $(document).rea ...

Dynamic Vue2 input field names

With Vue2, I am attempting to create input tags with dynamic content. My attempts at binding it to a function using :name="someFunction" have been unsuccessful in this case. The name attribute needs to be in the format people[0]['name'] people ...