Exploring the fundamentals of fragment shaders in three.js: utilizing position data to color individual fragments

I am experimenting with coloring the fragments in my shader based on their position between the highest and lowest vertex. Take a look at the shaders below:

<script type="x-shader/x-vertex" id="vertexshader">

    uniform     float   span;

    attribute   float   displacement;

    varying     vec3    vNormal;
    varying     float   color_according_to_z;

                float   z_actual;

    void main() {
        vNormal = normal;

        vec3 newPosition = position + normal * vec3(0.0, 0.0, displacement);
        gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0);

        z_actual = gl_Position.z + span / 2.0;
        color_according_to_z = 1.0 / span * z_actual;
    }

</script>

<script type="x-shader/x-fragment" id="fragmentshader">

    uniform     float   span;

    varying     float   color_according_to_z;

    void main()
    {
        gl_FragColor = vec4(color_according_to_z, 0.5, 0.5, 1.0);
    }

</script>

Below is the render function I am using:

function render() {
    requestAnimationFrame(render);

    plane.rotation.x = global_x_rotation;
    plane.rotation.z = global_z_rotation;

    for(var i = attributes.displacement.value.length - 1; i >= 0; i--) {
        attributes.displacement.value[i] = attributes.displacement.value[i] - 0.5 + Math.random();
    };

    uniforms.lowest = attributes.displacement.value.min();
    uniforms.highest = attributes.displacement.value.max();
    uniforms.span = uniforms.highest - uniforms.lowest;

    attributes.displacement.needsUpdate = true;

    uniforms.lowest.needsUpdate = true;
    uniforms.highest.needsUpdate = true;
    uniforms.span.needsUpdate = true;

    renderer.render(scene, camera);
}

I constantly adjust the displacement value and update the span between the highest and lowest vertices accordingly.

The challenge now lies in determining how to shade a fragment based on its proximity to the highest or lowest point, which I am still working on.

Here is a jsfiddle illustrating the code mentioned above.

Answer №1

Your code contains several errors that are visible. Make sure to check for NaN's in your variables.

The shader logic seems to be correct, but it may not generate the desired color output.

var max = -1.0e30;
var min = +1.0e30;
var x;
for(var i = attributes.displacement.value.length - 1; i >= 0; i--) {
    x = attributes.displacement.value[i] += - 0.5 + Math.random();
    if (x < min ) min = x;
    if (x > max ) max = x;
};

uniforms.lowest.value = min; // Remember lowest.value !
uniforms.highest.value = max;
uniforms.span.value = max - min;

attributes.displacement.needsUpdate = true;

//uniforms.lowest.needsUpdate = true; // This is unnecessary for uniforms
//uniforms.highest.needsUpdate = true;
//uniforms.span.needsUpdate = true;

Fiddle: http://jsfiddle.net/c2jry/2/

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 incorporate polling into the code provided below? I specifically need to retrieve data from the given URL every 60 seconds. How should I go about achieving this

Can you assist me in integrating polling into the code below? <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="https://code.highcharts.com/highcharts.js"> ...

Utilizing absolute path in Typescript: A comprehensive guide

I am currently working on a project written in Typescript running on NodeJS. Within the project, I have been using relative paths to import modules, but as the project grows, this approach is becoming messy. Therefore, I am looking to convert these relativ ...

Having trouble extracting the responseText from the Ajax request

My current challenge involves making an ajax call and receiving an Object in the response. However, when I attempt to access "responseText," it keeps returning as undefined: var results = API.get('users', { username: un, userpass: pw } ); conso ...

JavaScript: change array objects into a string separated by dots

