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.

feat(render): GPU-instance the particle renderer — REARCH_RENDER RC7-1

esengineb807fbb7b367
diff --git a/desktop/package.json b/desktop/package.json
index 58128062f..37d327f32 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -14,6 +14,7 @@
"test:watch": "vitest",
"verify:render": "vite build && electron scripts/headless-verify.mjs",
"verify:render:spine": "vite build && ESTELLA_VERIFY_SCENE=/scenes/spine-test.esscene ESTELLA_VERIFY_MANIFEST=/scenes/spine-test.textures.json electron scripts/headless-verify.mjs",
+ "verify:render:particles": "vite build && ESTELLA_VERIFY_PLAY=1 ESTELLA_VERIFY_SCENE=/scenes/particle-demo.esscene ESTELLA_VERIFY_MANIFEST=/scenes/particle-demo.textures.json ESTELLA_VERIFY_STEPS=90 electron scripts/headless-verify.mjs",
"verify:smoke": "vite build && electron scripts/headless-smoke.mjs",
"mcp": "electron electron/mcp/server.mjs",
"mcp:smoke": "vite build && node electron/mcp/smoke.mjs"
diff --git a/desktop/public/scenes/particle-demo.esscene b/desktop/public/scenes/particle-demo.esscene
new file mode 100644
index 000000000..3e1a9141c
--- /dev/null
+++ b/desktop/public/scenes/particle-demo.esscene
@@ -0,0 +1,169 @@
+{
+ "version": "1.0",
+ "name": "Main",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": { "x": 0, "y": 0, "z": 10 }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 300,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 1,
+ "name": "Fire",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": -250, "y": -100, "z": 0 } } },
+ { "type": "ParticleEmitter", "data": {
+ "rate": 40,
+ "maxParticles": 200,
+ "lifetimeMin": 0.8,
+ "lifetimeMax": 1.5,
+ "shape": 1,
+ "shapeRadius": 20,
+ "speedMin": 80,
+ "speedMax": 180,
+ "angleSpreadMin": 70,
+ "angleSpreadMax": 110,
+ "startSizeMin": 15,
+ "startSizeMax": 25,
+ "endSizeMin": 2,
+ "endSizeMax": 5,
+ "sizeEasing": 2,
+ "startColor": { "r": 1, "g": 0.6, "b": 0.1, "a": 1 },
+ "endColor": { "r": 1, "g": 0.1, "b": 0, "a": 0 },
+ "colorEasing": 1,
+ "gravity": { "x": 0, "y": 50 },
+ "simulationSpace": 0,
+ "looping": true,
+ "playOnStart": true,
+ "texture": "@uuid:24cb4e0f-7c75-4df4-9a4d-58480ee405c0"
+ }}
+ ],
+ "visible": true
+ },
+ {
+ "id": 2,
+ "name": "Sparkle",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": {} },
+ { "type": "ParticleEmitter", "data": {
+ "rate": 25,
+ "maxParticles": 150,
+ "lifetimeMin": 1,
+ "lifetimeMax": 2,
+ "shape": 0,
+ "speedMin": 100,
+ "speedMax": 250,
+ "angleSpreadMin": 0,
+ "angleSpreadMax": 360,
+ "startSizeMin": 8,
+ "startSizeMax": 14,
+ "endSizeMin": 0,
+ "endSizeMax": 0,
+ "sizeEasing": 2,
+ "startColor": { "r": 0.5, "g": 0.8, "b": 1, "a": 1 },
+ "endColor": { "r": 0.2, "g": 0.4, "b": 1, "a": 0 },
+ "colorEasing": 0,
+ "angularVelocityMin": -180,
+ "angularVelocityMax": 180,
+ "damping": 0.5,
+ "looping": true,
+ "playOnStart": true,
+ "texture": "@uuid:24cb4e0f-7c75-4df4-9a4d-58480ee405c0"
+ }}
+ ],
+ "visible": true
+ },
+ {
+ "id": 3,
+ "name": "Smoke",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 250, "y": -100, "z": 0 } } },
+ { "type": "ParticleEmitter", "data": {
+ "rate": 15,
+ "maxParticles": 100,
+ "lifetimeMin": 2,
+ "lifetimeMax": 4,
+ "shape": 1,
+ "shapeRadius": 10,
+ "speedMin": 30,
+ "speedMax": 60,
+ "angleSpreadMin": 60,
+ "angleSpreadMax": 120,
+ "startSizeMin": 20,
+ "startSizeMax": 30,
+ "endSizeMin": 80,
+ "endSizeMax": 120,
+ "sizeEasing": 2,
+ "startColor": { "r": 0.5, "g": 0.5, "b": 0.5, "a": 0.6 },
+ "endColor": { "r": 0.3, "g": 0.3, "b": 0.3, "a": 0 },
+ "colorEasing": 1,
+ "gravity": { "x": 0, "y": 20 },
+ "damping": 0.3,
+ "looping": true,
+ "playOnStart": true,
+ "texture": "@uuid:24cb4e0f-7c75-4df4-9a4d-58480ee405c0"
+ }}
+ ],
+ "visible": true
+ },
+ {
+ "id": 4,
+ "name": "Burst",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 180, "z": 0 } } },
+ { "type": "ParticleEmitter", "data": {
+ "rate": 0,
+ "burstCount": 30,
+ "burstInterval": 2,
+ "maxParticles": 200,
+ "lifetimeMin": 0.5,
+ "lifetimeMax": 1.2,
+ "shape": 0,
+ "speedMin": 200,
+ "speedMax": 400,
+ "angleSpreadMin": 0,
+ "angleSpreadMax": 360,
+ "startSizeMin": 6,
+ "startSizeMax": 12,
+ "endSizeMin": 0,
+ "endSizeMax": 0,
+ "sizeEasing": 0,
+ "startColor": { "r": 1, "g": 0.9, "b": 0.2, "a": 1 },
+ "endColor": { "r": 1, "g": 0.3, "b": 0.1, "a": 0 },
+ "gravity": { "x": 0, "y": -200 },
+ "looping": true,
+ "playOnStart": true,
+ "texture": "@uuid:24cb4e0f-7c75-4df4-9a4d-58480ee405c0"
+ }}
+ ],
+ "visible": true
+ }
+ ]
+}
diff --git a/desktop/public/scenes/particle-demo.textures.json b/desktop/public/scenes/particle-demo.textures.json
new file mode 100644
index 000000000..0acb647eb
--- /dev/null
+++ b/desktop/public/scenes/particle-demo.textures.json
@@ -0,0 +1,3 @@
+{
+ "24cb4e0f-7c75-4df4-9a4d-58480ee405c0": "/scenes/particle-demo/textures/particle.png"
+}
diff --git a/desktop/public/scenes/particle-demo/textures/particle.png b/desktop/public/scenes/particle-demo/textures/particle.png
new file mode 100644
index 000000000..a8962624f
Binary files /dev/null and b/desktop/public/scenes/particle-demo/textures/particle.png differ
diff --git a/desktop/scripts/headless-verify.mjs b/desktop/scripts/headless-verify.mjs
index b00f7eed2..cc7acfab6 100644
--- a/desktop/scripts/headless-verify.mjs
+++ b/desktop/scripts/headless-verify.mjs
@@ -91,6 +91,11 @@ app.whenReady().then(async () => {
const entityCount = await exec(
`window.__estellaHeadless.api.loadScene(${JSON.stringify(SCENE)}, ${JSON.stringify(MANIFEST)})`,
);
+ // Opt-in play mode (ESTELLA_VERIFY_PLAY=1): runs the SDK plugin updates — particle
+ // emission/simulation, animation — so time-driven content actually renders.
+ if (process.env.ESTELLA_VERIFY_PLAY === '1') {
+ await exec('window.__estellaHeadless.api.setRunMode(true)');
+ }
await exec(`window.__estellaHeadless.api.step(${STEPS}, 1 / 60)`);
const capture = await exec(`(() => {
const c = window.__estellaHeadless.api.captureViewport();
diff --git a/src/esengine/renderer/DrawCommand.hpp b/src/esengine/renderer/DrawCommand.hpp
index 50a93d236..05577b4e7 100644
--- a/src/esengine/renderer/DrawCommand.hpp
+++ b/src/esengine/renderer/DrawCommand.hpp
@@ -42,6 +42,10 @@ struct DrawCommand {
u32 entity_count = 1;
bool merged = false;
+ // > 0 selects an instanced draw: index_count indices drawn instance_count times,
+ // with per-instance attributes based at vertex_byte_offset (see LayoutId::ParticleInstance).
+ u32 instance_count = 0;
+
static u64 buildSortKey(RenderStage stage, i32 layer, u32 shaderId,
BlendMode blend, u16 stateFlags,
u32 textureId, f32 depth) {
@@ -69,6 +73,8 @@ struct DrawCommand {
}
bool canMergeWith(const DrawCommand& next) const {
+ // Instanced draws are one command per emitter — never coalesce them.
+ if (instance_count != 0 || next.instance_count != 0) return false;
if (shader_id != next.shader_id) return false;
if (blend_mode != next.blend_mode) return false;
if (layout_id != next.layout_id) return false;
diff --git a/src/esengine/renderer/DrawList.cpp b/src/esengine/renderer/DrawList.cpp
index 387a22ddd..2c4384b92 100644
--- a/src/esengine/renderer/DrawList.cpp
+++ b/src/esengine/renderer/DrawList.cpp
@@ -103,11 +103,18 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
device.bindTexture(slot, cmd.texture_ids[slot]);
}
- buffers.bindLayout(cmd.layout_id);
- device.drawElements(
- cmd.index_count,
- GfxDataType::UnsignedInt,
- static_cast<u32>(static_cast<uintptr_t>(cmd.index_offset) * sizeof(u32)));
+ if (cmd.instance_count > 0) {
+ // Instanced: static geometry (index_count indices from offset 0) drawn
+ // instance_count times, instance attributes rebased at vertex_byte_offset.
+ buffers.bindInstanceLayout(cmd.layout_id, cmd.vertex_byte_offset);
+ device.drawElementsInstanced(cmd.index_count, GfxDataType::UnsignedInt, 0, cmd.instance_count);
+ } else {
+ buffers.bindLayout(cmd.layout_id);
+ device.drawElements(
+ cmd.index_count,
+ GfxDataType::UnsignedInt,
+ static_cast<u32>(static_cast<uintptr_t>(cmd.index_offset) * sizeof(u32)));
+ }
if (capture && capture->isCapturing()) {
capture->recordDrawCall(
diff --git a/src/esengine/renderer/GfxEnums.hpp b/src/esengine/renderer/GfxEnums.hpp
index b21cfe3a5..02f0d1484 100644
--- a/src/esengine/renderer/GfxEnums.hpp
+++ b/src/esengine/renderer/GfxEnums.hpp
@@ -37,9 +37,10 @@ enum class GfxBufferTarget : u8 {
* VBO+EBO+VAO in TransientBufferPool and is part of a pipeline's identity.
*/
enum class LayoutId : u8 {
- Batch = 0,
- Shape = 2,
- MatSprite = 3,
+ Batch = 0,
+ ParticleInstance = 1, ///< Instanced: a static unit quad + a per-particle instance stream.
+ Shape = 2,
+ MatSprite = 3,
};
static constexpr u32 LAYOUT_COUNT = 4;
diff --git a/src/esengine/renderer/Shader.hpp b/src/esengine/renderer/Shader.hpp
index c934113d9..42bcc7d28 100644
--- a/src/esengine/renderer/Shader.hpp
+++ b/src/esengine/renderer/Shader.hpp
@@ -320,7 +320,9 @@ inline const char* PARTICLE_INSTANCE_VERTEX = R"(#version 300 es
layout(location = 6) in vec2 a_inst_uv_offset;
layout(location = 7) in vec2 a_inst_uv_scale;
- uniform mat4 u_projection;
+ layout(std140) uniform FrameConstants {
+ mat4 u_projection;
+ };
out vec2 v_texCoord;
out vec4 v_color;
diff --git a/src/esengine/renderer/TransientBufferPool.cpp b/src/esengine/renderer/TransientBufferPool.cpp
index 16939c12d..4f25a9fbc 100644
--- a/src/esengine/renderer/TransientBufferPool.cpp
+++ b/src/esengine/renderer/TransientBufferPool.cpp
@@ -15,7 +15,7 @@ void TransientBufferPool::init(u32 initialVertexBytes, u32 initialIndexCount) {
initial_vertex_bytes_ = initialVertexBytes;
initial_index_count_ = initialIndexCount;
- for (auto layout : {LayoutId::Batch, LayoutId::Shape, LayoutId::MatSprite}) {
+ for (auto layout : {LayoutId::Batch, LayoutId::ParticleInstance, LayoutId::Shape, LayoutId::MatSprite}) {
setupStream(layout);
}
@@ -29,6 +29,7 @@ void TransientBufferPool::shutdown() {
if (s.vao) { device_.deleteVertexArray(s.vao); s.vao = 0; }
if (s.vbo) { device_.deleteBuffer(s.vbo); s.vbo = 0; }
if (s.ebo) { device_.deleteBuffer(s.ebo); s.ebo = 0; }
+ if (s.quad_vbo) { device_.deleteBuffer(s.quad_vbo); s.quad_vbo = 0; }
s.vertex_staging.clear();
s.index_staging.clear();
s.vertex_write_pos = 0;
@@ -127,6 +128,20 @@ void TransientBufferPool::bindLayout(LayoutId layout) {
if (s.vao) device_.bindVertexArray(s.vao);
}
+void TransientBufferPool::bindInstanceLayout(LayoutId layout, u32 instanceByteOffset) {
+ Stream& s = stream(layout);
+ device_.bindVertexArray(s.vao);
+ // Rebase the per-instance attributes to this emitter's slice (no baseInstance in GLES3).
+ device_.bindVertexBuffer(s.vbo);
+ constexpr u32 IS = 40;
+ device_.vertexAttribPointer(2, 2, GfxDataType::Float, false, IS, instanceByteOffset + 0);
+ device_.vertexAttribPointer(3, 2, GfxDataType::Float, false, IS, instanceByteOffset + 8);
+ device_.vertexAttribPointer(4, 1, GfxDataType::Float, false, IS, instanceByteOffset + 16);
+ device_.vertexAttribPointer(5, 4, GfxDataType::UnsignedByte, true, IS, instanceByteOffset + 20);
+ device_.vertexAttribPointer(6, 2, GfxDataType::Float, false, IS, instanceByteOffset + 24);
+ device_.vertexAttribPointer(7, 2, GfxDataType::Float, false, IS, instanceByteOffset + 32);
+}
+
u8* TransientBufferPool::vertexData(LayoutId layout) {
return stream(layout).vertex_staging.data();
}
@@ -150,6 +165,59 @@ u32 TransientBufferPool::eboId(LayoutId layout) const {
void TransientBufferPool::setupStream(LayoutId layout) {
Stream& s = stream(layout);
+ if (layout == LayoutId::ParticleInstance) {
+ // Per-instance (per-particle) stream: dynamic, streamed each frame.
+ s.vertex_staging.resize(initial_vertex_bytes_);
+ s.vbo_capacity = initial_vertex_bytes_;
+ s.vbo = device_.createBuffer();
+ device_.bindVertexBuffer(s.vbo);
+ device_.bufferData(GfxBufferTarget::Vertex, nullptr, s.vbo_capacity, true);
+
+ // Static unit quad (pos + uv) and its 6 indices, uploaded once. UVs are laid out
+ // so the instance shader's a_texCoord*uvScale+uvOffset reproduces the prior
+ // per-corner particle UVs.
+ struct QuadV { f32 px, py, u, v; };
+ const QuadV quad[4] = {
+ { -0.5f, -0.5f, 0.0f, 1.0f },
+ { 0.5f, -0.5f, 1.0f, 1.0f },
+ { 0.5f, 0.5f, 1.0f, 0.0f },
+ { -0.5f, 0.5f, 0.0f, 0.0f },
+ };
+ const u32 quadIdx[6] = { 0, 1, 2, 2, 3, 0 };
+ s.quad_vbo = device_.createBuffer();
+ device_.bindVertexBuffer(s.quad_vbo);
+ device_.bufferData(GfxBufferTarget::Vertex, quad, sizeof(quad), false);
+ s.ebo = device_.createBuffer();
+ device_.bindIndexBuffer(s.ebo);
+ device_.bufferData(GfxBufferTarget::Index, quadIdx, sizeof(quadIdx), false);
+
+ s.vao = device_.createVertexArray();
+ device_.bindVertexArray(s.vao);
+ device_.bindIndexBuffer(s.ebo);
+
+ // Static quad attributes (divisor 0).
+ device_.bindVertexBuffer(s.quad_vbo);
+ device_.enableVertexAttrib(0);
+ device_.vertexAttribPointer(0, 2, GfxDataType::Float, false, 16, 0);
+ device_.enableVertexAttrib(1);
+ device_.vertexAttribPointer(1, 2, GfxDataType::Float, false, 16, 8);
+
+ // Per-instance attributes (divisor 1); offsets rebased per draw in bindInstanceLayout.
+ constexpr u32 IS = 40;
+ device_.bindVertexBuffer(s.vbo);
+ device_.enableVertexAttrib(2); device_.vertexAttribPointer(2, 2, GfxDataType::Float, false, IS, 0); device_.vertexAttribDivisor(2, 1);
+ device_.enableVertexAttrib(3); device_.vertexAttribPointer(3, 2, GfxDataType::Float, false, IS, 8); device_.vertexAttribDivisor(3, 1);
+ device_.enableVertexAttrib(4); device_.vertexAttribPointer(4, 1, GfxDataType::Float, false, IS, 16); device_.vertexAttribDivisor(4, 1);
+ device_.enableVertexAttrib(5); device_.vertexAttribPointer(5, 4, GfxDataType::UnsignedByte, true, IS, 20); device_.vertexAttribDivisor(5, 1);
+ device_.enableVertexAttrib(6); device_.vertexAttribPointer(6, 2, GfxDataType::Float, false, IS, 24); device_.vertexAttribDivisor(6, 1);
+ device_.enableVertexAttrib(7); device_.vertexAttribPointer(7, 2, GfxDataType::Float, false, IS, 32); device_.vertexAttribDivisor(7, 1);
+
+ device_.bindVertexArray(0);
+ device_.bindVertexBuffer(0);
+ device_.bindIndexBuffer(0);
+ return;
+ }
+
s.vertex_staging.resize(initial_vertex_bytes_);
s.index_staging.resize(initial_index_count_);
s.vbo_capacity = initial_vertex_bytes_;
diff --git a/src/esengine/renderer/TransientBufferPool.hpp b/src/esengine/renderer/TransientBufferPool.hpp
index 090fed1a4..46cf11edc 100644
--- a/src/esengine/renderer/TransientBufferPool.hpp
+++ b/src/esengine/renderer/TransientBufferPool.hpp
@@ -47,6 +47,13 @@ public:
/** Bind the VAO for this layout (which also binds its EBO — VAO state). */
void bindLayout(LayoutId layout);
+ /**
+ * Bind an instanced layout and re-point its per-instance attributes to @p instanceByteOffset.
+ * GLES3 has no baseInstance, so each emitter's instanced draw rebases the instance
+ * attributes here before drawElementsInstanced. The static quad attributes are untouched.
+ */
+ void bindInstanceLayout(LayoutId layout, u32 instanceByteOffset);
+
/** Direct write-through pointer into a layout's staging, for hot paths
* that want to format vertices in place after `allocVertices`. */
u8* vertexData(LayoutId layout);
@@ -57,9 +64,10 @@ public:
private:
struct Stream {
- u32 vbo = 0;
+ u32 vbo = 0; // for ParticleInstance this is the per-instance (streamed) buffer
u32 ebo = 0;
u32 vao = 0;
+ u32 quad_vbo = 0; // ParticleInstance only: static unit-quad geometry (divisor 0)
std::vector<u8> vertex_staging;
std::vector<u32> index_staging; // 32-bit indices: a single Batch stream can exceed 65535 vertices
u32 vertex_write_pos = 0;
diff --git a/src/esengine/renderer/plugins/ParticlePlugin.cpp b/src/esengine/renderer/plugins/ParticlePlugin.cpp
index f7e117191..7c2909d2f 100644
--- a/src/esengine/renderer/plugins/ParticlePlugin.cpp
+++ b/src/esengine/renderer/plugins/ParticlePlugin.cpp
@@ -1,8 +1,9 @@
#include "ParticlePlugin.hpp"
-#include "../BatchBuilder.hpp"
#include "../RenderContext.hpp"
+#include "../RenderFrame.hpp"
+#include "../Shader.hpp"
#include "../Texture.hpp"
-#include "../BatchVertex.hpp"
+#include "../BatchVertex.hpp" // packColor
#include "../../ecs/components/Transform.hpp"
#include "../../ecs/components/ParticleEmitter.hpp"
#include "../../particle/ParticleSystem.hpp"
@@ -12,8 +13,35 @@
namespace esengine {
+namespace {
+// One record per live particle, matching the PARTICLE_INSTANCE vertex attributes
+// (locations 2-7). The GPU expands the 4-vertex quad; the CPU only fills these 40 bytes
+// per particle (vs. the old 4 verts + 6 indices), which is the whole point of RC7-1.
+struct ParticleInstanceData {
+ f32 px, py; // a_inst_position (world)
+ f32 sx, sy; // a_inst_size
+ f32 rotation; // a_inst_rotation
+ u32 color; // a_inst_color (RGBA8)
+ f32 uvOffsetX, uvOffsetY;
+ f32 uvScaleX, uvScaleY;
+};
+static_assert(sizeof(ParticleInstanceData) == 40, "instance stride must match the VAO layout");
+} // namespace
+
void ParticlePlugin::init(RenderFrameContext& ctx) {
- batch_shader_id_ = ctx.batch_shader_id;
+ // Activate the (previously dead) instancing shader. Attribute locations are explicit
+ // in the GLSL, so no name bindings are needed.
+ auto handle = ctx.resources.createShaderWithBindings(
+ ShaderSources::PARTICLE_INSTANCE_VERTEX,
+ ShaderSources::PARTICLE_INSTANCE_FRAGMENT,
+ {});
+ Shader* shader = ctx.resources.getShader(handle);
+ if (shader && shader->isValid()) {
+ particle_shader_id_ = shader->getProgramId();
+ shader->bind();
+ shader->setUniform("u_texture", 0); // sampler unit 0
+ shader->unbind();
+ }
}
void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {
@@ -22,7 +50,7 @@ void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {
auto& buffers = collect_ctx.buffer_pool;
auto& draw_list = collect_ctx.draw_list;
auto& ctx = collect_ctx.frame_context;
- if (!particle_system_) return;
+ if (!particle_system_ || particle_shader_id_ == 0) return;
auto emitterView = registry.view<ecs::Transform, ecs::ParticleEmitter>();
@@ -39,15 +67,14 @@ void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {
u32 textureId = ctx.white_texture_id;
if (emitter.texture.isValid()) {
Texture* tex = ctx.resources.getTexture(emitter.texture);
- if (tex) {
- textureId = tex->getId();
- }
+ if (tex) textureId = tex->getId();
}
i32 cols = std::max(emitter.spriteColumns, 1);
i32 rows = std::max(emitter.spriteRows, 1);
f32 uvScaleX = 1.0f / static_cast<f32>(cols);
f32 uvScaleY = 1.0f / static_cast<f32>(rows);
+ bool sheet = (cols > 1 || rows > 1);
bool isLocalSpace = emitter.simulationSpace ==
static_cast<i32>(ecs::SimulationSpace::Local);
@@ -67,27 +94,20 @@ void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {
BlendMode blendMode = static_cast<BlendMode>(emitter.blendMode);
u32 particleCount = state->pool.aliveCount();
- u32 vertCount = particleCount * 4;
- u32 idxCount = particleCount * 6;
-
- u32 vertByteSize = vertCount * sizeof(BatchVertex);
- u32 vertByteOffset = buffers.allocVertices(LayoutId::Batch, vertByteSize);
- u32 idxOffset = buffers.allocIndices(LayoutId::Batch, idxCount);
+ u32 instByteOffset = buffers.allocVertices(LayoutId::ParticleInstance,
+ particleCount * sizeof(ParticleInstanceData));
+ auto* inst = reinterpret_cast<ParticleInstanceData*>(
+ buffers.vertexData(LayoutId::ParticleInstance) + instByteOffset);
- auto* verts = reinterpret_cast<BatchVertex*>(buffers.vertexData(LayoutId::Batch) + vertByteOffset);
- u32 baseVertex = static_cast<u32>(vertByteOffset / sizeof(BatchVertex));
-
- u32 pi = 0;
+ u32 i = 0;
state->pool.forEachAlive([&](const particle::Particle& p) {
glm::vec2 worldPos;
glm::vec2 size;
-
if (isLocalSpace) {
glm::vec2 rel = p.position * emitterScale;
if (std::abs(emitterAngle) > 0.001f) {
worldPos = glm::vec2(emitterWorldPos) +
- glm::vec2(rel.x * cosA - rel.y * sinA,
- rel.x * sinA + rel.y * cosA);
+ glm::vec2(rel.x * cosA - rel.y * sinA, rel.x * sinA + rel.y * cosA);
} else {
worldPos = glm::vec2(emitterWorldPos) + rel;
}
@@ -97,66 +117,44 @@ void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {
size = glm::vec2(p.size);
}
- u32 color = packColor(p.color);
- f32 halfW = size.x * 0.5f;
- f32 halfH = size.y * 0.5f;
-
- f32 cosR = std::cos(p.rotation);
- f32 sinR = std::sin(p.rotation);
-
- glm::vec2 corners[4] = {
- { -halfW, -halfH },
- { halfW, -halfH },
- { halfW, halfH },
- { -halfW, halfH },
- };
-
- f32 u0, v0, u1, v1;
- if (cols > 1 || rows > 1) {
+ f32 u0 = 0.0f, v0 = 0.0f;
+ if (sheet) {
i32 col = p.sprite_frame % cols;
i32 row = p.sprite_frame / cols;
u0 = static_cast<f32>(col) * uvScaleX;
v0 = static_cast<f32>(row) * uvScaleY;
- u1 = u0 + uvScaleX;
- v1 = v0 + uvScaleY;
- } else {
- u0 = 0.0f; v0 = 0.0f; u1 = 1.0f; v1 = 1.0f;
}
- u32 vi = pi * 4;
- for (u32 c = 0; c < 4; ++c) {
- f32 rx = corners[c].x * cosR - corners[c].y * sinR;
- f32 ry = corners[c].x * sinR + corners[c].y * cosR;
- verts[vi + c].position = worldPos + glm::vec2(rx, ry);
- verts[vi + c].color = color;
- }
- verts[vi + 0].texCoord = { u0, v1 };
- verts[vi + 1].texCoord = { u1, v1 };
- verts[vi + 2].texCoord = { u1, v0 };
- verts[vi + 3].texCoord = { u0, v0 };
-
- u32 ii = pi * 6;
- u32 bv = baseVertex + static_cast<u32>(vi);
- // Patch base vertex into indices
- u32 patched[6];
- for (u32 q = 0; q < 6; ++q) {
- patched[q] = bv + BATCH_QUAD_INDICES[q];
- }
- buffers.writeIndices(LayoutId::Batch, idxOffset + ii, patched, 6);
-
- ++pi;
+ ParticleInstanceData& d = inst[i++];
+ d.px = worldPos.x; d.py = worldPos.y;
+ d.sx = size.x; d.sy = size.y;
+ d.rotation = p.rotation;
+ d.color = packColor(p.color);
+ d.uvOffsetX = u0; d.uvOffsetY = v0;
+ d.uvScaleX = sheet ? uvScaleX : 1.0f;
+ d.uvScaleY = sheet ? uvScaleY : 1.0f;
});
- pushBatchDraw(draw_list, clips, vertByteOffset, idxOffset, idxCount, BatchDrawKey{
- .stage = ctx.current_stage,
- .layer = emitter.layer,
- .shaderId = batch_shader_id_,
- .blend = blendMode,
- .textureId = textureId,
- .depth = emitterWorldPos.z,
- .entity = entity,
- .type = RenderType::Particle,
- });
+ DrawCommand cmd{};
+ cmd.sort_key = DrawCommand::buildSortKey(
+ ctx.current_stage, emitter.layer, particle_shader_id_, blendMode, 0, textureId,
+ emitterWorldPos.z);
+ cmd.index_offset = 0; // static unit-quad indices
+ cmd.index_count = 6;
+ cmd.vertex_byte_offset = instByteOffset; // base of this emitter's instance slice
+ cmd.instance_count = particleCount;
+ cmd.shader_id = particle_shader_id_;
+ cmd.blend_mode = blendMode;
+ cmd.layout_id = LayoutId::ParticleInstance;
+ cmd.texture_count = 1;
+ cmd.texture_ids[0] = textureId;
+ cmd.entity = entity;
+ cmd.entity_count = 1;
+ cmd.type = RenderType::Particle;
+ cmd.layer = emitter.layer;
+
+ clips.applyTo(entity, cmd);
+ draw_list.push(cmd);
}
}
diff --git a/src/esengine/renderer/plugins/ParticlePlugin.hpp b/src/esengine/renderer/plugins/ParticlePlugin.hpp
index 08609cdd5..68266b131 100644
--- a/src/esengine/renderer/plugins/ParticlePlugin.hpp
+++ b/src/esengine/renderer/plugins/ParticlePlugin.hpp
@@ -19,7 +19,7 @@ public:
private:
particle::ParticleSystem* particle_system_ = nullptr;
- u32 batch_shader_id_ = 0;
+ u32 particle_shader_id_ = 0; // PARTICLE_INSTANCE program (GPU instancing)
};
} // namespace esengine