Dealing with reflection problems in a fragment shader within the three.js framework

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

I am experiencing difficulties with my gltf CUP model that has texture and PBR effect. I am trying to apply reflection of the environment (Cubereflection), but I'm facing issues. The color and texture are being altered, and only the environmental reflection is visible. I am unsure where the problem lies in my shader program or if there is another issue at play. Since I lack extensive knowledge on shader programs, I am struggling to solve this problem. How can I achieve the proper color (similar to the first image) with the reflection? Two images have been attached - one without reflection and one with reflection. While the reflection seems to be working correctly, it remains a mystery why the proper color is not showing up. Any help would be greatly appreciated.

my shader program.
        var meshlambert_vert =
        varying vec3 vReflect;
        varying vec3 vRefract[3];
        varying float vReflectionFactor;
        attribute vec3 a_normal;
        varying vec3 v_normal;
        varying vec3 v_position;
        uniform mat3 u_normalMatrix;
        void main() {
                vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
                v_position = mvPosition.xyz;
                vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
                vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );
                vec3 I = worldPosition.xyz - cameraPosition;
                vReflect = reflect( I, worldNormal );
                v_normal = u_normalMatrix * a_normal;
                vRefract[0] = refract( normalize( I ), worldNormal, 0.02 );
                vRefract[1] = refract( normalize( I ), worldNormal, 0.02 * 0.2);
                vRefract[2] = refract( normalize( I ), worldNormal, 0.02 * 0.2 );
                vReflectionFactor = 0.1 + 1.0 * pow( 1.0 + dot( normalize( I ), worldNormal ), 0.2 );
                gl_Position = projectionMatrix * mvPosition;
        };


var meshlambert_frag =
    uniform samplerCube tCube;
    varying vec3 vReflect;
    varying vec3 vRefract[3];
    varying float vReflectionFactor;
    uniform vec4 u_ambient;
    uniform vec4 u_emission;
    uniform vec4 u_specular;
    uniform vec4 u_diffuse;
    varying vec3 v_normal;
    varying vec3 v_position;
    void main() {
        // shader code here...
    }";

cubmaping code with reflection:https://i.sstatic.net/aOGxA.jpg

var loader = new THREE.CubeTextureLoader();
        loader.setPath( 'textures/env1/' );

        var textureCube = loader.load( [
            'posx.jpg', 'negx.jpg',
            'posy.jpg', 'negy.jpg',
            'posz.jpg', 'negz.jpg'
        ] );
    textureCube.mapping = THREE.CubeReflectionMapping;

    var cubeShader = THREE.ShaderLib[ "cube" ];
    var cubeMaterial = new THREE.ShaderMaterial( {
            fragmentShader: cubeShader.fragmentShader,
            vertexShader: cubeShader.vertexShader,
            uniforms: cubeShader.uniforms,
            depthWrite: false,
            side: THREE.BackSide
        } );

        cubeMaterial.uniforms[ "tCube" ].value = textureCube;

    cubeMesh = new THREE.Mesh( new THREE.BoxBufferGeometry( 100, 100, 100 ), cubeMaterial );
    scene.add( cubeMesh );
var sphereMaterial=new THREE.MeshLambertMaterial( {envMap: textureCube } );
                    object.traverse( function ( child ) {
                        if ( child instanceof THREE.Mesh ) {
                             child.material = sphereMaterial;

                         }
                     } );

Answer №1

The combination of the reflection color and material color is achieved by maintaining a constant ratio of 98:2

gl_FragColor = mix( color, reflectedColor, clamp( 0.98, 0.0, 1.0 ) );

The intensity of the material's color may be too subtle to detect.

For debugging purposes, consider using a 50:50 ratio:

gl_FragColor = mix( color, reflectedColor, 0.5 );

To utilize vReflectionFactor for the ratio:

gl_FragColor = mix( color, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );

Another point to note is that when utilizing vReflectionFactor, only the reflection will be visible due to the result of

vReflectionFactor = 0.1 + 1.0 * pow( 1.0 + dot( normalize( I ), worldNormal ), 0.2 );

always being greater than 1.0. This occurs because

