webgl_instancing_performance.html 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - instancing - performance</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. .lil-gui .gui-stats {
  13. line-height: var(--widget-height);
  14. padding: var(--padding);
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="info">
  20. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - instancing - performance
  21. </div>
  22. <div id="container"></div>
  23. <!-- Import maps polyfill -->
  24. <!-- Remove this when import maps will be widely supported -->
  25. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  26. <script type="importmap">
  27. {
  28. "imports": {
  29. "three": "../build/three.module.js",
  30. "three/addons/": "./jsm/"
  31. }
  32. }
  33. </script>
  34. <script type="module">
  35. import * as THREE from 'three';
  36. import Stats from 'three/addons/libs/stats.module.js';
  37. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  38. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  39. import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
  40. let container, stats, gui, guiStatsEl;
  41. let camera, controls, scene, renderer, material;
  42. // gui
  43. const Method = {
  44. INSTANCED: 'INSTANCED',
  45. MERGED: 'MERGED',
  46. NAIVE: 'NAIVE'
  47. };
  48. const api = {
  49. method: Method.INSTANCED,
  50. count: 1000
  51. };
  52. //
  53. init();
  54. initMesh();
  55. animate();
  56. //
  57. function clean() {
  58. const meshes = [];
  59. scene.traverse( function ( object ) {
  60. if ( object.isMesh ) meshes.push( object );
  61. } );
  62. for ( let i = 0; i < meshes.length; i ++ ) {
  63. const mesh = meshes[ i ];
  64. mesh.material.dispose();
  65. mesh.geometry.dispose();
  66. scene.remove( mesh );
  67. }
  68. }
  69. const randomizeMatrix = function () {
  70. const position = new THREE.Vector3();
  71. const rotation = new THREE.Euler();
  72. const quaternion = new THREE.Quaternion();
  73. const scale = new THREE.Vector3();
  74. return function ( matrix ) {
  75. position.x = Math.random() * 40 - 20;
  76. position.y = Math.random() * 40 - 20;
  77. position.z = Math.random() * 40 - 20;
  78. rotation.x = Math.random() * 2 * Math.PI;
  79. rotation.y = Math.random() * 2 * Math.PI;
  80. rotation.z = Math.random() * 2 * Math.PI;
  81. quaternion.setFromEuler( rotation );
  82. scale.x = scale.y = scale.z = Math.random() * 1;
  83. matrix.compose( position, quaternion, scale );
  84. };
  85. }();
  86. function initMesh() {
  87. clean();
  88. // make instances
  89. new THREE.BufferGeometryLoader()
  90. .setPath( 'models/json/' )
  91. .load( 'suzanne_buffergeometry.json', function ( geometry ) {
  92. material = new THREE.MeshNormalMaterial();
  93. geometry.computeVertexNormals();
  94. console.time( api.method + ' (build)' );
  95. switch ( api.method ) {
  96. case Method.INSTANCED:
  97. makeInstanced( geometry );
  98. break;
  99. case Method.MERGED:
  100. makeMerged( geometry );
  101. break;
  102. case Method.NAIVE:
  103. makeNaive( geometry );
  104. break;
  105. }
  106. console.timeEnd( api.method + ' (build)' );
  107. } );
  108. }
  109. function makeInstanced( geometry ) {
  110. const matrix = new THREE.Matrix4();
  111. const mesh = new THREE.InstancedMesh( geometry, material, api.count );
  112. for ( let i = 0; i < api.count; i ++ ) {
  113. randomizeMatrix( matrix );
  114. mesh.setMatrixAt( i, matrix );
  115. }
  116. scene.add( mesh );
  117. //
  118. const geometryByteLength = getGeometryByteLength( geometry );
  119. guiStatsEl.innerHTML = [
  120. '<i>GPU draw calls</i>: 1',
  121. '<i>GPU memory</i>: ' + formatBytes( api.count * 16 + geometryByteLength, 2 )
  122. ].join( '<br/>' );
  123. }
  124. function makeMerged( geometry ) {
  125. const geometries = [];
  126. const matrix = new THREE.Matrix4();
  127. for ( let i = 0; i < api.count; i ++ ) {
  128. randomizeMatrix( matrix );
  129. const instanceGeometry = geometry.clone();
  130. instanceGeometry.applyMatrix4( matrix );
  131. geometries.push( instanceGeometry );
  132. }
  133. const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries( geometries );
  134. scene.add( new THREE.Mesh( mergedGeometry, material ) );
  135. //
  136. guiStatsEl.innerHTML = [
  137. '<i>GPU draw calls</i>: 1',
  138. '<i>GPU memory</i>: ' + formatBytes( getGeometryByteLength( mergedGeometry ), 2 )
  139. ].join( '<br/>' );
  140. }
  141. function makeNaive( geometry ) {
  142. const matrix = new THREE.Matrix4();
  143. for ( let i = 0; i < api.count; i ++ ) {
  144. randomizeMatrix( matrix );
  145. const mesh = new THREE.Mesh( geometry, material );
  146. mesh.applyMatrix4( matrix );
  147. scene.add( mesh );
  148. }
  149. //
  150. const geometryByteLength = getGeometryByteLength( geometry );
  151. guiStatsEl.innerHTML = [
  152. '<i>GPU draw calls</i>: ' + api.count,
  153. '<i>GPU memory</i>: ' + formatBytes( api.count * 16 + geometryByteLength, 2 )
  154. ].join( '<br/>' );
  155. }
  156. function init() {
  157. const width = window.innerWidth;
  158. const height = window.innerHeight;
  159. // camera
  160. camera = new THREE.PerspectiveCamera( 70, width / height, 1, 100 );
  161. camera.position.z = 30;
  162. // renderer
  163. renderer = new THREE.WebGLRenderer( { antialias: true } );
  164. renderer.setPixelRatio( window.devicePixelRatio );
  165. renderer.setSize( width, height );
  166. renderer.outputEncoding = THREE.sRGBEncoding;
  167. container = document.getElementById( 'container' );
  168. container.appendChild( renderer.domElement );
  169. // scene
  170. scene = new THREE.Scene();
  171. scene.background = new THREE.Color( 0xffffff );
  172. // controls
  173. controls = new OrbitControls( camera, renderer.domElement );
  174. controls.autoRotate = true;
  175. // stats
  176. stats = new Stats();
  177. container.appendChild( stats.dom );
  178. // gui
  179. gui = new GUI();
  180. gui.add( api, 'method', Method ).onChange( initMesh );
  181. gui.add( api, 'count', 1, 10000 ).step( 1 ).onChange( initMesh );
  182. const perfFolder = gui.addFolder( 'Performance' );
  183. guiStatsEl = document.createElement( 'div' );
  184. guiStatsEl.classList.add( 'gui-stats' );
  185. perfFolder.$children.appendChild( guiStatsEl );
  186. perfFolder.open();
  187. // listeners
  188. window.addEventListener( 'resize', onWindowResize );
  189. Object.assign( window, { scene } );
  190. }
  191. //
  192. function onWindowResize() {
  193. const width = window.innerWidth;
  194. const height = window.innerHeight;
  195. camera.aspect = width / height;
  196. camera.updateProjectionMatrix();
  197. renderer.setSize( width, height );
  198. }
  199. function animate() {
  200. requestAnimationFrame( animate );
  201. controls.update();
  202. stats.update();
  203. render();
  204. }
  205. function render() {
  206. renderer.render( scene, camera );
  207. }
  208. //
  209. function getGeometryByteLength( geometry ) {
  210. let total = 0;
  211. if ( geometry.index ) total += geometry.index.array.byteLength;
  212. for ( const name in geometry.attributes ) {
  213. total += geometry.attributes[ name ].array.byteLength;
  214. }
  215. return total;
  216. }
  217. // Source: https://stackoverflow.com/a/18650828/1314762
  218. function formatBytes( bytes, decimals ) {
  219. if ( bytes === 0 ) return '0 bytes';
  220. const k = 1024;
  221. const dm = decimals < 0 ? 0 : decimals;
  222. const sizes = [ 'bytes', 'KB', 'MB' ];
  223. const i = Math.floor( Math.log( bytes ) / Math.log( k ) );
  224. return parseFloat( ( bytes / Math.pow( k, i ) ).toFixed( dm ) ) + ' ' + sizes[ i ];
  225. }
  226. </script>
  227. </body>
  228. </html>