NormalMapNode.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import TempNode from '../core/TempNode.js';
  2. import ModelNode from '../accessors/ModelNode.js';
  3. import { ShaderNode, positionView, normalView, uv, vec3, add, sub, mul, dFdx, dFdy, cross, max, dot, normalize, inversesqrt, faceDirection } from '../shadernode/ShaderNodeBaseElements.js';
  4. import { TangentSpaceNormalMap, ObjectSpaceNormalMap } from 'three';
  5. // Normal Mapping Without Precomputed Tangents
  6. // http://www.thetenthplanet.de/archives/1180
  7. const perturbNormal2ArbNode = new ShaderNode( ( inputs ) => {
  8. const { eye_pos, surf_norm, mapN, uv } = inputs;
  9. const q0 = dFdx( eye_pos.xyz );
  10. const q1 = dFdy( eye_pos.xyz );
  11. const st0 = dFdx( uv.st );
  12. const st1 = dFdy( uv.st );
  13. const N = surf_norm; // normalized
  14. const q1perp = cross( q1, N );
  15. const q0perp = cross( N, q0 );
  16. const T = add( mul( q1perp, st0.x ), mul( q0perp, st1.x ) );
  17. const B = add( mul( q1perp, st0.y ), mul( q0perp, st1.y ) );
  18. const det = max( dot( T, T ), dot( B, B ) );
  19. const scale = mul( faceDirection, inversesqrt( det ) );
  20. return normalize( add( mul( T, mul( mapN.x, scale ) ), mul( B, mul( mapN.y, scale ) ), mul( N, mapN.z ) ) );
  21. } );
  22. class NormalMapNode extends TempNode {
  23. constructor( node, scaleNode = null ) {
  24. super( 'vec3' );
  25. this.node = node;
  26. this.scaleNode = scaleNode;
  27. this.normalMapType = TangentSpaceNormalMap;
  28. }
  29. construct() {
  30. const { normalMapType, scaleNode } = this;
  31. const normalOP = mul( this.node, 2.0 );
  32. let normalMap = sub( normalOP, 1.0 );
  33. if ( scaleNode !== null ) {
  34. const normalMapScale = mul( normalMap.xy, scaleNode );
  35. normalMap = vec3( normalMapScale, normalMap.z );
  36. }
  37. let outputNode = null;
  38. if ( normalMapType === ObjectSpaceNormalMap ) {
  39. const vertexNormalNode = mul( new ModelNode( ModelNode.NORMAL_MATRIX ), normalMap );
  40. outputNode = normalize( vertexNormalNode );
  41. } else if ( normalMapType === TangentSpaceNormalMap ) {
  42. outputNode = perturbNormal2ArbNode.call( {
  43. eye_pos: positionView,
  44. surf_norm: normalView,
  45. mapN: normalMap,
  46. uv: uv()
  47. } );
  48. }
  49. return outputNode;
  50. }
  51. }
  52. export default NormalMapNode;