webgpu_volume_lighting_traa.html 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - volumetric lighting using TRAA</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="example.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  12. <div class="title-wrapper">
  13. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>Volumetric Lighting using TRAA</span>
  14. </div>
  15. <small>Compatible with native lights and shadows using TRAA.</small>
  16. </div>
  17. <script type="importmap">
  18. {
  19. "imports": {
  20. "three": "../build/three.webgpu.js",
  21. "three/webgpu": "../build/three.webgpu.js",
  22. "three/tsl": "../build/three.tsl.js",
  23. "three/addons/": "./jsm/"
  24. }
  25. }
  26. </script>
  27. <script type="module">
  28. import * as THREE from 'three/webgpu';
  29. import { vec2, vec3, Fn, texture3D, screenUV, uniform, screenCoordinate, pass, depthPass, mrt, output, velocity, fract, interleavedGradientNoise } from 'three/tsl';
  30. import { traa } from 'three/addons/tsl/display/TRAANode.js';
  31. import { Inspector } from 'three/addons/inspector/Inspector.js';
  32. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  33. import { ImprovedNoise } from 'three/addons/math/ImprovedNoise.js';
  34. import { TeapotGeometry } from 'three/addons/geometries/TeapotGeometry.js';
  35. // Halton sequence for temporal offset - matches TRAA's 32-sample Halton jitter
  36. // This creates optimal low-discrepancy distribution that accumulates well with TRAA
  37. function halton( index, base ) {
  38. let result = 0;
  39. let f = 1;
  40. while ( index > 0 ) {
  41. f /= base;
  42. result += f * ( index % base );
  43. index = Math.floor( index / base );
  44. }
  45. return result;
  46. }
  47. // Generate 32 Halton offsets (base 2, 3) - same length as TRAA
  48. const _haltonOffsets = Array.from(
  49. { length: 32 },
  50. ( _, i ) => [ halton( i + 1, 2 ), halton( i + 1, 3 ) ]
  51. );
  52. let renderer, scene, camera;
  53. let volumetricMesh, teapot, pointLight, spotLight;
  54. let renderPipeline;
  55. let temporalOffset, temporalRotation, shaderTime;
  56. let params;
  57. init();
  58. function createTexture3D() {
  59. let i = 0;
  60. const size = 128;
  61. const data = new Uint8Array( size * size * size );
  62. const scale = 10;
  63. const perlin = new ImprovedNoise();
  64. const repeatFactor = 5.0;
  65. for ( let z = 0; z < size; z ++ ) {
  66. for ( let y = 0; y < size; y ++ ) {
  67. for ( let x = 0; x < size; x ++ ) {
  68. const nx = ( x / size ) * repeatFactor;
  69. const ny = ( y / size ) * repeatFactor;
  70. const nz = ( z / size ) * repeatFactor;
  71. const noiseValue = perlin.noise( nx * scale, ny * scale, nz * scale );
  72. data[ i ] = ( 128 + 128 * noiseValue );
  73. i ++;
  74. }
  75. }
  76. }
  77. const texture = new THREE.Data3DTexture( data, size, size, size );
  78. texture.format = THREE.RedFormat;
  79. texture.minFilter = THREE.LinearFilter;
  80. texture.magFilter = THREE.LinearFilter;
  81. texture.wrapS = THREE.RepeatWrapping;
  82. texture.wrapT = THREE.RepeatWrapping;
  83. texture.unpackAlignment = 1;
  84. texture.needsUpdate = true;
  85. return texture;
  86. }
  87. function init() {
  88. renderer = new THREE.WebGPURenderer();
  89. // renderer.setPixelRatio( window.devicePixelRatio ); // Disable DPR for performance
  90. renderer.setSize( window.innerWidth, window.innerHeight );
  91. renderer.setAnimationLoop( animate );
  92. renderer.toneMapping = THREE.NeutralToneMapping;
  93. renderer.toneMappingExposure = 2;
  94. renderer.shadowMap.enabled = true;
  95. renderer.inspector = new Inspector();
  96. document.body.appendChild( renderer.domElement );
  97. scene = new THREE.Scene();
  98. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 100 );
  99. camera.position.set( - 8, 1, - 6 );
  100. const controls = new OrbitControls( camera, renderer.domElement );
  101. controls.maxDistance = 40;
  102. controls.minDistance = 2;
  103. // Volumetric Fog Area
  104. const noiseTexture3D = createTexture3D();
  105. const smokeAmount = uniform( 2 );
  106. const volumetricMaterial = new THREE.VolumeNodeMaterial();
  107. volumetricMaterial.steps = 12;
  108. volumetricMaterial.transparent = true;
  109. volumetricMaterial.blending = THREE.AdditiveBlending;
  110. // Temporal dithering using Interleaved Gradient Noise (IGN) + Halton sequence
  111. temporalOffset = uniform( 0 );
  112. temporalRotation = uniform( 0 );
  113. shaderTime = uniform( 0 );
  114. const temporalJitter2D = vec2( temporalOffset, temporalRotation );
  115. volumetricMaterial.offsetNode = fract( interleavedGradientNoise( screenCoordinate.add( temporalJitter2D.mul( 100 ) ) ).add( temporalOffset ) );
  116. volumetricMaterial.scatteringNode = Fn( ( { positionRay } ) => {
  117. const timeScaled = vec3( shaderTime, 0, shaderTime.mul( .3 ) );
  118. const sampleGrain = ( scale, timeScale = 1 ) => texture3D( noiseTexture3D, positionRay.add( timeScaled.mul( timeScale ) ).mul( scale ).mod( 1 ), 0 ).r.add( .5 );
  119. let density = sampleGrain( .1 );
  120. density = density.mul( sampleGrain( .05, 1 ) );
  121. density = density.mul( sampleGrain( .02, 2 ) );
  122. return smokeAmount.mix( 1, density );
  123. } );
  124. volumetricMesh = new THREE.Mesh( new THREE.BoxGeometry( 20, 10, 20 ), volumetricMaterial );
  125. volumetricMesh.receiveShadow = true;
  126. volumetricMesh.position.y = 2;
  127. scene.add( volumetricMesh );
  128. // Objects
  129. teapot = new THREE.Mesh( new TeapotGeometry( .8, 18 ), new THREE.MeshStandardMaterial( { color: 0xffffff, side: THREE.DoubleSide } ) );
  130. teapot.castShadow = true;
  131. scene.add( teapot );
  132. const floor = new THREE.Mesh( new THREE.PlaneGeometry( 100, 100 ), new THREE.MeshStandardMaterial( { color: 0xffffff } ) );
  133. floor.rotation.x = - Math.PI / 2;
  134. floor.position.y = - 3;
  135. floor.receiveShadow = true;
  136. scene.add( floor );
  137. // Lights
  138. pointLight = new THREE.PointLight( 0xf9bb50, 3, 100 );
  139. pointLight.castShadow = true;
  140. pointLight.position.set( 0, 1.4, 0 );
  141. scene.add( pointLight );
  142. spotLight = new THREE.SpotLight( 0xffffff, 100 );
  143. spotLight.position.set( 2.5, 5, 2.5 );
  144. spotLight.angle = Math.PI / 6;
  145. spotLight.penumbra = 1;
  146. spotLight.decay = 2;
  147. spotLight.distance = 0;
  148. spotLight.map = new THREE.TextureLoader().setPath( 'textures/' ).load( 'colors.png' );
  149. spotLight.castShadow = true;
  150. spotLight.shadow.intensity = .98;
  151. spotLight.shadow.mapSize.width = 1024;
  152. spotLight.shadow.mapSize.height = 1024;
  153. spotLight.shadow.camera.near = 1;
  154. spotLight.shadow.camera.far = 15;
  155. spotLight.shadow.focus = 1;
  156. scene.add( spotLight );
  157. // Render Pipeline
  158. renderPipeline = new THREE.RenderPipeline( renderer );
  159. const volumetricIntensity = uniform( 1 );
  160. // Pre-Pass: Opaque objects only (volumetric is transparent, excluded automatically)
  161. const prePass = depthPass( scene, camera );
  162. prePass.name = 'Pre Pass';
  163. prePass.transparent = false;
  164. const prePassDepth = prePass.getTextureNode( 'depth' ).toInspector( 'Depth', () => prePass.getLinearDepthNode() );
  165. // Apply depth to volumetric material for proper occlusion
  166. volumetricMaterial.depthNode = prePassDepth.sample( screenUV );
  167. // Scene Pass: Full scene including volumetric with MRT
  168. const scenePass = pass( scene, camera ).toInspector( 'Scene' );
  169. scenePass.name = 'Scene Pass';
  170. scenePass.setMRT( mrt( {
  171. output: output,
  172. velocity: velocity
  173. } ) );
  174. const scenePassColor = scenePass.getTextureNode().toInspector( 'Output' );
  175. const scenePassVelocity = scenePass.getTextureNode( 'velocity' ).toInspector( 'Velocity' );
  176. // TRAA with scene pass depth/velocity (includes volumetric)
  177. const traaPass = traa( scenePassColor, prePassDepth, scenePassVelocity, camera );
  178. renderPipeline.outputNode = traaPass;
  179. // GUI
  180. params = {
  181. traa: true,
  182. animated: true
  183. };
  184. const gui = renderer.inspector.createParameters( 'Volumetric Lighting' );
  185. gui.add( params, 'animated' );
  186. gui.add( params, 'traa' ).name( 'TRAA' ).onChange( updatePostProcessing );
  187. const rayMarching = gui.addFolder( 'Ray Marching' );
  188. rayMarching.add( volumetricMaterial, 'steps', 2, 16, 1 ).name( 'step count' );
  189. function updatePostProcessing() {
  190. renderPipeline.outputNode = params.traa ? traaPass : scenePassColor;
  191. renderPipeline.needsUpdate = true;
  192. }
  193. const lighting = gui.addFolder( 'Lighting / Scene' );
  194. lighting.add( pointLight, 'intensity', 0, 6 ).name( 'light intensity' );
  195. lighting.add( spotLight, 'intensity', 0, 200 ).name( 'spot intensity' );
  196. lighting.add( volumetricIntensity, 'value', 0, 2 ).name( 'volumetric intensity' );
  197. lighting.add( smokeAmount, 'value', 0, 3 ).name( 'smoke amount' );
  198. window.addEventListener( 'resize', onWindowResize );
  199. }
  200. function onWindowResize() {
  201. camera.aspect = window.innerWidth / window.innerHeight;
  202. camera.updateProjectionMatrix();
  203. renderer.setSize( window.innerWidth, window.innerHeight );
  204. }
  205. let frameCount = 0;
  206. let animationTime = 0;
  207. let lastTime = performance.now();
  208. function animate() {
  209. const currentTime = performance.now();
  210. const delta = ( currentTime - lastTime ) * 0.001;
  211. lastTime = currentTime;
  212. // Update temporal uniforms - synced with TRAA's Halton sequence for optimal accumulation
  213. const haltonIndex = frameCount % 32;
  214. temporalOffset.value = _haltonOffsets[ haltonIndex ][ 0 ];
  215. temporalRotation.value = _haltonOffsets[ haltonIndex ][ 1 ];
  216. frameCount ++;
  217. if ( params.animated ) {
  218. animationTime += delta;
  219. }
  220. shaderTime.value = animationTime;
  221. const scale = 2.4;
  222. pointLight.position.x = Math.sin( animationTime * 0.7 ) * scale;
  223. pointLight.position.y = Math.cos( animationTime * 0.5 ) * scale;
  224. pointLight.position.z = Math.cos( animationTime * 0.3 ) * scale;
  225. spotLight.position.x = Math.cos( animationTime * 0.3 ) * scale;
  226. spotLight.lookAt( 0, 0, 0 );
  227. teapot.rotation.y = animationTime * 0.2;
  228. renderPipeline.render();
  229. }
  230. </script>
  231. </body>
  232. </html>
粤ICP备19079148号