Are the shadows in the scene being affected by a problem between DirectionalLightHelper and CameraHelper?

Currently, I am working on a complex static render in the browser using three.js and I have encountered an issue while trying to produce accurate shadows with a single THREE.DirectionalLight that represents the sun in my scene. All the geometry in another .js file has shadows enabled. The green sphere serves as a debug tool and is moved to (50,0,50) at the center of the plane to indicate the camera target and location of DirectionalLight.target. Both the directional light position and main camera position are set correctly.

I suspect that the reason why the shadows are not functioning properly is because the orthogonal camera representing the shadow camera is not pointing in the correct direction. Despite trying to solve it yesterday, I couldn't figure out the behavior of the directional light helper (white line towards the origin) and the shadow camera helper.

My assumption is that for the correct orientation, the directional light helper and shadow camera helper should be aligned at the center of the plane. However, even after extensive research yesterday, my shadow camera does not seem to automatically detect the light position or light target vector. They still appear anchored to the origin. What could be causing this?

Does anyone have any suggestions on how to fix the DirectionalLight.target in my scene? Why do the DirectionalLightHelper and CameraHelper show inconsistency?

// Initialization
const canvus = document.getElementById('canvus');
const scene = new THREE.Scene();
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFShadowMap;

// Camera Setup
const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 500);
camera.position.set(200, 100, 100);
camera.lookAt(50, 0, 50);

// Lighting Configuration
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(100, 200, 200);
directionalLight.target.position.set(50, 0, 50);
directionalLight.castShadow = true;
directionalLight.shadow.bias = 0.0001;
directionalLight.shadow.mapSize.width = 1024; // default
directionalLight.shadow.mapSize.height = 1024; // default

const view_n = 50;
directionalLight.shadow.camera = new THREE.OrthographicCamera(
    -view_n,
    view_n,
    view_n,
    -view_n,
    60,
    150
);

scene.add(directionalLight, directionalLight.target);

// Helpers
const lighthelper = new THREE.DirectionalLightHelper(directionalLight, 10);
const camerahelper = new THREE.CameraHelper(directionalLight.shadow.camera);
scene.add(lighthelper);
scene.add(camerahelper);

// Main Rendering
createBasicGeometry(scene); // from geometry.js
createGroundPlane(scene); // from geometry.js
renderer.render(scene, camera);

Update 2020-1-5

Initially, I attempted setting the camera and also saw instances where people were directly setting a new ortho shadow camera. In my pursuit to resolve this issue, I made changes to reflect the suggestion but unfortunately, the problem persists. I double-checked that all mesh geometries are defined with both object.receiveShadow = true and object.castShadow = true, along with using MeshPhongMaterial. It's perplexing why

directionalLight.target.position.set(50, 0, 50)
is not updating as anticipated. What could be triggering this behavior?

// Updated Lighting Configuration
const view_n = 50;
directionalLight.castShadow = true;
directionalLight.shadow.bias = 0.0001;

directionalLight.shadow.camera.right = view_n;
directionalLight.shadow.camera.left = -view_n;
directionalLight.shadow.camera.top = view_n;
directionalLight.shadow.camera.bottom = -view_n;
directionalLight.shadow.camera.near = 60;
directionalLight.shadow.camera.far = 150;

directionalLight.shadow.mapSize.width = 1024; // default
directionalLight.shadow.mapSize.height = 1024; // default

scene.add(directionalLight, directionalLight.target);

When I log the directionalLight, I receive the expected target position, although it is not correctly aligned in the scene. Additionally, the camera position reveals unexpected results.

console.log(directionalLight.target.position);
//Vector3 {x: 50, y: 0, z: 50, isVector3: true}
console.log(directionalLight.shadow.camera.position);

Answer №1

directionalLight.shadow.camera = new THREE.OrthographicCamera( -view_n, view_n, view_n, -view_n, 60, 150 );

To ensure proper configuration of the directional light, refrain from replacing the camera reference of LightShadow.camera. Follow this setup instead:

dirLight.castShadow = true;
dirLight.shadow.camera.top = view_n;
dirLight.shadow.camera.bottom = - view_n;
dirLight.shadow.camera.left = - view_n;
dirLight.shadow.camera.right = view_n;
dirLight.shadow.camera.near = 60;
dirLight.shadow.camera.far = 150;

Note that shadow casting is only effective if all objects capable of casting shadows (such as your boxes) have castShadow set to true. Similarly, objects intended to receive shadows (like your floor) must enable the receiveShadow attribute by setting it to true.

Answer №2

It could be that the issue arose because I was rendering statically without an animation loop, but I managed to resolve it by adding updateMatrixWorld to the directional light target. Unfortunately, I couldn't update the shadow's camerahelper, but at least the shadows are now functioning as expected.

directionalLight.target.updateMatrixWorld();
scene.add(directionalLight);
scene.add(directionalLight.target);

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

Error: The function res.json is not recognized. Despite searching through related inquiries, I cannot find a solution to my specific issue

Struggling to find a solution and avoiding repetitive questions, I am facing an issue with my bug tracker. After submitting the form and sending it to the server side, the bug is created in the database. However, when I save the bug using await bug.save() ...

What is the best way to adjust the priority of elements using JavaScript in an ASP.NET MVC application?

