Obtain the ThreeJS coordinates for shadow pixel positions in a 3D environment

In my ThreeJS project, I have created a scene where a gold object casts a curved shadow on a spherical surface. The shadow is achieved by rendering only the backside of the sphere and using a point light at the center of the eye model. I am looking to extract the 3D coordinates (x,y,z) of each pixel in this shadow for further analysis. Below is a simplified version of the code that generates the shadow:

renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.BasicShadowMap//THREE.PCFSoftShadowMap;

const light = new THREE.PointLight( 0xffffff, 20, 0 );
light.position.set( 0, 0, 0 );
light.castShadow = true;
light.shadow.mapSize.width = 512;
light.shadow.camera.near = 0.5;
light.shadow.camera.far = 500;
scene.add( light );

const sphereGeometry = new THREE.SphereGeometry( 25, 32, 32 );
const sphereMaterial = new THREE.MeshStandardMaterial( { color: 0xffffff } );
sphereMaterial.side=THREE.BackSide;

const sphere = new THREE.Mesh( sphereGeometry, sphereMaterial );
sphere.castShadow = false;
sphere.receiveShadow = true;
scene.add( sphere );

I have tried to locate this information in the model's matrix property, but without clear documentation, I am unsure about the exact location of the shadow data. Any assistance in this matter would be greatly appreciated!

--- Extra not important info ---

Furthermore, the extracted shadow coordinates will enable me to perform raycasting back into the eye and generate a different type of shadow using an azimuthal equidistant projection. This advanced technique is crucial for achieving the desired effect on the right side of the eye model. Your help in obtaining the 3D shadow pixel coordinates will greatly enhance my project!

Answer №1

In the realm of GPU shaders at rendertime, extracting the shadow into a new geometry using JavaScript proves challenging due to limited access to shadowMap positions. Nevertheless, there exists a workaround.

Imagine your point light resides at (0, 0, 0) at the sphere's center. By iterating through the vertices of the gold object and projecting these positions onto the sphere, a potential solution emerges:

// Defining sphere radius
const radius = 25;

const vec3 = new THREE.Vector3();

// Retrieving the vertex position array
const vertices = goldObject.geometry.getAttribute("position").array;

// Loop to iterate through all vertex positions
for (let i3 = 0; i3 < vertices.length; i3 += 3) {
    // Assigning vertex to vec3
    vec3.set(
        vertices[i3 + 0], // x
        vertices[i3 + 1], // y
        vertices[i3 + 2]  // z
    );

    // Normalizing vector magnitudes
    vec3.normalize();

    // Scaling vector magnitude to match sphere radius
    vec3.multiplyScalar(sphereRadius);

    // Generating spherical projection for each vertex
    console.log(vec3);
}

Assuming the light source aligns perfectly with the sphere's center, normalizing and multiplying the position of each gold object vertex by the sphere's radius proves effective. This iterative process creates the vec3 array for constructing a custom THREE.BufferGeometry positioned against the sphere.

It is worth noting that any translations or rotations applied to the gold object will impact vertex positions, necessitating the reversal of these transformations during the vertex iteration process.

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 issue causing "ReferenceError: fetch is not defined" is causing the test to fail

