webgpu_mesh_batch.html 7.9 KB

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