UNPKG

@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.

478 lines (477 loc) • 17.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Container = void 0; const MathUtils_js_1 = require("../Utils/MathUtils.js"); const Constants_js_1 = require("./Utils/Constants.js"); const Utils_js_1 = require("../Utils/Utils.js"); const CanvasManager_js_1 = require("./CanvasManager.js"); const EventListeners_js_1 = require("./Utils/EventListeners.js"); const EventType_js_1 = require("../Enums/Types/EventType.js"); const HdrMode_js_1 = require("../Enums/Modes/HdrMode.js"); const Options_js_1 = require("../Options/Classes/Options.js"); const ParticlesManager_js_1 = require("./ParticlesManager.js"); const Retina_js_1 = require("./Retina.js"); const LogUtils_js_1 = require("../Utils/LogUtils.js"); const OptionLoader_js_1 = require("../Utils/OptionLoader.js"); const TypeUtils_js_1 = require("../Utils/TypeUtils.js"); function guardCheck(container) { return !container.destroyed; } function updateDelta(delta, value, fpsLimit = Constants_js_1.defaultFps, smooth = false) { delta.value = value; delta.factor = smooth ? Constants_js_1.defaultFps / fpsLimit : (Constants_js_1.defaultFps * value) / Constants_js_1.millisecondsToSeconds; } function loadContainerOptions(pluginManager, container, ...sourceOptionsArr) { const options = new Options_js_1.Options(pluginManager, container); (0, OptionLoader_js_1.loadOptions)(options, ...sourceOptionsArr); return options; } const emptyPlugins = Object.freeze([]); class Container { actualOptions; canvas; destroyed; effectDrawers; fpsLimit; hdr; hdrMode; id; pageHidden; particles; particleUpdaters; peakNits; retina; shapeDrawers; started; zLayers; #delay; #delayResolve; #delayTimeout; #delta = { value: 0, factor: 0 }; #dispatchCallback; #drawAnimationFrame; #duration; #eventListeners; #firstStart; #initialSourceOptions; #lastFrameTime; #lifeTime; #onDestroy; #options; #particleCreatedPlugins = emptyPlugins; #particleDestroyedPlugins = emptyPlugins; #particlePositionPlugins = emptyPlugins; #paused; #pluginManager; #plugins = emptyPlugins; #smooth; #sourceOptions; #startCancel; #startGeneration = 0; #startPromise; constructor(params) { const { dispatchCallback, pluginManager, id, onDestroy, sourceOptions } = params; this.#pluginManager = pluginManager; this.#dispatchCallback = dispatchCallback; this.#onDestroy = onDestroy; this.id = Symbol(id); this.fpsLimit = 120; this.hdr = false; this.hdrMode = HdrMode_js_1.HdrMode.standard; this.peakNits = 400; this.#smooth = false; this.#delay = 0; this.#duration = 0; this.#lifeTime = 0; this.#firstStart = true; this.started = false; this.destroyed = false; this.#paused = true; this.#lastFrameTime = 0; this.zLayers = 100; this.pageHidden = false; this.#sourceOptions = sourceOptions; this.#initialSourceOptions = sourceOptions; this.effectDrawers = new Map(); this.shapeDrawers = new Map(); this.particleUpdaters = []; this.retina = new Retina_js_1.Retina(this); this.canvas = new CanvasManager_js_1.CanvasManager(this.#pluginManager, this); this.particles = new ParticlesManager_js_1.ParticlesManager(this.#pluginManager, this); this.#options = loadContainerOptions(this.#pluginManager, this); this.actualOptions = loadContainerOptions(this.#pluginManager, this); this.#eventListeners = new EventListeners_js_1.EventListeners(this); this.dispatchEvent(EventType_js_1.EventType.containerBuilt); } get animationStatus() { return !this.#paused && !this.pageHidden && guardCheck(this); } get options() { return this.#options; } get particleCreatedPlugins() { return this.#particleCreatedPlugins; } get particleDestroyedPlugins() { return this.#particleDestroyedPlugins; } get particlePositionPlugins() { return this.#particlePositionPlugins; } get plugins() { return this.#plugins; } get sourceOptions() { return this.#sourceOptions; } addLifeTime(value) { this.#lifeTime += value; } alive() { return !this.#duration || this.#lifeTime <= this.#duration; } destroy(remove = true) { if (!guardCheck(this)) { return; } this.stop(); this.particles.destroy(); this.canvas.destroy(); for (const [, effectDrawer] of this.effectDrawers) { effectDrawer.destroy?.(this); } for (const [, shapeDrawer] of this.shapeDrawers) { shapeDrawer.destroy?.(this); } for (const plugin of this.plugins) { plugin.destroy?.(); } this.effectDrawers = new Map(); this.shapeDrawers = new Map(); this.particleUpdaters = []; this.#plugins = emptyPlugins; this.destroyed = true; this.#onDestroy(remove); this.dispatchEvent(EventType_js_1.EventType.containerDestroyed); } dispatchEvent(type, data) { this.#dispatchCallback(type, { container: this, data, }); } draw(force) { if (!guardCheck(this)) { return; } if (this.#drawAnimationFrame !== undefined) { if (!force) { return; } (0, MathUtils_js_1.cancelAnimation)(this.#drawAnimationFrame); this.#drawAnimationFrame = undefined; } let refreshTime = force; this.#drawAnimationFrame = (0, MathUtils_js_1.animate)((timestamp) => { this.#drawAnimationFrame = undefined; if (refreshTime) { this.#lastFrameTime = undefined; refreshTime = false; } this.#nextFrame(timestamp); }); } async export(type, options = {}) { for (const plugin of this.plugins) { if (!plugin.export) { continue; } const res = await plugin.export(type, options); if (!res.supported) { continue; } return res.blob; } (0, LogUtils_js_1.getLogger)().error(`Export plugin with type ${type} not found`); return undefined; } async init() { if (!guardCheck(this)) { return; } const generation = this.#startGeneration, allContainerPlugins = new Map(); for (const plugin of this.#pluginManager.plugins) { const containerPlugin = await plugin.getPlugin(this); if (generation !== this.#startGeneration || this.destroyed) { return; } if (containerPlugin.preInit) { await containerPlugin.preInit(); if (generation !== this.#startGeneration) { return; } } allContainerPlugins.set(plugin, containerPlugin); } await this.initDrawersAndUpdaters(); if (generation !== this.#startGeneration) { return; } this.#options = loadContainerOptions(this.#pluginManager, this, this.#initialSourceOptions, this.sourceOptions); this.actualOptions = loadContainerOptions(this.#pluginManager, this, this.#options); this.#initPlugins(allContainerPlugins); this.retina.init(); this.canvas.init(); this.updateActualOptions(); this.canvas.initBackground(); this.canvas.resize(); const { delay, duration, fpsLimit, smooth, zLayers } = this.actualOptions, hdrOptions = this.actualOptions.hdr; this.hdrMode = (0, TypeUtils_js_1.toEnumValue)(HdrMode_js_1.HdrMode, hdrOptions.mode, HdrMode_js_1.HdrMode.standard); this.peakNits = hdrOptions.peakNits; this.zLayers = zLayers; this.#duration = (0, MathUtils_js_1.getRangeValue)(duration) * Constants_js_1.millisecondsToSeconds; this.#delay = (0, MathUtils_js_1.getRangeValue)(delay) * Constants_js_1.millisecondsToSeconds; this.#lifeTime = 0; this.fpsLimit = fpsLimit > Constants_js_1.minFpsLimit ? fpsLimit : Constants_js_1.defaultFpsLimit; this.#smooth = smooth; for (const plugin of this.plugins) { await plugin.init?.(); if (generation !== this.#startGeneration) { return; } } await this.particles.init(); if (generation !== this.#startGeneration) { return; } this.dispatchEvent(EventType_js_1.EventType.containerInit); this.particles.setDensity(); for (const plugin of this.plugins) { plugin.particlesSetup?.(); } this.dispatchEvent(EventType_js_1.EventType.particlesSetup); } async initDrawersAndUpdaters() { const pluginManager = this.#pluginManager; this.effectDrawers = await (0, Utils_js_1.getItemMapFromInitializer)(this, pluginManager.initializers.effects); this.shapeDrawers = await (0, Utils_js_1.getItemMapFromInitializer)(this, pluginManager.initializers.shapes); this.particleUpdaters = await (0, Utils_js_1.getItemsFromInitializer)(this, pluginManager.initializers.updaters); } pause() { if (!guardCheck(this)) { return; } if (this.#drawAnimationFrame !== undefined) { (0, MathUtils_js_1.cancelAnimation)(this.#drawAnimationFrame); this.#drawAnimationFrame = undefined; } if (this.#paused) { return; } for (const plugin of this.plugins) { plugin.pause?.(); } if (!this.pageHidden) { this.#paused = true; } this.dispatchEvent(EventType_js_1.EventType.containerPaused); } play(force) { if (!guardCheck(this)) { return; } const needsUpdate = this.#paused || force; if (this.#firstStart && !this.actualOptions.autoPlay) { this.#firstStart = false; return; } if (this.#paused) { this.#paused = false; } if (needsUpdate) { for (const plugin of this.plugins) { if (plugin.play) { plugin.play(); } } } this.dispatchEvent(EventType_js_1.EventType.containerPlay); this.draw(needsUpdate ?? false); } async refresh() { if (!guardCheck(this)) { return; } this.stop(); return this.start(); } async reset(sourceOptions) { if (!guardCheck(this)) { return; } this.#initialSourceOptions = sourceOptions; this.#sourceOptions = sourceOptions; this.#options = loadContainerOptions(this.#pluginManager, this, this.#initialSourceOptions, this.sourceOptions); this.actualOptions = loadContainerOptions(this.#pluginManager, this, this.#options); return this.refresh(); } async start() { if (!guardCheck(this) || this.started) { return; } if (this.#startPromise) { return this.#startPromise; } const generation = ++this.#startGeneration; let cancel; const cancelled = new Promise(resolve => { cancel = resolve; }); this.#startCancel = cancel; this.#startPromise = (async () => { try { await Promise.race([this.init(), cancelled]); if (generation !== this.#startGeneration) { return; } this.started = true; await Promise.race([ new Promise(resolve => { this.#delayResolve = resolve; this.#delayTimeout = setTimeout(() => { this.#delayTimeout = undefined; this.#delayResolve = undefined; resolve(); }, this.#delay); }), cancelled, ]); if (generation !== this.#startGeneration || this.destroyed) { return; } this.#eventListeners.addListeners(); const startPlugins = async () => { for (const plugin of this.plugins) { if (generation !== this.#startGeneration) { return; } await plugin.start?.(); } }; await Promise.race([startPlugins(), cancelled]); if (generation !== this.#startGeneration) { return; } this.dispatchEvent(EventType_js_1.EventType.containerStarted); this.play(); } catch (error) { if (generation === this.#startGeneration && !this.destroyed) { this.stop(); } throw error; } finally { if (generation === this.#startGeneration) { this.#startPromise = undefined; this.#startCancel = undefined; } } })(); return this.#startPromise; } stop() { if (!guardCheck(this)) { return; } this.#startGeneration++; this.#startCancel?.(); this.#startCancel = undefined; this.#startPromise = undefined; if (!this.started) { return; } if (this.#delayTimeout !== undefined) { clearTimeout(this.#delayTimeout); this.#delayTimeout = undefined; this.#delayResolve?.(); this.#delayResolve = undefined; } this.#firstStart = true; this.started = false; this.#eventListeners.removeListeners(); this.pause(); this.particles.clear(); this.canvas.stop(); for (const plugin of this.plugins) { plugin.stop?.(); } this.#particleCreatedPlugins = emptyPlugins; this.#particleDestroyedPlugins = emptyPlugins; this.#particlePositionPlugins = emptyPlugins; this.#sourceOptions = this.#options; this.dispatchEvent(EventType_js_1.EventType.containerStopped); } updateActualOptions() { let refresh = false; for (const plugin of this.plugins) { if (plugin.updateActualOptions) { refresh = plugin.updateActualOptions() || refresh; } } this.canvas.render.updateBackgroundElement(); return refresh; } #initPlugins(allContainerPlugins) { const plugins = [], particleCreatedPlugins = [], particleDestroyedPlugins = [], particlePositionPlugins = []; for (const [plugin, containerPlugin] of allContainerPlugins) { if (!plugin.needsPlugin(this.actualOptions)) { continue; } plugins.push(containerPlugin); if (containerPlugin.particleCreated) { particleCreatedPlugins.push(containerPlugin); } if (containerPlugin.particleDestroyed) { particleDestroyedPlugins.push(containerPlugin); } if (containerPlugin.particlePosition) { particlePositionPlugins.push(containerPlugin); } } this.#plugins = Object.freeze(plugins); this.#particleCreatedPlugins = Object.freeze(particleCreatedPlugins); this.#particleDestroyedPlugins = Object.freeze(particleDestroyedPlugins); this.#particlePositionPlugins = Object.freeze(particlePositionPlugins); } #nextFrame(timestamp) { try { if (!this.#smooth && this.#lastFrameTime !== undefined && timestamp < this.#lastFrameTime + Constants_js_1.millisecondsToSeconds / this.fpsLimit) { this.draw(false); return; } this.#lastFrameTime ??= timestamp; updateDelta(this.#delta, timestamp - this.#lastFrameTime, this.fpsLimit, this.#smooth); this.addLifeTime(this.#delta.value); this.#lastFrameTime = timestamp; if (this.#delta.value > Constants_js_1.millisecondsToSeconds) { this.draw(false); return; } this.canvas.render.drawParticles(this.#delta); if (!this.alive()) { this.destroy(); return; } if (this.animationStatus) { this.draw(false); } } catch (e) { (0, LogUtils_js_1.getLogger)().error("error in animation loop", e); } } } exports.Container = Container;