webgl_instancing_scatter.html 7.7 KB

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