Transfer vertices into a texture and send it to the shader for processing

Finally found some time to experiment with shaders, but I hit a roadblock. My goal is to pass vertices to a shader and perform general-purpose computing on them.

It seems like the gpgpu functionality is working fine because I can see a few pixels being shifted to the side in the center as I added some test code.

Now, my aim is to pass the vertices of a sphere. Here are the steps I am following. Please let me know if you spot any mistakes :-)

edit: fiddle included - click here

1) Creating geometry and storing it in a data array.

geometry = new THREE.SphereGeometry( 0.2, 15, 15 );
console.log(geometry.vertices.length);
var a = new Float32Array(geometry.vertices.length * 4);
for(var k=0; k<geometry.vertices.length; k++) {
                a[ k*4 + 0 ] = geometry.vertices[k].x;
                a[ k*4 + 1 ] = geometry.vertices[k].y;
                a[ k*4 + 2 ] = geometry.vertices[k].z;
                a[ k*4 + 3 ] = 1;   
}

2) Saving it in a data texture.

posTexture[2] = new THREE.DataTexture(a, 16, 16, THREE.RGBAFormat, THREE.FloatType);

3) Setting up the 'Set scene' (it should pass the data texture to it once). setUniforms = { posTexture: {type: "t", value: posTexture[2]} };

var setMaterial = new THREE.ShaderMaterial({
    uniforms: setUniforms,
    vertexShader:   document.getElementById('setVert').textContent,
    fragmentShader: document.getElementById('setFrag').textContent,
    wireframe: true
});

var setPlane = new THREE.Mesh(new THREE.PlaneGeometry(16,16), setMaterial);
setScene.add(setPlane);

4) Defining the shaders.

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

    // enabling high precision floats
    #ifdef GL_ES
    precision highp float;
    #endif
    varying vec2 vUv;
    uniform sampler2D posTexture;

    void main(){
        vUv = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
    }

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

    #ifdef GL_ES
    precision highp float;
    #endif
    uniform sampler2D posTexture;
    varying vec2 vUv;

    void main(){
        vec3 color = texture2D( posTexture, vUv ).xyz;

        gl_FragColor = vec4(col, 1.0);
    }
</script>

5) Time to animate!!! The 'start' function initializes the SetShader to store the data and output a WebGLRenderTarget for the next shaders: one for calculations and providing a texture with coordinates, and another for display.

function animate() {

    requestAnimationFrame(animate);
    renderer.setViewport(0,0,16, 16);
    if(buffer == 0) {
        buffer = 1;
        a = 0;
        b = 1;
    } else {
        buffer = 0;
        a = 1;
        b = 0;
    }

    if(start) {
        renderer.render(setScene, processCamera, posTexture[a]);
        start = false;
    }

    posUniforms.posTexture.value = posTexture[a];
    renderer.render(posScene, processCamera, posTexture[b])
    dispUniforms.posTexture.value = posTexture[b];
    renderer.setViewport(0,0,dispSize.x, dispSize.y);
    renderer.render(scene, camera);

}

Answer №1

After some adjustments, I polished the shader code as it appeared a bit disorganized to me ^^ http://jsfiddle.net/ec5zU/1/

It seems like you are attempting to send sphere vertices to the gpu. This suggests that there might be a misunderstanding of the gpgpu concept. Gpgpu is used for calculations (algorithms, mathematics) on the GPU without focusing on 3D graphics.

The idea of passing sphere vertices into a texture and manipulating it doesn't seem logical to me - unless I'm missing something. Could you provide more insight into your ultimate goal with this gpgpu approach?

In the demo, textures are utilized because transferring data from CPU (JavaScript) to GPU is easier than in reverse. One method involves creating a render target for GPU output, converting it to a texture after rendering, effectively "storing the data".

In conclusion, my advice would be to deepen your knowledge of shaders and three.js, as tasks can often be simplified and improved. Implement the suggestions provided by myself and Andon M. Coleman, rethink your sphere logic, and consider a more coherent approach since the current method lacks coherence...

If you believe that constantly updating positions via textures is the best route, then proceed with it :) After further experimentation and refinement, including comments and fixes, a red dot now moves across the screen: http://jsfiddle.net/ec5zU/2/. However, I won't dedicate more time to this project as Stackoverflow isn't meant for full coding projects ^^. Hopefully, this guidance serves as a helpful starting point, with some functionality now in motion.

(Stackoverflow requirements dictate including code, hence the refined shader code below.)

<script type="x-shader/x-fragment" id="fragmentshader">
    
    precision highp float;
    
    varying vec2 vUv;
    uniform sampler2D posTexture;

    void main()
    {
        vec3 color = texture2D(posTexture, vUv).rgb;
        color.x += 0.01;
        gl_FragColor = vec4(color, 1.0);

    }
    
</script>

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

Show the percentage of completion on the progress bar while uploading with AJAX

