Calculate the normals from the displacement map in three. Js r.58?

I use a regular shader in the three.js r.58 file, which, as I understand it, requires a normal map . However, I am using a dynamic displacement map, so a pre-computed normal map will not work in this situation.

All the examples that I found in slow motion maps either use flat shading or pre-computed normal maps. Is it possible to calculate normals dynamically based on offset vertices instead?

Edit: I posted a sphere demo with an offset map showing flat normals :

Sphere with displacement but incorrect normals

Here's a link to a github rehearsal with all my examples illustrating this problem, and the solutions I ended up finding: https://github.com/meetar/three.js-normal-map-0

+3
shader webgl fragment-shader
source share
3 answers

This answer is based on your comments above.

You can do what you want, but it's quite complicated, and of course you have to change the usual shader of the three. js.

Take a look at http://alteredqualia.com/three/examples/webgl_cubes_indexed.html . Look at the fragment shader and you will see

vec3 normal = normalize( cross( dFdx( vViewPosition ), dFdy( vViewPosition ) ) ); 

Alteredqualia uses the normal derivative in the fragment shader (instead of the normal attribute), since the positions of the vertices change in the vertex shader, and the normal is not known.

What he does is calculate the norm using the cross product of the derivatives of the screen space x and y of the fragment position.

This will establish a normal, normal face. It will be intermittent on hard edges.

three.js r.58

+4
source share

What I described above is called a "bump map", and it is used by default with the ph.ths shader. I combined the normalmap shader with the phong shader pieces responsible for displaying the terrain:

http://meetar.imtqy.com/three.js-normal-map-0/bump.html

Although the normals are a bit noisy, they are mostly correct.

sphere with displacement and bump mapping

+3
source share

You can also calculate the normal map from the displacement map using JavaScript. This leads to smooth normals and is a good option if the displacement map does not change too often.

This method uses the code found in this demo: http://mrdoob.com/lab/javascript/height2normal/

Demo here: http://meetar.imtqy.com/three.js-normal-map-0/index14.html

enter image description here

+2
source share

All Articles