webgl_instancing_scatter.html 7.7 KB

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