webgpu_postprocessing_ssgi_ballpool.html 13 KB

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