### Initialize and Style Example Source: https://github.com/kellycode/shaderparticleengine/blob/master/examples/examples.html Sets up the initial module and applies styling to the selected element. Call this function to initialize a specific example module and update the UI. ```javascript let setStyle = function (elem) { // accepts an html element or an ID string if (typeof elem === "string") { elem = document.getElementById(elem); } // remove the existing active class for span (link) color document.querySelectorAll(".spanLink").forEach((element) => { element.classList.remove("activeItem"); }); // add the class to the new active span elem.classList.add("activeItem"); // for css to show the correct page elements document.body.className = ""; document.body.classList.add(elem.id); }; let modules = {}; import { ActiveMultiplier } from "./ActiveMultiplier.js"; modules["ActiveMultiplier"] = ActiveMultiplier; import { Basic } from "./Basic.js"; modules["Basic"] = Basic; import { Clock } from "./Clock.js"; modules["Clock"] = Clock; import { Clouds } from "./Clouds.js"; modules["Clouds"] = Clouds; import { Distributions } from "./Distributions.js"; modules["Distributions"] = Distributions; import { Explosion } from "./Explosion.js"; modules["Explosion"] = Explosion; import { Fog } from "./Fog.js"; modules["Fog"] = Fog; import { MouseFollow } from "./MouseFollow.js"; modules["MouseFollow"] = MouseFollow; import { MultipleEmitters } from "./MultipleEmitters.js"; modules["MultipleEmitters"] = MultipleEmitters; import { Orbit } from "./Orbit.js"; modules["Orbit"] = Orbit; import { Pool } from "./Pool.js"; modules["Pool"] = Pool; import { Rotation } from "./Rotation.js"; modules["Rotation"] = Rotation; import { RuntimeChanging } from "./RuntimeChanging.js"; modules["RuntimeChanging"] = RuntimeChanging; // module name is sent as a string window.initExample = function (module, elem) { // clean up dat-gui from RuntimeChanging.js let datCheck = document.getElementById("DAT_GUI"); if (datCheck) { datCheck.remove(); } // start the chosen module modules[module].init(); setStyle(elem); }; // start one up on start ActiveMultiplier.init(); setStyle("ActiveMultiplier"); ``` -------------------------------- ### Install Grunt CLI Source: https://github.com/kellycode/shaderparticleengine/blob/master/README.md Global installation of the Grunt command line interface via NPM. ```bash npm install -g grunt-cli ``` -------------------------------- ### Build Project with Grunt Source: https://github.com/kellycode/shaderparticleengine/blob/master/README.md Install local dependencies and execute the Grunt build process. ```bash cd [projectFolder] && npm install && grunt ``` -------------------------------- ### Method: enable() Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/SPE.Emitter.html Enables the emitter to start emitting particles. ```APIDOC ## enable() ### Description Enables the emitter. If not already enabled, the emitter will start emitting particles. ### Response - **Returns** (Emitter) - The emitter instance. ``` -------------------------------- ### Setup emitter pooling Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Configures properties for managing emitter object pooling. ```javascript this._pool = []; this._poolCreationSettings = null; this._createNewWhenPoolEmpty = 0; ``` -------------------------------- ### Enable Emitter Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/core_SPE.Emitter.js.html Starts the emitter if it is currently disabled. ```javascript SPE.Emitter.prototype.enable = function() { 'use strict'; this.alive = true; return this; }; ``` -------------------------------- ### SPE.Emitter.prototype.enable Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Enables the emitter, causing it to start emitting particles if not already enabled. ```APIDOC ## SPE.Emitter.prototype.enable ### Description Enables the emitter. If not already enabled, the emitter will start emitting particles. ### Method `enable()` ### Return Value - **Emitter** - This emitter instance. ### Request Example ```javascript emitter.enable(); ``` ### Response Example ```javascript // Returns the emitter instance for chaining ``` ``` -------------------------------- ### Method: reset(force) Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/SPE.Emitter.html Resets the emitter's particles to their starting positions. ```APIDOC ## reset(force) ### Description Resets all the emitter's particles to their start positions and marks the particles as dead if the force argument is true. ### Parameters #### Query Parameters - **force** (Boolean) - Optional - If true, all particles will be marked as dead instantly. ### Response - **Returns** (Emitter) - The emitter instance. ``` -------------------------------- ### Enable Emitter Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Enables the emitter, causing it to start emitting particles if it is not already alive. Returns the emitter instance. ```javascript SPE.Emitter.prototype.enable = function() { 'use strict'; this.alive = true; return this; }; ``` -------------------------------- ### LINE Distribution Emitter Configuration Source: https://context7.com/kellycode/shaderparticleengine/llms.txt Configures an emitter to spawn particles along a line. Define the start and end points of the line using the position spread. ```javascript // LINE distribution - particles spawn along a line const lineEmitter = new SPE.Emitter({ type: SPE.distributions.LINE, position: { value: new THREE.Vector3(0, 0, 0), spread: new THREE.Vector3(100, 0, 0) // Line endpoint }, particleCount: 500 }); ``` -------------------------------- ### Emitter Pooling and Management Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Methods for managing a pool of emitters within a group, including getting from and releasing to the pool, and adding new pools. ```APIDOC ## SPE.Group.prototype.getFromPool ### Description Fetch a single emitter instance from the pool. If there are no objects in the pool, a new emitter will be created if specified. ### Method GET ### Endpoint N/A (Method on SPE.Group prototype) ### Parameters None ### Request Example None ### Response #### Success Response (200) - **Emitter|null** - An emitter instance from the pool or null if the pool is empty and creation is disabled. #### Response Example ```json { "emitter": "SPE.Emitter instance or null" } ``` ## SPE.Group.prototype.releaseIntoPool ### Description Release an emitter into the pool. The emitter is reset before being added to the pool. ### Method POST ### Endpoint N/A (Method on SPE.Group prototype) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **emitter** (SPE.Emitter) - Required - The emitter instance to release into the pool. ### Request Example ```json { "emitter": "emitter_instance" } ``` ### Response #### Success Response (200) - **Group** - The group instance for chaining. #### Response Example ```json { "group": "SPE.Group instance" } ``` ## SPE.Group.prototype.getPool ### Description Get the pool array containing all available emitters. ### Method GET ### Endpoint N/A (Method on SPE.Group prototype) ### Parameters None ### Request Example None ### Response #### Success Response (200) - **Array** - The array of emitter instances in the pool. #### Response Example ```json { "pool": "["emitter1", "emitter2", ...]" } ``` ## SPE.Group.prototype.addPool ### Description Add a pool of emitters to this particle group. This method initializes emitters, adds them to the group, and then releases them into the pool. ### Method POST ### Endpoint N/A (Method on SPE.Group prototype) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **numEmitters** (Number) - Required - The number of emitters to add to the pool. - **emitterOptions** (EmitterOptions|Array) - Required - An object or array of objects describing the options to pass to each emitter. - **createNew** (Boolean) - Optional - Should a new emitter be created if the pool runs out? Defaults to false. ### Request Example ```json { "numEmitters": 100, "emitterOptions": {"particleCount": 1000}, "createNew": true } ``` ### Response #### Success Response (200) - **Group** - The group instance for chaining. #### Response Example ```json { "group": "SPE.Group instance" } ``` ``` -------------------------------- ### Constructor: new Emitter(options) Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/SPE.Emitter.html Initializes a new instance of the Emitter class with the provided configuration options. ```APIDOC ## new Emitter(options) ### Description Creates a new SPE.Emitter instance to manage particle emission based on the provided configuration. ### Parameters #### Request Body - **options** (EmitterOptions) - Required - A map of options to configure the emitter. ``` -------------------------------- ### Get Pool Array Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/core_SPE.Group.js.html Returns the current array of emitters in the pool. ```javascript SPE.Group.prototype.getPool = function() { 'use strict'; return this._pool; }; ``` -------------------------------- ### Create an SPE.Group instance Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/SPE.Group.md Initialize a group by passing a configuration object containing required options. ```javascript var group = new SPE.Group( { optionName: optionValue, // etc. } ); ``` -------------------------------- ### Initialize appearance properties Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Sets basic perspective, colorization, and particle count options using typed arguments. ```javascript this.hasPerspective = utils.ensureTypedArg( options.hasPerspective, types.BOOLEAN, true ); this.colorize = utils.ensureTypedArg( options.colorize, types.BOOLEAN, true ); this.maxParticleCount = utils.ensureTypedArg( options.maxParticleCount, types.NUMBER, null ); ``` -------------------------------- ### SPE.Emitter Constructor Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/Emitter.html Information about the SPE.Emitter constructor, its parameters, and how to initialize an emitter. ```APIDOC ## new Emitter(options) ### Description Initializes a new instance of the SPE.Emitter class. ### Method constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** ([EmitterOptions](global.html#EmitterOptions)) - Required - A map of options to configure the emitter. ``` -------------------------------- ### SPE.Emitter.prototype.reset Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Resets all the emitter's particles to their start positions and optionally marks them as dead. ```APIDOC ## SPE.Emitter.prototype.reset ### Description Resets all the emitter's particles to their start positions and marks the particles as dead if the `force` argument is true. ### Method `reset( force )` ### Parameters #### Arguments - **force** (Boolean) - Optional - If true, all particles will be marked as dead instantly. ### Return Value - **Emitter** - This emitter instance. ### Request Example ```javascript emitter.reset( true ); ``` ### Response Example ```javascript // Returns the emitter instance for chaining ``` ``` -------------------------------- ### Initialize SPE.Emitter with Options Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/core_SPE.Emitter.js.html Use this constructor to create a new particle emitter. Ensure options are provided as a map and are correctly typed. ```javascript var options = { // Emitter options here }; var emitter = new SPE.Emitter( options ); ``` -------------------------------- ### SPE.Emitter Constructor Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/core_SPE.Emitter.js.html Initializes a new SPE.Emitter instance with specified options. ```APIDOC ## SPE.Emitter Constructor ### Description Creates a new particle emitter instance. ### Parameters - **options** (EmitterOptions) - Required - An object containing configuration options for the emitter. ``` -------------------------------- ### SPE.Emitter.reset Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/core_SPE.Emitter.js.html Resets all the emitter's particles to their start positions and optionally marks them as dead. ```APIDOC ## reset(force) ### Description Resets all the emitter's particles to their start positions and marks the particles as dead if the `force` argument is true. ### Parameters #### Parameters - **force** (Boolean) - Optional - If true, all particles will be marked as dead instantly. ### Response - **Emitter** (Object) - This emitter instance. ``` -------------------------------- ### Initialize SPE.Group Properties Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/core_SPE.Group.js.html Sets up various properties for the particle system, such as blending, transparency, depth testing, and fog settings. It also initializes arrays for emitters and internal pooling mechanisms. ```javascript this.blending = utils.ensureTypedArg( options.blending, types.NUMBER, THREE.AdditiveBlending ); this.transparent = utils.ensureTypedArg( options.transparent, types.BOOLEAN, true ); this.alphaTest = parseFloat( utils.ensureTypedArg( options.alphaTest, types.NUMBER, 0.0 ) ); this.depthWrite = utils.ensureTypedArg( options.depthWrite, types.BOOLEAN, false ); this.depthTest = utils.ensureTypedArg( options.depthTest, types.BOOLEAN, true ); this.fog = utils.ensureTypedArg( options.fog, types.BOOLEAN, true ); this.scale = utils.ensureTypedArg( options.scale, types.NUMBER, 300 ); // Where emitter's go to curl up in a warm blanket and live // out their days. this.emitters = []; this.emitterIDs = []; // Create properties for use by the emitter pooling functions. this._pool = []; this._poolCreationSettings = null; this._createNewWhenPoolEmpty = 0; // Whether all attributes should be forced to updated // their entire buffer contents on the next tick. // // Used when an emitter is removed. this._attributesNeedRefresh = false; this._attributesNeedDynamicReset = false; this.particleCount = 0; ``` -------------------------------- ### Set Emitter Attribute Offset Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Stores the starting offset value in the TypedArray attributes for a specific emitter. ```javascript emitter._setAttributeOffset( start ); ``` -------------------------------- ### Define SPE Namespace and Configuration Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/SPE.js.html Initializes the SPE namespace with distribution constants and global interpolation settings. ```javascript var SPE = { /** * A map of supported distribution types used * by SPE.Emitter instances. * * These distribution types can be applied to * an emitter globally, which will affect the * `position`, `velocity`, and `acceleration` * value calculations for an emitter, or they * can be applied on a per-property basis. * * @enum {Number} */ distributions: { /** * Values will be distributed within a box. * @type {Number} */ BOX: 1, /** * Values will be distributed on a sphere. * @type {Number} */ SPHERE: 2, /** * Values will be distributed on a 2d-disc shape. * @type {Number} */ DISC: 3, }, /** * Set this value to however many 'steps' you * want value-over-lifetime properties to have. * * It's adjustable to fix an interpolation problem: * * Assuming you specify an opacity value as [0, 1, 0] * and the `valueOverLifetimeLength` is 4, then the * opacity value array will be reinterpolated to * be [0, 0.66, 0.66, 0]. * This isn't ideal, as particles would never reach * full opacity. * * NOTE: * This property affects the length of ALL * value-over-lifetime properties for ALL * emitters and ALL groups. * * Only values >= 3 && <= 4 are allowed. * * @type {Number} */ valueOverLifetimeLength: 4 }; ``` -------------------------------- ### Initialize emitter storage Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Initializes arrays to track active emitters. ```javascript this.emitters = []; this.emitterIDs = []; ``` -------------------------------- ### Splice TypedArray Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Performs a splice operation on the array's buffer by removing elements between start and end indices. ```javascript SPE.TypedArrayHelper.prototype.splice = function( start, end ) { 'use strict'; start *= this.componentSize; end *= this.componentSize; var data = [], array = this.array, size = array.length; for ( var i = 0; i < size; ++i ) { if ( i < start || i >= end ) { data.push( array[ i ] ); } array[ i ] = 0; } this.setFromArray( 0, data ); return this; }; ``` -------------------------------- ### Get Typed Array Length Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/helpers_SPE.ShaderAttribute.js.html Retrieves the current length of the associated typed array, returning 0 if it has not been initialized. ```javascript SPE.ShaderAttribute.prototype.getLength = function() { 'use strict'; if ( this.typedArray === null ) { return 0; } return this.typedArray.array.length; }; ``` -------------------------------- ### Create an SPE.Emitter Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/SPE.Emitter.md Instantiate a new emitter by passing an options object to the constructor. ```javascript var emitter = new SPE.Emitter( { optionName: optionValue } ); ``` -------------------------------- ### Initialize SPE.Group constructor Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/core_SPE.Group.js.html The constructor initializes the group with a configuration object, setting up default values for texture handling, simulation timing, and rendering properties. ```javascript SPE.Group = function( options ) { 'use strict'; var utils = SPE.utils, types = utils.types; // Ensure we have a map of options to play with options = utils.ensureTypedArg( options, types.OBJECT, {} ); options.texture = utils.ensureTypedArg( options.texture, types.OBJECT, {} ); // Assign a UUID to this instance this.uuid = THREE.Math.generateUUID(); // If no `deltaTime` value is passed to the `SPE.Group.tick` function, // the value of this property will be used to advance the simulation. this.fixedTimeStep = utils.ensureTypedArg( options.fixedTimeStep, types.NUMBER, 0.016 ); // Set properties used in the uniforms map, starting with the // texture stuff. this.texture = utils.ensureInstanceOf( options.texture.value, THREE.Texture, null ); this.textureFrames = utils.ensureInstanceOf( options.texture.frames, THREE.Vector2, new THREE.Vector2( 1, 1 ) ); this.textureFrameCount = utils.ensureTypedArg( options.texture.frameCount, types.NUMBER, this.textureFrames.x * this.textureFrames.y ); this.textureLoop = utils.ensureTypedArg( options.texture.loop, types.NUMBER, 1 ); this.textureFrames.max( new THREE.Vector2( 1, 1 ) ); this.hasPerspective = utils.ensureTypedArg( options.hasPerspective, types.BOOLEAN, true ); this.colorize = utils.ensureTypedArg( options.colorize, types.BOOLEAN, true ); this.maxParticleCount = utils.ensureTypedArg( options.maxParticleCount, types.NUMBER, null ); // Set properties used to define the ShaderMaterial's appearance. ``` -------------------------------- ### SPE.TypedArrayHelper.splice Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/SPE.TypedArrayHelper.html Performs a splice operation on the array's buffer. The start and end indices are multiplied by the number of components for the attribute. ```APIDOC ## splice(start, end) ### Description Perform a splice operation on this array's buffer. ### Method N/A (Instance Method) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) Returns the SPE.TypedArrayHelper instance. #### Response Example N/A ``` -------------------------------- ### Initialize Acceleration Properties Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/core_SPE.Emitter.js.html Sets up particle acceleration properties, including value, spread, and distribution. Similar to velocity, it uses Vector3 for value and spread, with randomization. ```javascript this.acceleration = { _value: utils.ensureInstanceOf( options.acceleration.value, THREE.Vector3, new THREE.Vector3() ), _spread: utils.ensureInstanceOf( options.acceleration.spread, THREE.Vector3, new THREE.Vector3() ), _distribution: utils.ensureTypedArg( options.acceleration.distribution, types.NUMBER, this.type ), _randomise: utils.ensureTypedArg( options.position.randomise, types.BOOLEAN, false ) }; ``` -------------------------------- ### Reset Emitter Particles Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/core_SPE.Emitter.js.html Resets all particles to their start positions. If force is true, marks all particles as dead and updates the buffer attribute. ```javascript SPE.Emitter.prototype.reset = function( force ) { 'use strict'; this.age = 0.0; this.alive = false; if ( force === true ) { var start = this.attributeOffset, end = start + this.particleCount, array = this.paramsArray, attr = this.attributes.params.bufferAttribute; for ( var i = end - 1, index; i >= start; --i ) { index = i * 4; array[ index ] = 0.0; array[ index + 1 ] = 0.0; } attr.updateRange.offset = 0; attr.updateRange.count = -1; attr.needsUpdate = true; } return this; }; ``` -------------------------------- ### Initialize SPE.ShaderAttribute Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/helpers_SPE.ShaderAttribute.js.html Constructor for SPE.ShaderAttribute. Handles the creation and initialization of a THREE.BufferAttribute instance. It determines the component size based on the provided type and sets up the dynamic buffer flag. ```javascript SPE.ShaderAttribute = function( type, dynamicBuffer, arrayType ) { 'use strict'; var typeMap = SPE.ShaderAttribute.typeSizeMap; this.type = typeof type === 'string' && typeMap.hasOwnProperty( type ) ? type : 'f'; this.componentSize = typeMap[ this.type ]; this.arrayType = arrayType || Float32Array; this.typedArray = null; this.bufferAttribute = null; this.dynamicBuffer = !!dynamicBuffer; this.updateMin = 0; this.updateMax = 0; }; ``` -------------------------------- ### ShaderAttribute Methods Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/SPE.ShaderAttribute.html Documentation for the methods available on ShaderAttribute instances. ```APIDOC ## ShaderAttribute._createBufferAttribute(size) ### Description Creates a THREE.BufferAttribute instance if one doesn't exist already. Ensures a typed array is present by calling _ensureTypedArray() first. If a buffer attribute exists already, then it will be marked as needing an update. ### Parameters #### Parameters - **size** (Number) - The size of the typed array to create if one doesn't exist, or resize existing array to. ### Source * [helpers/SPE.ShaderAttribute.js](helpers_SPE.ShaderAttribute.js.html), [line 188](helpers_SPE.ShaderAttribute.js.html#line188) ``` ```APIDOC ## ShaderAttribute._ensureTypedArray(size) ### Description Make sure this attribute has a typed array associated with it. If it does, then it will ensure the typed array is of the correct size. If not, a new SPE.TypedArrayHelper instance will be created. ### Parameters #### Parameters - **size** (Number) - The size of the typed array to create or update to. ### Source * [helpers/SPE.ShaderAttribute.js](helpers_SPE.ShaderAttribute.js.html), [line 158](helpers_SPE.ShaderAttribute.js.html#line158) ``` ```APIDOC ## ShaderAttribute.flagUpdate() ### Description Calculate the number of indices that this attribute should mark as needing updating. Also marks the attribute as needing an update. ### Source * [helpers/SPE.ShaderAttribute.js](helpers_SPE.ShaderAttribute.js.html), [line 94](helpers_SPE.ShaderAttribute.js.html#line94) ``` ```APIDOC ## ShaderAttribute.getLength() ### Description Returns the length of the typed array associated with this attribute. ### Returns * Number - The length of the typed array. Will be 0 if no typed array has been created yet. ### Source * [helpers/SPE.ShaderAttribute.js](helpers_SPE.ShaderAttribute.js.html), [line 211](helpers_SPE.ShaderAttribute.js.html#line211) ``` ```APIDOC ## ShaderAttribute.resetUpdateRange() ### Description Reset the index update counts for this attribute ### Source * [helpers/SPE.ShaderAttribute.js](helpers_SPE.ShaderAttribute.js.html), [line 112](helpers_SPE.ShaderAttribute.js.html#line112) ``` ```APIDOC ## ShaderAttribute.setUpdateRange(min, max) ### Description Calculate the minimum and maximum update range for this buffer attribute using component size independant min and max values. ### Parameters #### Parameters - **min** (Number) - The start of the range to mark as needing an update. - **max** (Number) - The end of the range to mark as needing an update. ### Source * [helpers/SPE.ShaderAttribute.js](helpers_SPE.ShaderAttribute.js.html), [line 83](helpers_SPE.ShaderAttribute.js.html#line83) ``` ```APIDOC ## ShaderAttribute.splice(start, end) ### Description Perform a splice operation on this attribute's buffer. ### Parameters #### Parameters - **start** (Number) - The start index of the splice. Will be multiplied by the number of components for this attribute. - **end** (Number) - The end index of the splice. Will be multiplied by the number of components for this attribute. ### Source * [helpers/SPE.ShaderAttribute.js](helpers_SPE.ShaderAttribute.js.html), [line 129](helpers_SPE.ShaderAttribute.js.html#line129) ``` -------------------------------- ### Getting the Emitter Pool Array Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Returns the internal array that holds the pooled emitter instances. This method provides direct access to the pool. ```javascript return this._pool; ``` -------------------------------- ### Define shader preprocessor macros Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Sets configuration defines for the shader based on instance properties. ```javascript this.defines = { HAS_PERSPECTIVE: this.hasPerspective, COLORIZE: this.colorize, VALUE_OVER_LIFETIME_LENGTH: SPE.valueOverLifetimeLength, SHOULD_ROTATE_TEXTURE: false, SHOULD_ROTATE_PARTICLES: false, SHOULD_WIGGLE_PARTICLES: false, SHOULD_CALCULATE_SPRITE: this.textureFrames.x > 1 || this.textureFrames.y > 1 }; ``` -------------------------------- ### SPE.Group Constructor and Options Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Details the constructor for the SPE.Group class and the various options available for configuring a group instance. ```APIDOC ## SPE.Group Constructor ### Description Creates a new group, containing a material, geometry, and mesh for particle systems. ### Method `new SPE.Group(options)` ### Parameters #### Request Body - **options** (GroupOptions) - Required - A map of options to configure the group instance. ### GroupOptions Object - **texture** (Object) - Required - An object describing the texture used by the group. - **value** (THREE.Texture) - Required - An instance of THREE.Texture. - **frames** (THREE.Vector2) - Optional - A THREE.Vector2 instance describing the number of frames on the x- and y-axis of the given texture. If not provided, the texture will NOT be treated as a sprite-sheet and as such will NOT be animated. - **frameCount** (Number) - Optional - The total number of frames in the sprite-sheet. Allows for sprite-sheets that don't fill the entire texture. Defaults to `texture.frames.x * texture.frames.y`. - **loop** (Number) - Optional - The number of loops through the sprite-sheet that should be performed over the course of a single particle's lifetime. - **fixedTimeStep** (Number) - Optional - If no `dt` (or `deltaTime`) value is passed to this group's `tick()` function, this number will be used to move the particle simulation forward. Value in SECONDS. Defaults to `0.016`. - **hasPerspective** (Boolean) - Optional - Whether the distance a particle is from the camera should affect the particle's size. - **colorize** (Boolean) - Optional - Whether the particles in this group should be rendered with color, or whether the only color of particles will come from the provided texture. - **blending** (Number) - Optional - One of Three.js's blending modes to apply to this group's `ShaderMaterial`. - **transparent** (Boolean) - Optional - Whether these particle's should be rendered with transparency. - **alphaTest** (Number) - Optional - Sets the alpha value to be used when running an alpha test on the `texture.value` property. Value between 0 and 1. - **depthWrite** (Boolean) - Optional - Whether rendering the group has any effect on the depth buffer. - **depthTest** (Boolean) - Optional - Whether to have depth test enabled when rendering this group. - **fog** (Boolean) - Optional - Whether this group's particles should be affected by their scene's fog. - **scale** (Number) - Optional - The scale factor to apply to this group's particle sizes. Useful for setting particle sizes to be relative to renderer size. ### Example ```javascript var options = { texture: { value: texture, frames: new THREE.Vector2(4, 4), loop: 1 }, fixedTimeStep: 0.016, hasPerspective: true, colorize: true, blending: THREE.AdditiveBlending, transparent: true, alphaTest: 0.5, depthWrite: false, depthTest: true, fog: true, scale: 1 }; var group = new SPE.Group( options ); ``` ``` -------------------------------- ### Get Component Value in TypedArrayHelper Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/helpers_SPE.TypedArrayHelper.js.html Fetches a subarray representing component values at the specified index. If componentSize is 3, it returns a new TypedArray of length 3. ```javascript SPE.TypedArrayHelper.prototype.getComponentValueAtIndex = function( index ) { 'use strict'; return this.array.subarray( this.indexOffset + ( index * this.componentSize ) ); }; ``` -------------------------------- ### Get Value at Index in TypedArrayHelper Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/helpers_SPE.TypedArrayHelper.js.html Retrieves a single value from the typed array at the given index, ignoring component size. This is useful for accessing individual elements. ```javascript SPE.TypedArrayHelper.prototype.getValueAtIndex = function( index ) { 'use strict'; return this.array[ this.indexOffset + index ]; }; ``` -------------------------------- ### Initialize Position Properties Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/core_SPE.Emitter.js.html Sets up the particle's position properties, including value, spread, distribution, and randomization. Supports Vector3 for value and spread, with options for clamping and distribution types. ```javascript this.position = { _value: utils.ensureInstanceOf( options.position.value, THREE.Vector3, new THREE.Vector3() ), _spread: utils.ensureInstanceOf( options.position.spread, THREE.Vector3, new THREE.Vector3() ), _spreadClamp: utils.ensureInstanceOf( options.position.spreadClamp, THREE.Vector3, new THREE.Vector3() ), _distribution: utils.ensureTypedArg( options.position.distribution, types.NUMBER, this.type ), _randomise: utils.ensureTypedArg( options.position.randomise, types.BOOLEAN, false ), _radius: utils.ensureTypedArg( options.position.radius, types.NUMBER, 10 ), _radiusScale: utils.ensureInstanceOf( options.position.radiusScale, THREE.Vector3, new THREE.Vector3( 1, 1, 1 ) ), _distributionClamp: utils.ensureTypedArg( options.position.distributionClamp, types.NUMBER, 0 ), }; ``` -------------------------------- ### Set Array From Another TypedArray Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/helpers_SPE.TypedArrayHelper.js.html Copies data from a source TypedArray into this array, starting at a specified index. Resizes the internal array automatically if the source array is larger than the current capacity. ```javascript SPE.TypedArrayHelper.prototype.setFromArray = function( index, array ) { 'use strict'; var sourceArraySize = array.length, newSize = index + sourceArraySize; if ( newSize > this.array.length ) { ``` -------------------------------- ### Splice TypedArray Buffer Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/helpers_SPE.TypedArrayHelper.js.html Performs a splice operation on the array's buffer. The start and end indices are multiplied by the component size. The removed elements are effectively replaced by subsequent elements shifted forward. ```javascript SPE.TypedArrayHelper.prototype.splice = function( start, end ) { 'use strict'; start *= this.componentSize; end *= this.componentSize; var data = [], array = this.array, size = array.length; for ( var i = 0; i < size; ++i ) { if ( i < start || i >= end ) { data.push( array[ i ] ); } // array[ i ] = 0; } this.setFromArray( 0, data ); return this; }; ``` -------------------------------- ### Create BufferGeometry and Points Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Instantiate BufferGeometry and Points for particle rendering, ensuring both geometry and material are assigned to the Points instance. Handles cases where maxParticleCount might not be specified. ```javascript this.geometry = new THREE.BufferGeometry(); this.mesh = new THREE.Points( this.geometry, this.material ); if ( this.maxParticleCount === null ) { console.warn( 'SPE.Group: No maxParticleCount specified. Adding emitters after rendering will probably cause errors.' ); } ``` -------------------------------- ### Get Component Value at Index Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Retrieves a component value from the typed array at the specified index, considering the `indexOffset`. If `componentSize` is greater than 1, it may return a portion or a new array representing the component. ```javascript SPE.TypedArrayHelper.prototype.getComponentValueAtIndex = function( index ) { 'use strict'; if ( this.componentSize === 1 ) { return this.array[ this.indexOffset + index ]; } else { var values = new SPE.TypedArrayHelper( this.componentSize ); var i = this.indexOffset + ( index * this.componentSize ); for ( var j = 0; j < this.componentSize; j++ ) { values.array[ values.indexOffset + j ] = this.array[ i + j ]; } return values; } }; ``` -------------------------------- ### Create Three.js ShaderMaterial and BufferGeometry Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/core_SPE.Group.js.html Initializes the ShaderMaterial with uniforms, shaders, and rendering properties. It then creates a BufferGeometry and a Points instance to render the particles. ```javascript this.material = new THREE.ShaderMaterial( { uniforms: this.uniforms, vertexShader: SPE.shaders.vertex, fragmentShader: SPE.shaders.fragment, blending: this.blending, transparent: this.transparent, alphaTest: this.alphaTest, depthWrite: this.depthWrite, depthTest: this.depthTest, defines: this.defines, fog: this.fog } ); // Create the BufferGeometry and Points instances, ensuring // the geometry and material are given to the latter. this.geometry = new THREE.BufferGeometry(); this.mesh = new THREE.Points( this.geometry, this.material ); if ( this.maxParticleCount === null ) { console.warn( 'SPE.Group: No maxParticleCount specified. Adding emitters after rendering will probably cause errors.' ); } }; ``` -------------------------------- ### Group Constructor Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/SPE.Group.html Initializes a new SPE.Group instance. This group will contain a material, geometry, and mesh for rendering particles. ```APIDOC ## new Group(options) ### Description Creates a new group, containing a material, geometry, and mesh. ### Parameters #### Request Body - **options** (GroupOptions) - Required - A map of options to configure the group instance. ``` -------------------------------- ### Initialize Emitter Properties Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/core_SPE.Emitter.js.html Initializes core emitter state variables including particle counts and age. ```javascript this.activeParticleCount = 0; this.group = null; this.attributes = null; this.paramsArray = null; this.age = 0.0; }; ``` -------------------------------- ### Particle parameter and force fetching Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Helper functions to retrieve particle state parameters and physical forces. ```GLSL float getAlive() { return params.x; } float getAge() { return params.y; } float getMaxAge() { return params.z; } float getWiggle() { return params.w; } ``` ```GLSL vec4 getPosition( in float age ) { return modelViewMatrix * vec4( position, 1.0 ); } vec3 getVelocity( in float age ) { return velocity * age; } vec3 getAcceleration( in float age ) { return acceleration.xyz * age; } ``` -------------------------------- ### Initialize Emitter Attributes and Values Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/core_SPE.Group.js.html Configures emitter buffers and populates particle attributes like position, velocity, and color within the group. ```javascript // Set the `particlesPerSecond` value (PPS) on the emitter. // It's used to determine how many particles to release // on a per-frame basis. emitter._calculatePPSValue( emitter.maxAge._value + emitter.maxAge._spread ); emitter._setBufferUpdateRanges( this.attributeKeys ); // Store the offset value in the TypedArray attributes for this emitter. emitter._setAttributeOffset( start ); // Save a reference to this group on the emitter so it knows // where it belongs. emitter.group = this; // Store reference to the attributes on the emitter for // easier access during the emitter's tick function. emitter.attributes = this.attributes; // Ensure the attributes and their BufferAttributes exist, and their // TypedArrays are of the correct size. for ( var attr in attributes ) { if ( attributes.hasOwnProperty( attr ) ) { // When creating a buffer, pass through the maxParticle count // if one is specified. attributes[ attr ]._createBufferAttribute( this.maxParticleCount !== null ? this.maxParticleCount : this.particleCount ); } } // Loop through each particle this emitter wants to have, and create the attributes values, // storing them in the TypedArrays that each attribute holds. for ( var i = start; i < end; ++i ) { emitter._assignPositionValue( i ); emitter._assignForceValue( i, 'velocity' ); emitter._assignForceValue( i, 'acceleration' ); emitter._assignAbsLifetimeValue( i, 'opacity' ); emitter._assignAbsLifetimeValue( i, 'size' ); emitter._assignAngleValue( i ); emitter._assignRotationValue( i ); emitter._assignParamsValue( i ); emitter._assignColorValue( i ); } // Update the geometry and make sure the attributes are referencing // the typed arrays properly. this._applyAttributesToGeometry(); // Store this emitter in this group's emitter's store. this.emitters.push( emitter ); this.emitterIDs.push( emitter.uuid ); // Update certain flags to enable shader calculations only if they're necessary. this._updateDefines( emitter ); // Update the material since defines might have changed this.material.needsUpdate = true; this.geometry.needsUpdate = true; this._attributesNeedRefresh = true; // Return the group to enable chaining. return this; }; ``` -------------------------------- ### Constructor SPE.Group Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/core_SPE.Group.js.html Initializes a new particle group instance with specific configuration options for rendering and simulation. ```APIDOC ## Constructor SPE.Group ### Description Creates a new group, containing a material, geometry, and mesh for particle rendering. ### Parameters #### Request Body - **options** (GroupOptions) - Required - A map of options to configure the group instance. - **texture** (Object) - Required - Describes the texture used by the group. - **value** (THREE.Texture) - Required - The texture instance. - **frames** (THREE.Vector2) - Optional - Number of frames on x and y axis for sprite-sheets. - **frameCount** (Number) - Optional - Total number of frames in the sprite-sheet. - **loop** (Number) - Optional - Number of loops through the sprite-sheet over particle lifetime. - **fixedTimeStep** (Number) - Optional - Seconds to advance simulation if no dt is provided. - **hasPerspective** (Boolean) - Optional - Whether distance affects particle size. - **colorize** (Boolean) - Optional - Whether particles are rendered with color. - **blending** (Number) - Optional - Three.js blending mode. - **transparent** (Boolean) - Optional - Whether to render with transparency. - **alphaTest** (Number) - Optional - Alpha value for alpha testing (0-1). - **depthWrite** (Boolean) - Optional - Whether to affect the depth buffer. - **depthTest** (Boolean) - Optional - Whether to enable depth testing. - **fog** (Boolean) - Optional - Whether to be affected by scene fog. - **scale** (Number) - Optional - Scale factor for particle sizes. ``` -------------------------------- ### Use SPE.distributions Constants for Emitter Types Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/MigrationLog.md When creating an emitter, reference SPE.distributions constants like SPE.distributions.SPHERE instead of string values. Constants include SPE.distributions.SPHERE, SPE.distributions.DISC, and SPE.distributions.BOX. ```javascript var emitter = new SPE.Emitter( { type: SPE.distributions.SPHERE } ); ``` -------------------------------- ### Initialize Particle Properties Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/source/SPE.html Initializes properties for color, opacity, size, and angle, ensuring they are arrays and have appropriate default values or spreads. ```javascript this.opacity = { _value: utils.ensureArrayTypedArg( options.opacity.value, types.NUMBER, 1 ), _spread: utils.ensureArrayTypedArg( options.opacity.spread, types.NUMBER, 0 ), _randomise: utils.ensureTypedArg( options.position.randomise, types.BOOLEAN, false ) }; ``` ```javascript this.size = { _value: utils.ensureArrayTypedArg( options.size.value, types.NUMBER, 1 ), _spread: utils.ensureArrayTypedArg( options.size.spread, types.NUMBER, 0 ), _randomise: utils.ensureTypedArg( options.position.randomise, types.BOOLEAN, false ) }; ``` ```javascript this.angle = { _value: utils.ensureArrayTypedArg( options.angle.value, types.NUMBER, 0 ), _spread: utils.ensureArrayTypedArg( options.angle.spread, types.NUMBER, 0 ), _randomise: utils.ensureTypedArg( options.position.randomise, types.BOOLEAN, false ) }; ``` -------------------------------- ### ShaderAttribute Constructor Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/SPE.ShaderAttribute.html Initializes a new ShaderAttribute instance to help create and update THREE.BufferAttribute instances. ```APIDOC ## new ShaderAttribute(type, dynamicBufferopt, arrayTypeopt) ### Description A helper to handle creating and updating a THREE.BufferAttribute instance. ### Parameters #### Parameters - **type** (String) - The buffer attribute type. See SPE.ShaderAttribute.typeSizeMap for valid values. - **dynamicBuffer** (Boolean) - Whether this buffer attribute should be marked as dynamic or not. - **arrayType** (function) - A reference to a TypedArray constructor. Defaults to Float32Array if none provided. ``` -------------------------------- ### SPE.Emitter Configuration Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/global.html Defines the structure and properties for configuring an SPE.Emitter instance. ```APIDOC ## EmitterOptions ### Description A map of options to configure an SPE.Emitter instance. ### Parameters #### Request Body - **type** (distribution) - Optional - The default distribution (BOX, SPHERE, DISC) for particle spawn position and force behavior. - **particleCount** (Number) - Optional - The total number of particles the emitter holds. - **duration** (Number | null) - Optional - The duration in seconds the emitter should live for. - **isStatic** (Boolean) - Optional - Whether the emitter should not be simulated. - **activeMultiplier** (Boolean) - Optional - Percentage of particlesPerSecond to emit (0 to 1). - **direction** (Boolean) - Optional - Direction of the emitter (1 for forward, -1 for backward). - **maxAge** (Object) - Optional - Configuration for particle maximum age. - **value** (Number) - Max age value. - **spread** (Number) - Max age variance. - **position** (Object) - Optional - Configuration for emitter position. - **value** (THREE.Vector3) - Base position. - **spread** (THREE.Vector3) - Position variance. - **spreadClamp** (THREE.Vector3) - Numeric multiples for spread. - **radius** (Number) - Base radius. - **radiusScale** (THREE.Vector3) - Radius scale for axes. - **distribution** (distribution) - Specific distribution override. - **randomise** (Boolean) - Whether to re-randomize position on respawn. ``` -------------------------------- ### Initialize Emitter Properties and Update Flags Source: https://github.com/kellycode/shaderparticleengine/blob/master/docs/api/core_SPE.Emitter.js.html Initializes emitter properties and sets up flags and counts to track updates for various particle attributes. Ensures that value-over-lifetime properties comply with length requirements. ```javascript opacity: utils.ensureTypedArg( options.opacity.randomise, types.BOOLEAN, false ), angle: utils.ensureTypedArg( options.angle.randomise, types.BOOLEAN, false ) }; this.updateFlags = {}; this.updateCounts = {}; // A map to indicate which emitter parameters should update // which attribute. this.updateMap = { maxAge: 'params', position: 'position', velocity: 'velocity', acceleration: 'acceleration', drag: 'acceleration', wiggle: 'params', rotation: 'rotation', size: 'size', color: 'color', opacity: 'opacity', angle: 'angle' }; for ( var i in this.updateMap ) { if ( this.updateMap.hasOwnProperty( i ) ) { this.updateCounts[ this.updateMap[ i ] ] = 0.0; this.updateFlags[ this.updateMap[ i ] ] = false; this._createGetterSetters( this[ i ], i ); } } this.bufferUpdateRanges = {}; this.attributeKeys = null; this.attributeCount = 0; // Ensure that the value-over-lifetime property objects above // have value and spread properties that are of the same length. // // Also, for now, make sure they have a length of 3 (min/max arguments here). utils.ensureValueOverLifetimeCompliance( this.color, lifetimeLength, lifetimeLength ); utils.ensureValueOverLifetimeCompliance( this.opacity, lifetimeLength, lifetimeLength ); utils.ensureValueOverLifetimeCompliance( this.size, lifetimeLength, lifetimeLength ); utils.ensureValueOverLifetimeCompliance( this.angle, lifetimeLength, lifetimeLength ); }; SPE.Emitter.constructor = SPE.Emitter; ```