webgpu_compile_async.html 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - async node compilation</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 - async node compilation">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgpu_compile_async.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgpu_compile_async.jpg">
  11. <link type="text/css" rel="stylesheet" href="example.css">
  12. <style>
  13. #stats {
  14. position: fixed;
  15. top: 80px;
  16. left: 20px;
  17. background: rgba(0,0,0,0.7);
  18. color: #fff;
  19. padding: 10px 15px;
  20. font-family: monospace;
  21. font-size: 12px;
  22. border-radius: 4px;
  23. z-index: 100;
  24. min-width: 220px;
  25. }
  26. #stats .label { color: #888; }
  27. #stats .value { color: #0f0; font-weight: bold; }
  28. #stats .value.bad { color: #f55; }
  29. </style>
  30. </head>
  31. <body>
  32. <div id="info">
  33. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  34. <div class="title-wrapper">
  35. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>Async Node Compilation</span>
  36. </div>
  37. <small id="description">NodeMaterial shaders compile asynchronously without blocking the render loop. Animation stays smooth while <span id="materialCount">256</span> unique TSL materials build in the background.</small>
  38. </div>
  39. <div id="stats">
  40. <div><span class="label">Longest frame: </span><span id="longestFrame" class="value">-</span></div>
  41. <div><span class="label">Meshes added: </span><span id="meshCount" class="value">0 / 256</span></div>
  42. <div><span class="label">Mode: </span><span id="compileMode" class="value">-</span></div>
  43. </div>
  44. <script type="importmap">
  45. {
  46. "imports": {
  47. "three": "../build/three.webgpu.js",
  48. "three/webgpu": "../build/three.webgpu.js",
  49. "three/tsl": "../build/three.tsl.js",
  50. "three/addons/": "./jsm/"
  51. }
  52. }
  53. </script>
  54. <script type="module">
  55. import * as THREE from 'three/webgpu';
  56. import { uv, float, vec3, hash, mx_noise_vec3, mx_worley_noise_vec3, mx_cell_noise_float, mx_fractal_noise_vec3 } from 'three/tsl';
  57. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  58. let MESH_COUNT = 256;
  59. let GRID_SIZE = 16;
  60. const ADD_DELAY = 1000;
  61. let camera, scene, renderer;
  62. let sphere;
  63. let gui;
  64. // Frame timing
  65. let lastFrameTime = 0;
  66. let longestFrameTime = 0;
  67. let isTracking = false;
  68. let shouldStartTracking = false;
  69. let sphereStartTime = 0;
  70. let currentMode = '';
  71. let framesAfterComplete = 0;
  72. let testDone = false;
  73. let meshGroup = null;
  74. const longestFrameEl = document.getElementById( 'longestFrame' );
  75. const meshCountEl = document.getElementById( 'meshCount' );
  76. const compileModeEl = document.getElementById( 'compileMode' );
  77. const params = {
  78. withoutCompile: function () {
  79. window.location.href = window.location.pathname + '?mode=no-compile';
  80. },
  81. withCompileAsync: function () {
  82. window.location.href = window.location.pathname + '?mode=compile-async';
  83. }
  84. };
  85. init();
  86. async function init() {
  87. // GUI
  88. gui = new GUI();
  89. gui.add( params, 'withoutCompile' ).name( 'Build on render' );
  90. gui.add( params, 'withCompileAsync' ).name( 'Pre-build (compileAsync)' );
  91. window.addEventListener( 'resize', onWindowResize );
  92. // Orthographic camera
  93. const aspect = window.innerWidth / window.innerHeight;
  94. const frustumSize = 20;
  95. camera = new THREE.OrthographicCamera(
  96. frustumSize * aspect / - 2,
  97. frustumSize * aspect / 2,
  98. frustumSize / 2,
  99. frustumSize / - 2,
  100. 0.1,
  101. 100
  102. );
  103. camera.position.set( 0, 0, 20 );
  104. camera.lookAt( 0, 0, 0 );
  105. scene = new THREE.Scene();
  106. scene.background = new THREE.Color( 0x111111 );
  107. // Create animated sphere
  108. const sphereGeometry = new THREE.SphereGeometry( 0.5, 32, 32 );
  109. const sphereMaterial = new THREE.MeshNormalMaterial();
  110. sphere = new THREE.Mesh( sphereGeometry, sphereMaterial );
  111. scene.add( sphere );
  112. // Renderer
  113. renderer = new THREE.WebGPURenderer( { antialias: true } );
  114. renderer.setPixelRatio( window.devicePixelRatio );
  115. renderer.setSize( window.innerWidth, window.innerHeight );
  116. renderer.setAnimationLoop( animate );
  117. document.body.appendChild( renderer.domElement );
  118. await renderer.init();
  119. // Reduce mesh count for WebGL (slower compilation)
  120. if ( renderer.backend.isWebGLBackend ) {
  121. MESH_COUNT = 64;
  122. GRID_SIZE = 8;
  123. document.getElementById( 'materialCount' ).textContent = '64';
  124. meshCountEl.textContent = '0 / 64';
  125. }
  126. // Get mode from URL
  127. const urlParams = new URLSearchParams( window.location.search );
  128. const mode = urlParams.get( 'mode' ) || 'compile-async';
  129. const modeLabel = mode === 'compile-async' ? 'Pre-build (compileAsync)' : 'Build on render';
  130. compileModeEl.textContent = modeLabel;
  131. // Start sphere animation
  132. sphereStartTime = performance.now();
  133. // Schedule mesh addition after delay
  134. setTimeout( () => addMeshes( mode ), ADD_DELAY );
  135. }
  136. function createUniqueMaterial( index ) {
  137. const material = new THREE.MeshBasicNodeMaterial();
  138. const seed = float( index * 0.1 + 1.0 );
  139. const scale = float( ( index % 5 ) + 2.0 );
  140. const uvNode = uv().mul( scale ).add( hash( float( index ) ) );
  141. const noiseType = index % 4;
  142. let colorNode;
  143. switch ( noiseType ) {
  144. case 0:
  145. colorNode = mx_noise_vec3( uvNode.mul( seed ) ).mul( 0.5 ).add( 0.5 );
  146. break;
  147. case 1:
  148. colorNode = mx_worley_noise_vec3( uvNode.mul( seed.mul( 0.5 ) ) );
  149. break;
  150. case 2:
  151. const cellNoise = mx_cell_noise_float( uvNode.mul( seed ) );
  152. colorNode = vec3( cellNoise, cellNoise.mul( 0.7 ), cellNoise.mul( 0.4 ) );
  153. break;
  154. case 3:
  155. colorNode = mx_fractal_noise_vec3( uvNode.mul( seed.mul( 0.3 ) ), float( 3 ), float( 2.0 ), float( 0.5 ) )
  156. .mul( 0.5 ).add( 0.5 );
  157. break;
  158. }
  159. const tintR = hash( float( index * 3 ) );
  160. const tintG = hash( float( index * 3 + 1 ) );
  161. const tintB = hash( float( index * 3 + 2 ) );
  162. const tint = vec3( tintR, tintG, tintB ).mul( 0.3 ).add( 0.7 );
  163. material.colorNode = colorNode.mul( tint );
  164. return material;
  165. }
  166. async function addMeshes( mode ) {
  167. const geometry = new THREE.PlaneGeometry( 0.9, 0.9 );
  168. const startX = - ( GRID_SIZE - 1 ) / 2;
  169. const startY = - ( GRID_SIZE - 1 ) / 2;
  170. meshGroup = new THREE.Group();
  171. for ( let i = 0; i < MESH_COUNT; i ++ ) {
  172. const material = createUniqueMaterial( i );
  173. const mesh = new THREE.Mesh( geometry, material );
  174. const col = i % GRID_SIZE;
  175. const row = Math.floor( i / GRID_SIZE );
  176. mesh.position.x = startX + col;
  177. mesh.position.y = startY + row;
  178. meshGroup.add( mesh );
  179. }
  180. currentMode = mode;
  181. if ( mode === 'compile-async' ) {
  182. // Pre-compile all meshes before adding to scene
  183. // Start tracking BEFORE compile to measure longest frame during compile
  184. shouldStartTracking = true;
  185. await renderer.compileAsync( meshGroup, camera, scene );
  186. // Add all meshes at once (already compiled - should render instantly)
  187. scene.add( meshGroup );
  188. testDone = true;
  189. } else {
  190. // Add all meshes at once - renderer compiles on-demand
  191. // Meshes appear progressively as they compile
  192. scene.add( meshGroup );
  193. // Start tracking on next animate() frame
  194. shouldStartTracking = true;
  195. testDone = true;
  196. }
  197. }
  198. function finishTest() {
  199. isTracking = false;
  200. longestFrameEl.textContent = longestFrameTime.toFixed( 1 ) + ' ms';
  201. longestFrameEl.className = longestFrameTime > 100 ? 'value bad' : 'value';
  202. }
  203. function onWindowResize() {
  204. if ( ! renderer || ! camera ) return;
  205. const aspect = window.innerWidth / window.innerHeight;
  206. const frustumSize = 12;
  207. camera.left = frustumSize * aspect / - 2;
  208. camera.right = frustumSize * aspect / 2;
  209. camera.top = frustumSize / 2;
  210. camera.bottom = frustumSize / - 2;
  211. camera.updateProjectionMatrix();
  212. renderer.setSize( window.innerWidth, window.innerHeight );
  213. }
  214. function animate() {
  215. const now = performance.now();
  216. // Initialize tracking on first frame after meshes added
  217. if ( shouldStartTracking ) {
  218. shouldStartTracking = false;
  219. isTracking = true;
  220. lastFrameTime = now;
  221. longestFrameTime = 0;
  222. framesAfterComplete = 0;
  223. }
  224. // Track longest frame during test
  225. if ( isTracking && lastFrameTime > 0 && lastFrameTime !== now ) {
  226. const frameTime = now - lastFrameTime;
  227. if ( frameTime > longestFrameTime ) {
  228. longestFrameTime = frameTime;
  229. }
  230. }
  231. lastFrameTime = now;
  232. // Animate sphere left to right
  233. if ( sphere && sphereStartTime > 0 ) {
  234. const elapsed = ( now - sphereStartTime ) / 1000;
  235. sphere.position.x = Math.sin( elapsed * 2 ) * 8;
  236. }
  237. renderer.render( scene, camera );
  238. // Update mesh count display
  239. if ( meshGroup ) {
  240. meshCountEl.textContent = meshGroup.children.length + ' / ' + MESH_COUNT;
  241. }
  242. // Finish test - wait a few frames after testDone to capture frame times
  243. if ( isTracking && testDone ) {
  244. framesAfterComplete ++;
  245. // Wait longer for deferred mode (meshes compile progressively)
  246. const framesToWait = currentMode === 'compile-async' ? 2 : 60;
  247. if ( framesAfterComplete >= framesToWait ) {
  248. finishTest();
  249. }
  250. }
  251. }
  252. </script>
  253. </body>
  254. </html>
粤ICP备19079148号