Modify the material of all other models to match the material of the selected model

I've been tinkering with the vertex shader for 3D models, but I'm running into an issue where I can't seem to change all other models' materials to match the selected model's material. Each viewport contains 4 models, and when I select one (v1 in the bottom left), I want the rest of the models to update their materials accordingly. I've implemented the logic in the Model Selection code, but it doesn't seem to apply to all other models. Below, there are assumptions made about having 4 vertex shaders and model creations. Any advice on how to solve this would be greatly appreciated! =)

https://i.sstatic.net/h747n.png

Main

function init() {
container = document.getElementById('container');

// scene
scene = new THREE.Scene();

defineViewports();
initCameras();

// shader properties and object loaders
var shaderMaterial1 = createShaderMaterial(vertexShader(), fragmentShader());
loadModelWithShader("male_model_object.json", shaderMaterial1, 0, 0);

var shaderMaterial2 = createShaderMaterial(vertexShader2(), fragmentShader());
loadModelWithShader("male_model_object.json", shaderMaterial2, 500, 14);

var shaderMaterial3 = createShaderMaterial(vertexShader3(), fragmentShader());
loadModelWithShader("male_model_object.json", shaderMaterial3, 0, 514);

var shaderMaterial4 = createShaderMaterial(vertexShader4(), fragmentShader());
loadModelWithShader("male_model_object.json", shaderMaterial4, 500, 514);

// fps stats
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild(stats.domElement);

// renderer
renderer = initializeRenderer();
container.appendChild(renderer.domElement);

// event listeners
window.addEventListener('updateSize', updateSize, false);
window.addEventListener('click', onClick, false);
window.addEventListener('keypress', onDocumentKeyPress, false);
}

Model Selection

function onDocumentKeyPress(event) {
switch(event.keyCode) {
    case 13: // enter key
        if(selectedIndex >= 0) {
            var selectedVertexShader = objects[selectedIndex].children[0].material.vertexShader;

            for(var j = 0; j < objects.length; ++j) {
                for(var i = 0; i < materials.length; ++i) {
                    materials[i].vertexShader = selectedVertexShader;
                    materials[i].needsUpdate = true;
                }
            }
        }
}}

Renderer

function render() {
updateSize();
for (var i = 0; i < views.length; ++i ) {
    view = views[i];
    camera = view.camera;

    // set up rendering parameters
    adjustViewportAndScissor(view);
    setupCameraAspect(camera, view.width, view.height);
    
    renderer.render(scene, camera);
}}

Answer №1

If you want to set materials as a variable reference outside the model and access them through this reference for making changes, you can do so by following this approach. Any changes made to the material will be reflected in all models that use the same material.

var customMaterial1 = new THREE.ShaderMaterial(shaderProp);
var customMaterial2 = new THREE.ShaderMaterial(shaderProp);

