Various textures intersecting in a webGL environment

Having a bit of trouble rendering two objects in separate textures using WebGLRenderTarget. When I map both textures to a plane with shaders and add it to the main scene, I'm running into issues with drawing the object that is closer.

If you want to check out the problem, here's a link to a jsfiddle with some example code: https://jsfiddle.net/11qb7ay7/82/ The key part of the code where the issue arises is:

void main() {
    vec4 color = texture2D(tex_sphere, vUv);
    vec4 color_cube = texture2D(tex_cube, vUv);

    gl_FragColor = vec4(color.rgb * color_cube.rgb, 1.0);
}

Just for clarification, the sphere is positioned in front of the cube relative to the camera. How can I make sure that when they overlap, the pixels from the sphere are drawn instead of the cube?

Essentially, I'm looking for a way to calculate the distance of each pixel from the camera and then render the closer one first.

Answer №1

Typically, when the texture tex_sphere contains an alpha channel, you can blend colors using that alpha channel:

void main()
{
    vec4 color = texture2D(tex_sphere, vUv);
    vec4 color_cube = texture2D(tex_cube, vUv);

    vec3 mixCol  = mix(color_cube.rgb, color.rgb, color.a);
    gl_FragColor = vec4(mixCol.rgb, 1.0);
}

If the background of texture tex_sphere is black and needs to be ignored, you should verify that the color of tex_sphere is not black:

void main()
{
    vec4 color = texture2D(tex_sphere, vUv);
    vec4 color_cube = texture2D(tex_cube, vUv);

    vec3  test   = step(1.0/512.0, color.rgb);
    float a      = max(max(test.r, test.g), test.b);
    vec3  mixCol = mix(color_cube.rgb, color.rgb, a);
    gl_FragColor = vec4(mixCol.rgb, 1.0);
}


Note: The mix function interpolates between two values based on a floating-point interpolation value a ranging from [0.0, 1.0]. When a is 0.0, the first value is returned, and when a is 1.0, the second value is returned.

The step function checks if a value is less than a specified edge value. It returns 0.0 if the condition is met, otherwise 1.0 is returned.


To achieve a black background, ensure you set a black "clear" color when rendering the sphere to the render target:

function render() {
    controls.update();

    renderer.setClearColor(0x00);
    renderer.render(sphereScene, camera, renderTargets.sphere, true);

    renderer.setClearColor(0xccccff);
    renderer.render(cubeScene, camera, renderTargets.cube, true);

    renderer.setClearColor(0xccccff);
    renderer.render(scene, camera);
}

If you intend to utilize an alpha channel, make sure to set setClearAlpha before rendering to the render target:

function render() {
    controls.update();

    renderer.setClearAlpha(0);
    renderer.render(sphereScene, camera, renderTargets.sphere, true);

    renderer.setClearAlpha(1);
    renderer.render(cubeScene, camera, renderTargets.cube, true);

    renderer.render(scene, camera);
}

var scene, renderer, camera, controls;
var cubeScene, sphereScene;
var renderTargets;

// Function to initialize all components
init();
animate();

// Initialization logic for setting up scenes, render targets, etc.
function init() {
    // Code for initializing various elements like scene, renderer, camera...

}

// Function triggered on window resize event
function onResize() {
    // Code to handle resizing of elements

}

// Initialize objects like cubes, spheres...
function initObjects() {
    // Code to create and position objects in scenes

}

// Initialize render targets with textures
function initRenderTargets(width, height){
    // Logic for creating render targets and assigning textures

}

// Create WebGL render targets
function createRenderTargets(width, height) {
    // Logic for generating render targets

}

// Animation loop
function animate() {
    // Continuous rendering loop

}


