webgpu_mesh_batch.html 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - mesh - batch</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. <style>
  9. #info {
  10. background-color: rgba(0,0,0,0.75);
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <div id="info">
  16. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgpu - mesh - batch
  17. </div>
  18. <script type="importmap">
  19. {
  20. "imports": {
  21. "three": "../build/three.webgpu.js",
  22. "three/tsl": "../build/three.webgpu.js",
  23. "three/addons/": "./jsm/"
  24. }
  25. }
  26. </script>
  27. <script type="module">
  28. import * as THREE from 'three';
  29. import Stats from 'three/addons/libs/stats.module.js';
  30. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  31. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  32. import { radixSort } from 'three/addons/utils/SortUtils.js';
  33. import { transformedNormalView, directionToColor, diffuseColor } from 'three/tsl';
  34. let camera, scene, renderer;
  35. let controls, stats;
  36. let gui;
  37. let geometries, mesh, material;
  38. const ids = [];
  39. const matrix = new THREE.Matrix4();
  40. //
  41. const position = new THREE.Vector3();
  42. const rotation = new THREE.Euler();
  43. const quaternion = new THREE.Quaternion();
  44. const scale = new THREE.Vector3();
  45. //
  46. const MAX_GEOMETRY_COUNT = 20000;
  47. const api = {
  48. webgpu: true,
  49. count: 512,
  50. dynamic: 16,
  51. sortObjects: true,
  52. perObjectFrustumCulled: true,
  53. opacity: 1,
  54. useCustomSort: true,
  55. };
  56. init();
  57. //
  58. function randomizeMatrix( matrix ) {
  59. position.x = Math.random() * 40 - 20;
  60. position.y = Math.random() * 40 - 20;
  61. position.z = Math.random() * 40 - 20;
  62. rotation.x = Math.random() * 2 * Math.PI;
  63. rotation.y = Math.random() * 2 * Math.PI;
  64. rotation.z = Math.random() * 2 * Math.PI;
  65. quaternion.setFromEuler( rotation );
  66. scale.x = scale.y = scale.z = 0.5 + ( Math.random() * 0.5 );
  67. return matrix.compose( position, quaternion, scale );
  68. }
  69. function randomizeRotationSpeed( rotation ) {
  70. rotation.x = Math.random() * 0.01;
  71. rotation.y = Math.random() * 0.01;
  72. rotation.z = Math.random() * 0.01;
  73. return rotation;
  74. }
  75. function initGeometries() {
  76. geometries = [
  77. new THREE.ConeGeometry( 1.0, 2.0 ),
  78. new THREE.BoxGeometry( 2.0, 2.0, 2.0 ),
  79. new THREE.SphereGeometry( 1.0, 16, 8 ),
  80. ];
  81. }
  82. function createMaterial() {
  83. if ( ! material ) {
  84. material = new THREE.MeshBasicNodeMaterial();
  85. material.outputNode = diffuseColor.mul( directionToColor( transformedNormalView ).y.add( 0.5 ) );
  86. }
  87. return material;
  88. }
  89. function cleanup() {
  90. if ( mesh ) {
  91. mesh.parent.remove( mesh );
  92. if ( mesh.dispose ) {
  93. mesh.dispose();
  94. }
  95. }
  96. }
  97. function initMesh() {
  98. cleanup();
  99. initBatchedMesh();
  100. }
  101. function initBatchedMesh() {
  102. const geometryCount = api.count;
  103. const vertexCount = geometries.length * 512;
  104. const indexCount = geometries.length * 1024;
  105. const euler = new THREE.Euler();
  106. const matrix = new THREE.Matrix4();
  107. mesh = new THREE.BatchedMesh( geometryCount, vertexCount, indexCount, createMaterial() );
  108. mesh.userData.rotationSpeeds = [];
  109. // disable full-object frustum culling since all of the objects can be dynamic.
  110. mesh.frustumCulled = false;
  111. ids.length = 0;
  112. const geometryIds = [
  113. mesh.addGeometry( geometries[ 0 ] ),
  114. mesh.addGeometry( geometries[ 1 ] ),
  115. mesh.addGeometry( geometries[ 2 ] ),
  116. ];
  117. for ( let i = 0; i < api.count; i ++ ) {
  118. const id = mesh.addInstance( geometryIds[ i % geometryIds.length ] );
  119. mesh.setMatrixAt( id, randomizeMatrix( matrix ) );
  120. mesh.setColorAt( id, new THREE.Color( Math.random() * 0xffffff ) );
  121. const rotationMatrix = new THREE.Matrix4();
  122. rotationMatrix.makeRotationFromEuler( randomizeRotationSpeed( euler ) );
  123. mesh.userData.rotationSpeeds.push( rotationMatrix );
  124. ids.push( id );
  125. }
  126. scene.add( mesh );
  127. }
  128. function init( forceWebGL = false ) {
  129. if ( renderer ) {
  130. renderer.dispose();
  131. controls.dispose();
  132. document.body.removeChild( stats.dom );
  133. document.body.removeChild( renderer.domElement );
  134. }
  135. // camera
  136. const aspect = window.innerWidth / window.innerHeight;
  137. camera = new THREE.PerspectiveCamera( 70, aspect, 1, 100 );
  138. camera.position.z = 30;
  139. // renderer
  140. renderer = new THREE.WebGPURenderer( { antialias: true, forceWebGL } );
  141. renderer.setPixelRatio( window.devicePixelRatio );
  142. renderer.setSize( window.innerWidth, window.innerHeight );
  143. renderer.setAnimationLoop( animate );
  144. // scene
  145. scene = new THREE.Scene();
  146. scene.background = forceWebGL ? new THREE.Color( 0xffc1c1 ) : new THREE.Color( 0xc1c1ff );
  147. document.body.appendChild( renderer.domElement );
  148. initGeometries();
  149. initMesh();
  150. // controls
  151. controls = new OrbitControls( camera, renderer.domElement );
  152. controls.autoRotate = true;
  153. controls.autoRotateSpeed = 1.0;
  154. // stats
  155. stats = new Stats();
  156. document.body.appendChild( stats.dom );
  157. // gui
  158. gui = new GUI();
  159. gui.add( api, 'webgpu' ).onChange( () => {
  160. init( ! api.webgpu );
  161. } );
  162. gui.add( api, 'count', 1, MAX_GEOMETRY_COUNT ).step( 1 ).onChange( initMesh );
  163. gui.add( api, 'dynamic', 0, MAX_GEOMETRY_COUNT ).step( 1 );
  164. gui.add( api, 'opacity', 0, 1 ).onChange( v => {
  165. if ( v < 1 ) {
  166. material.transparent = true;
  167. material.depthWrite = false;
  168. } else {
  169. material.transparent = false;
  170. material.depthWrite = true;
  171. }
  172. material.opacity = v;
  173. material.needsUpdate = true;
  174. } );
  175. gui.add( api, 'sortObjects' );
  176. gui.add( api, 'perObjectFrustumCulled' );
  177. gui.add( api, 'useCustomSort' );
  178. // listeners
  179. window.addEventListener( 'resize', onWindowResize );
  180. function onWindowResize() {
  181. const width = window.innerWidth;
  182. const height = window.innerHeight;
  183. camera.aspect = width / height;
  184. camera.updateProjectionMatrix();
  185. renderer.setSize( width, height );
  186. }
  187. async function animate() {
  188. animateMeshes();
  189. controls.update();
  190. if ( mesh.isBatchedMesh ) {
  191. mesh.sortObjects = api.sortObjects;
  192. mesh.perObjectFrustumCulled = api.perObjectFrustumCulled;
  193. mesh.setCustomSort( api.useCustomSort ? sortFunction : null );
  194. }
  195. await renderer.renderAsync( scene, camera );
  196. stats.update();
  197. }
  198. function animateMeshes() {
  199. const loopNum = Math.min( api.count, api.dynamic );
  200. for ( let i = 0; i < loopNum; i ++ ) {
  201. const rotationMatrix = mesh.userData.rotationSpeeds[ i ];
  202. const id = ids[ i ];
  203. mesh.getMatrixAt( id, matrix );
  204. matrix.multiply( rotationMatrix );
  205. mesh.setMatrixAt( id, matrix );
  206. }
  207. }
  208. }
  209. //
  210. function sortFunction( list, camera ) {
  211. // initialize options
  212. this._options = this._options || {
  213. get: el => el.z,
  214. aux: new Array( this.maxInstanceCount )
  215. };
  216. const options = this._options;
  217. options.reversed = this.material.transparent;
  218. // convert depth to unsigned 32 bit range
  219. const factor = ( 2 ** 32 - 1 ) / camera.far; // UINT32_MAX / max_depth
  220. for ( let i = 0, l = list.length; i < l; i ++ ) {
  221. list[ i ].z *= factor;
  222. }
  223. // perform a fast-sort using the hybrid radix sort function
  224. radixSort( list, options );
  225. }
  226. </script>
  227. </body>
  228. </html>