Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
UIElementPlugin.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 "UIElementPlugin.hpp"
7#include "../rhi/Texture.hpp"
14
15#include <algorithm>
16#include <cmath>
17
18namespace esengine {
19
25
26// Clockwise radial start direction (box-local, +y = up), by origin edge:
27// Top = 12 o'clock, Right = 3, Bottom = 6, Left = 9.
29 constexpr f32 HALF_PI = 1.57079632679f;
30 switch (origin) {
31 case ecs::UIFillOrigin::Right: return 0.0f;
32 case ecs::UIFillOrigin::Bottom: return -HALF_PI;
33 case ecs::UIFillOrigin::Left: return 2.0f * HALF_PI;
34 case ecs::UIFillOrigin::Top: return HALF_PI;
35 }
36 return HALF_PI;
37}
38
39// The mode's full arc; fillAmount scales the swept angle within it.
41 constexpr f32 HALF_PI = 1.57079632679f;
42 switch (m) {
43 case ecs::UIFillMethod::Radial90: return HALF_PI;
44 case ecs::UIFillMethod::Radial180: return 2.0f * HALF_PI;
45 default: return 4.0f * HALF_PI; // Radial360
46 }
47}
48
50 auto& registry = collect_ctx.registry;
51 auto& clips = collect_ctx.clip_state;
52 auto& buffers = collect_ctx.buffer_pool;
53 auto& draw_list = collect_ctx.draw_list;
54 auto& ctx = collect_ctx.frame_context;
55 auto uiView = registry.activeView<ecs::Transform, ecs::UIVisual>();
56
57 for (auto entity : uiView) {
58 if (!collect_ctx.accepts(entity)) continue;
59 const auto& renderer = uiView.get<ecs::UIVisual>(entity);
60 if (!renderer.enabled || renderer.visualType == ecs::UIVisualType::None) continue;
61
62 // Geometry from the UINode (CSS box) — always pivot-centered.
63 const auto* node = registry.tryGet<ecs::UINode>(entity);
64 if (!node || node->hidden_in_tree_) continue;
65 const auto* mask = registry.tryGet<ecs::UIMask>(entity);
66 const bool writesStencil = mask && mask->enabled && mask->mode == ecs::MaskMode::Stencil;
67 // Stencil draws still define clipping at zero alpha; custom materials
68 // may produce visible output independently of the vertex alpha.
69 if (renderer.material == 0 && !writesStencil
70 && renderer.color.a * node->alpha_in_tree_ == 0.0f
71 && !clips.isStencilMask(entity)) continue;
72 if (clips.isEmptyScissor(entity)) { ++collect_ctx.culled; continue; }
73 f32 w = node->computed_size_.x, h = node->computed_size_.y;
74 f32 pivotX = 0.5f, pivotY = 0.5f;
75 if (w <= 0.0f || h <= 0.0f) continue;
76
77 auto& transform = uiView.get<ecs::Transform>(entity);
78 transform.ensureDecomposed();
79
80 // Screen-space UI is laid out in screen units, which have no origin to take; UI standing in the world has.
81 glm::vec3 position = collect_ctx.isOverlay() ? glm::vec3(transform.worldPosition) : rebased(transform.worldPosition);
82 const auto& rotation = transform.worldRotation;
83 const auto& scale = transform.worldScale;
84 const bool parented = registry.has<ecs::Parent>(entity);
85 if (scale.x == 0 || scale.y == 0 || !ecs::hasFlatGeometryArea(registry, entity, transform)) continue;
86 const glm::vec3 basisOrigin = position;
87 const auto& matrix = transform.cachedMatrix_;
88 const bool mapBasis = parented && (matrix[0].y != 0 || matrix[1].x != 0
89 || matrix[0].z != 0 || matrix[1].z != 0 || matrix[0].x < 0 || matrix[1].y < 0);
90
91 // UI bakes the pivot into the world position here, so the quad is emitted centered.
92 f32 dx = (0.5f - pivotX) * w * scale.x;
93 f32 dy = (0.5f - pivotY) * h * scale.y;
94 f32 sinHalf = rotation.z;
95 if (sinHalf * sinHalf > 1e-6f) {
96 f32 cosHalf = rotation.w;
97 f32 s = 2.0f * sinHalf * cosHalf;
98 f32 c = cosHalf * cosHalf - sinHalf * sinHalf;
99 f32 rdx = dx * c - dy * s;
100 f32 rdy = dx * s + dy * c;
101 dx = rdx;
102 dy = rdy;
103 }
104 position.x += dx;
105 position.y += dy;
106
107 // `position` above already carries the turned offset, so only the extents do.
108 glm::vec3 halfExtents = flatHalfExtents(
109 flatTurnZ(rotation), glm::vec3(w * scale.x, h * scale.y, 0.0f) * 0.5f);
110 if (parented) {
111 halfExtents = glm::abs(glm::vec3(transform.cachedMatrix_[0])) * w * .5f
112 + glm::abs(glm::vec3(transform.cachedMatrix_[1])) * h * .5f;
113 }
114 if (!collect_ctx.visible(position, halfExtents, false)) { ++collect_ctx.culled; continue; }
115
116 f32 angle = 2.0f * std::atan2(rotation.z, rotation.w);
117 if (mapBasis) angle = 0.0f;
118 i32 layer = UI_BASE_LAYER + renderer.uiOrder;
119
120 u32 textureId = ctx.white_texture_id;
121 glm::vec2 texSize{0.0f};
122 bool useNineSlice = false;
123 glm::vec4 sliceBorder{0.0f};
124
125 if (renderer.texture.isValid()) {
126 Texture* tex = ctx.resources.getTexture(renderer.texture);
127 if (tex) {
128 textureId = tex->getId();
129 texSize = glm::vec2(
130 static_cast<f32>(tex->getWidth()),
131 static_cast<f32>(tex->getHeight())
132 );
133 const auto* metadata = ctx.resources.getTextureMetadata(renderer.texture);
134 if (metadata && metadata->sliceBorder.hasSlicing()) {
135 useNineSlice = true;
136 sliceBorder = glm::vec4(
137 metadata->sliceBorder.left,
138 metadata->sliceBorder.right,
139 metadata->sliceBorder.top,
140 metadata->sliceBorder.bottom
141 );
142 }
143 }
144 }
145
146 if (renderer.visualType == ecs::UIVisualType::NineSlice) {
147 useNineSlice = true;
148 if (sliceBorder == glm::vec4(0.0f)) {
149 sliceBorder = renderer.sliceBorder;
150 }
151 }
152
153 // Derive the sampled UV from the base sub-region + the fill mode. This
154 // replaces the old per-frame Image->UIRenderer copy: Tiled repeats by
155 // box/tileSize, Filled crops to fillAmount.
156 glm::vec2 uvOffset = renderer.uvOffset;
157 glm::vec2 uvScale = renderer.uvScale;
158 if (renderer.visualType == ecs::UIVisualType::Tiled) {
159 if (renderer.tileSize.x > 0.0f && renderer.tileSize.y > 0.0f) {
160 uvScale.x = renderer.uvScale.x * (w / renderer.tileSize.x);
161 uvScale.y = renderer.uvScale.y * (h / renderer.tileSize.y);
162 }
163 } else if (renderer.visualType == ecs::UIVisualType::Filled) {
164 f32 amount = std::clamp(renderer.fillAmount, 0.0f, 1.0f);
165 if (renderer.fillMethod == ecs::UIFillMethod::Horizontal) {
166 uvScale.x = renderer.uvScale.x * amount;
167 if (renderer.fillOrigin == ecs::UIFillOrigin::Right) {
168 uvOffset.x = renderer.uvOffset.x + renderer.uvScale.x * (1.0f - amount);
169 }
170 } else if (renderer.fillMethod == ecs::UIFillMethod::Vertical) {
171 uvScale.y = renderer.uvScale.y * amount;
172 if (renderer.fillOrigin == ecs::UIFillOrigin::Top) {
173 uvOffset.y = renderer.uvOffset.y + renderer.uvScale.y * (1.0f - amount);
174 }
175 }
176 // Radial360 samples the full base UV per fan vertex — no crop here.
177 }
178
179 glm::vec2 finalSize = glm::vec2(w, h) * glm::vec2(scale);
180
181 // object-fit. Contain shrinks the QUAD until the whole image fits (the
182 // box keeps its layout size; the image just stops filling it), Cover
183 // keeps the quad and crops the UV instead — so neither ever distorts the
184 // artwork. NineSlice and Tiled opt out: adapting to the box IS their job,
185 // and a ratio-preserving 9-slice is a contradiction.
186 if (renderer.fit != ecs::UIVisualFit::Fill && !useNineSlice
187 && renderer.visualType != ecs::UIVisualType::Tiled
188 && texSize.x > 0.0f && texSize.y > 0.0f
189 && finalSize.x > 0.0f && finalSize.y > 0.0f) {
190 const f32 boxRatio = finalSize.x / finalSize.y;
191 const f32 texRatio = texSize.x / texSize.y;
192 if (renderer.fit == ecs::UIVisualFit::Contain) {
193 if (texRatio > boxRatio) finalSize.y = finalSize.x / texRatio;
194 else finalSize.x = finalSize.y * texRatio;
195 } else { // Cover: crop the overflowing axis in UV space, centred.
196 if (texRatio > boxRatio) {
197 const f32 keep = boxRatio / texRatio; // fraction of width kept
198 uvOffset.x += uvScale.x * (1.0f - keep) * 0.5f;
199 uvScale.x *= keep;
200 } else {
201 const f32 keep = texRatio / boxRatio; // fraction of height kept
202 uvOffset.y += uvScale.y * (1.0f - keep) * 0.5f;
203 uvScale.y *= keep;
204 }
205 }
206 }
207
208 const bool isRadialFill = renderer.visualType == ecs::UIVisualType::Filled
209 && isRadialMethod(renderer.fillMethod);
210
211 // Filled derives its own UV/geometry, so 9-slice never applies. Linear
212 // fills crop the box in lockstep with the UV crop above: the box shrinks
213 // to fillAmount along the axis, anchored at fillOrigin, its center shifting
214 // toward that edge by half the removed extent (rotated into world space to
215 // match the pivot bake). A UV-only crop would no-op on a solid colour and
216 // stretch a texture; cropping geometry too makes both reveal. Radial fills
217 // are emitted as a wedge fan instead (below), so they skip the box crop.
218 if (renderer.visualType == ecs::UIVisualType::Filled) {
219 useNineSlice = false;
220 if (!isRadialFill) {
221 f32 amount = std::clamp(renderer.fillAmount, 0.0f, 1.0f);
222 f32 offX = 0.0f, offY = 0.0f;
223 if (renderer.fillMethod == ecs::UIFillMethod::Horizontal) {
224 f32 removed = finalSize.x * (1.0f - amount);
225 offX = (renderer.fillOrigin == ecs::UIFillOrigin::Right ? 0.5f : -0.5f) * removed;
226 finalSize.x *= amount;
227 } else {
228 f32 removed = finalSize.y * (1.0f - amount);
229 offY = (renderer.fillOrigin == ecs::UIFillOrigin::Top ? 0.5f : -0.5f) * removed;
230 finalSize.y *= amount;
231 }
232 if (std::abs(angle) > 0.001f) {
233 f32 cosA = std::cos(angle), sinA = std::sin(angle);
234 f32 rx = offX * cosA - offY * sinA;
235 f32 ry = offX * sinA + offY * cosA;
236 offX = rx;
237 offY = ry;
238 }
239 position.x += offX;
240 position.y += offY;
241 }
242 }
243
244 BatchDrawKey key{
245 .stage = ctx.current_stage,
246 .layer = layer,
247 .shaderId = batch_shader_id_,
248 .blend = BlendMode::Normal,
249 .textureId = textureId,
250 .depth = collect_ctx.sortDepth(position),
251 .cullBit = renderer.uiCullBit,
252 .entity = entity,
253 .type = RenderType::UIElement,
254 };
255
256 // A stencil mask with a cutoff clips to the SHAPE it draws, not its box:
257 // the mask pass runs this same draw with color writes off, so it needs
258 // the variant that discards transparent fragments — otherwise the whole
259 // quad writes stencil and a circular mask clips a rectangle.
260 if (writesStencil && mask->alphaCutoff > 0.0f) {
261 key.shaderId = ctx.frame->batchProgram(BatchVariant::AlphaClip);
262 }
263
264 // Same resolution as SpritePlugin: an unregistered handle falls back to
265 // the default batch shader, so a dangling material renders plainly.
266 if (renderer.material != 0) {
267 if (const MaterialRecord* m = ctx.materials ? ctx.materials->find(renderer.material) : nullptr) {
268 key.shaderId = (m->shader != 0) ? m->shader : batch_shader_id_;
269 key.blend = m->blend;
270 key.materialId = renderer.material;
271 key.depthTest = m->depthTest;
272 key.depthWrite = m->depthWrite;
273 key.cull = static_cast<u8>(m->cull);
274 key.depthBias = m->depthBias;
275 }
276 }
277
278 constexpr glm::vec2 CENTERED_PIVOT{0.5f, 0.5f};
279
280 // Subtree opacity (UINode.opacity, resolved down the tree by the layout
281 // pass) multiplies into this visual's own alpha — the CSS `opacity`
282 // model, applied per-visual rather than by compositing the subtree.
283 glm::vec4 color = renderer.color;
284 color.a *= node->alpha_in_tree_;
285
286 const u32 vertexStart = buffers.vertexBytesUsed(LayoutId::Batch);
287 if (isRadialFill) {
288 f32 sweep = std::clamp(renderer.fillAmount, 0.0f, 1.0f)
289 * radialMaxSweep(renderer.fillMethod);
290 emitRadialFill(buffers, draw_list, clips,
291 position, finalSize, angle,
292 radialStartAngle(renderer.fillOrigin), sweep,
293 uvOffset, uvScale, color, key);
294 } else if (useNineSlice) {
295 emitNineSlice(buffers, draw_list, clips,
296 position, finalSize, CENTERED_PIVOT,
297 angle, texSize, sliceBorder,
298 uvOffset, uvScale, color, key);
299 } else {
300 emitQuad(buffers, draw_list, clips,
301 position, finalSize, CENTERED_PIVOT,
302 angle, uvOffset, uvScale, color, key);
303 }
304 if (mapBasis) {
305 const glm::vec3 basisX = glm::vec3(transform.cachedMatrix_[0]) / scale.x;
306 const glm::vec3 basisY = glm::vec3(transform.cachedMatrix_[1]) / scale.y;
307 const u32 vertexEnd = buffers.vertexBytesUsed(LayoutId::Batch);
308 auto* vertices = reinterpret_cast<BatchVertex*>(buffers.vertexData(LayoutId::Batch));
309 for (u32 i = vertexStart / sizeof(BatchVertex); i < vertexEnd / sizeof(BatchVertex); ++i) {
310 const auto delta = vertices[i].position - basisOrigin;
311 vertices[i].position = basisOrigin + basisX * delta.x + basisY * delta.y;
312 }
313 }
314 }
315}
316
317} // namespace esengine
Hierarchy components for parent-child relationships.
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.
GPU texture abstraction for 2D images.
Unified Transform component with local and world-space data.
void emitRadialFill(TransientBufferPool &buffers, DrawList &draw_list, const ClipState &clips, const glm::vec3 &center, const glm::vec2 &size, f32 angle, f32 startAngle, f32 sweep, const glm::vec2 &uvOffset, const glm::vec2 &uvScale, const glm::vec4 &color, const BatchDrawKey &key)
Emits a centered angular wedge (Radial Filled): a triangle fan from the box center out to its perimet...
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.
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
void collect(RenderCollectContext &ctx) override
static constexpr i32 UI_BASE_LAYER
bool hasFlatGeometryArea(Transform &transform, bool parented)
UIFillMethod
Fill mode for a Filled UIVisual. Horizontal/Vertical are linear crops along the axis; the Radial mode...
Definition UIVisual.hpp:41
static f32 radialMaxSweep(ecs::UIFillMethod m)
static f32 radialStartAngle(ecs::UIFillOrigin origin)
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
static bool isRadialMethod(ecs::UIFillMethod m)
bool writesStencil(GfxStencilMode mode)
glm::vec3 flatHalfExtents(const glm::vec2 &turn, const glm::vec3 &half)
World AABB half-extents of a flat box turned by turn (from flatTurnZ). |R| * half,...
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
glm::vec3 rebased(const glm::vec3 &world)
A world position as the frame draws it: from the origin.
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
glm::vec2 flatTurnZ(const glm::quat &rotation)
The cos/sin of the turn a plane renderable draws with: its entity's rotation about Z,...
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.
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.
bool visible(const glm::vec3 &centre, const glm::vec3 &halfExtents, bool depthTested)
Whether a renderable bounded by centre / halfExtents is drawn.
bool isOverlay() const
Whether this collect is the frame's screen overlay.
Parent reference component.
Definition Hierarchy.hpp:46
Unified transform component.
Definition Transform.hpp:45
UINode — the CSS box-model layout input (the CSS/Flex primary layout model).
Definition UINode.hpp:79
UIVisual — the single UI visual component, merging the former low-level UIRenderer (what the renderer...
Definition UIVisual.hpp:84