import { cloneVector3 } from "./Particle.js";
function distanceSquared(left, right) {
    const x = left.x - right.x;
    const y = left.y - right.y;
    const z = left.z - right.z;
    return x * x + y * y + z * z;
}
export class TrailModule {
    name = "TrailModule";
    maxPoints;
    minDistance;
    lifetime;
    constructor(options = {}) {
        this.maxPoints = options.maxPoints ?? 16;
        this.minDistance = options.minDistance ?? 0.05;
        this.lifetime = options.lifetime ?? 0.5;
        if (this.maxPoints <= 0 || this.minDistance < 0 || this.lifetime <= 0) {
            throw new RangeError("TrailModule maxPoints and lifetime must be positive, and minDistance must be non-negative.");
        }
    }
    onSpawn(particle, _context) {
        particle.userData.trail = [{ position: cloneVector3(particle.position), age: 0 }];
    }
    afterIntegrate(particle, context) {
        const trail = this.getTrail(particle);
        for (const point of trail) {
            point.age += context.deltaTime;
        }
        while (trail.length > 0 && trail[0].age > this.lifetime) {
            trail.shift();
        }
        const last = trail[trail.length - 1];
        if (!last || distanceSquared(last.position, particle.position) >= this.minDistance * this.minDistance) {
            trail.push({ position: cloneVector3(particle.position), age: 0 });
        }
        while (trail.length > this.maxPoints) {
            trail.shift();
        }
    }
    getTrail(particle) {
        const trail = particle.userData.trail;
        if (!Array.isArray(trail)) {
            const next = [];
            particle.userData.trail = next;
            return next;
        }
        return trail;
    }
}
//# sourceMappingURL=TrailModule.js.map