Having trouble displaying dynamically generated texture from a fragment shader in ThreeJS

I've been working on creating a texture using a Three.WebGLRenderTarget and then trying to access it in a fragment shader in the following stage. The concept is to execute the first stage once to generate a complex and costly SDF map, and then access it in subsequent stages as required. Currently, I can create the test texture if I display it directly on the screen, but when I send it to a texture and attempt to read it, I only get a black screen.

I believe it's a simple issue and would appreciate any assistance.

Here is the test code:

import * as Three from 'three'

// Code for creating WebGLRenderer, WebGLRenderTarget, camera, buffer, scenes, quad meshes, etc.

window.addEventListener('resize', onWindowResize, false)

function onWindowResize() {
    // Code for resizing window and updating camera
}

function loop() {
    // Requesting animation frame and rendering
}

function render(scene) {
    // Rendering the scene with the camera
}

function main() {
    // Rendering buffer scene and starting the loop
}

main()

And the shaders:

const vertShader = `
// Vertex shader code
`;

const bufferShader = `
// Fragment shader code to generate a color based on UV coordinates
`;

const screenShader = `
// Fragment shader code to sample buffer texture and display it
`;

Answer №1

It appears that the render target is set in the renderer. To correct this, consider updating your main() function as follows:

function main() {
    renderer.setRenderTarget(buffer);
    render(bufferScene);
    renderer.setRenderTarget(null);
    loop();
}

Here is the full updated code:

const vertShader = `
varying vec2 vUv;

void main(){
    
    vUv=position.xy*.5+.5;
    gl_Position=vec4(position.xy,1.,1.);
}`;

const bufferShader = `
precision highp float;

uniform vec2 u_resolution;

void main(){
    vec2 uv=gl_FragCoord.xy/u_resolution.xy;
    gl_FragColor=vec4(uv,0.,1.);
}`;

const screenShader = `
precision highp float;

uniform sampler2D buffer;
varying vec2 vUv;

void main(){
    
    vec4 texel=texture2D(buffer,vUv);
    gl_FragColor=texel;
}`;

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)


const buffer = new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight, {
  minFilter: THREE.LinearFilter,
  magFilter: THREE.LinearFilter,
  stencilBuffer: false,
  depthBuffer: false,
  type: THREE.UnsignedByteType
});
buffer.texture.needsUpdate = false;

const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
)
camera.position.set(0, 0, 1000);

//Buffer scene
const bufferScene = new THREE.Scene()

const bufferQuad = new THREE.Mesh(
  new THREE.PlaneGeometry(2, 2),
  new THREE.ShaderMaterial({
    uniforms: {
      u_resolution: {
        value: new THREE.Vector2(window.innerWidth, window.innerHeight)
      }
    },
    blending: THREE.NoBlending,
    vertexShader: vertShader,
    fragmentShader: bufferShader,
    depthWrite: false,
    depthTest: false,
  })
);

bufferScene.add(bufferQuad);


//Screen Scene
const screenScene = new THREE.Scene()

const screenQuad = new THREE.Mesh(
  new THREE.PlaneGeometry(2, 2),
  new THREE.ShaderMaterial({
    uniforms: {
      buffer: {
        value: buffer.texture
      }
    },
    blending: THREE.NoBlending,
    vertexShader: vertShader,
    fragmentShader: screenShader,
    depthWrite: false,
    depthTest: false,

  })
);

screenScene.add(screenQuad);


window.addEventListener('resize', onWindowResize, false)

function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
  renderer.setSize(window.innerWidth, window.innerHeight)
  render(screenScene)
}

function loop() {
  requestAnimationFrame(loop)
  render(screenScene)
}

function render(scene) {
  renderer.render(scene, camera)
}

function main() {
  renderer.setRenderTarget(buffer);
  render(bufferScene);
  renderer.setRenderTarget(null);
  loop();
}