//------------------------------------------
// Main rendering function
//------------------------------------------
function render() {
    // Rendering functionality within the animation loop
        
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/three.js/89/three.min.js"></script>
<script type="text/javascript" src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script id="vs_rt" type="x-shader/x-vertex">
    // Vertex shader code
    
</script>

<script id="fs_rt" type="x-shader/x-fragment">
    // Fragment shader code
    
</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

Tips for Resolving the Problem with React Hook Closures

import React, { useState } from "react"; import ReactDOM from "react-dom"; function App() { const [count, setCount] = useState(0); function handleAlertClick() { return (setTimeout(() => { alert("You clicked on: & ...

Where should AJAX-related content be placed within a hyperlink?

When needing a link to contain information for an AJAX call, where is the correct place to include the info? I have typically placed it in the rel attribute, but after reviewing the documentation for rel, it appears that this may not be the right location ...

Integrating Endless Scrolling feature into current website

We are currently working on incorporating infinite scroll functionality into our existing website. Currently, we have an image that says 'click for more' which triggers an ajax call to the method GetArticlesFromNextSection(true). This method retu ...

Instructions for rearranging the configuration of a 2D array?

A 2-dimensional array is created from a string called matrix: 131 673 234 103 018 201 096 342 965 150 630 803 746 422 111 537 699 497 121 956 805 732 524 037 331 After parsing, it becomes an array of arrays like this: [ [131, 673, 234, 103, 018], [2 ...

Please ensure that busboy on#file completes their task before requesting on#finish

Alright, here's the scenario: req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) { core.upload(filename, file, function(key2) { if (key2 != null) { key = key2; } console.lo ...

Storing user responses in an array using jQuery Form

I have developed a form/questionnaire that prompts users with a series of questions. The initial question categorizes users into two groups, either trucks or cars in this scenario. Subsequently, the form delves into specific questions about the chosen vehi ...

Adjusting Column Widths with JavaScript

Currently, I am attempting to find a solution on how to adjust column widths and heights using JavaScript so that they can be set based on the browser window size. I have tried the code below, but it does not seem to be working as expected. Any assistance ...

Uncaught ReferenceError: ajaxUrl is undefined

After pressing a green button on the website , instead of the expected popup image and email confirmation, I receive an error message stating "ajaxUrl is not defined". I have attempted to find a solution to this problem by searching on Google and Stackove ...

Every time I attempt to insert a background image into a div using jQuery, I am consistently faced with a 404 error message

When I hit enter in my search bar, a new div is created each time. However, I am struggling to assign a background image to the created div as I keep receiving a 404 error in the console. Below is the code snippet I'm working with: function appendToD ...

Javascript auto submission fails to execute following the completion of the printer script

As someone new to javascript, I have a question. I have a function called sendToQuickPrinter() that prints correctly, but after it finishes executing, I need to automatically submit a form to return to my "cart.php" page. I feel like I'm almost there, ...

Issue with Jquery Conflict in WordPress

Apologies if my inquiry is not up to standard. I am currently utilizing a Google library in my project. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> The issue arises when this conflicts with the jQuery u ...

Errors have been observed when using JavaScript variables that begin with the symbol $

For the longest time, I've used JavaScript variable names that begin with $ to signify that they hold jQuery values. For example: $buttons = $( 'button' ); However, a couple of nights ago, I encountered an issue when loading the page in the ...

Using Ajax to fetch project data from an API

Currently immersed in a personal coding project, I'm struggling to troubleshoot my code. Essentially, I need to retrieve data from an API and display it on my HTML page. The data type is "jsonp" due to CORS errors that required this workaround for de ...

Are there any methods to personalize the CSS transition?

I have a question about modifying the style of an element with the transition property. It seems that any changes made are done gradually. Is there a way to monitor these style changes, prevent immediate modifications, and instead replace them with a cus ...

Troubleshooting a Node.js problem with variable scope

I'm working on a nodejs route that downloads a URL as an mp3 using npm-youtube-dl. I have a download directory being monitored with chokidar for new files, and once a file is added, I save the file link. After the download completes, a function is cal ...

Changing the context results in the entire component being re-rendered

Currently, I am encountering a challenge where I have two different components within my Layout.js component that need to "share" props with each other. To address this issue, I introduced a ContextProvider named IntegrationProvider. However, a new proble ...

Optimal methods for organizing various perspectives on a one-page website

I am developing an application that incorporates AngularJS and Bootstrap. The current setup involves organizing various views using ng-show, allowing for view changes based on button interactions and the enablement/disabling of ng-show values. Within a si ...

issue with horizontal scrolling in react menu component

**Hi there, I'm encountering an issue with react-horizontal-scrolling-menu. When scrolling, it moves to the right excessively and causes other elements to disappear. Additionally, adding overflowX: 'scroll' to the BOX doesn't activate t ...

Developing an attribute in a constructor using Typescript

My javascript code is functioning perfectly: class myController { constructor () { this.language = 'english' } } However, I encountered an issue when trying to replicate the same in Typescript export default class myController { co ...

Utilizing Angular 1.4.8 and lodash to effectively parse an array of objects with conditional parameters

DEVELOPER TOOLS Angular version 1.4.8, lodash version 4.0 SOLUTION IMPLEMENTATION After building on Derek's code contribution below, I have arrived at the following solution. It was necessary to make adjustments as using _.property() or _.map() ch ...