A guide on shading specific faces based on their normal vectors' alignment with the camera's view

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

I'm currently working on a shader that requires darkening the faces with normals perpendicular to the camera (dot product is 0). How can I calculate this dot product and make sure it works correctly?

uniform float time;
uniform vec3 eye_dir;

varying float darkening;

void main(){

  float product=dot(normalize(eye_dir),normalize(normal.xyz));

  darkening=product;

  gl_Position=
  projectionMatrix*
  modelViewMatrix*
  vec4(position,1.);
}
// Using THREE.js library
this.camera.getWorldDirection(this.eyeDir);
...
cell.material.uniforms.eye_dir = new Uniform(this.eyeDir);

Answer №1

To achieve your goal, you must determine the vector from the fragment to the camera. The most straightforward method is to perform this calculation in view space (camera space), where the camera's position is at (0, 0, 0).
Convert the position using the modelViewMatrix from model space to view space, and transform the normal using the normalMatrix from model space to view space. Refer to WebGLProgram.

As the result of the dot product equals 1.0 when the vectors are aligned in the same direction, the darkening effect can be calculated as 1.0 - abs(dotproduct).

varying float darkening;

void main(){

    vec4 view_pos = modelViewMatrix * vec4(position, 1.0);

    vec3 view_dir = normalize(-view_pos.xyz); // vec3(0.0) - view_pos;
    vec3 view_nv  = normalize(normalMatrix * normal.xyz);

    float NdotV   = dot(view_dir, view_nv);
    darkening     = 1.0 - abs(NdotV);

    gl_Position   = projectionMatrix * view_pos;
}

It is important to note that calculating the Dot product between eye_dir and normal is not meaningful, as eye_dir is a vector in world space while normal is a vector in model (object) space.

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

Monitoring separate upload progress within $q.all() in AngularJS

I recently started using the angular-file-upload module created by danialfarid (https://github.com/danialfarid/angular-file-upload) and I must say, it's been a great experience so far. After successfully integrating it into my wrapper service for RES ...

In order to ensure a valid JSON for parsing in JavaScript, one must reverse the usage of single quotes and double quotes. This adjustment

Received an API response structured like this: [{'name': 'men', 'slug': 'men'}, {'name': 'women', 'slug': 'women'}] After stringifying: const data = JSON.stringify(resp) " ...

Using jQuery to animate a DIV sliding in from the side

When a user scrolls down (x) pixels, I'm smoothly sliding a DIV into the viewport horizontally. If the user scrolls back up, the DIV scrolls out again. However, the sliding motion appears jerky and pauses at certain moments. <div id="doom_o">&l ...

Issue with Sliding Transition in React Material UI Drawer Component

I developed a custom drawer component for my React application const CustomSidebar = () => { return ( <Drawer open={drawerOpen} onClose={() => setDrawerOpen(false)} > <Box> <Navigator / ...

The request body for MERN full stack development is returning empty

I am currently facing an issue while trying to establish a connection between my client and the backend. Here is the snippet of code I am using: //client const body = { email: value, }; axios.get("http://localhost:5000/checkEmail", body) // ...

Displaying two THREE.js scenes overlapping each other

I am currently working on a project that involves a scene with 10 cubes in it. You can check out the fiddle for reference: https://jsfiddle.net/gilomer88/tcpwez72/47/ The goal is to allow users to tap on a cube, which will trigger a new "details scene" to ...

What is the best way to implement validation for individual elements within an array that are being displayed on a webpage using a for loop?

Currently, I am utilizing Vue JS within the Vuetify framework to build a dynamic form: <v-text-field v-for="items in itemsArray" :key="items.id" v-model="items.data" :label="items.name" ></v-text-field> ...

Tips for displaying real-time error notifications from server-side validation using AJAX

Seeking a way to display inline error messages from my Symfony2 Backend without refreshing the page. I considered replacing the current form in the HTML with the validated form containing the error messages returned by the backend through AJAX. However, ...

Merge the values into an array based on their shared id within a JSON object

Is it possible to map JSON objects with duplicate id values to their association property in an array using JavaScript after a join operation? { "id": 1, "name": "doc 1", "appointmentTime": "2018-12-28T00:00:43" }, { "id": 2, "name": ...

An unusual problem stemming from jQuery/AJAX arises when variables within a function fail to update while a click

I've been struggling with a small issue for the past three days that I just can't seem to resolve. It doesn't seem to be a coding error, but rather a misunderstanding of variables and why the onClick event isn't functioning properly. H ...

The call stack limit has been exceeded in VueJS/VueX

I'm currently developing a Vue project with Vuex for state management. However, I encountered a Maximum call stack size exceeded error in my console when attempting to bind actions and getters in my component using mapActions and mapGetters. I'm ...

Encountering error: Unknown flag '-p' when trying to execute yarn build:prod in Angular 6

For the past two days, I have been encountering a problem. After updating Angular from version 4 to 6, I am unable to generate a production build. Commands like yarn build and yarn dev are functioning properly. However, when I execute yarn build:prod, I re ...

JavaScript error: Attempting to assign a value to an undefined property, causing a TypeError

I keep encountering an issue with the following message: "Cannot set property '0' of undefined" var arrItems = { 'product1': [], 'product2': [], 'product3': [] }; var temArr = {}; var dataFor = ""; fu ...

Elements powered by jQuery failing to load upon dynamic webpage(s) loading via ajax

Dynamic loading of jQuery elements, such as Ibuttons, seems to be causing issues when implemented with an ajax dynamic content loader. The entirety of my website is rendered through Ajax just like this: <html> <header> {jQuery} </header> ...

Effortlessly move events to a different calendar using the tab menu feature in FullCalendar

My issue involves having multiple calendars within a tab container that can be switched using a navigation menu. I want to be able to drag events between these calendars using the navigation menu, but I encounter an error where if I switch tabs while dragg ...

Node.js and Express.js fails to transmit files to clients

Attempting to send a gif to the client for future use in CSS, but encountering a 404 error in the console log. The gif is located within the public directory. Server: var app = require('express')(); var http = require('http').Server(a ...

applying attributes to an element

Can you tell me why the addClass method is adding the class 'foo' to both the div and p element in the code snippet below? $('<div/>').after('<p></p>').addClass('foo') .filter('p').attr ...

Generate TypeScript type definitions for environment variables in my configuration file using code

Imagine I have a configuration file named .env.local: SOME_VAR="this is very secret" SOME_OTHER_VAR="this is not so secret, but needs to be different during tests" Is there a way to create a TypeScript type based on the keys in this fi ...

Any suggestions for solving the issue of breaking the line at the end of a <td> within a <table> element using jQuery or JavaScript?

Here is a table format that I have: $(document).ready(function() { var enteredText = document.getElementById("textArea").value; var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length; var characterCount = enteredText.length + numberOfLineB ...

What is the best way to add table pagination at the bottom of a table?

Can someone provide guidance on implementing table pagination for the material-ui table below? The documentation is a bit unclear: <Table ria-label="a dense table"> <TableHead> <TableRow> ...