webgl_mesh_batch.html 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - 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> webgl - mesh - batch
  17. </div>
  18. <script type="importmap">
  19. {
  20. "imports": {
  21. "three": "../build/three.module.js",
  22. "three/addons/": "./jsm/"
  23. }
  24. }
  25. </script>
  26. <script type="module">
  27. import * as THREE from 'three';
  28. import Stats from 'three/addons/libs/stats.module.js';
  29. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  30. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  31. import { radixSort } from 'three/addons/utils/SortUtils.js';
  32. let stats, gui, guiStatsEl;
  33. let camera, controls, scene, renderer;
  34. let geometries, mesh, material;
  35. const ids = [];
  36. const matrix = new THREE.Matrix4();
  37. //
  38. const position = new THREE.Vector3();
  39. const rotation = new THREE.Euler();
  40. const quaternion = new THREE.Quaternion();
  41. const scale = new THREE.Vector3();
  42. //
  43. const MAX_GEOMETRY_COUNT = 20000;
  44. const Method = {
  45. BATCHED: 'BATCHED',
  46. NAIVE: 'NAIVE'
  47. };
  48. const api = {
  49. method: Method.BATCHED,
  50. count: 256,
  51. dynamic: 16,
  52. sortObjects: true,
  53. perObjectFrustumCulled: true,
  54. opacity: 1,
  55. useCustomSort: true,
  56. };
  57. init();
  58. initGeometries();
  59. initMesh();
  60. //
  61. function randomizeMatrix( matrix ) {
  62. position.x = Math.random() * 40 - 20;
  63. position.y = Math.random() * 40 - 20;
  64. position.z = Math.random() * 40 - 20;
  65. rotation.x = Math.random() * 2 * Math.PI;
  66. rotation.y = Math.random() * 2 * Math.PI;
  67. rotation.z = Math.random() * 2 * Math.PI;
  68. quaternion.setFromEuler( rotation );
  69. scale.x = scale.y = scale.z = 0.5 + ( Math.random() * 0.5 );
  70. return matrix.compose( position, quaternion, scale );
  71. }
  72. function randomizeRotationSpeed( rotation ) {
  73. rotation.x = Math.random() * 0.01;
  74. rotation.y = Math.random() * 0.01;
  75. rotation.z = Math.random() * 0.01;
  76. return rotation;
  77. }
  78. function initGeometries() {
  79. geometries = [
  80. new THREE.ConeGeometry( 1.0, 2.0 ),
  81. new THREE.BoxGeometry( 2.0, 2.0, 2.0 ),
  82. new THREE.SphereGeometry( 1.0, 16, 8 ),
  83. ];
  84. }
  85. function createMaterial() {
  86. if ( ! material ) {
  87. material = new THREE.MeshNormalMaterial();
  88. }
  89. return material;
  90. }
  91. function cleanup() {
  92. if ( mesh ) {
  93. mesh.parent.remove( mesh );
  94. if ( mesh.dispose ) {
  95. mesh.dispose();
  96. }
  97. }
  98. }
  99. function initMesh() {
  100. cleanup();
  101. if ( api.method === Method.BATCHED ) {
  102. initBatchedMesh();
  103. } else {
  104. initRegularMesh();
  105. }
  106. }
  107. function initRegularMesh() {
  108. mesh = new THREE.Group();
  109. const material = createMaterial();
  110. for ( let i = 0; i < api.count; i ++ ) {
  111. const child = new THREE.Mesh( geometries[ i % geometries.length ], material );
  112. randomizeMatrix( child.matrix );
  113. child.matrix.decompose( child.position, child.quaternion, child.scale );
  114. child.userData.rotationSpeed = randomizeRotationSpeed( new THREE.Euler() );
  115. mesh.add( child );
  116. }
  117. scene.add( mesh );
  118. }
  119. function initBatchedMesh() {
  120. const geometryCount = api.count;
  121. const vertexCount = geometries.length * 512;
  122. const indexCount = geometries.length * 1024;
  123. const euler = new THREE.Euler();
  124. const matrix = new THREE.Matrix4();
  125. mesh = new THREE.BatchedMesh( geometryCount, vertexCount, indexCount, createMaterial() );
  126. mesh.userData.rotationSpeeds = [];
  127. // disable full-object frustum culling since all of the objects can be dynamic.
  128. mesh.frustumCulled = false;
  129. ids.length = 0;
  130. const geometryIds = [
  131. mesh.addGeometry( geometries[ 0 ] ),
  132. mesh.addGeometry( geometries[ 1 ] ),
  133. mesh.addGeometry( geometries[ 2 ] ),
  134. ];
  135. for ( let i = 0; i < api.count; i ++ ) {
  136. const id = mesh.addInstance( geometryIds[ i % geometryIds.length ] );
  137. mesh.setMatrixAt( id, randomizeMatrix( matrix ) );
  138. const rotationMatrix = new THREE.Matrix4();
  139. rotationMatrix.makeRotationFromEuler( randomizeRotationSpeed( euler ) );
  140. mesh.userData.rotationSpeeds.push( rotationMatrix );
  141. ids.push( id );
  142. }
  143. scene.add( mesh );
  144. }
  145. function init() {
  146. const width = window.innerWidth;
  147. const height = window.innerHeight;
  148. // camera
  149. camera = new THREE.PerspectiveCamera( 70, width / height, 1, 100 );
  150. camera.position.z = 30;
  151. // renderer
  152. renderer = new THREE.WebGLRenderer( { antialias: true } );
  153. renderer.setPixelRatio( window.devicePixelRatio );
  154. renderer.setSize( width, height );
  155. renderer.setAnimationLoop( animate );
  156. document.body.appendChild( renderer.domElement );
  157. // scene
  158. scene = new THREE.Scene();
  159. scene.background = new THREE.Color( 0xffffff );
  160. // controls
  161. controls = new OrbitControls( camera, renderer.domElement );
  162. controls.autoRotate = true;
  163. controls.autoRotateSpeed = 1.0;
  164. // stats
  165. stats = new Stats();
  166. document.body.appendChild( stats.dom );
  167. // gui
  168. gui = new GUI();
  169. gui.add( api, 'count', 1, MAX_GEOMETRY_COUNT ).step( 1 ).onChange( initMesh );
  170. gui.add( api, 'dynamic', 0, MAX_GEOMETRY_COUNT ).step( 1 );
  171. gui.add( api, 'method', Method ).onChange( initMesh );
  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. guiStatsEl = document.createElement( 'li' );
  187. guiStatsEl.classList.add( 'gui-stats' );
  188. // listeners
  189. window.addEventListener( 'resize', onWindowResize );
  190. }
  191. //
  192. function sortFunction( list ) {
  193. // initialize options
  194. this._options = this._options || {
  195. get: el => el.z,
  196. aux: new Array( this.maxInstanceCount )
  197. };
  198. const options = this._options;
  199. options.reversed = this.material.transparent;
  200. let minZ = Infinity;
  201. let maxZ = - Infinity;
  202. for ( let i = 0, l = list.length; i < l; i ++ ) {
  203. const z = list[ i ].z;
  204. if ( z > maxZ ) maxZ = z;
  205. if ( z < minZ ) minZ = z;
  206. }
  207. // convert depth to unsigned 32 bit range
  208. const depthDelta = maxZ - minZ;
  209. const factor = ( 2 ** 32 - 1 ) / depthDelta; // UINT32_MAX / z range
  210. for ( let i = 0, l = list.length; i < l; i ++ ) {
  211. list[ i ].z -= minZ;
  212. list[ i ].z *= factor;
  213. }
  214. // perform a fast-sort using the hybrid radix sort function
  215. radixSort( list, options );
  216. }
  217. function onWindowResize() {
  218. const width = window.innerWidth;
  219. const height = window.innerHeight;
  220. camera.aspect = width / height;
  221. camera.updateProjectionMatrix();
  222. renderer.setSize( width, height );
  223. }
  224. function animate() {
  225. animateMeshes();
  226. controls.update();
  227. stats.update();
  228. render();
  229. }
  230. function animateMeshes() {
  231. const loopNum = Math.min( api.count, api.dynamic );
  232. if ( api.method === Method.BATCHED ) {
  233. for ( let i = 0; i < loopNum; i ++ ) {
  234. const rotationMatrix = mesh.userData.rotationSpeeds[ i ];
  235. const id = ids[ i ];
  236. mesh.getMatrixAt( id, matrix );
  237. matrix.multiply( rotationMatrix );
  238. mesh.setMatrixAt( id, matrix );
  239. }
  240. } else {
  241. for ( let i = 0; i < loopNum; i ++ ) {
  242. const child = mesh.children[ i ];
  243. const rotationSpeed = child.userData.rotationSpeed;
  244. child.rotation.set(
  245. child.rotation.x + rotationSpeed.x,
  246. child.rotation.y + rotationSpeed.y,
  247. child.rotation.z + rotationSpeed.z
  248. );
  249. }
  250. }
  251. }
  252. function render() {
  253. if ( mesh.isBatchedMesh ) {
  254. mesh.sortObjects = api.sortObjects;
  255. mesh.perObjectFrustumCulled = api.perObjectFrustumCulled;
  256. mesh.setCustomSort( api.useCustomSort ? sortFunction : null );
  257. }
  258. renderer.render( scene, camera );
  259. }
  260. </script>
  261. </body>
  262. </html>