Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
RenderFrameMask.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 "./RenderFrame.hpp"
4#include "../../core/Log.hpp"
11
12#include <glm/glm.hpp>
13
14#include <algorithm>
15#include <cmath>
16#include <unordered_set>
17#include <vector>
18
19namespace esengine {
20
21namespace {
22
23using ScreenRect = ScissorRect;
24
25ScreenRect intersectRects(const ScreenRect& a, const ScreenRect& b) {
26 i32 x1 = std::max(a.x, b.x);
27 i32 y1 = std::max(a.y, b.y);
28 i32 x2 = std::min(a.x + a.w, b.x + b.w);
29 i32 y2 = std::min(a.y + a.h, b.y + b.h);
30 if (x2 <= x1 || y2 <= y1) return {0, 0, 0, 0};
31 return {x1, y1, x2 - x1, y2 - y1};
32}
33
34glm::vec2 worldToScreen(const glm::vec3& world, const glm::mat4& vp,
35 i32 vpX, i32 vpY, i32 vpW, i32 vpH) {
36 glm::vec4 clip = vp * glm::vec4(world, 1.0f);
37 f32 ndcX = clip.x / clip.w;
38 f32 ndcY = clip.y / clip.w;
39 f32 sx = static_cast<f32>(vpX) + (ndcX * 0.5f + 0.5f) * static_cast<f32>(vpW);
40 f32 sy = static_cast<f32>(vpY) + (ndcY * 0.5f + 0.5f) * static_cast<f32>(vpH);
41 return {sx, sy};
42}
43
45thread_local bool g_masksInWorld = false;
46
49struct MaskBox {
50 glm::vec2 size{0.0f, 0.0f};
52 glm::vec2 centerOffset{0.0f, 0.0f};
53 bool present = false;
54};
55
56MaskBox maskBoxOf(ecs::Registry& registry, Entity entity) {
57 if (const auto* node = registry.tryGet<ecs::UINode>(entity)) {
58 return {node->computed_size_, {0.0f, 0.0f}, true};
59 }
60 if (const auto* rect = registry.tryGet<ecs::ContentRect>(entity)) {
61 return {rect->size, {(0.5f - rect->pivot.x) * rect->size.x, (0.5f - rect->pivot.y) * rect->size.y}, true};
62 }
63 return {};
64}
65
66ScreenRect computeMaskScreenRect(
67 ecs::Registry& registry, Entity entity,
68 const glm::mat4& vp, i32 vpX, i32 vpY, i32 vpW, i32 vpH
69) {
70 const MaskBox box = maskBoxOf(registry, entity);
71 if (!box.present || !registry.has<ecs::Transform>(entity)) {
72 return {0, 0, 0, 0};
73 }
74 if (box.size.x <= 0.0f || box.size.y <= 0.0f) return {0, 0, 0, 0};
75 auto& transform = registry.get<ecs::Transform>(entity);
76 // The world TRS below is decomposed on demand, so a mask whose transform no
77 // other pass has read this frame would be clipped to where it used to be.
78 transform.ensureDecomposed();
79
80 if (transform.worldScale.x == 0 || transform.worldScale.y == 0
81 || !ecs::hasFlatGeometryArea(registry, entity, transform)) return {0, 0, 0, 0};
82 glm::vec3 axisX, axisY;
83 if (registry.has<ecs::Parent>(entity)) {
84 axisX = glm::vec3(transform.cachedMatrix_[0]);
85 axisY = glm::vec3(transform.cachedMatrix_[1]);
86 } else {
87 const auto turn = flatTurnZ(transform.worldRotation);
88 axisX = glm::vec3(turn.x, turn.y, 0) * transform.worldScale.x;
89 axisY = glm::vec3(-turn.y, turn.x, 0) * transform.worldScale.y;
90 }
91 const glm::vec3 hx = axisX * box.size.x * .5f;
92 const glm::vec3 hy = axisY * box.size.y * .5f;
93 const glm::vec3 origin = g_masksInWorld ? rebased(transform.worldPosition) : glm::vec3(transform.worldPosition);
94 const glm::vec3 center = origin + axisX * box.centerOffset.x + axisY * box.centerOffset.y;
95 const glm::vec3 corners[] = {center - hx - hy, center + hx - hy,
96 center + hx + hy, center - hx + hy};
97
98 f32 minX = std::numeric_limits<f32>::max();
99 f32 minY = std::numeric_limits<f32>::max();
100 f32 maxX = std::numeric_limits<f32>::lowest();
101 f32 maxY = std::numeric_limits<f32>::lowest();
102 for (const auto& c : corners) {
103 glm::vec2 s = worldToScreen(c, vp, vpX, vpY, vpW, vpH);
104 minX = std::min(minX, s.x);
105 minY = std::min(minY, s.y);
106 maxX = std::max(maxX, s.x);
107 maxY = std::max(maxY, s.y);
108 }
109
110 return {
111 static_cast<i32>(std::round(minX)),
112 static_cast<i32>(std::round(minY)),
113 static_cast<i32>(std::round(maxX - minX)),
114 static_cast<i32>(std::round(maxY - minY)),
115 };
116}
117
118bool hasAncestorScissorMask(ecs::Registry& registry, Entity entity,
119 const std::unordered_set<u32>& maskSet) {
120 Entity current = entity;
121 while (registry.has<ecs::Parent>(current)) {
122 Entity parent = registry.get<ecs::Parent>(current).entity;
123 if (parent == INVALID_ENTITY) break;
124 if (maskSet.count(parent.id())) {
125 const auto& parentMask = registry.get<ecs::UIMask>(parent);
126 if (parentMask.mode == ecs::MaskMode::Scissor) return true;
127 }
128 current = parent;
129 }
130 return false;
131}
132
133bool hasAncestorStencilMask(ecs::Registry& registry, Entity entity,
134 const std::unordered_set<u32>& stencilSet) {
135 Entity current = entity;
136 while (registry.has<ecs::Parent>(current)) {
137 Entity parent = registry.get<ecs::Parent>(current).entity;
138 if (parent == INVALID_ENTITY) break;
139 if (stencilSet.count(parent.id())) return true;
140 current = parent;
141 }
142 return false;
143}
144
145void applyScissorToDescendants(
146 ecs::Registry& registry, RenderFrame& frame, Entity entity,
147 const ScreenRect& clipRect, const std::unordered_set<u32>& maskSet,
148 const glm::mat4& vp, i32 vpX, i32 vpY, i32 vpW, i32 vpH,
149 std::vector<std::pair<Entity, ScissorRect>>& work
150) {
151 work.clear();
152 work.emplace_back(entity, clipRect);
153 usize walked = 0;
154 while (!work.empty()) {
155 if (++walked > registry.entityCount()) {
156 ES_LOG_WARN("Scissor hierarchy repeats nodes; stopping mask traversal");
157 work.clear();
158 return;
159 }
160 const auto [owner, parentClip] = work.back();
161 work.pop_back();
162 if (!registry.has<ecs::Children>(owner)) continue;
163 const auto& children = registry.get<ecs::Children>(owner).entities;
164 for (auto it = children.rbegin(); it != children.rend(); ++it) {
165 const Entity child = *it;
166 if (!registry.valid(child)) continue;
167 ScreenRect childClip = parentClip;
168 if (maskSet.count(child.id())) {
169 const auto& childMask = registry.get<ecs::UIMask>(child);
170 if (childMask.mode == ecs::MaskMode::Scissor) {
171 const auto childRect = computeMaskScreenRect(registry, child, vp, vpX, vpY, vpW, vpH);
172 childClip = intersectRects(parentClip, childRect);
173 }
174 }
175 frame.setEntityClipRect(child.id(), childClip.x, childClip.y, childClip.w, childClip.h);
176 work.emplace_back(child, childClip);
177 }
178 }
179}
180
181static constexpr i32 MAX_STENCIL_REF = 255;
182
183bool hasEmptyMaskBox(ecs::Registry& registry, Entity entity) {
184 const MaskBox box = maskBoxOf(registry, entity);
185 auto* transform = registry.tryGet<ecs::Transform>(entity);
186 if (!box.present || !transform) return false;
187 if (box.size.x <= 0.0f || box.size.y <= 0.0f) return true;
188 transform->ensureDecomposed();
189 return transform->worldScale.x == 0 || transform->worldScale.y == 0
190 || !ecs::hasFlatGeometryArea(registry, entity, *transform);
191}
192
193void applyStencilHierarchy(ecs::Registry& registry, RenderFrame& frame,
194 Entity entity, i32 refValue,
195 const std::unordered_set<u32>& stencilSet, bool& overflowed,
196 std::vector<std::pair<Entity, i32>>& work) {
197 work.clear();
198 if (hasEmptyMaskBox(registry, entity)) {
199 refValue = 0;
200 frame.setEntityClipRect(entity.id(), 0, 0, 0, 0);
201 } else {
202 frame.setEntityStencilMask(entity.id(), refValue, true);
203 }
204 const auto enqueueChildren = [&](Entity owner, i32 parentRef) {
205 if (!registry.has<ecs::Children>(owner)) return;
206 const auto& children = registry.get<ecs::Children>(owner).entities;
207 for (auto it = children.rbegin(); it != children.rend(); ++it) {
208 if (registry.valid(*it)) work.emplace_back(*it, parentRef);
209 }
210 };
211 enqueueChildren(entity, refValue);
212 usize walked = 0;
213 while (!work.empty()) {
214 if (++walked > registry.entityCount()) {
215 ES_LOG_WARN("Stencil hierarchy repeats nodes; stopping mask traversal");
216 work.clear();
217 return;
218 }
219 auto [owner, currentRef] = work.back();
220 work.pop_back();
221 if (currentRef == 0) {
222 frame.setEntityClipRect(owner.id(), 0, 0, 0, 0);
223 } else if (stencilSet.count(owner.id())) {
224 if (hasEmptyMaskBox(registry, owner)) {
225 frame.setEntityClipRect(owner.id(), 0, 0, 0, 0);
226 enqueueChildren(owner, 0);
227 continue;
228 }
229 if (currentRef == MAX_STENCIL_REF) {
230 overflowed = true;
231 frame.setEntityClipRect(owner.id(), 0, 0, 0, 0);
232 enqueueChildren(owner, 0);
233 continue;
234 }
235 ++currentRef;
236 frame.setEntityStencilMask(owner.id(), currentRef, true);
237 } else {
238 frame.setEntityStencilTest(owner.id(), currentRef, true);
239 }
240 enqueueChildren(owner, currentRef);
241 }
242}
243
244} // anonymous namespace
245
246void RenderFrame::processMasks(ecs::Registry& registry, i32 vpX, i32 vpY, i32 vpW, i32 vpH) {
247 g_masksInWorld = true;
248 processMasks(registry, view_projection_, vpX, vpY, vpW, vpH);
249 g_masksInWorld = false;
250}
251
252void RenderFrame::processMasks(ecs::Registry& registry, const glm::mat4& projection,
253 i32 vpX, i32 vpY, i32 vpW, i32 vpH) {
256
257 auto maskView = registry.activeView<ecs::UIMask>();
258 std::vector<Entity>& scissorMasks = mask_scissor_scratch_;
259 std::vector<Entity>& stencilMasks = mask_stencil_scratch_;
260 std::unordered_set<u32>& maskSet = mask_set_scratch_;
261 std::unordered_set<u32>& stencilSet = stencil_set_scratch_;
262 scissorMasks.clear();
263 stencilMasks.clear();
264 maskSet.clear();
265 stencilSet.clear();
266
267 for (auto entity : maskView) {
268 const auto& mask = registry.get<ecs::UIMask>(entity);
269 if (!mask.enabled) continue;
270 maskSet.insert(entity.id());
271 if (mask.mode == ecs::MaskMode::Stencil) {
272 stencilMasks.push_back(entity);
273 stencilSet.insert(entity.id());
274 } else {
275 scissorMasks.push_back(entity);
276 }
277 }
278
279 if (scissorMasks.empty() && stencilMasks.empty()) return;
280
281 if (!scissorMasks.empty()) {
282 std::vector<Entity>& rootScissors = mask_root_scratch_;
283 rootScissors.clear();
284 for (auto entity : scissorMasks) {
285 if (!hasAncestorScissorMask(registry, entity, maskSet)) {
286 rootScissors.push_back(entity);
287 }
288 }
289
290 for (auto entity : rootScissors) {
291 ScreenRect rect = computeMaskScreenRect(registry, entity, projection, vpX, vpY, vpW, vpH);
292 rect = intersectRects(rect, {vpX, vpY, vpW, vpH});
293 applyScissorToDescendants(registry, *this, entity, rect, maskSet, projection, vpX, vpY, vpW, vpH, mask_scissor_walk_scratch_);
294 }
295 }
296
297 if (!stencilMasks.empty()) {
298#ifdef ES_PLATFORM_WEB
299 device_.clearStencil(0);
300#endif
301
302 std::vector<Entity>& rootStencils = mask_root_scratch_;
303 rootStencils.clear();
304 for (auto entity : stencilMasks) {
305 if (!hasAncestorStencilMask(registry, entity, stencilSet)) {
306 rootStencils.push_back(entity);
307 }
308 }
309
310 bool overflowed = false;
311 for (auto entity : rootStencils) {
312 applyStencilHierarchy(registry, *this, entity, 1, stencilSet, overflowed, mask_stencil_walk_scratch_);
313 }
314
315 if (overflowed) {
316 ES_LOG_WARN("Stencil mask overflow: too many nested masks (>255)");
317 }
318 }
319}
320
321} // namespace esengine
The rectangle a piece of world content occupies: a size, and the point of it the entity's transform s...
Hierarchy components for parent-child relationships.
Logging utilities for ESEngine.
#define ES_LOG_WARN(...)
Logs a warning message.
Definition Log.hpp:294
Frame resources and the shared scene rendering contract.
Unified Transform component with local and world-space data.
void processMasks(ecs::Registry &registry, i32 vpX, i32 vpY, i32 vpW, i32 vpH)
Central container for all entities and components.
Definition Registry.hpp:73
T & get(Entity entity)
Gets a component from an entity (must exist).
Definition Registry.hpp:649
bool hasFlatGeometryArea(Transform &transform, bool parented)
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
constexpr Entity INVALID_ENTITY
Invalid entity sentinel value.
Definition Types.hpp:174
glm::vec3 rebased(const glm::vec3 &world)
A world position as the frame draws it: from the origin.
glm::vec2 flatTurnZ(const glm::quat &rotation)
The cos/sin of the turn a plane renderable draws with: its entity's rotation about Z,...
float f32
32-bit floating point
Definition Types.hpp:59
Entity identifier with packed index + generation.
Definition Types.hpp:135
Children list component.
Definition Hierarchy.hpp:66
The rectangle of this entity's content, in its own units.
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