@tsparticles/engine
Version:
Easily create highly customizable particle, confetti and fireworks animations and use them as animated backgrounds for your website. Ready to use components available also for React, Vue.js (2.x and 3.x), Angular, Svelte, jQuery, Preact, Riot.js, Inferno.
562 lines (561 loc) • 23.9 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Particle = void 0;
const ErrorUtils_js_1 = require("../Utils/ErrorUtils.js");
const Vectors_js_1 = require("./Utils/Vectors.js");
const ColorUtils_js_1 = require("../Utils/ColorUtils.js");
const MathUtils_js_1 = require("../Utils/MathUtils.js");
const Utils_js_1 = require("../Utils/Utils.js");
const Constants_js_1 = require("./Utils/Constants.js");
const EventType_js_1 = require("../Enums/Types/EventType.js");
const MoveDirection_js_1 = require("../Enums/Directions/MoveDirection.js");
const OutMode_js_1 = require("../Enums/Modes/OutMode.js");
const OutModeDirection_js_1 = require("../Enums/Directions/OutModeDirection.js");
const ParticleOutType_js_1 = require("../Enums/Types/ParticleOutType.js");
const ParticlesOptionsLoader_js_1 = require("../Utils/ParticlesOptionsLoader.js");
function loadEffectData(effect, effectOptions, id, reduceDuplicates) {
const effectData = effectOptions.options[effect];
return (0, Utils_js_1.deepExtend)({
close: effectOptions.close,
}, (0, Utils_js_1.itemFromSingleOrMultiple)(effectData, id, reduceDuplicates));
}
function loadShapeData(shape, shapeOptions, id, reduceDuplicates) {
const shapeData = shapeOptions.options[shape];
return (0, Utils_js_1.deepExtend)({
close: shapeOptions.close,
}, (0, Utils_js_1.itemFromSingleOrMultiple)(shapeData, id, reduceDuplicates));
}
function fixOutMode(data) {
if (!(0, Utils_js_1.isInArray)(data.outMode, data.checkModes)) {
return;
}
const diameter = data.radius * Constants_js_1.double;
if (data.coord > data.maxCoord - diameter) {
data.setCb(-data.radius);
}
else if (data.coord < diameter) {
data.setCb(data.radius);
}
}
function normalizeAngle(angle, modulus) {
const normalized = angle % modulus;
return normalized < Constants_js_1.defaultAngle ? normalized + modulus : normalized;
}
function initParticleState(particle, id, group) {
particle.id = id;
particle.group = group;
particle.justWarped = false;
particle.effectClose = true;
particle.shapeClose = true;
particle.pathRotation = false;
particle.lastPathTime = 0;
particle.destroyed = false;
particle.unbreakable = false;
particle.isRotating = false;
particle.rotation = 0;
particle.misplaced = false;
particle.retina = {
maxDistance: {},
maxSpeed: 0,
moveDrift: 0,
moveSpeed: 0,
sizeAnimationSpeed: 0,
};
particle.size = {
value: 1,
max: 1,
min: 1,
enable: false,
};
particle.outType = ParticleOutType_js_1.ParticleOutType.normal;
particle.ignoresResizeRatio = true;
}
function resolveParticleOptions(particle, container, pluginManager, overrideOptions) {
const mainOptions = container.actualOptions, particlesOptions = (0, ParticlesOptionsLoader_js_1.loadParticlesOptions)(pluginManager, container, mainOptions.particles), reduceDuplicates = particlesOptions.reduceDuplicates;
particle.effect = (0, Utils_js_1.itemFromSingleOrMultiple)(particlesOptions.effect.type, particle.id, reduceDuplicates);
particle.shape = (0, Utils_js_1.itemFromSingleOrMultiple)(particlesOptions.shape.type, particle.id, reduceDuplicates);
const effectOptions = particlesOptions.effect, shapeOptions = particlesOptions.shape;
if (overrideOptions) {
if (overrideOptions.effect) {
const overrideEffectType = overrideOptions.effect.type;
if (overrideEffectType && overrideEffectType !== particle.effect) {
const effect = (0, Utils_js_1.itemFromSingleOrMultiple)(overrideEffectType, particle.id, reduceDuplicates);
if (effect) {
particle.effect = effect;
}
}
effectOptions.load(overrideOptions.effect);
}
if (overrideOptions.shape) {
const overrideShapeType = overrideOptions.shape.type;
if (overrideShapeType && overrideShapeType !== particle.shape) {
const shape = (0, Utils_js_1.itemFromSingleOrMultiple)(overrideShapeType, particle.id, reduceDuplicates);
if (shape) {
particle.shape = shape;
}
}
shapeOptions.load(overrideOptions.shape);
}
}
if (particle.effect === Constants_js_1.randomColorValue) {
const availableEffects = [...container.effectDrawers.keys()];
particle.effect = availableEffects[Math.floor((0, MathUtils_js_1.getRandom)() * availableEffects.length)];
}
if (particle.shape === Constants_js_1.randomColorValue) {
const availableShapes = [...container.shapeDrawers.keys()];
particle.shape = availableShapes[Math.floor((0, MathUtils_js_1.getRandom)() * availableShapes.length)];
}
particle.effectData = particle.effect
? loadEffectData(particle.effect, effectOptions, particle.id, reduceDuplicates)
: undefined;
particle.shapeData = particle.shape
? loadShapeData(particle.shape, shapeOptions, particle.id, reduceDuplicates)
: undefined;
particlesOptions.load(overrideOptions);
const effectData = particle.effectData, shapeData = particle.shapeData;
if (effectData) {
particlesOptions.load(effectData.particles);
}
if (shapeData) {
particlesOptions.load(shapeData.particles);
}
particle.effectClose = effectData?.close ?? particlesOptions.effect.close;
particle.shapeClose = shapeData?.close ?? particlesOptions.shape.close;
return particlesOptions;
}
function initParticleDrawers(particle, container) {
let effectDrawer, shapeDrawer;
if (particle.effect) {
effectDrawer = container.effectDrawers.get(particle.effect);
}
if (effectDrawer?.loadEffect) {
effectDrawer.loadEffect(particle);
}
if (particle.shape) {
shapeDrawer = container.shapeDrawers.get(particle.shape);
}
if (shapeDrawer?.loadShape) {
shapeDrawer.loadShape(particle);
}
const sideCountFunc = shapeDrawer?.getSidesCount;
if (sideCountFunc) {
particle.sides = sideCountFunc(particle);
}
}
function runUpdaterPreInit(updaters, particle) {
for (const updater of updaters) {
updater.preInit?.(particle);
}
}
function runUpdaterInit(updaters, particle) {
for (const updater of updaters) {
updater.init(particle);
}
}
function runDrawerInit(container, particle) {
const shapeDrawer = particle.shape ? container.shapeDrawers.get(particle.shape) : undefined, effectDrawer = particle.effect ? container.effectDrawers.get(particle.effect) : undefined;
effectDrawer?.particleInit?.(container, particle);
shapeDrawer?.particleInit?.(container, particle);
}
function runParticleCreatedPlugins(container, particle) {
for (const plugin of container.particleCreatedPlugins) {
plugin.particleCreated?.(particle);
}
}
class Particle {
backColor;
destroyed;
direction;
effect;
effectClose;
effectData;
fillColor;
fillEnabled;
fillOpacity;
group;
id;
ignoresResizeRatio;
initialPosition;
initialVelocity;
isRotating;
justWarped;
lastPathTime;
misplaced;
moveCenter;
offset;
opacity;
options;
outType;
pathRotation;
position;
randomIndexData;
retina;
roll;
rotation;
shape;
shapeClose;
shapeData;
sides;
size;
spawning;
strokeColor;
strokeOpacity;
strokeWidth;
unbreakable;
velocity;
zIndexFactor;
#cachedOpacityData = {
fillOpacity: Constants_js_1.defaultOpacity,
opacity: Constants_js_1.defaultOpacity,
strokeOpacity: Constants_js_1.defaultOpacity,
};
#cachedPosition = Vectors_js_1.Vector3d.origin;
#cachedRotateData = { sin: 0, cos: 0 };
#cachedTransform = {
a: 1,
b: 0,
c: 0,
d: 1,
};
#container;
#modifiers = [];
#pluginManager;
constructor(pluginManager, container) {
this.#pluginManager = pluginManager;
this.#container = container;
}
addModifier(modifier) {
this.#modifiers.push(modifier);
this.#modifiers.sort((a, b) => a.priority - b.priority);
}
clearModifiers() {
this.#modifiers.length = 0;
}
destroy(override) {
if (this.unbreakable || this.destroyed) {
return;
}
this.destroyed = true;
this.clearModifiers();
const container = this.#container, shapeDrawer = this.shape ? container.shapeDrawers.get(this.shape) : undefined;
shapeDrawer?.particleDestroy?.(this);
for (const plugin of container.particleDestroyedPlugins) {
plugin.particleDestroyed?.(this, override);
}
for (const updater of container.particleUpdaters) {
updater.particleDestroyed?.(this, override);
}
this.#container.dispatchEvent(EventType_js_1.EventType.particleDestroyed, {
particle: this,
});
}
draw(delta) {
const container = this.#container, render = container.canvas.render;
render.drawParticlePlugins(this, delta);
render.drawParticle(this, delta);
}
getAngle() {
return this.rotation + (this.pathRotation ? this.velocity.angle : Constants_js_1.defaultAngle);
}
getFillColor() {
return this.#getRollColor(this.#applyModifiers((0, ColorUtils_js_1.getHslFromAnimation)(this.fillColor), m => m.fillColor));
}
getMass() {
return this.getRadius() ** Constants_js_1.squareExp * Math.PI * Constants_js_1.half;
}
getModifier(id) {
return this.#modifiers.find(m => m.id === id);
}
getOpacity() {
const zIndexOptions = this.options.zIndex, zIndexFactor = Constants_js_1.zIndexFactorOffset - this.zIndexFactor, zOpacityFactor = zIndexFactor ** zIndexOptions.opacityRate, baseOpacity = (0, MathUtils_js_1.getRangeValue)(this.opacity?.value ?? Constants_js_1.defaultOpacity), modifierOpacity = this.#applyModifiers(undefined, m => m.opacity), opacity = modifierOpacity ?? baseOpacity;
this.#cachedOpacityData.fillOpacity = this.fillOpacity ?? Constants_js_1.defaultOpacity;
this.#cachedOpacityData.opacity = opacity * zOpacityFactor;
this.#cachedOpacityData.strokeOpacity = this.strokeOpacity ?? Constants_js_1.defaultOpacity;
return this.#cachedOpacityData;
}
getPosition() {
this.#cachedPosition.x = this.position.x + this.offset.x;
this.#cachedPosition.y = this.position.y + this.offset.y;
this.#cachedPosition.z = this.position.z;
return this.#cachedPosition;
}
getRadius() {
return this.#applyModifiers(this.size.value, m => m.radius);
}
getRotateData() {
const angle = this.getAngle();
this.#cachedRotateData.sin = Math.sin(angle);
this.#cachedRotateData.cos = Math.cos(angle);
return this.#cachedRotateData;
}
getStrokeColor() {
return this.#getRollColor(this.#applyModifiers((0, ColorUtils_js_1.getHslFromAnimation)(this.strokeColor), m => m.strokeColor));
}
getTransformData(externalTransform) {
const rotateData = this.getRotateData(), rotating = this.isRotating;
this.#cachedTransform.a = rotateData.cos * (externalTransform.a ?? Constants_js_1.defaultTransform.a);
this.#cachedTransform.b = rotating
? rotateData.sin * (externalTransform.b ?? Constants_js_1.identity)
: (externalTransform.b ?? Constants_js_1.defaultTransform.b);
this.#cachedTransform.c = rotating
? -rotateData.sin * (externalTransform.c ?? Constants_js_1.identity)
: (externalTransform.c ?? Constants_js_1.defaultTransform.c);
this.#cachedTransform.d = rotateData.cos * (externalTransform.d ?? Constants_js_1.defaultTransform.d);
return this.#cachedTransform;
}
init(id, position, overrideOptions, group) {
const container = this.#container;
initParticleState(this, id, group);
this.options = resolveParticleOptions(this, container, this.#pluginManager, overrideOptions);
container.retina.initParticle(this);
runUpdaterPreInit(container.particleUpdaters, this);
this.#initPosition(position);
this.initialVelocity = this.#calculateVelocity();
this.velocity = this.initialVelocity.copy();
this.zIndexFactor = this.position.z / container.zLayers;
this.sides = 24;
initParticleDrawers(this, container);
this.spawning = false;
runUpdaterInit(container.particleUpdaters, this);
runDrawerInit(container, this);
runParticleCreatedPlugins(container, this);
}
isInsideCanvas(direction) {
return this.#getInsideCanvasResult(direction).inside;
}
isInsideCanvasForOutMode(outMode, direction) {
return this.#getInsideCanvasResult(direction, outMode).inside;
}
isShowingBack() {
if (!this.roll) {
return false;
}
const angle = this.roll.angle;
if (this.roll.horizontal && this.roll.vertical) {
const adjustedAngle = normalizeAngle(angle, Constants_js_1.doublePI);
return adjustedAngle >= Math.PI * Constants_js_1.half && adjustedAngle < Math.PI * Constants_js_1.triple * Constants_js_1.half;
}
if (this.roll.horizontal) {
const adjustedAngle = normalizeAngle(angle + Math.PI * Constants_js_1.half, Constants_js_1.doublePI);
return adjustedAngle >= Math.PI && adjustedAngle < Math.PI * Constants_js_1.double;
}
if (this.roll.vertical) {
const adjustedAngle = normalizeAngle(angle, Constants_js_1.doublePI);
return adjustedAngle >= Math.PI && adjustedAngle < Math.PI * Constants_js_1.double;
}
return false;
}
isVisible() {
return !this.destroyed && !this.spawning && this.isInsideCanvas();
}
removeModifier(id) {
const idx = this.#modifiers.findIndex(m => m.id === id);
if (idx >= Constants_js_1.defaultAngle) {
this.#modifiers.splice(idx, Constants_js_1.identity);
}
}
reset() {
for (const updater of this.#container.particleUpdaters) {
updater.reset?.(this);
}
}
#applyModifiers(base, getter) {
let value = base;
for (const mod of this.#modifiers) {
if (mod.enabled) {
const override = getter(mod);
if (override !== undefined) {
value = override;
}
}
}
return value;
}
#calcPosition(position, zIndex) {
let tryCount = Constants_js_1.defaultRetryCount, posVec = position ? Vectors_js_1.Vector3d.create(position.x, position.y, zIndex) : undefined;
const container = this.#container, plugins = container.particlePositionPlugins, outModes = this.options.move.outModes, radius = this.getRadius(), canvasSize = container.canvas.size;
for (;;) {
for (const plugin of plugins) {
const pluginPos = plugin.particlePosition?.(posVec, this);
if (pluginPos) {
return Vectors_js_1.Vector3d.create(pluginPos.x, pluginPos.y, zIndex);
}
}
const exactPosition = (0, MathUtils_js_1.calcExactPositionOrRandomFromSize)({
size: canvasSize,
position: posVec,
}), pos = Vectors_js_1.Vector3d.create(exactPosition.x, exactPosition.y, zIndex);
this.#fixHorizontal(pos, radius, outModes.left ?? outModes.default);
this.#fixHorizontal(pos, radius, outModes.right ?? outModes.default);
this.#fixVertical(pos, radius, outModes.top ?? outModes.default);
this.#fixVertical(pos, radius, outModes.bottom ?? outModes.default);
let isValidPosition = true;
for (const plugin of container.particles.checkParticlePositionPlugins) {
isValidPosition = plugin.checkParticlePosition?.(this, pos, tryCount) ?? true;
if (!isValidPosition) {
break;
}
}
if (isValidPosition) {
return pos;
}
tryCount += Constants_js_1.tryCountIncrement;
posVec = undefined;
}
}
#calculateVelocity() {
const moveOptions = this.options.move, baseVelocity = (0, MathUtils_js_1.getParticleBaseVelocity)(this.direction), res = baseVelocity.copy();
if (moveOptions.direction === MoveDirection_js_1.MoveDirection.inside || moveOptions.direction === MoveDirection_js_1.MoveDirection.outside) {
return res;
}
const rad = (0, MathUtils_js_1.degToRad)((0, MathUtils_js_1.getRangeValue)(moveOptions.angle.value)), radOffset = (0, MathUtils_js_1.degToRad)((0, MathUtils_js_1.getRangeValue)(moveOptions.angle.offset)), range = {
left: radOffset - rad * Constants_js_1.half,
right: radOffset + rad * Constants_js_1.half,
};
if (!moveOptions.straight) {
res.angle += (0, MathUtils_js_1.randomInRangeValue)((0, MathUtils_js_1.setRangeValue)(range.left, range.right));
}
if (moveOptions.random && typeof moveOptions.speed === "number") {
res.length *= (0, MathUtils_js_1.getRandom)();
}
return res;
}
#fixHorizontal(pos, radius, outMode) {
fixOutMode({
outMode,
checkModes: [OutMode_js_1.OutMode.bounce],
coord: pos.x,
maxCoord: this.#container.canvas.size.width,
setCb: (value) => (pos.x += value),
radius,
});
}
#fixVertical(pos, radius, outMode) {
fixOutMode({
outMode,
checkModes: [OutMode_js_1.OutMode.bounce],
coord: pos.y,
maxCoord: this.#container.canvas.size.height,
setCb: (value) => (pos.y += value),
radius,
});
}
#getDefaultInsideCanvasResult(direction, outMode) {
const radius = this.getRadius(), canvasSize = this.#container.canvas.size, isBounce = outMode === OutMode_js_1.OutMode.bounce || outMode === OutMode_js_1.OutMode.split, position = isBounce ? this.getPosition() : this.position;
if (direction === OutModeDirection_js_1.OutModeDirection.bottom) {
return {
inside: isBounce ? position.y + radius < canvasSize.height : position.y - radius < canvasSize.height,
reason: "default",
};
}
if (direction === OutModeDirection_js_1.OutModeDirection.left) {
return {
inside: isBounce ? position.x - radius > Constants_js_1.defaultAngle : position.x + radius > Constants_js_1.defaultAngle,
reason: "default",
};
}
if (direction === OutModeDirection_js_1.OutModeDirection.right) {
return {
inside: isBounce ? position.x + radius < canvasSize.width : position.x - radius < canvasSize.width,
reason: "default",
};
}
if (direction === OutModeDirection_js_1.OutModeDirection.top) {
return {
inside: isBounce ? position.y - radius > Constants_js_1.defaultAngle : position.y + radius > Constants_js_1.defaultAngle,
reason: "default",
};
}
return {
inside: position.x >= -radius &&
position.y >= -radius &&
position.y <= canvasSize.height + radius &&
position.x <= canvasSize.width + radius,
reason: "default",
};
}
#getInsideCanvasCallbackData(direction, outMode) {
return {
canvasSize: this.#container.canvas.size,
direction,
outMode,
particle: this,
radius: this.getRadius(),
};
}
#getInsideCanvasResult(direction, outMode) {
const defaultResult = this.#getDefaultInsideCanvasResult(direction, outMode), container = this.#container, shapeDrawer = this.shape ? container.shapeDrawers.get(this.shape) : undefined, effectDrawer = this.effect ? container.effectDrawers.get(this.effect) : undefined;
if (!shapeDrawer?.isInsideCanvas && !effectDrawer?.isInsideCanvas) {
return defaultResult;
}
const callbackData = this.#getInsideCanvasCallbackData(direction, outMode), shapeResult = shapeDrawer?.isInsideCanvas
? this.#normalizeInsideCanvasResult(shapeDrawer.isInsideCanvas(callbackData), "shape")
: undefined, effectResult = effectDrawer?.isInsideCanvas
? this.#normalizeInsideCanvasResult(effectDrawer.isInsideCanvas(callbackData), "effect")
: undefined;
if (shapeResult && effectResult) {
const margin = Math.max(shapeResult.margin ?? Constants_js_1.defaultAngle, effectResult.margin ?? Constants_js_1.defaultAngle), useUnion = outMode === OutMode_js_1.OutMode.destroy || outMode === OutMode_js_1.OutMode.out;
return {
inside: useUnion ? shapeResult.inside || effectResult.inside : shapeResult.inside && effectResult.inside,
margin: margin > Constants_js_1.defaultAngle ? margin : undefined,
reason: "combined",
};
}
return shapeResult ?? effectResult ?? defaultResult;
}
#getRollColor(color) {
if (!color || !this.roll || (!this.backColor && !this.roll.alter)) {
return color;
}
if (!this.isShowingBack()) {
return color;
}
if (this.backColor) {
return this.backColor;
}
if (this.roll.alter) {
return (0, ColorUtils_js_1.alterHsl)(color, this.roll.alter.type, this.roll.alter.value);
}
return color;
}
#initPosition(position) {
const container = this.#container, zIndexValue = Math.floor((0, MathUtils_js_1.getRangeValue)(this.options.zIndex.value)), initialPosition = this.#calcPosition(position, (0, MathUtils_js_1.clamp)(zIndexValue, Constants_js_1.minZ, container.zLayers));
if (!initialPosition) {
throw new Error((0, ErrorUtils_js_1.getErrorMessage)(ErrorUtils_js_1.ErrorCodes.particlePositionNotFound));
}
this.position = initialPosition;
this.initialPosition = this.position.copy();
const canvasSize = container.canvas.size;
this.moveCenter = {
...(0, Utils_js_1.getPosition)(this.options.move.center, canvasSize),
radius: this.options.move.center.radius,
mode: this.options.move.center.mode,
};
this.direction = (0, MathUtils_js_1.getParticleDirectionAngle)(this.options.move.direction, this.position, this.moveCenter);
switch (this.options.move.direction) {
case MoveDirection_js_1.MoveDirection.inside:
this.outType = ParticleOutType_js_1.ParticleOutType.inside;
break;
case MoveDirection_js_1.MoveDirection.outside:
this.outType = ParticleOutType_js_1.ParticleOutType.outside;
break;
default:
break;
}
this.offset = Vectors_js_1.Vector.origin;
}
#normalizeInsideCanvasResult(result, reason) {
if (typeof result === "boolean") {
return {
inside: result,
reason,
};
}
return {
inside: result.inside,
margin: result.margin,
reason: result.reason ?? reason,
};
}
}
exports.Particle = Particle;