webgpu_mesh_batch.html 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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 } 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 = diffuseColor.mul( directionToColor( normalView ).y.add( 0.5 ) );
  90. }
  91. return material;
  92. }
  93. function cleanup() {
  94. if ( mesh ) {
  95. mesh.parent.remove( mesh );
  96. if ( mesh.dispose ) {
  97. mesh.dispose();
  98. }
  99. }
  100. }
  101. function initMesh() {
  102. cleanup();
  103. initBatchedMesh();
  104. }
  105. function initBatchedMesh() {
  106. const geometryCount = api.count;
  107. const vertexCount = geometries.length * 512;
  108. const indexCount = geometries.length * 1024;
  109. const euler = new THREE.Euler();
  110. const matrix = new THREE.Matrix4();
  111. mesh = new THREE.BatchedMesh( geometryCount, vertexCount, indexCount, createMaterial() );
  112. mesh.userData.rotationSpeeds = [];
  113. // disable full-object frustum culling since all of the objects can be dynamic.
  114. mesh.frustumCulled = false;
  115. ids.length = 0;
  116. const geometryIds = [
  117. mesh.addGeometry( geometries[ 0 ] ),
  118. mesh.addGeometry( geometries[ 1 ] ),
  119. mesh.addGeometry( geometries[ 2 ] ),
  120. ];
  121. for ( let i = 0; i < api.count; i ++ ) {
  122. const id = mesh.addInstance( geometryIds[ i % geometryIds.length ] );
  123. mesh.setMatrixAt( id, randomizeMatrix( matrix ) );
  124. mesh.setColorAt( id, new THREE.Color( Math.random() * 0xffffff ) );
  125. const rotationMatrix = new THREE.Matrix4();
  126. rotationMatrix.makeRotationFromEuler( randomizeRotationSpeed( euler ) );
  127. mesh.userData.rotationSpeeds.push( rotationMatrix );
  128. ids.push( id );
  129. }
  130. scene.add( mesh );
  131. }
  132. function init( forceWebGL = false ) {
  133. if ( renderer ) {
  134. renderer.dispose();
  135. controls.dispose();
  136. document.body.removeChild( renderer.domElement );
  137. }
  138. // camera
  139. const aspect = window.innerWidth / window.innerHeight;
  140. camera = new THREE.PerspectiveCamera( 70, aspect, 1, 100 );
  141. camera.position.z = 30;
  142. // renderer
  143. renderer = new THREE.WebGPURenderer( { antialias: true, forceWebGL } );
  144. renderer.setPixelRatio( window.devicePixelRatio );
  145. renderer.setSize( window.innerWidth, window.innerHeight );
  146. renderer.inspector = new Inspector();
  147. renderer.setAnimationLoop( animate );
  148. // scene
  149. scene = new THREE.Scene();
  150. scene.background = forceWebGL ? new THREE.Color( 0xffc1c1 ) : new THREE.Color( 0xc1c1ff );
  151. document.body.appendChild( renderer.domElement );
  152. initGeometries();
  153. initMesh();
  154. // controls
  155. controls = new OrbitControls( camera, renderer.domElement );
  156. controls.autoRotate = true;
  157. controls.autoRotateSpeed = 1.0;
  158. // gui
  159. gui = renderer.inspector.createParameters( 'Settings' );
  160. gui.add( api, 'webgpu' ).onChange( () => {
  161. init( ! api.webgpu );
  162. } );
  163. gui.add( api, 'count', 1, MAX_GEOMETRY_COUNT ).step( 1 ).onChange( initMesh );
  164. gui.add( api, 'dynamic', 0, MAX_GEOMETRY_COUNT ).step( 1 );
  165. gui.add( api, 'opacity', 0, 1 ).onChange( v => {
  166. if ( v < 1 ) {
  167. material.transparent = true;
  168. material.depthWrite = false;
  169. } else {
  170. material.transparent = false;
  171. material.depthWrite = true;
  172. }
  173. material.opacity = v;
  174. material.needsUpdate = true;
  175. } );
  176. gui.add( api, 'sortObjects' );
  177. gui.add( api, 'perObjectFrustumCulled' );
  178. gui.add( api, 'useCustomSort' );
  179. gui.add( api, 'randomizeGeometry' );
  180. // listeners
  181. window.addEventListener( 'resize', onWindowResize );
  182. function onWindowResize() {
  183. const width = window.innerWidth;
  184. const height = window.innerHeight;
  185. camera.aspect = width / height;
  186. camera.updateProjectionMatrix();
  187. renderer.setSize( width, height );
  188. }
  189. async function animate() {
  190. animateMeshes();
  191. controls.update();
  192. if ( mesh.isBatchedMesh ) {
  193. mesh.sortObjects = api.sortObjects;
  194. mesh.perObjectFrustumCulled = api.perObjectFrustumCulled;
  195. mesh.setCustomSort( api.useCustomSort ? sortFunction : null );
  196. }
  197. renderer.render( scene, camera );
  198. }
  199. function animateMeshes() {
  200. const loopNum = Math.min( api.count, api.dynamic );
  201. for ( let i = 0; i < loopNum; i ++ ) {
  202. const rotationMatrix = mesh.userData.rotationSpeeds[ i ];
  203. const id = ids[ i ];
  204. mesh.getMatrixAt( id, matrix );
  205. matrix.multiply( rotationMatrix );
  206. mesh.setMatrixAt( id, matrix );
  207. }
  208. }
  209. }
  210. //
  211. function sortFunction( list, camera ) {
  212. // initialize options
  213. this._options = this._options || {
  214. get: el => el.z,
  215. aux: new Array( this.maxInstanceCount )
  216. };
  217. const options = this._options;
  218. options.reversed = this.material.transparent;
  219. // convert depth to unsigned 32 bit range
  220. const factor = ( 2 ** 32 - 1 ) / camera.far; // UINT32_MAX / max_depth
  221. for ( let i = 0, l = list.length; i < l; i ++ ) {
  222. list[ i ].z *= factor;
  223. }
  224. // perform a fast-sort using the hybrid radix sort function
  225. radixSort( list, options );
  226. }
  227. </script>
  228. </body>
  229. </html>
粤ICP备19079148号