webgl_instancing_scatter.html 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - instancing - scatter</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. </head>
  9. <body>
  10. <!-- Import maps polyfill -->
  11. <!-- Remove this when import maps will be widely supported -->
  12. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  13. <script type="importmap">
  14. {
  15. "imports": {
  16. "three": "../build/three.module.js",
  17. "three/addons/": "./jsm/"
  18. }
  19. }
  20. </script>
  21. <script type="module">
  22. import * as THREE from 'three';
  23. import { MeshSurfaceSampler } from 'three/addons/math/MeshSurfaceSampler.js';
  24. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  25. import Stats from 'three/addons/libs/stats.module.js';
  26. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  27. let camera, scene, renderer, stats;
  28. const api = {
  29. count: 2000,
  30. distribution: 'random',
  31. resample: resample,
  32. surfaceColor: 0xFFF784,
  33. backgroundColor: 0xE39469,
  34. };
  35. let stemMesh, blossomMesh;
  36. let stemGeometry, blossomGeometry;
  37. let stemMaterial, blossomMaterial;
  38. let sampler;
  39. const count = api.count;
  40. const ages = new Float32Array( count );
  41. const scales = new Float32Array( count );
  42. const dummy = new THREE.Object3D();
  43. const _position = new THREE.Vector3();
  44. const _normal = new THREE.Vector3();
  45. const _scale = new THREE.Vector3();
  46. // let surfaceGeometry = new THREE.BoxGeometry( 10, 10, 10 ).toNonIndexed();
  47. const surfaceGeometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 ).toNonIndexed();
  48. const surfaceMaterial = new THREE.MeshLambertMaterial( { color: api.surfaceColor, wireframe: false } );
  49. const surface = new THREE.Mesh( surfaceGeometry, surfaceMaterial );
  50. // Source: https://gist.github.com/gre/1650294
  51. const easeOutCubic = function ( t ) {
  52. return ( -- t ) * t * t + 1;
  53. };
  54. // Scaling curve causes particles to grow quickly, ease gradually into full scale, then
  55. // disappear quickly. More of the particle's lifetime is spent around full scale.
  56. const scaleCurve = function ( t ) {
  57. return Math.abs( easeOutCubic( ( t > 0.5 ? 1 - t : t ) * 2 ) );
  58. };
  59. const loader = new GLTFLoader();
  60. loader.load( './models/gltf/Flower/Flower.glb', function ( gltf ) {
  61. const _stemMesh = gltf.scene.getObjectByName( 'Stem' );
  62. const _blossomMesh = gltf.scene.getObjectByName( 'Blossom' );
  63. stemGeometry = _stemMesh.geometry.clone();
  64. blossomGeometry = _blossomMesh.geometry.clone();
  65. const defaultTransform = new THREE.Matrix4()
  66. .makeRotationX( Math.PI )
  67. .multiply( new THREE.Matrix4().makeScale( 7, 7, 7 ) );
  68. stemGeometry.applyMatrix4( defaultTransform );
  69. blossomGeometry.applyMatrix4( defaultTransform );
  70. stemMaterial = _stemMesh.material;
  71. blossomMaterial = _blossomMesh.material;
  72. stemMesh = new THREE.InstancedMesh( stemGeometry, stemMaterial, count );
  73. blossomMesh = new THREE.InstancedMesh( blossomGeometry, blossomMaterial, count );
  74. // Assign random colors to the blossoms.
  75. const color = new THREE.Color();
  76. const blossomPalette = [ 0xF20587, 0xF2D479, 0xF2C879, 0xF2B077, 0xF24405 ];
  77. for ( let i = 0; i < count; i ++ ) {
  78. color.setHex( blossomPalette[ Math.floor( Math.random() * blossomPalette.length ) ] );
  79. blossomMesh.setColorAt( i, color );
  80. }
  81. // Instance matrices will be updated every frame.
  82. stemMesh.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
  83. blossomMesh.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
  84. resample();
  85. init();
  86. animate();
  87. } );
  88. function init() {
  89. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 100 );
  90. camera.position.set( 25, 25, 25 );
  91. camera.lookAt( 0, 0, 0 );
  92. //
  93. scene = new THREE.Scene();
  94. scene.background = new THREE.Color( api.backgroundColor );
  95. const pointLight = new THREE.PointLight( 0xAA8899, 0.75 );
  96. pointLight.position.set( 50, - 25, 75 );
  97. scene.add( pointLight );
  98. scene.add( new THREE.HemisphereLight() );
  99. //
  100. scene.add( stemMesh );
  101. scene.add( blossomMesh );
  102. scene.add( surface );
  103. //
  104. const gui = new GUI();
  105. gui.add( api, 'count', 0, count ).onChange( function () {
  106. stemMesh.count = api.count;
  107. blossomMesh.count = api.count;
  108. } );
  109. // gui.addColor( api, 'backgroundColor' ).onChange( function () {
  110. // scene.background.setHex( api.backgroundColor );
  111. // } );
  112. // gui.addColor( api, 'surfaceColor' ).onChange( function () {
  113. // surfaceMaterial.color.setHex( api.surfaceColor );
  114. // } );
  115. gui.add( api, 'distribution' ).options( [ 'random', 'weighted' ] ).onChange( resample );
  116. gui.add( api, 'resample' );
  117. //
  118. renderer = new THREE.WebGLRenderer( { antialias: true } );
  119. renderer.setPixelRatio( window.devicePixelRatio );
  120. renderer.setSize( window.innerWidth, window.innerHeight );
  121. document.body.appendChild( renderer.domElement );
  122. //
  123. stats = new Stats();
  124. document.body.appendChild( stats.dom );
  125. //
  126. window.addEventListener( 'resize', onWindowResize );
  127. }
  128. function resample() {
  129. const vertexCount = surface.geometry.getAttribute( 'position' ).count;
  130. console.info( 'Sampling ' + count + ' points from a surface with ' + vertexCount + ' vertices...' );
  131. //
  132. console.time( '.build()' );
  133. sampler = new MeshSurfaceSampler( surface )
  134. .setWeightAttribute( api.distribution === 'weighted' ? 'uv' : null )
  135. .build();
  136. console.timeEnd( '.build()' );
  137. //
  138. console.time( '.sample()' );
  139. for ( let i = 0; i < count; i ++ ) {
  140. ages[ i ] = Math.random();
  141. scales[ i ] = scaleCurve( ages[ i ] );
  142. resampleParticle( i );
  143. }
  144. console.timeEnd( '.sample()' );
  145. stemMesh.instanceMatrix.needsUpdate = true;
  146. blossomMesh.instanceMatrix.needsUpdate = true;
  147. }
  148. function resampleParticle( i ) {
  149. sampler.sample( _position, _normal );
  150. _normal.add( _position );
  151. dummy.position.copy( _position );
  152. dummy.scale.set( scales[ i ], scales[ i ], scales[ i ] );
  153. dummy.lookAt( _normal );
  154. dummy.updateMatrix();
  155. stemMesh.setMatrixAt( i, dummy.matrix );
  156. blossomMesh.setMatrixAt( i, dummy.matrix );
  157. }
  158. function updateParticle( i ) {
  159. // Update lifecycle.
  160. ages[ i ] += 0.005;
  161. if ( ages[ i ] >= 1 ) {
  162. ages[ i ] = 0.001;
  163. scales[ i ] = scaleCurve( ages[ i ] );
  164. resampleParticle( i );
  165. return;
  166. }
  167. // Update scale.
  168. const prevScale = scales[ i ];
  169. scales[ i ] = scaleCurve( ages[ i ] );
  170. _scale.set( scales[ i ] / prevScale, scales[ i ] / prevScale, scales[ i ] / prevScale );
  171. // Update transform.
  172. stemMesh.getMatrixAt( i, dummy.matrix );
  173. dummy.matrix.scale( _scale );
  174. stemMesh.setMatrixAt( i, dummy.matrix );
  175. blossomMesh.setMatrixAt( i, dummy.matrix );
  176. }
  177. function onWindowResize() {
  178. camera.aspect = window.innerWidth / window.innerHeight;
  179. camera.updateProjectionMatrix();
  180. renderer.setSize( window.innerWidth, window.innerHeight );
  181. }
  182. //
  183. function animate() {
  184. requestAnimationFrame( animate );
  185. render();
  186. stats.update();
  187. }
  188. function render() {
  189. if ( stemMesh && blossomMesh ) {
  190. const time = Date.now() * 0.001;
  191. scene.rotation.x = Math.sin( time / 4 );
  192. scene.rotation.y = Math.sin( time / 2 );
  193. for ( let i = 0; i < api.count; i ++ ) {
  194. updateParticle( i );
  195. }
  196. stemMesh.instanceMatrix.needsUpdate = true;
  197. blossomMesh.instanceMatrix.needsUpdate = true;
  198. stemMesh.computeBoundingSphere();
  199. blossomMesh.computeBoundingSphere();
  200. }
  201. renderer.render( scene, camera );
  202. }
  203. </script>
  204. </body>
  205. </html>