var objectLoader = new THREE.ObjectLoader();
    objectLoader.load("male_model_object.json", function(object) {
        object.traverse(function (child) {
          if (child instanceof THREE.Mesh)
              child.material = customMaterial;
          
        }
    });
    scene.add(object);

function onDocumentKeyPress(event) {
...
    for(var j = 0; j < objects.length; ++j) {
            for(var i = 0; i < materials.length; ++i) {
                materials[i] = customMaterial2;
                materials[i].needsUpdate = true;
            }
    }
...

}

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

What is the best way to send user input text to a Vue method using v-on:change?

I am trying to pass the input value from my HTML to a Vue method called checkExist(). I need to get this value within the checkExist() method. Can anyone provide advice on how I can achieve this? I am new to Vue and could use some guidance. HTML: <inp ...

Encountering a problem when utilizing webview in react native due to an error with the evaluation of

While utilizing webview for trading charts, I am encountering an issue where a warning is displayed and the URL fails to load. Below is the code snippet used for loading. It seems like the video URI works fine in full screen mode, but other URIs are not ...

Enhance your spreadsheet by incorporating dynamic columns utilizing xlsx and sheetjs libraries

I have an array consisting of multiple tags with unique ids and corresponding data: [ { "id": "tagID1", "error": { "code": 0, "success": true }, "data": [ [1604395417575, 108 ...

Understanding how to read a JSON response when the dataType is specifically set to JSONP

I am attempting to send a JSONP request for cross-domain functionality. The issue is that my server does not support JSONP requests and interprets them as regular JSON, responding with an object: {result: 1} Below is the AJAX request I have made: jQuery. ...

Executing a series of functions in succession using jQuery

I am trying to iterate through an object that contains functions which need to execute consecutively. Ideally, I would like these functions to be chained together in a way where one function waits for the previous one to finish before executing (e.g., func ...

My NodeJS MongoDB application is being bombarded by an infinite loop of "Sending request..." messages from the Postman

This is the complete code for my chatbot application const express = require('express'); const app = express(); const MongoClient = require('mongodb').MongoClient; const assert = require('assert'); const bodyParser = require(& ...

Retrieve JSON data by making an AJAX request to a PHP file using the POST method

I am looking to extract data from a form using an AJAX call. The information is received in PHP as a string that looks like: 'fname':'abc','lname':'xyz','email':'','pass':'',& ...

utilizing the data provided by a user in the "prompt" window within my HTML code

Looking to utilize user input from the prompt window. This is my custom JavaScript form: var answer; function load() { answer=prompt("what is your name?", "Write your name here"); return answer; } function hideNsee() { var HNS = docume ...

Is it possible for a d3 chart to render twice in one area if it's rendered in two different places?

When attempting to showcase two distinct d3 pie charts on my webpage within individual mat-cards, they both end up displaying in the svg tag of the first d3 chart in my code. This is what my code looks like: <section class="three"> <! ...

Leveraging Javascript Variable in Kendo Grid Template

Creating two variables through an ajax call, their values remain constant after the page loads. var approvalLevel; var fullName; $(function() { $.ajax({ type: "GET", async: "false", url: approvalLevelURL, contentType: ...

Having trouble accessing news feed with jQuery due to an unexpected token error when attempting to cross domains

I am attempting to access the Yahoo News feed from a SharePoint site, but it is causing a cross-domain access issue. Despite trying various solutions found on numerous websites and blogs, I still cannot resolve the problem. (I am executing this code in the ...

Requesting a resource using the HTTP GET method returned no data

Looking to process the response from an http-request using JavaScript? Check out this straightforward example below. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html x ...

Several treeviews for selecting data

I need some help with a specific assignment. The back end code is all set, but I'm struggling with the UI component. The task requires two tree views, one on the left and one on the right. The left tree view will contain states with multiple children, ...

Having trouble with Node.js multiparty upload functionality

I'm facing an issue with the functionality of multiparty.Form(). Specifically, I am attempting to print numbers like 2, 3, and 4. Below is the code snippet for uploading images: app.post('/gallery/add',function(req, res,next) { var input = ...

The controller is providing a null response following an ajax Post request

I am having trouble with my ajax Post request targeting the edit action method in my controller. The issue is that none of the values are being populated, they all come back as null. What should be happening is that when the '.save-user' button ...

Determine the number of days without including weekends and holidays using JavaScript

I am working on a code that calculates the total number of days excluding weekends and specified holidays. After researching on various platforms like stackoverflow and adobe forum, I have come up with the following code. If a public holiday falls on a w ...

Unable to modify the content of a table cell after triggering a Bootstrap modal event

Looking to update values in rows of a table? Here is an example table: https://i.sstatic.net/6l4f3.png I need to update the title per selected row. After selecting the first row, changing the value works fine. However, when I choose the second row, the ...

Can someone provide me with a practical example of utilizing Threejs Frustum in a project?

While browsing through Stack Overflow, I came across some outdated examples regarding the Frustum Despite my extensive search efforts, I have been unable to find a suitable solution. My project involves a plane with over 10000 stands, and I am looking to ...

creating a personalized CSS style rule

Can a custom rule be created in CSS using @media for a parent class to make changes based on the class? <div class="parentGreen"> <ul class="ul1"> <li>1</li> <li>2</li> &l ...

My Express server is having trouble loading the Static JS

I'm feeling frustrated about this particular issue. The problem seems to be well-solved, and my code looks fine, but I can't figure out what's wrong . . . I have a JavaScript file connecting to my survey page, which I've added at the b ...