webgl_particles_shapes.html 16 KB

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