ViewportDepthNode.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import Node, { addNodeClass } from '../core/Node.js';
  2. import { nodeImmutable, nodeProxy } from '../shadernode/ShaderNode.js';
  3. import { cameraNear, cameraFar } from '../accessors/CameraNode.js';
  4. import { positionView } from '../accessors/PositionNode.js';
  5. import { viewportDepthTexture } from './ViewportDepthTextureNode.js';
  6. class ViewportDepthNode extends Node {
  7. constructor( scope, textureNode = null ) {
  8. super( 'float' );
  9. this.scope = scope;
  10. this.textureNode = textureNode;
  11. this.isViewportDepthNode = true;
  12. }
  13. setup( /*builder*/ ) {
  14. const { scope } = this;
  15. let node = null;
  16. if ( scope === ViewportDepthNode.DEPTH ) {
  17. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  18. } else if ( scope === ViewportDepthNode.DEPTH_TEXTURE ) {
  19. const texture = this.textureNode || viewportDepthTexture();
  20. const viewZ = perspectiveDepthToViewZ( texture, cameraNear, cameraFar );
  21. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  22. }
  23. return node;
  24. }
  25. }
  26. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  27. // -near maps to 0; -far maps to 1
  28. export const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  29. // maps orthographic depth in [ 0, 1 ] to viewZ
  30. export const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  31. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  32. // -near maps to 0; -far maps to 1
  33. export const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( near.sub( far ).mul( viewZ ) );
  34. // maps perspective depth in [ 0, 1 ] to viewZ
  35. export const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  36. ViewportDepthNode.DEPTH = 'depth';
  37. ViewportDepthNode.DEPTH_TEXTURE = 'depthTexture';
  38. export default ViewportDepthNode;
  39. export const depth = nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  40. export const depthTexture = nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_TEXTURE );
  41. addNodeClass( 'ViewportDepthNode', ViewportDepthNode );