webgl_tsl_instancing.html 8.0 KB

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