webgl_instancing_scatter.html 7.6 KB

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