Task: Converting Nested Objects in an Array to Dot Notation String Using JavaScript Here is a sample data structure that needs to be converted: [ { property: 'name', children: [], message: 'name should not be empty', } ...

Mouse over the image to reveal a fresh window

I'm attempting to achieve a similar effect to that of this website (you may need to register to view it). Here's the image that illustrates it: As you can observe, when I hover over the image, a box appears and then when I hover over the YouTube ...

Activate on-demand static regeneration with Next.js

I am thoroughly impressed by the functionality of Incremental Static Regeneration in Next.js. However, I am currently seeking a method to manually trigger static page regeneration as needed. It would be ideal to have a command that can be executed via an ...

A recursive function that utilizes a for loop is implemented

I am encountering a critical issue with a recursive function. Here is the code snippet of my recursive function: iterateJson(data, jsonData, returnedSelf) { var obj = { "name": data.groupName, "size": 4350, "type": data.groupType }; if ...

Sending an AJAX request with conditionals using PHP

I am working on a form where selecting a Name populates two other dropboxes automatically. With the help of an AJAX script, a variable is passed to another page to retrieve data from a query and display it. The current setup successfully updates one dropbo ...

Is React the ideal choice for implementing a shared state subscription mechanism in your project?

Trying to determine if this falls under the "pub/sub" pattern or a variation of it. The goal is to establish a shared state where different components can subscribe to it and only receive updates when the state changes. const useForceUpdate = () => useR ...

The `this` keyword is incapable of accessing the object. It is instead pointing to the `window` object

Here is a sample of Javascript constructor code: function TestEngine() { this.id='Foo'; } TestEngine.prototype.fooBar = function() { this.id='bar'; return true; } TestEngine.prototype.start = function() { this.fooBar( ...

conversion of text to number using JavaScript

After pulling values from an XML file using JavaScript, I face the challenge of converting a string to an integer in order to perform calculations. To extract data from the XML file, I use the following snippet: var pop = JSON.stringify(feature.attribute ...

Obtain all meshes in Three.js based on their name attribute

In my Three.js scene, I have created various meshes, some of which have a name property set to 'quadrant'. I am trying to retrieve all the meshes with the name 'quadrant' in any way possible. When using scene.getObjectByName("quadrant") ...

Using the getAttribute method in Edge with JavaScript

My goal is to dynamically load videos on the page after it has fully loaded. I have a script that successfully works in Firefox and Chrome, but I encounter errors when using Edge/IE. The specific error message I receive is SCRIPT5007: Unable to get propert ...

Start the setInterval function again after clearing it with the clearInterval button, but wait for

Currently, I am working on a content slider that automatically cycles through slides using the "next" function and setInterval. However, I want it to stop when the user clicks on the prev/next buttons by using clearInterval. Is there a way to resume setInt ...

Whenever I attempt to run my script, the console on replit fails to function properly

As a complete beginner to Javascript, I'm having trouble getting my script to respond when I try to execute it. It just moves on to the next line and waits for me to type 'node index.js' again. I've included 2 images in an Imgur album - ...

Tips for adjusting the vertical position of an image within a bootstrap column by a small amount

Apologies in advance if this question has already been addressed, and I am struggling to adapt it to my specific scenario. My objective is to adjust the positioning of the two images shown in the screenshot example below so that they align with the grey b ...

Removing an element from an array within MongoDB

After closely examining my mongodb data structure, it appears like this: [ { "_id": "582bc918e3ff1bf021ae8b66", "boardName": "Test Board", "created_at": 1479264483957, "__v": 0, "person": [ { "name": "Steve", "w ...

There is a complete absence of light within my three.js scene

Hey there! I'm facing an issue with my code. I've been working on a project using three.js which includes a scene, 2 objects, renderer and camera. However, when I added the light, it didn't show up at all! I've tried multiple options bu ...

Toggle visibility with jQuery's Show & Hide feature

Currently, I am working with some divs that need to be hidden (with the class .hideable) and others that need to be shown (with the class .toggleable). I have made progress in getting everything to work as desired. However, I am facing a challenge - once t ...

How come my audio element in HTML refuses to play once I adjust its volume setting?

I'm currently working through a React tutorial and I've encountered an issue with my component. I have implemented an audio HTML tag in the component, with its volume controlled by an input from another React component. However, despite setting u ...