Can each `InstancedBufferGeometry` instance have its own set of unique vertex colors?

Is it possible to assign different vertex colors to each instance of InstancedBufferGeometry?

const xRes = 3;
const yRes = 2;
const numVertices = xRes * yRes;
geometry = new THREE.InstancedBufferGeometry();
geometry.copy(new THREE.PlaneBufferGeometry(3, 2, xRes, yRes));

const particleCount = 500;

const vertexColorArray = new Float32Array(particleCount * numVertices * 3);
for (let i = 0; i < particleCount * numVertices * 3; i++) {
    vertexColorArray[i] = Math.random();
}
const colors = new THREE.BufferAttribute(vertexColorArray, 3);
geometry.addAttribute("vertexColor", colors);

Currently, all instances share the same vertex colors. If I try

const colors = new THREE.InstancedBufferAttribute(vertexColorArray, 3, 1);
each instance gets a separate color, but not per vertex.

Here are the shaders:

<script id="vshader" type="x-shader/x-vertex">
    precision highp float;
    uniform mat4 modelViewMatrix;
    uniform mat4 projectionMatrix;
    uniform float time;

    attribute vec3 position;
    attribute vec3 translate;
    attribute vec3 vertexColor;

    varying vec3 vVertexColor;

    void main() {
        vec4 mvPosition = modelViewMatrix * vec4(translate, 1.0);
        vec3 trTime = vec3(
            translate.x + time,
            translate.y + time, 
            translate.z + time
        );
        float scale = 1.0;
        scale = scale * 10.0 + 10.0;
        mvPosition.xyz += position * scale;
        vVertexColor = vertexColor;
        gl_Position = projectionMatrix * mvPosition;
    }
</script>
<script id="fshader" type="x-shader/x-fragment">
    precision highp float;
    varying vec3 vVertexColor;

    void main() {
        gl_FragColor = vec4(vVertexColor, 1);
    }
</script>

Answer №1

Do you ever wonder if, with the use of InstancedBufferGeometry, it's viable for each vertex of every instance to possess a distinct vertex color?

Absolutely, it's achievable.

One approach is to calculate the color in the shader programmatically or through a lookup table based on the geometry vertex ID and instance ID:

geometry.addAttribute( 'vertexID', new THREE.BufferAttribute( vertexIDs, 1 ) );

geometry.addAttribute( 'instanceID', new THREE.InstancedBufferAttribute( instanceIDs, 1 ) );

Thus, in your shader, the original geometry's vertex ID and the instance ID are accessible. Using these values, you can uniquely assign colors to each vertex of every instance in the shader.

three.js r.84

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

Traversing an array of objects to extract and display the key-value pairs for each object

Here is an array I am working with: const cuisines = [ { african: "African" }, { american: "American" }, { arabian: "Arabian" }, { argentine: "Argentine" }, { asian: "Asian" }, { asian_fusion: "Asian Fusion" }, { australian: "Australi ...

Fixing the hydration error in Next 13 can be challenging, especially when it occurs outside of a Suspense boundary

Encountering an issue while working with Next.js 13: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching <div> in <html>. Every time I attempt to r ...

Jquery(Ajax) call encountered a problem when attempting to send the object

Struggling to send data to a MongoLab DB using JS and JQueryAjax call. The issue lies in being able to see the OID in the DB but no data is actually populated. Upon checking the code and network settings, it's evident that the payload always remains e ...

Troubleshooting: jQuery animation for background-color doesn't function in Internet Explorer

I've been working on a website and I'm trying to create a navigation bar similar to the one found at . My goal is to have the navbar transition from transparent to a colored background as the user scrolls down the page. For this project, I am ut ...

Seeking the location of the `onconnect` event within the Express framework

With the use of "express," I have implemented a middleware function like so: app.use(function(request, response, next) { console.log(request.headers["user-agent"]); // etc. }); This currently displays the user-agent header in the console for ever ...

Exploring every conceivable method for accessing a file from a distant server

I am striving to maximize the flexibility of my script, thus I am seeking all potential methods in PHP and JavaScript to access the content (and not the source code) of a PHP file from a remote server. I have come across CURL, fopen, and include for PHP ...

Having difficulty incorporating external SASS styles into my React.js project

In most of my projects, I follow a similar process for importing SASS styles. First, I create my react app and then install SASS using the command npm install node-sass. Next, I import my SASS file into my app components as shown below: import React from & ...

An issue occurred while trying to retrieve the js file, as an error with code net::ERR_ABORTED 404 (Not

Although this question has been asked before, I am unsure where to find the solution. My express backend server needs to render an HTML page with main.js in it upon launch. app.js code: var createError = require('http-errors'); var express = req ...

Could this be a Vue.js memory leakage issue?

Check out this component's code: import { defineComponent, ref } from "@vue/composition-api"; const template = /* html */ ` <div> <nav> <button @click="showCanvas = !showCanvas">Toggle</button> </nav>a <can ...

Generating a dynamic method for uploading multiple files

Is there a way to dynamically generate multiple upload forms upon clicking a button? I currently have code that allows for uploading one file, but I would like to be able to add additional forms for each file. In other words, if I need to upload 7 files, I ...

Divide the data received from an AJAX request

After making my ajax request, I am facing an issue where two values are being returned as one when I retrieve them using "data". Javascript $(document).ready(function() { $.ajax({ type: 'POST', url: 'checkinfo.php', data: ...

Leveraging GSAP and Vue by utilizing props to dynamically calculate a maxWidth

I am working on animating buttons in my application using GSAP. The idea is that when a user clicks the button, it should animate the maxWidth of the button. I want this to be dynamic by adding a percentage of the max width set using props. Is it possibl ...

Restricting the amount of requests per user within a single hour [Node.js]

As I work on developing a server side application using Nodejs and Express, one thing that crosses my mind is limiting the number of requests per user within a specific time frame to prevent malicious hackers from overwhelming the server with spam. I&apos ...

"The onkeydown event dynamically not triggering for children elements within a parent element that is contentEditable

Can anyone offer some insights into why this code isn't functioning as expected? My goal is to attach the listener to the children elements instead of the body so that I can later disable specific keystrokes, such as the return key. <!DOCTYPE html ...

Tips for sending a parameter to a URL from a controller using AngularJS

I am currently working on a feature where I need to combine adding and editing functionalities on one page. The items are listed in a table below, and when the edit button is clicked, I want to pass the ID of that specific item in the URL. This way, if the ...

Incorporate VLC player into a webpage without any visible control options

Is there a way to embed a flash video in a webpage without showing any controls? I managed to embed a flash video using VLC with the following code: <embed src="img/Wildlife.wmv" height="480" width="640"> However, I want the video to play without ...

PHP is returning an empty response during an AJAX request

I am facing an issue with my AJAX request where I am trying to return a simple echo, but for some reason, it's not working this time. Even after stripping down the code to its bare essentials, the response is still blank. Javascript function getUs ...

What steps can I take to hide my textarea after it has been clicked on?

Recently, I reached out for help on how to make my img clickable to display a textarea upon clicking. While I received the solution I needed, I now face a new challenge - figuring out how to make the textarea disappear when I click the img again. Each clic ...

Deactivate the submission button when there are no search results in typeahead.js

How can I disable the submit button if there are no search results found? The form should not be submitted in this scenario. I am currently using typeahead.js for my code. $('.typeahead').typeahead(null, { name: 'suburb', disp ...

Retrieve the property values of `T` using a string key through the `in

Having trouble accessing a property in an object using a string index, where the interface is defined with in keyof. Consider the following code snippet: interface IFilm { name: string; author: string; } type IExtra<T extends {}> = { [i ...