Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
SpritePlugin.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#include "SpritePlugin.hpp"
7#include "../rhi/Texture.hpp"
17
19
20#include <algorithm>
21#include <bit>
22#include <cmath>
23
24namespace esengine {
25
27 auto& registry = collect_ctx.registry;
28 auto& clips = collect_ctx.clip_state;
29 auto& buffers = collect_ctx.buffer_pool;
30 auto& draw_list = collect_ctx.draw_list;
31 auto& ctx = collect_ctx.frame_context;
32 auto spriteView = registry.activeView<ecs::Transform, ecs::Sprite>();
33
34 u32 litProgram = 0;
35 const ecs::GroupOpacityLookup groupOpacity(registry);
36
37 for (auto entity : spriteView) {
38 if (!collect_ctx.accepts(entity)) continue;
39 const auto& sprite = spriteView.get<ecs::Sprite>(entity);
40 if (!sprite.enabled) continue;
41 if (registry.has<ecs::UINode>(entity)) continue; // UI sprites are drawn by UIElementPlugin
42
43 auto& transform = spriteView.get<ecs::Transform>(entity);
44 glm::vec3 position = parallaxedWorldPosition(transform, sprite.parallax, collect_ctx.camera);
45 const auto& rotation = transform.worldRotation;
46 const auto& scale = transform.worldScale;
47
48 const bool parented = registry.has<ecs::Parent>(entity);
49 if (scale.x == 0 || scale.y == 0 || !ecs::hasFlatGeometryArea(registry, entity, transform)
50 || sprite.size.x == 0.0f || sprite.size.y == 0.0f) continue;
51
52 glm::vec2 finalSize = sprite.size * glm::vec2(scale);
53 // The quad turns about `position`, so its pivot offset turns with it and its
54 // extents grow. Bounding the unturned box instead loses a turned sprite while
55 // part of it is still on screen — at 45 degrees the box is 41% short.
56 const glm::vec2 turn = flatTurnZ(rotation);
57 const glm::vec3 axisX = parented ? glm::vec3(transform.cachedMatrix_[0])
58 : glm::vec3(turn.x, turn.y, 0.0f) * scale.x;
59 const glm::vec3 axisY = parented ? glm::vec3(transform.cachedMatrix_[1])
60 : glm::vec3(-turn.y, turn.x, 0.0f) * scale.y;
61 const glm::vec2 pivotOffset = (glm::vec2(.5f) - sprite.pivot) * sprite.size;
62 const glm::vec3 aabbCenter = position + axisX * pivotOffset.x + axisY * pivotOffset.y;
63 const glm::vec3 halfExtents = glm::abs(axisX) * std::abs(sprite.size.x) * .5f
64 + glm::abs(axisY) * std::abs(sprite.size.y) * .5f;
65 // Never depth-tested unless a material says so, and that is resolved
66 // below — so a sprite is judged by the view alone, and an occluder in
67 // front of it does not get to speak.
68 if (!collect_ctx.visible(aabbCenter, halfExtents, false)) {
69 ++collect_ctx.culled;
70 continue;
71 }
72
73 f32 angle = 2.0f * std::atan2(rotation.z, rotation.w);
74
75 u32 textureId = ctx.white_texture_id;
76 glm::vec2 texSize{0.0f};
77 bool useNineSlice = false;
78 resource::SliceBorder sliceBorder{};
79
80 if (sprite.texture.isValid()) {
81 Texture* tex = ctx.resources.getTexture(sprite.texture);
82 if (tex) {
83 textureId = tex->getId();
84 texSize = glm::vec2(
85 static_cast<f32>(tex->getWidth()),
86 static_cast<f32>(tex->getHeight())
87 );
88 const auto* metadata = ctx.resources.getTextureMetadata(sprite.texture);
89 if (metadata && metadata->sliceBorder.hasSlicing()) {
90 useNineSlice = true;
91 sliceBorder = metadata->sliceBorder;
92 }
93 }
94 }
95
96 glm::vec2 uvOff = sprite.uvOffset;
97 glm::vec2 uvSc = sprite.uvScale;
98 if (sprite.flipX) {
99 uvOff.x += uvSc.x;
100 uvSc.x = -uvSc.x;
101 }
102 if (sprite.flipY) {
103 uvOff.y += uvSc.y;
104 uvSc.y = -uvSc.y;
105 }
106
108 sprite.drawMode,
109 sprite.tileSize.x > 0.0f && sprite.tileSize.y > 0.0f,
110 useNineSlice);
111 const bool hasTiling = draw.tiled;
112 useNineSlice = draw.nineSlice;
113
114 // Emit into the existing batch stream, then map just this sprite's new
115 // vertices through its full basis. Parent matrices may contain shear;
116 // tiled grids also need positive steps before applying signed axes.
117 const bool mapBasis = parented || hasTiling;
118 if (mapBasis) angle = 0.0f;
119 const u32 vertexStart = buffers.vertexBytesUsed(LayoutId::Batch);
120
121 BatchDrawKey key{
122 .stage = ctx.current_stage,
123 .layer = collect_ctx.treeLayer(entity, sprite.layer),
124 .order = sprite.order,
125 .shaderId = batch_shader_id_,
126 .blend = BlendMode::Normal,
127 .textureId = textureId,
128 .depth = collect_ctx.sortDepth(position),
129 .y = position.y,
130 .entity = entity,
131 .type = RenderType::Sprite,
132 };
133
134 // Resolve the material handle to its engine-side render state. An unregistered
135 // handle falls back to the default batch shader (treated as no material), so a
136 // dangling reference renders plainly instead of binding a bogus program.
137 if (sprite.material != 0) {
138 if (const MaterialRecord* m = ctx.materials ? ctx.materials->find(sprite.material) : nullptr) {
139 key.shaderId = (m->shader != 0) ? m->shader : batch_shader_id_;
140 key.blend = m->blend;
141 key.materialId = sprite.material;
142 key.depthTest = m->depthTest;
143 key.depthWrite = m->depthWrite;
144 key.cull = static_cast<u8>(m->cull);
145 key.depthBias = m->depthBias;
146 }
147 } else if (sprite.lit && ctx.frame) {
148 // A material owns shading fully, so it takes precedence over the toggle.
149 if (litProgram == 0) litProgram = ctx.frame->batchProgram(BatchVariant::Lit);
150 if (litProgram != 0) key.shaderId = litProgram;
151 }
152
153 // A mask with a cutoff cuts to the SHAPE it draws, not its box: this same draw runs
154 // with colour writes off to fill the stencil, so it needs the variant that discards
155 // transparent fragments or a round mask cuts a rectangle. Same resolution as UIMask.
156 if (ctx.frame) {
157 if (const auto* mask = registry.tryGet<ecs::SpriteMask>(entity);
158 mask && mask->enabled && mask->alphaCutoff > 0.0f) {
159 key.shaderId = ctx.frame->batchProgram(BatchVariant::AlphaClip);
160 }
161 }
162
163 glm::vec4 color = sprite.color;
164 color.a *= groupOpacity.of(entity);
165 if (color.a <= 0.0f) continue;
166
167 if (hasTiling) {
168 emitTiledQuads(buffers, draw_list, clips,
169 position, finalSize, sprite.pivot,
170 angle, color, uvOff, uvSc,
171 sprite.tileSize * glm::abs(glm::vec2(scale)),
172 sprite.tileSpacing * glm::abs(glm::vec2(scale)),
173 key);
174 } else if (useNineSlice) {
175 emitNineSlice(buffers, draw_list, clips,
176 position, finalSize, sprite.pivot,
177 angle, texSize,
178 glm::vec4(sliceBorder.left, sliceBorder.right, sliceBorder.top, sliceBorder.bottom),
179 uvOff, uvSc, color, key);
180 } else {
181 emitQuad(buffers, draw_list, clips,
182 position, finalSize, sprite.pivot,
183 angle, uvOff, uvSc, color, key);
184 }
185 if (mapBasis) {
186 const glm::vec2 divisor = hasTiling ? glm::abs(finalSize) / sprite.size
187 : glm::vec2(scale);
188 const glm::vec3 basisX = axisX / divisor.x;
189 const glm::vec3 basisY = axisY / divisor.y;
190 const u32 vertexEnd = buffers.vertexBytesUsed(LayoutId::Batch);
191 // appendQuad can grow the pool, so retrieve its pointer after emission.
192 auto* vertices = reinterpret_cast<BatchVertex*>(buffers.vertexData(LayoutId::Batch));
193 for (u32 i = vertexStart / sizeof(BatchVertex); i < vertexEnd / sizeof(BatchVertex); ++i) {
194 const glm::vec3 delta = vertices[i].position - position;
195 vertices[i].position = position + basisX * delta.x + basisY * delta.y;
196 }
197 }
198 // A lit sprite hands its layer to the fragment stage in the batch layout's last lane (text spends it on an outline, and a sprite
199 // is never SDF text), where a light's range of layers is tested against it. See SPRITE_LAYER_BIAS in LightConstants.hpp.
200 if (sprite.lit || sprite.material != 0) {
201 const u32 vertexEnd = buffers.vertexBytesUsed(LayoutId::Batch);
202 auto* vertices = reinterpret_cast<BatchVertex*>(buffers.vertexData(LayoutId::Batch));
203 // ...and with it, which of the frame's lights can reach each quad, so a pixel works out the lamps near it and not every
204 // lamp in the level (packSpriteLightLane). Quad by quad: a tiled floor is one sprite and hundreds of quads, and it is
205 // the floor that is lit. The lights were collected before any plugin ran, so the slots are the ones the loop reads.
206 const LightStore& lights = ctx.render_context.lights();
207 const GpuLight* slots = lights.data().lights;
208 const u32 lightCount = lights.count();
209 const u32 first = vertexStart / sizeof(BatchVertex);
210 const u32 end = vertexEnd / sizeof(BatchVertex);
211 const u32 step = (end - first) % 4 == 0 ? 4 : std::max(end - first, 1u);
212 for (u32 q = first; q < end; q += step) {
213 glm::vec2 lo{vertices[q].position};
214 glm::vec2 hi = lo;
215 for (u32 i = q + 1; i < q + step; ++i) {
216 lo = glm::min(lo, glm::vec2{vertices[i].position});
217 hi = glm::max(hi, glm::vec2{vertices[i].position});
218 }
219 const u32 reach = lightReachMask2D(slots, lightCount, lo, hi);
220 collect_ctx.lightsSpared += std::min(lightCount, SPRITE_LIGHT_REACH_BITS)
221 - static_cast<u32>(std::popcount(reach));
222 const f32 lane = packSpriteLightLane(sprite.layer, reach);
223 for (u32 i = q; i < q + step; ++i) vertices[i].sdfBias = lane;
224 }
225 }
226 }
227}
228
229void SpritePlugin::emitTiledQuads(
230 TransientBufferPool& buffers, DrawList& draw_list, const ClipState& clips,
231 const glm::vec3& position, const glm::vec2& size, const glm::vec2& pivot,
232 f32 angle, const glm::vec4& color,
233 const glm::vec2& uvOffset, const glm::vec2& uvScale,
234 const glm::vec2& tileSize, const glm::vec2& tileSpacing,
235 const BatchDrawKey& key
236) {
237 glm::vec2 step = tileSize + tileSpacing;
238 if (step.x <= 0.0f || step.y <= 0.0f
239 || !std::isfinite(step.x) || !std::isfinite(step.y)
240 || !std::isfinite(tileSize.x) || !std::isfinite(tileSize.y)) return;
241
242 glm::vec2 absSize = glm::vec2(std::abs(size.x), std::abs(size.y));
243 if (!std::isfinite(absSize.x) || !std::isfinite(absSize.y)) return;
244
245 f32 baseX = position.x - absSize.x * pivot.x;
246 f32 baseY = position.y - absSize.y * pivot.y;
247
248 bool hasRotation = std::abs(angle) > 0.001f;
249 f32 cosA = 1.0f, sinA = 0.0f;
250 if (hasRotation) {
251 cosA = std::cos(angle);
252 sinA = std::sin(angle);
253 }
254
255 u32 pc = packColor(color);
256
257 const f64 countY = std::ceil(static_cast<f64>(absSize.y) / step.y);
258 const f64 countX = std::ceil(static_cast<f64>(absSize.x) / step.x);
259
260 // Bound counts before integer conversion, which can turn overflowing native
261 // counts negative. Grids above the cap use one stretched quad.
262 constexpr f64 kMaxTiledQuads = 16384;
263 if (countX > kMaxTiledQuads || countY > kMaxTiledQuads
264 || countX * countY > kMaxTiledQuads) {
265 BatchVertex verts[4];
266 if (hasRotation) {
267 verts[0] = { rotatePoint(position, baseX, baseY, cosA, sinA), pc, { uvOffset.x, uvOffset.y } };
268 verts[1] = { rotatePoint(position, baseX + absSize.x, baseY, cosA, sinA), pc, { uvOffset.x + uvScale.x, uvOffset.y } };
269 verts[2] = { rotatePoint(position, baseX + absSize.x, baseY + absSize.y, cosA, sinA), pc, { uvOffset.x + uvScale.x, uvOffset.y + uvScale.y } };
270 verts[3] = { rotatePoint(position, baseX, baseY + absSize.y, cosA, sinA), pc, { uvOffset.x, uvOffset.y + uvScale.y } };
271 } else {
272 verts[0] = { { baseX, baseY, position.z }, pc, { uvOffset.x, uvOffset.y } };
273 verts[1] = { { baseX + absSize.x, baseY, position.z }, pc, { uvOffset.x + uvScale.x, uvOffset.y } };
274 verts[2] = { { baseX + absSize.x, baseY + absSize.y, position.z }, pc, { uvOffset.x + uvScale.x, uvOffset.y + uvScale.y } };
275 verts[3] = { { baseX, baseY + absSize.y, position.z }, pc, { uvOffset.x, uvOffset.y + uvScale.y } };
276 }
277 appendQuad(buffers, draw_list, clips, verts, key);
278 return;
279 }
280
281 const i32 tilesX = static_cast<i32>(countX);
282 const i32 tilesY = static_cast<i32>(countY);
283
284 tile_scratch_.clear();
285 for (i32 iy = 0; iy < tilesY; ++iy) {
286 f32 ty = static_cast<f32>(iy) * step.y;
287 f32 th = glm::min(tileSize.y, absSize.y - ty);
288 if (th <= 0.0f) break;
289 f32 vFrac = th / tileSize.y;
290
291 for (i32 ix = 0; ix < tilesX; ++ix) {
292 f32 tx = static_cast<f32>(ix) * step.x;
293 f32 tw = glm::min(tileSize.x, absSize.x - tx);
294 if (tw <= 0.0f) break;
295 f32 uFrac = tw / tileSize.x;
296
297 f32 x0 = baseX + tx;
298 f32 y0 = baseY + ty;
299 f32 x1 = x0 + tw;
300 f32 y1 = y0 + th;
301
302 glm::vec2 tileUvScale = { uvScale.x * uFrac, uvScale.y * vFrac };
303
304 if (hasRotation) {
305 tile_scratch_.push_back({ rotatePoint(position, x0, y0, cosA, sinA), pc, { uvOffset.x, uvOffset.y } });
306 tile_scratch_.push_back({ rotatePoint(position, x1, y0, cosA, sinA), pc, { uvOffset.x + tileUvScale.x, uvOffset.y } });
307 tile_scratch_.push_back({ rotatePoint(position, x1, y1, cosA, sinA), pc, { uvOffset.x + tileUvScale.x, uvOffset.y + tileUvScale.y } });
308 tile_scratch_.push_back({ rotatePoint(position, x0, y1, cosA, sinA), pc, { uvOffset.x, uvOffset.y + tileUvScale.y } });
309 } else {
310 tile_scratch_.push_back({ { x0, y0, position.z }, pc, { uvOffset.x, uvOffset.y } });
311 tile_scratch_.push_back({ { x1, y0, position.z }, pc, { uvOffset.x + tileUvScale.x, uvOffset.y } });
312 tile_scratch_.push_back({ { x1, y1, position.z }, pc, { uvOffset.x + tileUvScale.x, uvOffset.y + tileUvScale.y } });
313 tile_scratch_.push_back({ { x0, y1, position.z }, pc, { uvOffset.x, uvOffset.y + tileUvScale.y } });
314 }
315 }
316 }
317 appendQuads(buffers, draw_list, clips, tile_scratch_.data(), static_cast<u32>(tile_scratch_.size() / 4), key);
318}
319
320} // namespace esengine
Hierarchy components for parent-child relationships.
Per-frame 2D lighting constants — the third tier of the engine's constant-buffer layering (after per-...
Engine-side 2D light registry — the per-frame LightConstants UBO and its CPU mirror.
Engine-side material registry — the resolved "how to draw" for a material handle.
Rendering context containing all renderer state.
Frame resources and the shared scene rendering contract.
Which geometry a Sprite draws — the rule, apart from the frame.
Turns this entity's Sprite into a stencil the sprites drawn after it can be cut by.
2D sprite rendering component
GPU texture abstraction for 2D images.
Unified Transform component with local and world-space data.
void emitQuad(TransientBufferPool &buffers, DrawList &draw_list, const ClipState &clips, const glm::vec3 &position, const glm::vec2 &size, const glm::vec2 &pivotNorm, f32 angle, const glm::vec2 &uvOffset, const glm::vec2 &uvScale, const glm::vec4 &color, const BatchDrawKey &key)
Emits a single rotated/unrotated textured quad.
void emitNineSlice(TransientBufferPool &buffers, DrawList &draw_list, const ClipState &clips, const glm::vec3 &position, const glm::vec2 &size, const glm::vec2 &pivotNorm, f32 angle, const glm::vec2 &texSize, const glm::vec4 &border, const glm::vec2 &uvOffset, const glm::vec2 &uvScale, const glm::vec4 &color, const BatchDrawKey &key)
Emits a 3x3 nine-slice grid of quads sharing one BatchDrawKey.
Holds the per-frame 2D lights and their GPU UBO. Mirrors MaterialStore's UBO lifecycle (lazy create,...
const LightConstants & data() const
void collect(RenderCollectContext &ctx) override
2D texture for GPU rendering
Definition Texture.hpp:116
u32 getWidth() const
Gets the texture width in pixels.
Definition Texture.hpp:239
u32 getHeight() const
Gets the texture height in pixels.
Definition Texture.hpp:242
u32 getId() const
Gets the texture handle's raw value, for command payloads and the WASM boundary.
Definition Texture.hpp:236
The opacity a draw inherits from the GroupOpacity above it.
f32 of(Entity entity) const
1 when no enabled group encloses entity (itself included).
bool hasFlatGeometryArea(Transform &transform, bool parented)
void appendQuad(TransientBufferPool &pool, DrawList &drawList, const ClipState &clips, const BatchVertex quad[4], const BatchDrawKey &key)
void appendQuads(TransientBufferPool &pool, DrawList &drawList, const ClipState &clips, const BatchVertex *quads, u32 quadCount, const BatchDrawKey &key)
constexpr u32 SPRITE_LIGHT_REACH_BITS
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
constexpr SpriteDrawChoice resolveSpriteDraw(ecs::SpriteDrawMode mode, bool hasTileSize, bool hasSliceBorder)
Resolve the geometry from the author's mode and what the data offers.
glm::vec3 parallaxedWorldPosition(ecs::Transform &transform, const glm::vec2 &parallax, const CameraView &camera)
u32 packColor(f32 r, f32 g, f32 b, f32 a)
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
u32 lightReachMask2D(const GpuLight *lights, u32 count, const glm::vec2 &lo, const glm::vec2 &hi)
Bit i set when loop light i can put any light on the box lo .. hi (the plane's XY,...
double f64
64-bit floating point
Definition Types.hpp:61
glm::vec2 flatTurnZ(const glm::quat &rotation)
The cos/sin of the turn a plane renderable draws with: its entity's rotation about Z,...
glm::vec3 rotatePoint(const glm::vec3 &center, f32 px, f32 py, f32 cosA, f32 sinA)
Rotates a point around center in the XY plane, carrying the center's z through untouched — the rotati...
f32 packSpriteLightLane(i32 layer, u32 reachMask)
The lane a lit quad carries: its layer and the lights that reach it (lightReachMask2D).
static EstellaContext & ctx()
float f32
32-bit floating point
Definition Types.hpp:59
Non-geometry attributes of a batch draw — everything needed to build the sort key + DrawCommand.
i16 depthBias
Depth-buffer units toward the eye.
u8 cull
CullMode: 0 = none, 1 = back, 2 = front.
One vertex of the shared batch stream.
One 2D light, std140-packed (six vec4s, 96 bytes, 16-aligned).
GpuLight lights[MAX_LIGHTS]
A material's resolved render state (P0) plus its packed std140 constants (P1).
u32 culled
How many renderables this collect's frustum rejected.
f32 sortDepth(const glm::vec3 &worldPos) const
The sort depth of a draw anchored at worldPos.
bool accepts(Entity entity) const
Whether entity belongs to THIS collect.
i32 treeLayer(Entity entity, i32 authored) const
The layer entity draws at: its place in a Canvas's tree, unless its author named one.
bool visible(const glm::vec3 &centre, const glm::vec3 &halfExtents, bool depthTested)
Whether a renderable bounded by centre / halfExtents is drawn.
u32 lightsSpared
Light slots the lit quads of this collect were spared: per quad, the loop lights that cannot reach it...
Parent reference component.
Definition Hierarchy.hpp:46
A stencil cut from this entity's own Sprite.
bool enabled
Off is not a mask at all: the sprite goes back to being drawn normally, which is what makes "is this ...
Unified transform component.
Definition Transform.hpp:45
UINode — the CSS box-model layout input (the CSS/Flex primary layout model).
Definition UINode.hpp:79
Nine-slice border definition for UI sprites.
f32 left
Left border width in pixels.
f32 top
Top border height in pixels.
f32 bottom
Bottom border height in pixels.
f32 right
Right border width in pixels.