Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

1.6 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
#pragma once

#include "../core/Types.hpp"
#include "../math/Math.hpp"

#include <functional>
#include <vector>

namespace esengine::particle {

struct Particle {
    glm::vec3 position{0.0f};
    glm::vec3 velocity{0.0f};
    glm::vec3 added_velocity{0.0f};  ///< Carried on top of `velocity`, outside gravity, damping and the speed limit.
    f32 rotation = 0.0f;
    f32 angular_velocity = 0.0f;
    f32 lifetime = 1.0f;
    f32 age = 0.0f;
    f32 size = 1.0f;
    glm::vec4 color{1.0f};
    f32 start_size = 1.0f;
    f32 end_size = 0.0f;
    glm::vec4 start_color{1.0f};
    glm::vec4 end_color{1.0f, 1.0f, 1.0f, 0.0f};
    u16 sprite_frame = 0;
    bool alive = false;
    u32 generation = 0;
    u32 subEmitterDepth = 0;
};

class ParticlePool {
public:
    explicit ParticlePool(u32 capacity);

    Particle* allocate();
    void deallocate(Particle* particle);
    void clear();

    u32 capacity() const { return capacity_; }
    u32 aliveCount() const { return alive_count_; }
    std::vector<Particle>& particles() { return particles_; }
    const std::vector<Particle>& particles() const { return particles_; }

    void forEachAlive(const std::function<void(Particle&)>& fn);
    void forEachAlive(const std::function<void(const Particle&)>& fn) const;

    /** @brief Deallocate a particle by its pool index */
    void deallocateByIndex(u32 index);

private:
    std::vector<Particle> particles_;
    std::vector<u32> free_list_;
    u32 capacity_;
    u32 alive_count_ = 0;
    u32 next_generation_ = 0;
};

}  // namespace esengine::particle