webgpu_volume_caustics.html 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - volumetric caustics</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="main.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">three.js webgpu</a> - volumetric caustics
  12. </div>
  13. <script type="importmap">
  14. {
  15. "imports": {
  16. "three": "../build/three.webgpu.js",
  17. "three/webgpu": "../build/three.webgpu.js",
  18. "three/tsl": "../build/three.tsl.js",
  19. "three/addons/": "./jsm/"
  20. }
  21. }
  22. </script>
  23. <script type="module">
  24. import * as THREE from 'three';
  25. import { uniform, refract, div, frameId, lightViewPosition, float, positionView, positionViewDirection, screenUV, pass, texture3D, time, screenCoordinate, normalView, texture, Fn, vec2, vec3 } from 'three/tsl';
  26. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  27. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  28. import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
  29. import { ImprovedNoise } from 'three/addons/math/ImprovedNoise.js';
  30. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  31. import { bayer16 } from 'three/addons/tsl/math/Bayer.js';
  32. import { bloom } from 'three/addons/tsl/display/BloomNode.js';
  33. import Stats from 'three/addons/libs/stats.module.js';
  34. let camera, scene, renderer, controls;
  35. let postProcessing;
  36. let stats;
  37. let gltf;
  38. init();
  39. async function init() {
  40. const LAYER_VOLUMETRIC_LIGHTING = 10;
  41. camera = new THREE.PerspectiveCamera( 25, window.innerWidth / window.innerHeight, 0.025, 5 );
  42. camera.position.set( - 0.7, 0.2, 0.2 );
  43. scene = new THREE.Scene();
  44. // Light
  45. const spotLight = new THREE.SpotLight( 0xffffff, 1 );
  46. spotLight.position.set( .2, .3, .2 );
  47. spotLight.castShadow = true;
  48. spotLight.angle = Math.PI / 6;
  49. spotLight.penumbra = 1;
  50. spotLight.decay = 2;
  51. spotLight.distance = 0;
  52. spotLight.shadow.mapType = THREE.HalfFloatType; // For HDR Caustics
  53. spotLight.shadow.mapSize.width = 1024;
  54. spotLight.shadow.mapSize.height = 1024;
  55. spotLight.shadow.camera.near = .1;
  56. spotLight.shadow.camera.far = 1;
  57. spotLight.shadow.bias = - .003;
  58. spotLight.shadow.intensity = .95;
  59. spotLight.layers.enable( LAYER_VOLUMETRIC_LIGHTING );
  60. scene.add( spotLight );
  61. // Model / Textures
  62. const dracoLoader = new DRACOLoader();
  63. dracoLoader.setDecoderPath( 'jsm/libs/draco/' );
  64. dracoLoader.setDecoderConfig( { type: 'js' } );
  65. gltf = ( await new GLTFLoader().setDRACOLoader( dracoLoader ).loadAsync( './models/gltf/duck.glb' ) ).scene;
  66. gltf.scale.setScalar( .5 );
  67. scene.add( gltf );
  68. const causticMap = new THREE.TextureLoader().load( './textures/opengameart/Caustic_Free.jpg' );
  69. causticMap.wrapS = causticMap.wrapT = THREE.RepeatWrapping;
  70. causticMap.colorSpace = THREE.SRGBColorSpace;
  71. // Material
  72. const duck = gltf.children[ 0 ];
  73. duck.material = new THREE.MeshPhysicalNodeMaterial();
  74. duck.material.side = THREE.DoubleSide;
  75. duck.material.transparent = true;
  76. duck.material.color = new THREE.Color( 0xFFD700 );
  77. duck.material.transmission = 1;
  78. duck.material.thickness = .25;
  79. duck.material.ior = 1.5;
  80. duck.material.metalness = 0;
  81. duck.material.roughness = .1;
  82. duck.castShadow = true;
  83. // TSL Shader
  84. const causticOcclusion = uniform( 1 );
  85. const causticEffect = Fn( () => {
  86. const refractionVector = refract( positionViewDirection.negate(), normalView, div( 1.0, duck.material.ior ) ).normalize();
  87. const viewZ = normalView.z.pow( causticOcclusion );
  88. const textureUV = refractionVector.xy.mul( .6 );
  89. const causticColor = uniform( duck.material.color );
  90. const chromaticAberrationOffset = normalView.z.pow( - .9 ).mul( .004 );
  91. const causticProjection = vec3(
  92. texture( causticMap, textureUV.add( vec2( chromaticAberrationOffset.x.negate(), 0 ) ) ).r,
  93. texture( causticMap, textureUV.add( vec2( 0, chromaticAberrationOffset.y.negate() ) ) ).g,
  94. texture( causticMap, textureUV.add( vec2( chromaticAberrationOffset.x, chromaticAberrationOffset.y ) ) ).b
  95. );
  96. return causticProjection.mul( viewZ.mul( 60 ) ).add( viewZ ).mul( causticColor );
  97. } )().toVar();
  98. duck.material.castShadowNode = causticEffect;
  99. duck.material.emissiveNode = Fn( () => {
  100. // Custom emissive for illuminating backside of the mesh based on the caustic effect and light direction
  101. const thicknessPowerNode = float( 3.0 );
  102. const scatteringHalf = lightViewPosition( spotLight ).sub( positionView ).normalize();
  103. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ) );
  104. return causticEffect.mul( scatteringDot.add( .1 ) ).mul( .02 );
  105. } )();
  106. // GUI
  107. const gui = new GUI();
  108. gui.add( causticOcclusion, 'value', 0, 20 ).name( 'caustic occlusion' );
  109. gui.addColor( duck.material, 'color' ).name( 'material color' );
  110. // Ground
  111. const textureLoader = new THREE.TextureLoader();
  112. const map = textureLoader.load( 'textures/hardwood2_diffuse.jpg' );
  113. map.wrapS = map.wrapT = THREE.RepeatWrapping;
  114. map.repeat.set( 10, 10 );
  115. const geometry = new THREE.PlaneGeometry( 2, 2 );
  116. const material = new THREE.MeshStandardMaterial( { color: 0 } );
  117. const ground = new THREE.Mesh( geometry, material );
  118. ground.rotation.x = - Math.PI / 2;
  119. ground.receiveShadow = true;
  120. scene.add( ground );
  121. // Renderer
  122. renderer = new THREE.WebGPURenderer( { antialias: true } );
  123. renderer.shadowMap.enabled = true;
  124. renderer.setPixelRatio( window.devicePixelRatio );
  125. renderer.setSize( window.innerWidth, window.innerHeight );
  126. renderer.setAnimationLoop( animate );
  127. document.body.appendChild( renderer.domElement );
  128. // Post-Processing
  129. postProcessing = new THREE.PostProcessing( renderer );
  130. // Layers
  131. const volumetricLightingIntensity = uniform( .7 );
  132. const volumetricLayer = new THREE.Layers();
  133. volumetricLayer.disableAll();
  134. volumetricLayer.enable( LAYER_VOLUMETRIC_LIGHTING );
  135. // Volumetric Fog Area
  136. function createTexture3D() {
  137. let i = 0;
  138. const size = 128;
  139. const data = new Uint8Array( size * size * size );
  140. const scale = 10;
  141. const perlin = new ImprovedNoise();
  142. const repeatFactor = 5.0;
  143. for ( let z = 0; z < size; z ++ ) {
  144. for ( let y = 0; y < size; y ++ ) {
  145. for ( let x = 0; x < size; x ++ ) {
  146. const nx = ( x / size ) * repeatFactor;
  147. const ny = ( y / size ) * repeatFactor;
  148. const nz = ( z / size ) * repeatFactor;
  149. const noiseValue = perlin.noise( nx * scale, ny * scale, nz * scale );
  150. data[ i ] = ( 128 + 128 * noiseValue );
  151. i ++;
  152. }
  153. }
  154. }
  155. const texture = new THREE.Data3DTexture( data, size, size, size );
  156. texture.format = THREE.RedFormat;
  157. texture.minFilter = THREE.LinearFilter;
  158. texture.magFilter = THREE.LinearFilter;
  159. texture.wrapS = THREE.RepeatWrapping;
  160. texture.wrapT = THREE.RepeatWrapping;
  161. texture.unpackAlignment = 1;
  162. texture.needsUpdate = true;
  163. return texture;
  164. }
  165. const noiseTexture3D = createTexture3D();
  166. const smokeAmount = uniform( 3 );
  167. const volumetricMaterial = new THREE.VolumeNodeMaterial();
  168. volumetricMaterial.steps = 20;
  169. volumetricMaterial.offsetNode = bayer16( screenCoordinate.add( frameId ) ); // Add dithering to reduce banding
  170. volumetricMaterial.scatteringNode = Fn( ( { positionRay } ) => {
  171. // Return the amount of fog based on the noise texture
  172. const timeScaled = vec3( time.mul( .01 ), 0, time.mul( .03 ) );
  173. const sampleGrain = ( scale, timeScale = 1 ) => texture3D( noiseTexture3D, positionRay.add( timeScaled.mul( timeScale ) ).mul( scale ).mod( 1 ), 0 ).r.add( .5 );
  174. let density = sampleGrain( 1 );
  175. density = density.mul( sampleGrain( .5, 1 ) );
  176. density = density.mul( sampleGrain( .2, 2 ) );
  177. return smokeAmount.mix( 1, density );
  178. } );
  179. const volumetricMesh = new THREE.Mesh( new THREE.BoxGeometry( 1.5, .5, 1.5 ), volumetricMaterial );
  180. volumetricMesh.receiveShadow = true;
  181. volumetricMesh.position.y = .25;
  182. volumetricMesh.layers.disableAll();
  183. volumetricMesh.layers.enable( LAYER_VOLUMETRIC_LIGHTING );
  184. scene.add( volumetricMesh );
  185. // Scene Pass
  186. const scenePass = pass( scene, camera );
  187. const sceneDepth = scenePass.getTextureNode( 'depth' );
  188. // Material - Apply occlusion depth of volumetric lighting based on the scene depth
  189. volumetricMaterial.depthNode = sceneDepth.sample( screenUV );
  190. // Volumetric Lighting Pass
  191. const volumetricPass = pass( scene, camera, { depthBuffer: false } );
  192. volumetricPass.setLayers( volumetricLayer );
  193. volumetricPass.setResolution( .5 );
  194. // Compose and Denoise
  195. const bloomPass = bloom( volumetricPass, 1, 1, 0 );
  196. const scenePassColor = scenePass.add( bloomPass.mul( volumetricLightingIntensity ) );
  197. postProcessing.outputNode = scenePassColor;
  198. // Stats
  199. stats = new Stats();
  200. document.body.appendChild( stats.dom );
  201. // Controls
  202. controls = new OrbitControls( camera, renderer.domElement );
  203. controls.target.z = - .05;
  204. controls.target.y = .02;
  205. controls.maxDistance = 1;
  206. window.addEventListener( 'resize', onWindowResize );
  207. }
  208. function onWindowResize() {
  209. camera.aspect = window.innerWidth / window.innerHeight;
  210. camera.updateProjectionMatrix();
  211. renderer.setSize( window.innerWidth, window.innerHeight );
  212. }
  213. function animate() {
  214. stats.update();
  215. for ( const mesh of gltf.children ) {
  216. mesh.rotation.y -= .01;
  217. }
  218. controls.update();
  219. postProcessing.render();
  220. }
  221. </script>
  222. </body>
  223. </html>
粤ICP备19079148号