webgpu_postprocessing_ssgi_ballpool.html 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - SSGI Ball Pool</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. <meta property="og:title" content="three.js webgpu - SSGI Ball Pool">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgpu_postprocessing_ssgi_ballpool.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgpu_postprocessing_ssgi_ballpool.jpg">
  11. <link type="text/css" rel="stylesheet" href="example.css">
  12. <style>
  13. canvas {
  14. touch-action: none;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="info">
  20. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  21. <div class="title-wrapper">
  22. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>SSGI Ball Pool</span>
  23. </div>
  24. <small>Real-time indirect illumination with interactive physics ball pool.</small>
  25. </div>
  26. <script type="importmap">
  27. {
  28. "imports": {
  29. "three": "../build/three.webgpu.js",
  30. "three/webgpu": "../build/three.webgpu.js",
  31. "three/tsl": "../build/three.tsl.js",
  32. "three/addons/": "./jsm/",
  33. "monomorph": "https://cdn.jsdelivr.net/npm/monomorph@2.3.1/build/monomorph.js",
  34. "@perplexdotgg/bounce": "https://cdn.jsdelivr.net/npm/@perplexdotgg/bounce@1.8.1/build/bounce.js"
  35. }
  36. }
  37. </script>
  38. <script type="module">
  39. import * as THREE from 'three/webgpu';
  40. import { pass, mrt, output, normalView, diffuseColor, velocity, add, vec4, packNormalToRGB, unpackRGBToNormal, sample } from 'three/tsl';
  41. import { ssgi } from 'three/addons/tsl/display/SSGINode.js';
  42. import { svgf } from 'three/addons/tsl/display/SVGFNode.js';
  43. import { traa } from 'three/addons/tsl/display/TRAANode.js';
  44. import { blueNoise } from 'three/addons/tsl/math/BlueNoise.js';
  45. import { World } from '@perplexdotgg/bounce';
  46. import { Inspector } from 'three/addons/inspector/Inspector.js';
  47. const BALL_RADIUS = 0.4;
  48. const FILL_RATIO = 0.4;
  49. const PACKING = 0.6;
  50. const BOX_HEIGHT = 6;
  51. const BOX_DEPTH = 8;
  52. const WALL_THICKNESS = 0.5;
  53. const CAM_FOV = 45;
  54. const EASE_SPEED = 8;
  55. let camera, scene, renderer, renderPipeline;
  56. let raycaster, pointer;
  57. let mouseLight;
  58. let world;
  59. let ballCount = 0;
  60. let bodies = [];
  61. let ballsMesh = null;
  62. let wallMeshes = [];
  63. const boxSize = { w: 8, h: BOX_HEIGHT, d: BOX_DEPTH };
  64. const mouseRayOrigin = new THREE.Vector3();
  65. const mouseRayDir = new THREE.Vector3();
  66. let mouseMoving = false;
  67. let mouseStopTimer = 0;
  68. let pointerDown = false;
  69. const activePointers = new Set();
  70. const mouseLightTarget = new THREE.Vector3( 0, BOX_HEIGHT / 2, BOX_DEPTH / 2 );
  71. const mouseRayOriginTarget = new THREE.Vector3();
  72. const mouseRayDirTarget = new THREE.Vector3();
  73. init();
  74. async function init() {
  75. camera = new THREE.PerspectiveCamera( CAM_FOV, window.innerWidth / window.innerHeight, 0.1, 100 );
  76. scene = new THREE.Scene();
  77. renderer = new THREE.WebGPURenderer( { antialias: false } );
  78. renderer.setSize( window.innerWidth, window.innerHeight );
  79. renderer.setAnimationLoop( animate );
  80. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  81. renderer.toneMappingExposure = 0.5;
  82. renderer.shadowMap.enabled = true;
  83. renderer.inspector = new Inspector();
  84. document.body.appendChild( renderer.domElement );
  85. //
  86. renderPipeline = new THREE.RenderPipeline( renderer );
  87. const scenePass = pass( scene, camera );
  88. scenePass.setMRT( mrt( {
  89. output: output,
  90. diffuseColor: diffuseColor,
  91. normal: packNormalToRGB( normalView ),
  92. velocity: velocity
  93. } ) );
  94. const scenePassColor = scenePass.getTextureNode( 'output' );
  95. const scenePassDiffuse = scenePass.getTextureNode( 'diffuseColor' );
  96. const scenePassDepth = scenePass.getTextureNode( 'depth' );
  97. const scenePassNormal = scenePass.getTextureNode( 'normal' );
  98. const scenePassVelocity = scenePass.getTextureNode( 'velocity' );
  99. // bandwidth optimization
  100. const diffuseTexture = scenePass.getTexture( 'diffuseColor' );
  101. diffuseTexture.type = THREE.UnsignedByteType;
  102. const normalTexture = scenePass.getTexture( 'normal' );
  103. normalTexture.type = THREE.UnsignedByteType;
  104. const sceneNormal = sample( ( uv ) => {
  105. return unpackRGBToNormal( scenePassNormal.sample( uv ) );
  106. } );
  107. // gi
  108. const giPass = ssgi( scenePassColor, scenePassDepth, sceneNormal, camera );
  109. giPass.sliceCount.value = 2;
  110. giPass.stepCount.value = 8;
  111. giPass.noiseNode = blueNoise( 2 );
  112. // svgf denoise
  113. const svgfPass = svgf( giPass, scenePassDepth, sceneNormal, scenePassVelocity, camera );
  114. // composite
  115. const gi = svgfPass.rgb.toInspector( 'SSGI' );
  116. const ao = svgfPass.a.toInspector( 'AO' );
  117. const compositePass = vec4(
  118. add( scenePassColor.rgb.mul( ao ), scenePassDiffuse.rgb.mul( gi ) ),
  119. scenePassColor.a
  120. );
  121. // traa
  122. const traaPass = traa( compositePass, scenePassDepth, scenePassVelocity, camera );
  123. renderPipeline.outputNode = traaPass;
  124. // light
  125. mouseLight = new THREE.PointLight( 0xffffff, 80 );
  126. mouseLight.position.set( 0, BOX_HEIGHT / 2, BOX_DEPTH / 2 );
  127. mouseLight.castShadow = true;
  128. mouseLight.shadow.mapSize.set( 1024, 1024 );
  129. mouseLight.shadow.radius = 20;
  130. scene.add( mouseLight );
  131. //
  132. raycaster = new THREE.Raycaster();
  133. pointer = new THREE.Vector2();
  134. rebuildScene();
  135. //
  136. renderer.domElement.addEventListener( 'pointerdown', onPointerDown );
  137. renderer.domElement.addEventListener( 'pointermove', onPointerMove );
  138. renderer.domElement.addEventListener( 'pointerup', onPointerUp );
  139. renderer.domElement.addEventListener( 'pointercancel', onPointerUp );
  140. window.addEventListener( 'resize', onWindowResize );
  141. }
  142. function getBoxWidth() {
  143. const aspect = window.innerWidth / window.innerHeight;
  144. const vFov = THREE.MathUtils.degToRad( CAM_FOV / 2 );
  145. const dist = ( BOX_HEIGHT / 2 ) / Math.tan( vFov );
  146. return Math.tan( vFov ) * aspect * dist * 2;
  147. }
  148. function getBallCount() {
  149. const roomVolume = boxSize.w * boxSize.h * boxSize.d;
  150. const ballVolume = ( 4 / 3 ) * Math.PI * Math.pow( BALL_RADIUS, 3 );
  151. return Math.floor( roomVolume * FILL_RATIO * PACKING / ballVolume );
  152. }
  153. function rebuildScene() {
  154. for ( const mesh of wallMeshes ) {
  155. scene.remove( mesh );
  156. mesh.geometry.dispose();
  157. }
  158. wallMeshes = [];
  159. if ( ballsMesh ) {
  160. scene.remove( ballsMesh );
  161. ballsMesh.dispose();
  162. ballsMesh = null;
  163. }
  164. bodies = [];
  165. boxSize.w = getBoxWidth();
  166. ballCount = getBallCount();
  167. world = new World( {
  168. gravity: [ 0, - 9.81, 0 ],
  169. solveVelocityIterations: 6,
  170. solvePositionIterations: 2,
  171. linearDamping: 0.1,
  172. angularDamping: 0.1,
  173. restitution: 0.4,
  174. friction: 0.5
  175. } );
  176. fitCameraToBox();
  177. createBox();
  178. createBalls();
  179. }
  180. function createBox() {
  181. const hw = boxSize.w / 2;
  182. const hh = boxSize.h / 2;
  183. const hd = boxSize.d / 2;
  184. const t = WALL_THICKNESS;
  185. const whiteMaterial = new THREE.MeshPhysicalMaterial( {
  186. color: 0xeeeeee,
  187. roughness: 0.7,
  188. metalness: 0.0
  189. } );
  190. const redMaterial = new THREE.MeshPhysicalMaterial( {
  191. color: 0xff2222,
  192. roughness: 0.7,
  193. metalness: 0.0
  194. } );
  195. const greenMaterial = new THREE.MeshPhysicalMaterial( {
  196. color: 0x22ff22,
  197. roughness: 0.7,
  198. metalness: 0.0
  199. } );
  200. const walls = [
  201. { size: [ boxSize.w, t, boxSize.d ], pos: [ 0, - t / 2, 0 ], mat: whiteMaterial },
  202. { size: [ boxSize.w, t, boxSize.d ], pos: [ 0, boxSize.h + t / 2, 0 ], mat: whiteMaterial },
  203. { size: [ boxSize.w, boxSize.h, t ], pos: [ 0, hh, - hd - t / 2 ], mat: whiteMaterial },
  204. { size: [ boxSize.w, boxSize.h, t ], pos: [ 0, hh, hd + t / 2 ], noMesh: true },
  205. { size: [ t, boxSize.h, boxSize.d ], pos: [ - hw - t / 2, hh, 0 ], mat: redMaterial },
  206. { size: [ t, boxSize.h, boxSize.d ], pos: [ hw + t / 2, hh, 0 ], mat: greenMaterial }
  207. ];
  208. for ( const w of walls ) {
  209. const shape = world.createBox( { width: w.size[ 0 ], height: w.size[ 1 ], depth: w.size[ 2 ] } );
  210. world.createStaticBody( { shape, position: w.pos } );
  211. if ( ! w.noMesh ) {
  212. const geo = new THREE.BoxGeometry( w.size[ 0 ], w.size[ 1 ], w.size[ 2 ] );
  213. const mesh = new THREE.Mesh( geo, w.mat );
  214. mesh.position.set( ...w.pos );
  215. mesh.receiveShadow = true;
  216. scene.add( mesh );
  217. wallMeshes.push( mesh );
  218. }
  219. }
  220. }
  221. function createBalls() {
  222. const sphereGeo = new THREE.SphereGeometry( BALL_RADIUS, 32, 16 );
  223. const sphereShape = world.createSphere( { radius: BALL_RADIUS } );
  224. const material = new THREE.MeshPhysicalMaterial( {
  225. roughness: 0.3,
  226. metalness: 0.1
  227. } );
  228. ballsMesh = new THREE.InstancedMesh( sphereGeo, material, ballCount );
  229. ballsMesh.castShadow = true;
  230. ballsMesh.receiveShadow = true;
  231. scene.add( ballsMesh );
  232. const colors = [
  233. 0xff4444, 0x44ff44, 0x4488ff, 0xffaa00, 0xff44ff,
  234. 0x44ffff, 0xffff44, 0xff8844, 0x8844ff, 0x44ff88
  235. ];
  236. const color = new THREE.Color();
  237. const hw = boxSize.w / 2 - BALL_RADIUS - 0.1;
  238. const hd = boxSize.d / 2 - BALL_RADIUS - 0.1;
  239. for ( let i = 0; i < ballCount; i ++ ) {
  240. color.set( colors[ i % colors.length ] );
  241. ballsMesh.setColorAt( i, color );
  242. const x = ( Math.random() - 0.5 ) * 2 * hw;
  243. const y = BALL_RADIUS + Math.random() * ( boxSize.h - BALL_RADIUS * 2 );
  244. const z = ( Math.random() - 0.5 ) * 2 * hd;
  245. const body = world.createDynamicBody( {
  246. shape: sphereShape,
  247. position: [ x, y, z ],
  248. mass: 1,
  249. restitution: 0.5,
  250. friction: 0.4
  251. } );
  252. bodies.push( body );
  253. }
  254. }
  255. function onPointerDown( event ) {
  256. activePointers.add( event.pointerId );
  257. if ( event.pointerType === 'touch' ) {
  258. pointerDown = activePointers.size >= 2;
  259. } else {
  260. pointerDown = true;
  261. }
  262. }
  263. function onPointerUp( event ) {
  264. activePointers.delete( event.pointerId );
  265. if ( event.pointerType === 'touch' ) {
  266. pointerDown = activePointers.size >= 2;
  267. } else {
  268. pointerDown = false;
  269. }
  270. }
  271. function onPointerMove( event ) {
  272. pointer.x = ( event.clientX / window.innerWidth ) * 2 - 1;
  273. pointer.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
  274. raycaster.setFromCamera( pointer, camera );
  275. mouseRayOriginTarget.copy( raycaster.ray.origin );
  276. mouseRayDirTarget.copy( raycaster.ray.direction );
  277. mouseMoving = true;
  278. clearTimeout( mouseStopTimer );
  279. mouseStopTimer = setTimeout( () => mouseMoving = false, 50 );
  280. const frontPlane = new THREE.Plane( new THREE.Vector3( 0, 0, 1 ), - boxSize.d / 2 );
  281. const hit = new THREE.Vector3();
  282. if ( raycaster.ray.intersectPlane( frontPlane, hit ) ) {
  283. mouseLightTarget.copy( hit );
  284. }
  285. }
  286. function respawnBalls() {
  287. const hw = boxSize.w / 2 - BALL_RADIUS - 0.1;
  288. const hd = boxSize.d / 2 - BALL_RADIUS - 0.1;
  289. const count = 5;
  290. for ( let i = 0; i < count; i ++ ) {
  291. const body = bodies[ Math.floor( Math.random() * bodies.length ) ];
  292. body.position.set( [
  293. ( Math.random() - 0.5 ) * 2 * hw,
  294. boxSize.h - BALL_RADIUS - Math.random() * 1,
  295. ( Math.random() - 0.5 ) * 2 * hd
  296. ] );
  297. body.linearVelocity.set( [ 0, 0, 0 ] );
  298. body.angularVelocity.set( [ 0, 0, 0 ] );
  299. body.commitChanges();
  300. }
  301. }
  302. function fitCameraToBox() {
  303. const vFov = THREE.MathUtils.degToRad( CAM_FOV / 2 );
  304. const dist = ( boxSize.h / 2 ) / Math.tan( vFov );
  305. camera.aspect = window.innerWidth / window.innerHeight;
  306. camera.position.set( 0, boxSize.h / 2, dist + boxSize.d / 2 );
  307. camera.lookAt( 0, boxSize.h / 2, 0 );
  308. camera.updateProjectionMatrix();
  309. }
  310. function onWindowResize() {
  311. renderer.setSize( window.innerWidth, window.innerHeight );
  312. rebuildScene();
  313. }
  314. const timer = new THREE.Timer();
  315. const _dummy = new THREE.Object3D();
  316. function animate() {
  317. timer.update();
  318. const dt = Math.min( timer.getDelta(), 1 / 30 );
  319. const easeFactor = 1 - Math.exp( - EASE_SPEED * dt );
  320. mouseRayOrigin.lerp( mouseRayOriginTarget, easeFactor );
  321. mouseRayDir.lerp( mouseRayDirTarget, easeFactor );
  322. mouseLight.position.lerp( mouseLightTarget, easeFactor );
  323. if ( pointerDown ) {
  324. respawnBalls();
  325. }
  326. if ( mouseMoving ) {
  327. const pushRadius = 1.5;
  328. const pushStrength = 15;
  329. const _closest = new THREE.Vector3();
  330. const _ballPos = new THREE.Vector3();
  331. const _pushDir = new THREE.Vector3();
  332. for ( const body of bodies ) {
  333. const bp = body.position;
  334. _ballPos.set( bp.x, bp.y, bp.z );
  335. const ray = new THREE.Ray( mouseRayOrigin, mouseRayDir );
  336. ray.closestPointToPoint( _ballPos, _closest );
  337. const dist = _closest.distanceTo( _ballPos );
  338. if ( dist < pushRadius ) {
  339. _pushDir.subVectors( _ballPos, _closest );
  340. if ( _pushDir.lengthSq() < 0.001 ) _pushDir.set( 0, 1, 0 );
  341. _pushDir.normalize();
  342. const strength = pushStrength * ( 1 - dist / pushRadius );
  343. body.applyLinearImpulse( {
  344. x: _pushDir.x * strength,
  345. y: _pushDir.y * strength,
  346. z: _pushDir.z * strength
  347. } );
  348. }
  349. }
  350. }
  351. if ( world ) {
  352. world.advanceTime( 1 / 60, dt );
  353. }
  354. for ( let i = 0; i < bodies.length; i ++ ) {
  355. const body = bodies[ i ];
  356. const p = body.position;
  357. const q = body.orientation;
  358. _dummy.position.set( p.x, p.y, p.z );
  359. _dummy.quaternion.set( q.x, q.y, q.z, q.w );
  360. _dummy.updateMatrix();
  361. ballsMesh.setMatrixAt( i, _dummy.matrix );
  362. }
  363. ballsMesh.instanceMatrix.needsUpdate = true;
  364. renderPipeline.render();
  365. }
  366. </script>
  367. </body>
  368. </html>
粤ICP备19079148号