I'm having trouble updating the current upload value on my progress bar in real-time. I know how to do it when the progress bar has stopped, but I can't get it to update continuously. xhr.upload.onprogress = function(e) { if (e.lengthComputa ...

I am experiencing difficulty in successfully transmitting a variable from my jQuery code to my PHP code

I've been attempting to pass a variable from my jQuery code to my HTML/PHP code using AJAX and POST. However, I'm encountering an error message stating "Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php on l ...

Insert some text into the div element. Create a new line

I'm looking to make a specific text on my webpage trigger a new line when displayed in a div. I've been struggling to figure out how to accomplish this: var original= "the text @n to change"; var changed = original.replace(/@n /g, '\ ...

How to achieve the functionality of ocibindbyname in JavaScript

I am currently utilizing an HTA page that is coded in JavaScript to monitor various Oracle tables. My goal is to optimize the Oracle query caching by using bind variables, similar to how I implemented it in a PHP environment with this code: $sql = "selec ...

Retrieving data via AJAX from an SD card

I am using the Atmel SAM4E-EK microcontroller as a server to host a webpage and send data over HTTP protocol. I am currently facing an issue with the download function while trying to download a file from my sd_card, which will not be larger than 512MB. s ...

typescript error is not defined

While browsing online, I came across a post discussing how to transfer data from an MVC model to a .ts file. The suggestion was to include the following code: <script type="text/javascript"> var testUrl = @Html.Raw(Json.Encode(Model.testUrl) ...

How to set a cookie within an iframe while using Safari browser

Despite searching extensively on Stackoverflow and various other sources, I have not been able to find a solution that works for my specific case. The scenario is as follows: we have an application on domain A that we do not have control over, and an appl ...

Using trigonometry and Javascript to determine the necessary padding for an image to rotate without being cut off

Within the known rect (grey) of the outer parent element is an image element (orange) with its overflow hidden. I am trying to determine the necessary padding for the image element (with known width and height) in order to rotate it to a specific angle, s ...

Switching languages in Nuxt i18n causes the data object to reset

Recently, I incorporated nuxt-i18n into a project to support multiple languages. Everything was running smoothly until I encountered an issue where switching language while filling out a form resulted in all data on the page being lost. To tackle this pro ...

Using Node.js and Angular to Access Google Spreadsheet JSON Data Across Different Origins

Seeking to extract JSON data from a public Google Spreadsheets page, my initial attempt involved an AJAX call which successfully retrieved the data but I struggled with saving it to my $scope. Switching to $http.get led me to encounter cross-origin reques ...

Update the displayed image on the webpage based on information retrieved from the database

Can someone help me figure out how to change the clickable icon on getseats.php from available to unavailable when a seat's status is 0? I'm struggling with this and any advice would be appreciated. Here's the code I have: <?php $noerro ...

Easy way to eliminate empty elements following a class using jQuery

I'm encountering a situation where I have a group of elements following a specific class that are either empty or contain only white space. <div class="post-content"> <div class="slider-1-smart"> --- slider contents --- < ...

Eliminate items from within the Array object prototype

I am attempting to enhance the functionality of a JavaScript native array within an Angular service without extending global objects through prototyping. app.factory('Collection', function($http, $q) { var Collection = function(arr) { ...

Enhancing Your Website with Interactive Highlighting Tags

Looking at the following html: Let's see if we can <highlight data-id="10" data-comment="1"> focus on this part only </highlight> and ignore the rest My goal is to emphasize only the highlight section. I know how to emphasize a span ...

Click the button to instantly scroll to a particular word with highlighting, and with another click, jump to the next occurrence

In order to achieve the objective, simply click on a button that will search for and scroll to a specific word while highlighting it. The same button can be clicked again to find the next occurrence, and so on. If you need an example of how this works, ch ...

What is the method for accessing the AG-Grid Grid API beyond the Vue component?

In my application, I have a component called Home and another one called AgGrid. The AgGrid component is displayed within the Home component, containing the actual AG-Grid. Here's how the Home component is structured: <template> <AgGrid :ro ...

Node.JS, R, and Python are used for intensive computing tasks such as identifying when a callback function has finished executing and

My Node.js REST API exposes endpoints that trigger R and Python scripts for complex computations. Prior to executing these scripts, I must first identify the callback, assign a unique ID to it, and quickly send back the ID to the consumer. The consumer wil ...

What steps do I need to take to ensure this function runs sequentially? Perhaps my understanding of async and await is lacking

I have a function that is responsible for adding data to my database. However, I'm encountering some inconsistency where it works sometimes and fails other times. My suspicion is that the eDataBuilder function is taking too long to iterate through the ...

When implementing auto-generated IDs in HTML forms, rely on randomly generated values for increased uniqueness

When developing a form with multiple complex controls built as Backbone views, one wants to ensure that the labels are correctly linked to the input elements. This is typically done using the "for" attribute. However, in cases where the same control needs ...

Mastering the art of navigating through multiple nested objects is achievable by harnessing the power of recursive

I'm utilizing the AngularTree directive in my Angular application to display a tree view of a specific data structure. The data structure can be viewed at https://jsfiddle.net/eugene_goldberg/Lvwxx629/17/. You can find more information about the Angul ...