webgpu_compile_async.html 9.2 KB

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