main()
body {
      margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7a667c6b6b4e3e203f3a3b">[email protected]</a>/build/three.min.js"></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

Problem with HTML relative paths when linking script sources

Having trouble with a website I constructed using Angular. The problem lies in the references to javascript files in index.html. The issue is that the paths in the HTML are relative to the file, but the browser is searching for the files in the root direct ...

Guide to implementing the HttpOnly flag in a Node.js and Express.js application

Hey there! I'm currently working on a project using node.js and I need to ensure that the HttpOnly flag is set to true for the header response. I've written this code snippet in my app.js file but it doesn't seem to be affecting the respons ...

The script functions perfectly in jsfiddle, yet encounters issues when used in an HTML

I stumbled upon a seemingly peculiar issue with my script in jsfiddle: https://jsfiddle.net/oxw4e5yh/ Interestingly, the same script does not seem to work when embedded in an HTML document: <!DOCTYPE html> <html lang="en"> <head> & ...

How should I start working on coding these sliders?

Which programming language should I use? My understanding of Java Script is limited, so coding them on my own might be challenging. What would be the essential code to begin with? Here are the sliders - currently just Photoshop images... ...

Injecting data into a Q promise

I'm facing some issues related to what seems like JavaScript closures. In my Express + Mongoose web application, I am utilizing the Q library for Promises. I have a question regarding passing request data to the promise chain in order to successfully ...

Simulated web server for testing with Jest

Can I ask a unique question? I have a tool for extracting data from webpages directly, not through APIs. I want to create end-to-end tests for this tool using the Jest library, but I need to ensure the web pages I'm referencing remain consistent. It&a ...

Tips for adjusting the duration of a background in jQuery

jQuery(document).ready(function(){ jQuery('div').css('background-color','#ffffff').delay(12000).css('background-color','#000000'); }); Hello everyone! I'm having some trouble with this code. I am ...

Updating Angular model remotely without relying solely on the controller

I am struggling to call the addRectangleMethod method from my Javascript code in order to retrieve server-side information into the Angular datamodel. However, I keep encountering an error stating that the method I'm trying to call is undefined. It&ap ...

Ensuring continuous user login during webpage refreshes with the help of React and local storage

Currently, I am working on implementing the use of local storage to ensure that upon refresh, the user remains logged in rather than being signed out each time. Successfully, I have been able to store data in local storage by utilizing the following code ( ...

What are the benefits of using a combination of design patterns in JavaScript?

Currently, I am working on a personal project for learning purposes, which is a simple To-Do List. I am implementing the modular pattern (specifically, the revealing module pattern). The image below showcases my general idea of how I intend to build it. V ...

Is it possible to determine if a selected date falls within the current week using JavaScript?

Currently facing an issue with JavaScript. I have multiple dates retrieved from a database, and I need to extract the date that falls within the current week. ...

How can I modify the border color within a div element?

My journey into web development is just beginning, and I've grasped the basics of Java, JSP, HTML, JS, CSS, and JQ. However, I've hit a roadblock while attempting to change the border color of a div upon mouse hover. Despite my efforts, I haven&a ...

What is the method to generate an array of values using a single attribute in GeoJSON data?

Note: After reviewing some possible solutions mentioned in this thread, I found that .map is the perfect fit for what I need, which was not covered in the original post. Thomas's response below addresses my specific requirement. In JavaScript, how ca ...

Group the JSON data in JavaScript by applying a filter

I have a specific json object structure with keys cgi, tag and name, where the cgi key may be repeated in multiple objects. If any cgi has the tag 'revert', then that particular cgi should not be returned. [ { "cgi": "abc-123 ...

Exploring the method to extract a value from an array of objects using JSON parsing in Appcelerator

Visualize an artificial json response, here's the string representation of this JSON... [{"A":"1","B":{"name":"joe","lastname":"jones"},"COLORS:{"red":"rojo","blue":"azul"},"active":"yes"}] I am aiming to extract the name "joe" using the following c ...

The output from the Node.js child_process.exec command returned null for stdout, yet stderr was not empty

I'm currently working with a simple code that runs java -version in the command line to check if Java is installed on the user's system. Interestingly, when I execute this code, the stdout does not display anything, but the stderr shows the expe ...

Disabling prefetch in next.config.js: A comprehensive guide on eliminating data prefetching in Next.js

Typically, in many cases, the disabling of prefetching is achieved by specifically setting a link to not preload. An example of this can be seen below: <Link href="/about" prefetch={false}> <a>About us</a> </Link> My go ...

What is the best way to set up distinct Jest test environments for React Components and Backend API routes within NextJs?

In the realm of testing with NextJS, Jest comes into play effortlessly, complemented by React Testing Library for frontend testing. Interestingly, Jest can also be utilized to test backend code. Currently, I am incorporating a library in my API routes tha ...

Fixing the Material UI upgrade error: "Make sure you have the right loader for this file type."

As a beginner in React, Webpack, Babel, and web development, I have been tasked by my company to upgrade the material-ui version for a dropdown search component. The current version used in the project is "1.0.0-beta.43", and I decided to start by upgradin ...

Eliminate HTML TAG entries from the input form

My issue is that when I try to type a comma, it does not allow me to do so. How can I add other characters like <, >, /, \, etc? $("#in1").keypress(function (evt) { if (String.fromCharCode(evt.which) == ",") return false; }); < ...