Raymarching.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { varying, vec4, modelWorldMatrixInverse, cameraPosition, positionGeometry, float, Fn, Loop, max, min, vec2, vec3 } from 'three/tsl';
  2. /**
  3. * @module Raymarching
  4. * @three_import import { RaymarchingBox } from 'three/addons/tsl/utils/Raymarching.js';
  5. */
  6. const hitBox = /*@__PURE__*/ Fn( ( { orig, dir } ) => {
  7. const box_min = vec3( - 0.5 );
  8. const box_max = vec3( 0.5 );
  9. const inv_dir = dir.reciprocal();
  10. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  11. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  12. const tmin = min( tmin_tmp, tmax_tmp );
  13. const tmax = max( tmin_tmp, tmax_tmp );
  14. const t0 = max( tmin.x, max( tmin.y, tmin.z ) );
  15. const t1 = min( tmax.x, min( tmax.y, tmax.z ) );
  16. return vec2( t0, t1 );
  17. } );
  18. /**
  19. * TSL function for performing raymarching in a box-area using the specified number of steps
  20. * and a callback function.
  21. *
  22. * ```js
  23. * RaymarchingBox( count, ( { positionRay } ) => {
  24. *
  25. * } );
  26. * ```
  27. *
  28. * @tsl
  29. * @function
  30. * @param {number|Node} steps - The number of steps for raymarching.
  31. * @param {Function|FunctionNode} callback - The callback function to execute at each step.
  32. */
  33. export const RaymarchingBox = ( steps, callback ) => {
  34. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  35. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  36. const rayDir = vDirection.normalize();
  37. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  38. bounds.x.greaterThan( bounds.y ).discard();
  39. bounds.assign( vec2( max( bounds.x, 0.0 ), bounds.y ) );
  40. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  41. const delta = float( min( inc.x, min( inc.y, inc.z ) ) ).toVar();
  42. delta.divAssign( float( steps ) );
  43. const positionRay = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  44. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: delta }, () => {
  45. callback( { positionRay } );
  46. positionRay.addAssign( rayDir.mul( delta ) );
  47. } );
  48. };