Ways to implement HemisphereLight with ShaderMaterial?

I am facing an issue where I am trying to light an object that has been created with ShaderMaterial using HemisphereLight, but the object does not appear to be affected by any of the lights. I have tested it with various other lights as well, and none seem to be affecting the object. What settings do I need to adjust in order for the object to be influenced by the lights?

<script src="https://threejs.org/build/three.js"></script>

<script type="module">

var clock = new THREE.Clock()

function main() {

    var renderer = new THREE.WebGLRenderer();

    renderer.setSize(window.innerWidth, window.innerHeight);

    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera( 200, window.innerWidth/window.innerHeight, 0.1, 1000 );

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

    var vShader = `
    precision mediump float;
    uniform float uTime;
    void main() {
      float z = 0.1*cos(uTime)   * cos(position.y*40. - uTime) * position.y*sin(log(position.y))*0.5 + 0.5;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position.x, position.y, z, 1.0);
    }
  `
  var fShader = `
  precision mediump float;
    uniform vec2 uRes;
    void main() {
    vec2 uv = 1.5*gl_FragCoord.xy/uRes;
      gl_FragColor = vec4(uv.x, uv.y, 0.0, 1.0);
    }
//   `
        var planeG = new THREE.PlaneGeometry(25, 60, 20, 20);

        var planeM = new THREE.ShaderMaterial({
            uniforms: {
              //ambientLightColor: 0xffffff,
              uTime: {
                type:"f",
                value:0.0,
              },
              uRes: {
                type:"f",
                value:new THREE.Vector2(window.innerWidth, window.innerHeight),
              }
            },
            // wireframe:true,
            //lights:true,
            vertexShader:vShader,
            fragmentShader:fShader,
            side:THREE.DoubleSide,
        });
  
        var plane = new THREE.Mesh( planeG, planeM );
        var light = new THREE.HemisphereLight(0xffffff, 0x000000, 2);
        //var light = new THREE.AmbientLight(0xFFFFFF, 1.0)
        
  
        scene.add(light);
        scene.add(plane);
  
        plane.rotateZ(Math.PI/2)
        camera.position.z = 4;
  
        scene.background = new THREE.Color(0xfffffff);
    var render = function (time) {
          requestAnimationFrame( render );   
          plane.material.uniforms.uTime.value = time/100;
            renderer.render(scene, camera);
    };

    render();
};

main()
    </script>

Answer №1

ShaderMaterial does not interact with lights because you are manually specifying the color output in the fragment shader by assigning values to gl_FragColor. This means that you are responsible for controlling elements such as position, rotation, color.

If you want a hemisphere light to impact your shader, you will need to write these calculations in GLSL code, which can be quite intricate. You have to pass the light colors as uniforms and determine how each triangle reacts to receive and reflect those light colors based on their orientation.

Three.js breaks down its material shaders into various files within "ShaderChunks," making it challenging to pinpoint where each step occurs exactly.

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

The PHP header() function is not properly redirecting the page, instead it is only displaying the HTML

After double checking that no client sided data was being sent beforehand and enabling error reporting, I am still encountering issues. The issue revolves around a basic login script with redirection upon validation. <?php include_once "database- ...

Initiate and terminate server using supertest

I've developed a server class that looks like this: import express, { Request, Response } from 'express'; export default class Server { server: any; exp: any; constructor() { this.exp = express(); this.exp.get('/' ...

Error: Attempted to access the 'state' property of an undefined object

