NormalNode.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import Node, { addNodeClass } from '../core/Node.js';
  2. import { attribute } from '../core/AttributeNode.js';
  3. import { label } from '../core/VarNode.js';
  4. import { varying } from '../core/VaryingNode.js';
  5. import { normalize } from '../math/MathNode.js';
  6. import { cameraViewMatrix } from './CameraNode.js';
  7. import { modelNormalMatrix } from './ModelNode.js';
  8. import { nodeImmutable } from '../shadernode/ShaderNode.js';
  9. class NormalNode extends Node {
  10. constructor( scope = NormalNode.LOCAL ) {
  11. super( 'vec3' );
  12. this.scope = scope;
  13. }
  14. isGlobal() {
  15. return true;
  16. }
  17. getHash( /*builder*/ ) {
  18. return `normal-${this.scope}`;
  19. }
  20. generate( builder ) {
  21. const scope = this.scope;
  22. let outputNode = null;
  23. if ( scope === NormalNode.GEOMETRY ) {
  24. outputNode = attribute( 'normal', 'vec3' );
  25. } else if ( scope === NormalNode.LOCAL ) {
  26. outputNode = varying( normalGeometry );
  27. } else if ( scope === NormalNode.VIEW ) {
  28. const vertexNode = modelNormalMatrix.mul( normalLocal );
  29. outputNode = normalize( varying( vertexNode ) );
  30. } else if ( scope === NormalNode.WORLD ) {
  31. // To use inverseTransformDirection only inverse the param order like this: cameraViewMatrix.transformDirection( normalView )
  32. const vertexNode = normalView.transformDirection( cameraViewMatrix );
  33. outputNode = normalize( varying( vertexNode ) );
  34. }
  35. return outputNode.build( builder, this.getNodeType( builder ) );
  36. }
  37. serialize( data ) {
  38. super.serialize( data );
  39. data.scope = this.scope;
  40. }
  41. deserialize( data ) {
  42. super.deserialize( data );
  43. this.scope = data.scope;
  44. }
  45. }
  46. NormalNode.GEOMETRY = 'geometry';
  47. NormalNode.LOCAL = 'local';
  48. NormalNode.VIEW = 'view';
  49. NormalNode.WORLD = 'world';
  50. export default NormalNode;
  51. export const normalGeometry = nodeImmutable( NormalNode, NormalNode.GEOMETRY );
  52. export const normalLocal = nodeImmutable( NormalNode, NormalNode.LOCAL );
  53. export const normalView = nodeImmutable( NormalNode, NormalNode.VIEW );
  54. export const normalWorld = nodeImmutable( NormalNode, NormalNode.WORLD );
  55. export const transformedNormalView = label( normalView, 'TransformedNormalView' );
  56. export const transformedNormalWorld = transformedNormalView.transformDirection( cameraViewMatrix ).normalize();
  57. addNodeClass( NormalNode );