As part of my application, I need to create a function that allows for the changing of deputy priorities for each consultant. Here is what I have implemented so far: View: @model ML.Domain.DAL.DB_CONSULTANTS .... <table> <tr> < ...

Two select boxes trigger multiple sorting operations

Struggling to implement 2 different sorting operations on two separate columns in a datagrid, using 2 different select boxes has proven to be challenging. I attempted the code below, but as a beginner, I was unable to solve it... In HTML: <select ng ...

Input must be either a 12-byte string, a 24-character hexadecimal string, or an integer

As a beginner in coding, I am struggling to understand and fix this issue. If anyone could lend a helping hand, I would be truly grateful. Error Message: BSONTypeError - Argument passed in must be a string of 12 bytes or a string of 24 hex characters or a ...

Javascript code to verify whether the page is currently positioned at the top

How can I use JavaScript to determine if the page is at scroll(0,0)? I have a full-page slider that needs to pause when the page is no longer at the top. The page may not be scrolled manually, as there are internal HTML # links that could load the page d ...

Encountering issues with proper function of history.listen within React Router

I am struggling to get my function to work every time React detects a change in the URL. The history.listen method is not triggering (the console.log statement is not showing up). I have read that this issue may be related to using BrowserRouter, but when ...

Challenges with xmlHttpRequest in a search autocomplete feature similar to Google's suggestion feature

I am currently working on implementing an autosuggestion search field that functions similarly to Google Suggestion. I am utilizing pure JavaScript/AJAX along with two files: index.php and ajax-submit.php (which is responsible for querying the database). H ...

Share your ES module (.mjs) on NPMJS with support for Node versions older than 8.5.0 (Dual Package)

In the past, publishing a module written in ES6 to NPMJS was a simple process: transpile the code using Babel and publish the resulting `lib` directory to NPMJS while keeping the original `src` files on GitHub. However, with Node v8.5.0's experimenta ...

Observing input value in Popover Template with Angular UI

I am currently working on a directive that utilizes the Angular Bootstrap Popover and includes an input field. Everything seems to be functioning properly, except for the fact that the watch function is not being triggered. For reference, you can view the ...

Is it possible to integrate a Twitter bootstrap theme into a Rails 4 application if the Vendor/assets directory is missing?

My goal is to integrate a theme from wrapbootstrap.com into my rails 4.1 application. After creating a new app with rails 4 scaffolding, I proceeded to extract the downloaded zip directory which contains 4 directories and an index.html file. I then placed ...

What is the best way to toggle an element's visibility using the select tag?

Let me break down the issue for you. In my HTML code, I have a select element that looks like this: <select id="seasons" multiple="multiple"> <option value="s01">Season 1</option> <option value="s02">Season 2</option> ...

Issue: Infinite loops detected in AJAX functions

I am using $.get methods in the following code snippet: $.get("/url" , function(z) { var a = $(z).find("span"); for (var i = 0 ; i<a.length; i++){ var v = $(a).eq(i).children("strong:first").text(); alert(v); } }); However, the s ...

A dynamic substitute for the Supersized slideshow option

I am in the process of updating my website and the final task on my to-do list is to replace the Supersized plugin with a more suitable alternative. The website is constructed using WordPress and I am utilizing jQuery. My goal is to find a fullscreen slid ...

Creating unique identifiers/primary keys for resources in react-admin: A step-by-step guide

I am working on a nextJS project that utilizes redux for state management and an admin panel called react admin. In my project, I decided to use _id instead of id as the keys. To achieve this, I followed the instructions provided in this custom identifiers ...

JavaScript struggles to obtain the timezone information when Daylight Saving Time is

Can someone help me with setting a user's timezone offset for PHP through ajax? When a page is loaded with session data, if there is no pre-existing data, the following script is inserted into the page: <script type="text/javascript"> $(doc ...

Choosing premier class and modifying characteristics

Looking for a solution to hide a div without modifying the HTML code directly? By using JQuery, you can manipulate the appearance of elements on a page. While it's possible to select the first instance of a class and retrieve its value, adding an attr ...

What is the best way to showcase Vue data of a selected element from a v-for loop in a

Here is an example of how my json data is structured. I have multiple elements being displayed in a v-for loop, and when one is clicked, I want to show specific information from that element in a modal. [{ "id": 1, "companyNa ...

A JQuery function linked to the click event of the body element triggers another click event right away

$().ready(function(){ $("#move-to").click(function(){ $("body").bind("click",function(){ alert("foo"); }); }); }); Why do I receive an alert message of "foo" immediately after clicking on "move-to"? When I bind the " ...

Issue: the module '@raruto/leaflet-elevation' does not include the expected export 'control' as imported under the alias 'L' . This results in an error message indicating the absence of exports within the module

Looking for guidance on adding a custom Leaflet package to my Angular application called "leaflet-elevation". The package can be found at: https://github.com/Raruto/leaflet-elevation I have attempted to integrate it by running the command: npm i @raruto/ ...

Tips for setting limitations on a date picker's minimum and maximum values on an iPhone using JavaScript

I have encountered an issue with my JavaScript function that sets min and max values for the input type date. While it works perfectly on Android devices, I am facing a problem on iPhone where I am unable to restrict the calendar with the specified min and ...