1.0 + dot( normalize( I ), worldNormal
surpasses 1.0.

If you aim for an alternative approach, you can use

vReflectionFactor = 0.1 + pow( dot(normalize(I), worldNormal), 0.2 );

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

or

vReflectionFactor = 0.1 + pow( 1.0 - dot(normalize(I), worldNormal), 0.2 );

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

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

Controlling setInterval internally in JavaScript: A guide

While developing my application, I have implemented the following code snippet: setInterval(function() { // some code // goes here }, 60000); The goal is to run certain code on a 1-minute interval, but sometimes it may take 2-3 minutes to complete. ...

Having trouble getting basic JavaScript function to conceal a div element?

Looking to expand my knowledge in JavaScript and would greatly appreciate any assistance as I navigate this new world of learning. Despite exploring various resources on this site and trying out suggestions from other users, none have addressed my specific ...

What is the correct way to invoke openPane() in WinJS?

The Feature I Desire: I am looking to add a button on a closed splitView that triggers the .openPane() function. My Attempts So Far: After consulting this MSDN documentation, it was suggested that the SplitView should have a method called showPane(). Re ...

What is the best way to simulate an external class using jest?

My Vue page code looks like this: <template> // Button that triggers the submit method </template> <script> import { moveTo } from '@/lib/utils'; export default { components: { }, data() { }, methods: { async ...

Utilizing HTML to call a function and fetching data from AngularJS

I've been struggling to retrieve the value after calling a function in my HTML file. Despite trying various methods after conducting research, I have not achieved success yet. Take a look at the code below: HTML: <div class="form-group"> & ...

Using AngularJS, learn how to populate array objects within a JSON object

I'm trying to load array objects from a multi-select control, then populate a model object called "name" with its name and age values. After that, I want to load an array from a select element into the model object. However, the ng-model directive on ...

Endless loop in React Native with an array of objects using the useEffect hook

For the current project I am working on, I am facing the challenge of retrieving selected items from a Flatlist and passing them to the parent component. To tackle this issue, I have initialized a local state as follows: const [myState, setMyState] = useS ...

TinyMCE file multimedia upload feature allows users to easily add audio, video

I am looking to enhance the functionality of my TinyMCE Editor by enabling file uploads for audio/video and images. Although image uploading is functioning properly, I am encountering issues with other types of files. Despite setting up pickers throughout, ...

Attempting to utilize the LLL algorithm as described on Wikipedia has led to encountering significant challenges

I'm struggling with determining whether my issue stems from programming or understanding the LLL algorithm mentioned on Wikipedia. To gain a better understanding of the LLL algorithm, I attempted to implement it following the instructions outlined on ...

Display popup when hovering over an li element, but only after one second of hovering over it

My goal is to display an inner div when hovering over an li element. I have implemented a fadeIn and fadeOut effect, but the issue is that if I quickly hover over all li elements, the fadeIn effect triggers for all of them. Ideally, the inner div should on ...

Comparing innerHTML in JavaScript: A guide to string comparison

While attempting to filter a table alphabetically, I encountered an obstacle. The x.innerHTML > y.innerHTML concept in this code snippet is perplexing me: table = document.getElementById('myTable'); rows = table.getElementsByTagName('t ...

Ignoring TypeScript overloads after the initial overload declaration

Issue An error occurs when attempting to call an overload method for a specific function. The call only works for the first defined overload, causing an error if the call is made to the second overload with mismatched typing compared to the first overload ...

Convert the onChange event in JavaScript to a SQL query

Trying to figure out the best way to achieve this, but I'm hitting a roadblock in my code. Essentially, I want the user to have the ability to select time intervals in increments of 30 minutes up to a maximum of 5 hours (which would be 10 options). Ea ...

Setting default parameters for TypeScript generics

Let's say I define a function like this: const myFunc = <T, > (data: T) => { return data?.map((d) => ({name: d.name}) } The TypeScript compiler throws an error saying: Property 'name' does not exist on type 'T', whic ...

Ensuring that a service is completely initialized before Angular injects it into the system

When Angular starts, my service fetches documents and stores them in a Map<string, Document>. I use the HttpClient to retrieve these documents. Is there a way to postpone the creation of the service until all the documents have been fetched? In ot ...

AngularJS Toggle Directive tutorial: Building a toggle directive in Angular

I'm attempting to achieve a similar effect as demonstrated in this Stack Overflow post, but within the context of AngularJS. The goal is to trigger a 180-degree rotation animation on a button when it's clicked – counterclockwise if active and c ...

Printing keys of objects in an array in AngularJS through iteration

Here is an array of objects that I am attempting to iterate in ng-repeat and print keys, but I am facing some challenges. $scope.directivesInfo = [ {"ngRepeat": {"enter": true, "leave": true, "move": true, "add": false, "remove": false}}, {"ngView ...

Is there a way to show a specific div element only during the initial two occurrences of a jade each loop?

How can I display a specific div only during the first two iterations of a loop in Jade? Is there a way to achieve the following logic in Jade? counter = 0 for each tab in tabs if (counter == 0) div.nav-header NAVIGATION counter++ else if ( ...

Rotating an object in three.js based on the mouse position around its current center point with a specified degree value

The threejs model in my scene has its 0,0,0 point at the end, requiring me to rotate it to the desired angle and animate it into position. This results in its position and rotation not being at 0,0,0. The camera has also been positioned to look at the obje ...

Does the default input default to text format?

I have a somewhat peculiar question. I'm currently experimenting with Javascript for a plugin and came across an interesting scenario. Let's say I have an input element that is structured like this: <input type='cc' id='cc&apo ...