webgpu_mesh_batch.html 7.6 KB

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