webgl_tsl_instancing.html 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. <script type="importmap">
  24. {
  25. "imports": {
  26. "three": "../build/three.module.js",
  27. "three/webgpu": "../build/three.webgpu.js",
  28. "three/addons/": "./jsm/",
  29. "three/tsl": "../build/three.tsl.js"
  30. }
  31. }
  32. </script>
  33. <script type="module">
  34. import * as THREE from 'three';
  35. import { WebGLNodesHandler } from 'three/addons/tsl/WebGLNodesHandler.js';
  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. import { MeshPhongNodeMaterial } from 'three/webgpu';
  41. import { sin, time, vec3, positionWorld } from 'three/tsl';
  42. let container, stats, gui, guiStatsEl;
  43. let camera, controls, scene, renderer, material;
  44. // gui
  45. const Method = {
  46. INSTANCED: 'INSTANCED',
  47. MERGED: 'MERGED',
  48. NAIVE: 'NAIVE'
  49. };
  50. const api = {
  51. method: Method.INSTANCED,
  52. count: 1000
  53. };
  54. //
  55. init();
  56. initMesh();
  57. //
  58. function clean() {
  59. const meshes = [];
  60. scene.traverse( function ( object ) {
  61. if ( object.isMesh ) meshes.push( object );
  62. } );
  63. for ( let i = 0; i < meshes.length; i ++ ) {
  64. const mesh = meshes[ i ];
  65. mesh.material.dispose();
  66. mesh.geometry.dispose();
  67. scene.remove( mesh );
  68. }
  69. }
  70. const randomizeMatrix = function () {
  71. const position = new THREE.Vector3();
  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. quaternion.random();
  79. scale.x = scale.y = scale.z = Math.random() * 1;
  80. matrix.compose( position, quaternion, scale );
  81. };
  82. }();
  83. function initMesh() {
  84. clean();
  85. // make instances
  86. new THREE.BufferGeometryLoader()
  87. .setPath( 'models/json/' )
  88. .load( 'suzanne_buffergeometry.json', function ( geometry ) {
  89. const posY = positionWorld;
  90. const t = time.mul( 4 );
  91. material = new MeshPhongNodeMaterial();
  92. material.colorNode = vec3(
  93. sin( posY.mul( 0.1 ).add( t ) ).mul( 0.5 ).add( 0.5 ).x,
  94. sin( posY.mul( 0.1 ).add( t.mul( 0.5 ).add( 2 ) ) ).mul( 0.5 ).add( 0.5 ).y,
  95. sin( posY.mul( 0.1 ).add( t.mul( 1.5 ).add( 4 ) ) ).mul( 0.5 ).add( 0.5 ).z,
  96. );
  97. geometry.computeVertexNormals();
  98. console.time( api.method + ' (build)' );
  99. switch ( api.method ) {
  100. case Method.INSTANCED:
  101. makeInstanced( geometry );
  102. break;
  103. case Method.MERGED:
  104. makeMerged( geometry );
  105. break;
  106. case Method.NAIVE:
  107. makeNaive( geometry );
  108. break;
  109. }
  110. console.timeEnd( api.method + ' (build)' );
  111. } );
  112. }
  113. function makeInstanced( geometry ) {
  114. const matrix = new THREE.Matrix4();
  115. const mesh = new THREE.InstancedMesh( geometry, material, api.count );
  116. for ( let i = 0; i < api.count; i ++ ) {
  117. randomizeMatrix( matrix );
  118. mesh.setMatrixAt( i, matrix );
  119. }
  120. scene.add( mesh );
  121. //
  122. const geometryByteLength = getGeometryByteLength( geometry );
  123. guiStatsEl.innerHTML = [
  124. '<i>GPU draw calls</i>: 1',
  125. '<i>GPU memory</i>: ' + formatBytes( api.count * 16 + geometryByteLength, 2 )
  126. ].join( '<br/>' );
  127. }
  128. function makeMerged( geometry ) {
  129. const geometries = [];
  130. const matrix = new THREE.Matrix4();
  131. for ( let i = 0; i < api.count; i ++ ) {
  132. randomizeMatrix( matrix );
  133. const instanceGeometry = geometry.clone();
  134. instanceGeometry.applyMatrix4( matrix );
  135. geometries.push( instanceGeometry );
  136. }
  137. const mergedGeometry = BufferGeometryUtils.mergeGeometries( geometries );
  138. scene.add( new THREE.Mesh( mergedGeometry, material ) );
  139. //
  140. guiStatsEl.innerHTML = [
  141. '<i>GPU draw calls</i>: 1',
  142. '<i>GPU memory</i>: ' + formatBytes( getGeometryByteLength( mergedGeometry ), 2 )
  143. ].join( '<br/>' );
  144. }
  145. function makeNaive( geometry ) {
  146. const matrix = new THREE.Matrix4();
  147. for ( let i = 0; i < api.count; i ++ ) {
  148. randomizeMatrix( matrix );
  149. const mesh = new THREE.Mesh( geometry, material );
  150. mesh.applyMatrix4( matrix );
  151. scene.add( mesh );
  152. }
  153. //
  154. const geometryByteLength = getGeometryByteLength( geometry );
  155. guiStatsEl.innerHTML = [
  156. '<i>GPU draw calls</i>: ' + api.count,
  157. '<i>GPU memory</i>: ' + formatBytes( api.count * 16 + geometryByteLength, 2 )
  158. ].join( '<br/>' );
  159. }
  160. function init() {
  161. const width = window.innerWidth;
  162. const height = window.innerHeight;
  163. // camera
  164. camera = new THREE.PerspectiveCamera( 70, width / height, 1, 100 );
  165. camera.position.z = 30;
  166. // renderer
  167. renderer = new THREE.WebGLRenderer( { antialias: true } );
  168. renderer.setNodesHandler( new WebGLNodesHandler() );
  169. renderer.setPixelRatio( window.devicePixelRatio );
  170. renderer.setSize( width, height );
  171. renderer.setAnimationLoop( animate );
  172. container = document.getElementById( 'container' );
  173. container.appendChild( renderer.domElement );
  174. // scene
  175. scene = new THREE.Scene();
  176. scene.background = new THREE.Color( 0xffffff );
  177. // controls
  178. controls = new OrbitControls( camera, renderer.domElement );
  179. controls.autoRotate = true;
  180. controls.autoRotateSpeed = 0.5;
  181. // light
  182. const ambientLight = new THREE.AmbientLight( 0xffffff, 2 );
  183. const directionalLight = new THREE.DirectionalLight( 0xffffff, 2 );
  184. directionalLight.position.set( 1, 1, 1 );
  185. scene.add( directionalLight, ambientLight );
  186. // stats
  187. stats = new Stats();
  188. container.appendChild( stats.dom );
  189. // gui
  190. gui = new GUI();
  191. gui.add( api, 'method', Method ).onChange( initMesh );
  192. gui.add( api, 'count', 1, 10000 ).step( 1 ).onChange( initMesh );
  193. const perfFolder = gui.addFolder( 'Performance' );
  194. guiStatsEl = document.createElement( 'div' );
  195. guiStatsEl.classList.add( 'gui-stats' );
  196. perfFolder.$children.appendChild( guiStatsEl );
  197. perfFolder.open();
  198. // listeners
  199. window.addEventListener( 'resize', onWindowResize );
  200. Object.assign( window, { scene } );
  201. }
  202. //
  203. function onWindowResize() {
  204. const width = window.innerWidth;
  205. const height = window.innerHeight;
  206. camera.aspect = width / height;
  207. camera.updateProjectionMatrix();
  208. renderer.setSize( width, height );
  209. }
  210. function animate() {
  211. controls.update();
  212. renderer.render( scene, camera );
  213. stats.update();
  214. }
  215. //
  216. function getGeometryByteLength( geometry ) {
  217. let total = 0;
  218. if ( geometry.index ) total += geometry.index.array.byteLength;
  219. for ( const name in geometry.attributes ) {
  220. total += geometry.attributes[ name ].array.byteLength;
  221. }
  222. return total;
  223. }
  224. // Source: https://stackoverflow.com/a/18650828/1314762
  225. function formatBytes( bytes, decimals ) {
  226. if ( bytes === 0 ) return '0 bytes';
  227. const k = 1024;
  228. const dm = decimals < 0 ? 0 : decimals;
  229. const sizes = [ 'bytes', 'KB', 'MB' ];
  230. const i = Math.floor( Math.log( bytes ) / Math.log( k ) );
  231. return parseFloat( ( bytes / Math.pow( k, i ) ).toFixed( dm ) ) + ' ' + sizes[ i ];
  232. }
  233. </script>
  234. </body>
  235. </html>
粤ICP备19079148号