There seems to be an issue with my project where 'node-fetch' is installed, but the rest of the files are not importing it and the tests are not failing import { IQuery } from 'models/IQuery.interface'; import { NextApiRequest, NextApiR ...

Replicate the process of transferring table rows to the clipboard, but exclusively copying the contents

Currently, I am attempting to copy a paginated table to my clipboard by referring to this guide: Select a complete table with Javascript (to be copied to clipboard). However, the issue lies in the fact that it only copies the data from the first page. In ...

A guide on getting the `Message` return from `CommandInteraction.reply()` in the discord API

In my TypeScript code snippet, I am generating an embed in response to user interaction and sending it. Here is the code: const embed = await this.generateEmbed(...); await interaction.reply({embeds: [embed]}); const sentMessage: Message = <Message<b ...

Locating numerous occurrences of a specific string within an array and rearranging them

I am facing an issue with organizing data stored in the 'names' variable within the code snippet. The task at hand involves converting a string into an array, rearranging the elements within the array to ensure the text is in the correct order. W ...

A guide on retrieving and resetting the value of a radio button within a table

I need to create multiple radio buttons within a table using Razor syntax under ASP.NET Core MVC. Each row of the table should have an update and clear link to update the record and clear the selected radio button for that specific row. <table class=&qu ...

Unlocking the secrets to obtaining a socket.io client

I encountered an error when trying to set up a socket.io server and client. The error I received on the client side was: Failed to load resource:http://localhost:3000/socket.io/?EIO=4&transport=polling&t=OK-egu3 the server responded with a status o ...

What is the proper way to implement the scrollToIndex feature in a FlatList component in React Native

I have a problem where I need to automatically scroll down by a specific value whenever a onPress event is triggered (in this case, the value is 499). However, the code I have tried does not seem to be working as expected. Here is the code snippet I am u ...

Tips for creating a jasmine test scenario for a function executed within the ngOnInit lifecycle hook

I am finding it challenging to create a successful test case for the code snippet below. In my component.ts file id = 123456; data = []; constructor(private serv: ApiService){} ngOnInint(){ getData(id); } getData(id){ this.serv.getRequest(url+id) ...

Arrange JSON data in ascending order based on the dates, starting with the most recent date, by utilizing jquery

I'm in need of assistance on sorting a list of articles from an external json file based on their creation date. Can anyone provide guidance? Currently, I am fetching the data using AJAX and displaying only 6 results, but I'm facing difficulties ...

Error in Safari Browser: Unexpected token ':' found in AngularJS syntax

When using Chrome, my website works perfectly without any errors. However, when I try to access it on Safari, most of the pages fail to load. The specific error message that appears is: [Error] SyntaxError: Unexpected token ':' (angular.min.js.m ...

Access SCSS variable values in Angular HTML or TypeScript files

So, I've been looking into whether it's feasible to utilize the SCSS variable value within HTML or TS in Angular. For instance: Let's say I have a variable called $mdBreakpoint: 992px; stored inside the _variable.scss file. In my HTML cod ...

What does the buffer.copy() method do in Node.js?

Can someone please discuss the purpose and functionality of buffer.copy() in a Node.js application? Provide a real-time example for better understanding. Additionally, I am curious about the differences between the copy and slice methods in Node.js. How ...

Creating a dynamic onclick function that depends on a variable passed from a while loop in PHP

If you're familiar with PHP, I have a scenario for you. Let's say there's a list of items generated using a while loop in PHP. Each item has a sub-list that should only appear when clicked on. I tried using the onclick function in jQuery but ...

Tips on importing anime js after it has been successfully installed through npm

Today, I added anime js as a dependency to my package.json file. The version 3.0.1 is visible in the dependencies list. I used npm to install it. Next step was creating a folder and a JavaScript file in the public directory. I set up a simple event liste ...

The size of the cursor varies depending on the line it's placed on

I have a content editable div where three lines are separated by BR tags. When I click on the second line, the cursor becomes bigger than that in the first line. .content { line-height: 35px; } <div class="content" contenteditable="true"> ...

Utilizing the fetch() method in Vuex to obtain a restful API

Struggling to integrate my API data through Vuex, I am in dire need of a reliable guide or perhaps someone who can assist me with this task. Previously, without using Vuex, all my requests functioned flawlessly. However, now I'm unsure about the neces ...

Is the top bar feature malfunctioning in version 4.3.2 of Foundation?

During my previous project, I utilized the open-source Foundation 4 framework and successfully implemented a top bar navigation. Now, as I embark on a new project with Foundation, I have downloaded the Foundation 4.3.2 version from . Despite referencing th ...

Tips for updating a React component with Mobx when there are changes in RTCPeerConnection

I am currently involved in a project that utilizes React Native for mobile development, React for web applications, and MobX for creating an app that incorporates WebRTC for enabling video chat communication among users. The issue I am encountering is tha ...

What is the reason behind generating auth.js:65 Uncaught (in promise) TypeError: Unable to access property 'data' of undefined?

Encountering a login issue in my Django application while using Axios and React-Redux. The problem arises when providing incorrect login credentials, resulting in the LOGIN_FAIL action. However, when providing the correct information, the LOGIN_SUCCESS act ...

The sorting function in Vue data table is not functioning as intended

In my code, I have implemented a v-data-table: <v-data-table :headers="walletInHeaders" :items="filteredByQuantityIncome" class="elevation-1"> <template v-slot:items="props"> <td class=&quo ...