I am working with the following function: extractCountries: function() { var newLocales = []; _.forEach(this.props.countries, function(locale) { var monthTemp = Utils.thisMonthTemp(parseFloat(locale["name"]["temperature"])); if(p ...

Is it possible to refresh a div on one .aspx page using content from another .aspx page?

Just beginning my journey with asp.net and currently tackling a project that involves two .aspx pages. Events.aspx: This page is where the site admin can update upcoming events and webinars using an available panel to input event title, date, information ...

What is the best way to stop the browser from automatically redirecting to another page after submitting a form?

I am using an AJAX call to a method that returns JSON data. How can I retrieve and read the JSON response without being redirected to a new empty page? [HttpPost] public JsonResult Test() { return Json("JSON return test", JsonRequestBehavior.AllowGe ...

Can the position of the popover be customized using the right and top properties?

Utilizing Bootstrap popover within a gantt chart, I am dynamically adjusting the position of the popover based on mouse hover. popover.css('left', event.pageX + 'px'); popover.css('top', event.pageY+ 'px') However, ...

Utilizing Typescript Decorators to dynamically assign instance fields within a class for internal use

I am interested in delving into Typescript Decorators to enhance my coding skills. My primary objective is to emulate the functionality of @Slf4J from Project Lombok in Java using Typescript. The concept involves annotating/decorating a class with somethin ...

Inaccurate window dimensions on iOS Chrome are causing issues with innerWidth and inner

After rotating my iOS device, Google Chrome version 104 seems to be reporting incorrect values for window.innerWidth and window.innerHeight. The discrepancy is noticeable when comparing the dimensions before and after rotation: Initially in portrait mode: ...

How can tick values be displayed on a c3js line chart when all data is unselected?

I'm currently working with a c3js line chart that displays 3 different lines. However, I noticed that when I remove all data sources, the x-axis tick values disappear. Is there a way to keep the x-axis tick values visible even when there is no data pr ...

Replicate the array multiple times and combine them into a single flat array

I have a four-element array that I need to copy to another array four times. I achieved this by concatenating the array four times. Here is what I tried: let demoProperties = [] .concat(fourDemoProperties) .concat(fourDemoProperties) .concat(fourDe ...

Is it possible to bind to a service variable in a controller without using $scope and utilizing the

As I delve into the world of controllerAs syntax in AngularJS, I've encountered a snag when attempting to bind a service variable. The traditional approach using `$scope.$watch` or `$scope.$on` would require injecting `$scope`, which seems counterintu ...

Having trouble fetching AJAX POST data in PHP?

Attempting to send a variable as an object to my PHP file, but it's not receiving any data. Testing with window.alert(u.un) in the AJAX call shows that data is being passed successfully without errors in the console. However, the PHP file still does n ...

The HTML anchor tag paired with the italic tag is a powerful combination for

Here is some example code: <a href="#"> <i class="some-bg" /> Some Text </a> Along with some Javascript: $("a").bind("touchstart", function (e) { e.preventDefault(); console.log("Tag: " + e.target); console.log("Tag Nam ...

Performing live search with JQuery Ajax on two different types of fields - text input and dropdown select

Successfully implemented jQuery AJAX live search on an input field, returning desired results. Now aiming to create a compound search involving two fields. Current setup not yielding any results or errors: Form: <div class="form-group"> <div ...

Display two elements within a single table column by utilizing an array in Vue.js

I have a requirement to display 2 items from an array in one table TD ( column ). Below is the example mock data provided: agendas: [ [ { tag: 'p', class: 'm-agenda__date', value: & ...

Ways to retrieve object in Javascript

I retrieved this data object from a JSON file source. { "Apple": "Red", "Orange": "Orange", "Guava": "Green", } Afterward, I transformed it into an Object using: var data = JSON.parse(dataFromJson); which resulted in a JavaScript object ...

Incorporate a background image with the JavaScript CSS property

I'm having trouble adding a background image using the Javascript CSS property in my code. When I directly add the 'url', it works fine. Could the issue be with the 'weatherImage' variable? Javascript var OpenWeatherKey = ' ...

Application with Single Page design has a Large DOM, leading to sluggish performance

I've been working on a single page application that heavily relies on widgets like grids and tabs from the jqWidgets library. These widgets are all loaded when the page is first opened. However, I've noticed that after interacting with the site f ...

Bootstrap revamps dropdown menu code into a convoluted mess

I recently started working on a project with the Material Design theme from for a CodeIgniter application. However, I've encountered an issue with the dropdown functionality. It seems that Bootstrap is altering the original code, transforming it from ...

I constantly encounter a TypeError message that returns as undefined

I'm currently facing an issue while trying to run my Node.js server locally. The error message I keep receiving is: /Users/rogerjorns/Desktop/templateassignment/node_modules/express/lib/router/index.js:458 throw new TypeError('Router.use() ...