webgl_particles_shapes.html 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - particles - shapes</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. <style>
  8. body {
  9. font-family: Monospace;
  10. color: #aaa;
  11. background-color: #000;
  12. margin: 0px;
  13. overflow: hidden;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <script src="../build/three.min.js"></script>
  19. <script src="js/libs/stats.min.js"></script>
  20. <script src="js/libs/tween.min.js"></script>
  21. <script src="js/Sparks.js"></script>
  22. <script src="js/shaders/CopyShader.js"></script>
  23. <script src="js/shaders/FilmShader.js"></script>
  24. <script src="js/shaders/FocusShader.js"></script>
  25. <script src="js/shaders/HorizontalBlurShader.js"></script>
  26. <script src="js/shaders/TriangleBlurShader.js"></script>
  27. <script src="js/shaders/VerticalBlurShader.js"></script>
  28. <script src="js/postprocessing/EffectComposer.js"></script>
  29. <script src="js/postprocessing/RenderPass.js"></script>
  30. <script src="js/postprocessing/ShaderPass.js"></script>
  31. <script src="js/postprocessing/MaskPass.js"></script>
  32. <script src="js/postprocessing/BloomPass.js"></script>
  33. <script src="js/postprocessing/FilmPass.js"></script>
  34. <!-- load the font file from canvas-text -->
  35. <script src="fonts/helvetiker_regular.typeface.js"></script>
  36. <script type="x-shader/x-vertex" id="vertexshader">
  37. attribute float size;
  38. attribute vec3 pcolor;
  39. varying vec3 vColor;
  40. void main() {
  41. vColor = pcolor;
  42. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  43. gl_PointSize = size * ( 200.0 / length( mvPosition.xyz ) );
  44. gl_Position = projectionMatrix * mvPosition;
  45. }
  46. </script>
  47. <script type="x-shader/x-fragment" id="fragmentshader">
  48. uniform sampler2D texture;
  49. varying vec3 vColor;
  50. void main() {
  51. vec4 outColor = texture2D( texture, gl_PointCoord );
  52. gl_FragColor = outColor * vec4( vColor, 1.0 );
  53. }
  54. </script>
  55. <script>
  56. var container, stats;
  57. var camera, scene, renderer;
  58. var group, text, plane;
  59. var speed = 50;
  60. var pointLight;
  61. var targetRotation = 0;
  62. var targetRotationOnMouseDown = 0;
  63. var mouseX = 0;
  64. var mouseXOnMouseDown = 0;
  65. var windowHalfX = window.innerWidth / 2;
  66. var windowHalfY = window.innerHeight / 2;
  67. var delta = 1, clock = new THREE.Clock();
  68. var heartShape, particleCloud, sparksEmitter, emitterPos;
  69. var _rotation = 0;
  70. var timeOnShapePath = 0;
  71. var composer;
  72. var effectBlurX, effectBlurY, hblur, vblur;
  73. init();
  74. animate();
  75. function init() {
  76. container = document.createElement( 'div' );
  77. document.body.appendChild( container );
  78. var info = document.createElement( 'div' );
  79. info.style.position = 'absolute';
  80. info.style.top = '10px';
  81. info.style.width = '100%';
  82. info.style.textAlign = 'center';
  83. info.innerHTML = 'Three.js - simple particle systems with shapes by <a href="http://www.lab4games.net/zz85/blog">zz85</a><br>Move your mouse. Click to pause/resume.';
  84. container.appendChild( info );
  85. // CAMERA
  86. camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 2000 );
  87. camera.position.set( 0, 150, 400 );
  88. // SCENE
  89. scene = new THREE.Scene();
  90. // LIGHTS
  91. var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  92. directionalLight.position.set( 0, -1, 1 );
  93. directionalLight.position.normalize();
  94. scene.add( directionalLight );
  95. pointLight = new THREE.PointLight( 0xffffff, 2, 300 );
  96. pointLight.position.set( 0, 0, 0 );
  97. scene.add( pointLight );
  98. // TEXT
  99. var theText = "THREE.JS";
  100. // Get text from hash
  101. var hash = document.location.hash.substr( 1 );
  102. if ( hash.length !== 0 ) {
  103. theText = hash;
  104. }
  105. var material = new THREE.MeshFaceMaterial( [
  106. new THREE.MeshLambertMaterial( { color: 0xffffff, shading: THREE.FlatShading, opacity: 0.95 } ),
  107. new THREE.MeshLambertMaterial( { color: 0xffffff } )
  108. ] );
  109. var text3d = new THREE.TextGeometry( theText, {
  110. size: 70,
  111. height: 25,
  112. curveSegments: 4,
  113. font: "helvetiker",
  114. bevelEnabled: true,
  115. bevelThickness: 2,
  116. bevelSize: 2,
  117. material: 0,
  118. extrudeMaterial: 1
  119. });
  120. text3d.computeVertexNormals();
  121. text3d.computeBoundingBox();
  122. var centerOffset = -0.5 * ( text3d.boundingBox.max.x - text3d.boundingBox.min.x );
  123. group = new THREE.Group();
  124. scene.add( group );
  125. text = new THREE.Mesh( text3d, material );
  126. // Potentially, we can extract the vertices or faces of the text to generate particles too.
  127. // Geo > Vertices > Position
  128. text.position.x = centerOffset;
  129. text.position.y = 130;
  130. text.position.z = -50;
  131. text.rotation.x = 0;
  132. text.rotation.y = Math.PI * 2;
  133. group.add( text );
  134. // Create particle objects for Three.js
  135. var particlesLength = 70000;
  136. var particles = new THREE.Geometry();
  137. function newpos( x, y, z ) {
  138. return new THREE.Vector3( x, y, z );
  139. }
  140. var Pool = {
  141. __pools: [],
  142. // Get a new Vector
  143. get: function() {
  144. if ( this.__pools.length > 0 ) {
  145. return this.__pools.pop();
  146. }
  147. console.log( "pool ran out!" )
  148. return null;
  149. },
  150. // Release a vector back into the pool
  151. add: function( v ) {
  152. this.__pools.push( v );
  153. }
  154. };
  155. for ( i = 0; i < particlesLength; i ++ ) {
  156. particles.vertices.push( newpos( Math.random() * 200 - 100, Math.random() * 100 + 150, Math.random() * 50 ) );
  157. Pool.add( i );
  158. }
  159. // Create pools of vectors
  160. attributes = {
  161. size: { type: 'f', value: [] },
  162. pcolor: { type: 'c', value: [] }
  163. };
  164. var sprite = generateSprite() ;
  165. texture = new THREE.Texture( sprite );
  166. texture.needsUpdate = true;
  167. uniforms = {
  168. texture: { type: "t", value: texture }
  169. };
  170. // PARAMETERS
  171. // Steadycounter
  172. // Life
  173. // Opacity
  174. // Hue Speed
  175. // Movement Speed
  176. function generateSprite() {
  177. var canvas = document.createElement( 'canvas' );
  178. canvas.width = 128;
  179. canvas.height = 128;
  180. var context = canvas.getContext( '2d' );
  181. // Just a square, doesnt work too bad with blur pp.
  182. // context.fillStyle = "white";
  183. // context.strokeStyle = "white";
  184. // context.fillRect(0, 0, 63, 63) ;
  185. // Heart Shapes are not too pretty here
  186. // var x = 4, y = 0;
  187. // context.save();
  188. // context.scale(8, 8); // Scale so canvas render can redraw within bounds
  189. // context.beginPath();
  190. // context.bezierCurveTo( x + 2.5, y + 2.5, x + 2.0, y, x, y );
  191. // context.bezierCurveTo( x - 3.0, y, x - 3.0, y + 3.5,x - 3.0,y + 3.5 );
  192. // context.bezierCurveTo( x - 3.0, y + 5.5, x - 1.0, y + 7.7, x + 2.5, y + 9.5 );
  193. // context.bezierCurveTo( x + 6.0, y + 7.7, x + 8.0, y + 5.5, x + 8.0, y + 3.5 );
  194. // context.bezierCurveTo( x + 8.0, y + 3.5, x + 8.0, y, x + 5.0, y );
  195. // context.bezierCurveTo( x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5 );
  196. context.beginPath();
  197. context.arc( 64, 64, 60, 0, Math.PI * 2, false) ;
  198. context.lineWidth = 0.5; //0.05
  199. context.stroke();
  200. context.restore();
  201. var gradient = context.createRadialGradient( canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2 );
  202. gradient.addColorStop( 0, 'rgba(255,255,255,1)' );
  203. gradient.addColorStop( 0.2, 'rgba(255,255,255,1)' );
  204. gradient.addColorStop( 0.4, 'rgba(200,200,200,1)' );
  205. gradient.addColorStop( 1, 'rgba(0,0,0,1)' );
  206. context.fillStyle = gradient;
  207. context.fill();
  208. return canvas;
  209. }
  210. var shaderMaterial = new THREE.ShaderMaterial( {
  211. uniforms: uniforms,
  212. attributes: attributes,
  213. vertexShader: document.getElementById( 'vertexshader' ).textContent,
  214. fragmentShader: document.getElementById( 'fragmentshader' ).textContent,
  215. blending: THREE.AdditiveBlending,
  216. depthWrite: false,
  217. transparent: true
  218. });
  219. particleCloud = new THREE.PointCloud( particles, shaderMaterial );
  220. var vertices = particleCloud.geometry.vertices;
  221. var values_size = attributes.size.value;
  222. var values_color = attributes.pcolor.value;
  223. for( var v = 0; v < vertices.length; v ++ ) {
  224. values_size[ v ] = 50;
  225. values_color[ v ] = new THREE.Color( 0x000000 );
  226. particles.vertices[ v ].set( Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY );
  227. }
  228. group.add( particleCloud );
  229. particleCloud.y = 800;
  230. // Create Particle Systems
  231. // EMITTER STUFF
  232. // Heart
  233. var x = 0, y = 0;
  234. heartShape = new THREE.Shape();
  235. heartShape.moveTo( x + 25, y + 25 );
  236. heartShape.bezierCurveTo( x + 25, y + 25, x + 20, y, x, y );
  237. heartShape.bezierCurveTo( x - 30, y, x - 30, y + 35,x - 30,y + 35 );
  238. heartShape.bezierCurveTo( x - 30, y + 55, x - 10, y + 77, x + 25, y + 95 );
  239. heartShape.bezierCurveTo( x + 60, y + 77, x + 80, y + 55, x + 80, y + 35 );
  240. heartShape.bezierCurveTo( x + 80, y + 35, x + 80, y, x + 50, y );
  241. heartShape.bezierCurveTo( x + 35, y, x + 25, y + 25, x + 25, y + 25 );
  242. var hue = 0;
  243. var setTargetParticle = function() {
  244. var target = Pool.get();
  245. values_size[ target ] = Math.random() * 200 + 100;
  246. return target;
  247. };
  248. var onParticleCreated = function( p ) {
  249. var position = p.position;
  250. p.target.position = position;
  251. var target = p.target;
  252. if ( target ) {
  253. // console.log(target,particles.vertices[target]);
  254. // values_size[target]
  255. // values_color[target]
  256. hue += 0.0003 * delta;
  257. if ( hue > 1 ) hue -= 1;
  258. // TODO Create a PointOnShape Action/Zone in the particle engine
  259. timeOnShapePath += 0.00035 * delta;
  260. if ( timeOnShapePath > 1 ) timeOnShapePath -= 1;
  261. var pointOnShape = heartShape.getPointAt( timeOnShapePath );
  262. emitterpos.x = pointOnShape.x * 5 - 100;
  263. emitterpos.y = -pointOnShape.y * 5 + 400;
  264. // pointLight.position.copy( emitterpos );
  265. pointLight.position.x = emitterpos.x;
  266. pointLight.position.y = emitterpos.y;
  267. pointLight.position.z = 100;
  268. particles.vertices[ target ] = p.position;
  269. values_color[ target ].setHSL( hue, 0.6, 0.1 );
  270. pointLight.color.setHSL( hue, 0.8, 0.5 );
  271. };
  272. };
  273. var onParticleDead = function( particle ) {
  274. var target = particle.target;
  275. if ( target ) {
  276. // Hide the particle
  277. values_color[ target ].setRGB( 0, 0, 0 );
  278. particles.vertices[ target ].set( Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY );
  279. // Mark particle system as available by returning to pool
  280. Pool.add( particle.target );
  281. }
  282. };
  283. var engineLoopUpdate = function() {
  284. };
  285. sparksEmitter = new SPARKS.Emitter( new SPARKS.SteadyCounter( 500 ) );
  286. emitterpos = new THREE.Vector3( 0, 0, 0 );
  287. sparksEmitter.addInitializer( new SPARKS.Position( new SPARKS.PointZone( emitterpos ) ) );
  288. sparksEmitter.addInitializer( new SPARKS.Lifetime( 1, 15 ));
  289. sparksEmitter.addInitializer( new SPARKS.Target( null, setTargetParticle ) );
  290. sparksEmitter.addInitializer( new SPARKS.Velocity( new SPARKS.PointZone( new THREE.Vector3( 0, -5, 1 ) ) ) );
  291. sparksEmitter.addAction( new SPARKS.Age() );
  292. sparksEmitter.addAction( new SPARKS.Accelerate( 0, 0, -50 ) );
  293. sparksEmitter.addAction( new SPARKS.Move() );
  294. sparksEmitter.addAction( new SPARKS.RandomDrift( 90, 100, 2000 ) );
  295. sparksEmitter.addCallback( "created", onParticleCreated );
  296. sparksEmitter.addCallback( "dead", onParticleDead );
  297. sparksEmitter.start();
  298. // End Particles
  299. renderer = new THREE.WebGLRenderer();
  300. renderer.setPixelRatio( window.devicePixelRatio );
  301. renderer.setSize( window.innerWidth, window.innerHeight );
  302. container.appendChild( renderer.domElement );
  303. stats = new Stats();
  304. stats.domElement.style.position = 'absolute';
  305. stats.domElement.style.top = '0px';
  306. container.appendChild( stats.domElement );
  307. // POST PROCESSING
  308. var effectFocus = new THREE.ShaderPass( THREE.FocusShader );
  309. var effectCopy = new THREE.ShaderPass( THREE.CopyShader );
  310. effectFilm = new THREE.FilmPass( 0.5, 0.25, 2048, false );
  311. var shaderBlur = THREE.TriangleBlurShader;
  312. effectBlurX = new THREE.ShaderPass( shaderBlur, 'texture' );
  313. effectBlurY = new THREE.ShaderPass( shaderBlur, 'texture' );
  314. var radius = 15;
  315. var blurAmountX = radius / window.innerWidth;
  316. var blurAmountY = radius / window.innerHeight;
  317. hblur = new THREE.ShaderPass( THREE.HorizontalBlurShader );
  318. vblur = new THREE.ShaderPass( THREE.VerticalBlurShader);
  319. hblur.uniforms[ 'h' ].value = 1 / window.innerWidth;
  320. vblur.uniforms[ 'v' ].value = 1 / window.innerHeight;
  321. effectBlurX.uniforms[ 'delta' ].value = new THREE.Vector2( blurAmountX, 0 );
  322. effectBlurY.uniforms[ 'delta' ].value = new THREE.Vector2( 0, blurAmountY );
  323. effectFocus.uniforms[ 'sampleDistance' ].value = 0.99; //0.94
  324. effectFocus.uniforms[ 'waveFactor' ].value = 0.003; //0.00125
  325. var renderScene = new THREE.RenderPass( scene, camera );
  326. composer = new THREE.EffectComposer( renderer );
  327. composer.addPass( renderScene );
  328. composer.addPass( hblur );
  329. composer.addPass( vblur );
  330. // composer.addPass( effectBlurX );
  331. // composer.addPass( effectBlurY );
  332. // composer.addPass( effectCopy );
  333. // composer.addPass( effectFocus );
  334. // composer.addPass( effectFilm );
  335. vblur.renderToScreen = true;
  336. effectBlurY.renderToScreen = true;
  337. effectFocus.renderToScreen = true;
  338. effectCopy.renderToScreen = true;
  339. effectFilm.renderToScreen = true;
  340. document.addEventListener( 'mousedown', onDocumentMouseDown, false );
  341. document.addEventListener( 'touchstart', onDocumentTouchStart, false );
  342. document.addEventListener( 'touchmove', onDocumentTouchMove, false );
  343. //
  344. window.addEventListener( 'resize', onWindowResize, false );
  345. }
  346. function onWindowResize() {
  347. windowHalfX = window.innerWidth / 2;
  348. windowHalfY = window.innerHeight / 2;
  349. camera.aspect = window.innerWidth / window.innerHeight;
  350. camera.updateProjectionMatrix();
  351. renderer.setSize( window.innerWidth, window.innerHeight );
  352. //
  353. hblur.uniforms[ 'h' ].value = 1 / window.innerWidth;
  354. vblur.uniforms[ 'v' ].value = 1 / window.innerHeight;
  355. var radius = 15;
  356. var blurAmountX = radius / window.innerWidth;
  357. var blurAmountY = radius / window.innerHeight;
  358. effectBlurX.uniforms[ 'delta' ].value = new THREE.Vector2( blurAmountX, 0 );
  359. effectBlurY.uniforms[ 'delta' ].value = new THREE.Vector2( 0, blurAmountY );
  360. composer.reset();
  361. }
  362. //
  363. document.addEventListener( 'mousemove', onDocumentMouseMove, false );
  364. function onDocumentMouseDown( event ) {
  365. event.preventDefault();
  366. mouseXOnMouseDown = event.clientX - windowHalfX;
  367. targetRotationOnMouseDown = targetRotation;
  368. if ( sparksEmitter.isRunning() ) {
  369. sparksEmitter.stop();
  370. } else {
  371. sparksEmitter.start();
  372. }
  373. }
  374. function onDocumentMouseMove( event ) {
  375. mouseX = event.clientX - windowHalfX;
  376. targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.02;
  377. }
  378. function onDocumentTouchStart( event ) {
  379. if ( event.touches.length === 1 ) {
  380. event.preventDefault();
  381. mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX;
  382. targetRotationOnMouseDown = targetRotation;
  383. }
  384. }
  385. function onDocumentTouchMove( event ) {
  386. if ( event.touches.length === 1 ) {
  387. event.preventDefault();
  388. mouseX = event.touches[ 0 ].pageX - windowHalfX;
  389. targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05;
  390. }
  391. }
  392. //
  393. function animate() {
  394. requestAnimationFrame( animate );
  395. render();
  396. stats.update();
  397. }
  398. function render() {
  399. delta = speed * clock.getDelta();
  400. particleCloud.geometry.verticesNeedUpdate = true;
  401. attributes.size.needsUpdate = true;
  402. attributes.pcolor.needsUpdate = true;
  403. // Pretty cool effect if you enable this
  404. // particleCloud.rotation.y += 0.05;
  405. group.rotation.y += ( targetRotation - group.rotation.y ) * 0.05;
  406. renderer.clear();
  407. // renderer.render( scene, camera );
  408. composer.render( 0.1 );
  409. }
  410. </script>
  411. </body>
  412. </html>