Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
OcclusionView.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
26#pragma once
27
28#include "../../core/Types.hpp"
29
30#include <glm/glm.hpp>
31#include <glm/gtc/quaternion.hpp>
32
33#include <algorithm>
34#include <array>
35#include <cmath>
36#include <limits>
37
38namespace esengine {
39
49public:
53 static constexpr u32 kSize = 64;
56 static constexpr u32 kLevels = 7;
57
60 static constexpr u32 kTestSpan = 4;
61
63 static constexpr f32 kOpen = std::numeric_limits<f32>::infinity();
64
69 static constexpr f32 kMinW = 1e-4f;
70
72 u32 side = 1;
73 while (side * 2 <= std::min(std::max(size, 1u), kSize)) side *= 2;
74 if (side == size_) return;
75 size_ = side;
76 levels_ = 1;
77 while ((side >>= 1) > 0) ++levels_;
78 boxes_ = 0;
79 }
80
81 u32 size() const { return size_; }
82
86 void begin(const glm::mat4& viewProjection) {
87 view_projection_ = viewProjection;
88 boxes_ = 0;
89 }
90
100 bool addBox(const glm::vec3& centre, const glm::quat& rotation, const glm::vec3& half) {
101 glm::vec3 corners[8];
102 if (!projectBox(centre, rotation, half, corners)) return false;
103
104 // Grid coordinates, where a texel is one unit and its centre a half — the
105 // edge bias and the depth slope below are both read in texels, and two
106 // spaces would put the rounding in one of them only.
107 glm::vec2 lo(static_cast<f32>(size_)), hi(0.0f);
108 for (const glm::vec3& c : corners) {
109 lo = glm::min(lo, glm::vec2(c));
110 hi = glm::max(hi, glm::vec2(c));
111 }
112 // The texels the silhouette TOUCHES, both ends floored: a rectangle that
113 // rounded one end up would hand the coverage test a texel the box never
114 // reaches, and the test and the scan must agree on which texels exist.
115 const i32 x0 = std::max(0, static_cast<i32>(std::floor(lo.x)));
116 const i32 y0 = std::max(0, static_cast<i32>(std::floor(lo.y)));
117 const i32 x1 = std::min(static_cast<i32>(size_) - 1, static_cast<i32>(std::floor(hi.x)));
118 const i32 y1 = std::min(static_cast<i32>(size_) - 1, static_cast<i32>(std::floor(hi.y)));
119 // Off screen entirely: what is outside the view hides nothing inside it,
120 // and the frustum has already answered for anything out there.
121 if (x1 < x0 || y1 < y0) return false;
122
123 Face faces[6];
124 u32 faceCount = 0;
125 for (const auto& quad : kFaces) {
126 Face face;
127 if (buildFace(corners, quad, face)) faces[faceCount++] = face;
128 }
129 // Every face edge-on at once means a box with no thickness on screen.
130 if (faceCount == 0) return false;
131
132 if (boxes_ == 0) base_.fill(kOpen);
133 ++boxes_;
134
135 for (i32 y = y0; y <= y1; ++y) {
136 for (i32 x = x0; x <= x1; ++x) {
137 const glm::vec2 p(static_cast<f32>(x) + 0.5f, static_cast<f32>(y) + 0.5f);
138 f32 blocked = kOpen;
139 for (u32 f = 0; f < faceCount; ++f) {
140 const Face& face = faces[f];
141 if (!face.covers(p)) continue;
142 // The face's FARTHEST depth over the whole texel, not its depth
143 // at the centre: the claim a texel makes is about every point in
144 // it, and half a texel of slope is what separates the two.
145 blocked = std::min(blocked, face.maxDepthOver(p));
146 }
147 if (blocked < kOpen) {
148 f32& cell = base_[static_cast<usize>(y) * size_ + static_cast<usize>(x)];
149 // Nearest wins: whatever is in front blocks most, and which box
150 // it came from cannot change the answer — so the order the
151 // registry hands them over in cannot either.
152 cell = std::min(cell, blocked);
153 }
154 }
155 }
156 return true;
157 }
158
163 void finish() {
164 if (boxes_ == 0) return;
165 for (u32 level = 1; level < levels_; ++level) {
166 const u32 size = size_ >> level;
167 const u32 src = size_ >> (level - 1);
168 f32* out = levelData(level);
169 const f32* in = levelData(level - 1);
170 for (u32 y = 0; y < size; ++y) {
171 for (u32 x = 0; x < size; ++x) {
172 const f32 a = in[(2 * y) * src + 2 * x];
173 const f32 b = in[(2 * y) * src + 2 * x + 1];
174 const f32 c = in[(2 * y + 1) * src + 2 * x];
175 const f32 d = in[(2 * y + 1) * src + 2 * x + 1];
176 out[y * size + x] = std::max(std::max(a, b), std::max(c, d));
177 }
178 }
179 }
180 }
181
184 bool hidden(const glm::vec3& centre, const glm::vec3& half) const {
185 if (boxes_ == 0) return false;
186
187 glm::vec3 corners[8];
188 if (!projectBox(centre, glm::quat(1.0f, 0.0f, 0.0f, 0.0f), half, corners)) return false;
189
190 glm::vec2 lo(static_cast<f32>(size_)), hi(0.0f);
191 f32 nearest = kOpen;
192 for (const glm::vec3& c : corners) {
193 lo = glm::min(lo, glm::vec2(c));
194 hi = glm::max(hi, glm::vec2(c));
195 nearest = std::min(nearest, c.z);
196 }
197
198 // Clamped to the grid, because what falls outside it is off screen and needs
199 // no occluder to be unseen. An empty rectangle after the clamp is entirely
200 // off screen, which is the frustum's answer to give, not this one's.
201 const i32 x0 = std::max(0, static_cast<i32>(std::floor(lo.x)));
202 const i32 y0 = std::max(0, static_cast<i32>(std::floor(lo.y)));
203 const i32 x1 = std::min(static_cast<i32>(size_) - 1, static_cast<i32>(std::floor(hi.x)));
204 const i32 y1 = std::min(static_cast<i32>(size_) - 1, static_cast<i32>(std::floor(hi.y)));
205 if (x1 < x0 || y1 < y0) return false;
206
207 // FOUR texels a side, not two: a level's texels align to the grid and not to
208 // this rectangle, so at two the overhang is the object's own width again —
209 // measured, six of nine cubes squarely behind a wall went uncalled.
210 u32 level = 0;
211 while (level + 1 < levels_
212 && ((x1 >> level) - (x0 >> level) >= static_cast<i32>(kTestSpan)
213 || (y1 >> level) - (y0 >> level) >= static_cast<i32>(kTestSpan))) {
214 ++level;
215 }
216 const u32 size = size_ >> level;
217 const f32* cells = levelData(level);
218 f32 farthest = -kOpen;
219 for (i32 y = y0 >> level; y <= (y1 >> level); ++y) {
220 for (i32 x = x0 >> level; x <= (x1 >> level); ++x) {
221 farthest = std::max(farthest, cells[static_cast<usize>(y) * size
222 + static_cast<usize>(x)]);
223 }
224 }
225 // Strictly nearer, so a bound resting exactly on the blocking depth is drawn:
226 // equality here is a surface touching the occluder, which is visible.
227 return farthest < nearest;
228 }
229
231 bool empty() const { return boxes_ == 0; }
232
234 u32 boxes() const { return boxes_; }
235
236private:
238 struct Face {
240 glm::vec3 edges[4];
242 f32 bias[4];
245 f32 zx = 0.0f, zy = 0.0f, z0 = 0.0f;
246
247 bool covers(const glm::vec2& p) const {
248 for (u32 i = 0; i < 4; ++i) {
249 if (edges[i].x * p.x + edges[i].y * p.y + edges[i].z < bias[i]) return false;
250 }
251 return true;
252 }
253
254 f32 maxDepthOver(const glm::vec2& p) const {
255 return zx * p.x + zy * p.y + z0 + 0.5f * (std::fabs(zx) + std::fabs(zy));
256 }
257 };
258
262 static constexpr u32 kFaces[6][4] = {
263 {0, 1, 3, 2}, {4, 6, 7, 5}, {0, 4, 5, 1}, {2, 3, 7, 6}, {0, 2, 6, 4}, {1, 5, 7, 3},
264 };
265
275 bool projectBox(const glm::vec3& centre, const glm::quat& rotation, const glm::vec3& half,
276 glm::vec3 (&out)[8]) const {
277 const glm::mat3 basis = glm::mat3_cast(rotation);
278 for (u32 i = 0; i < 8; ++i) {
279 const glm::vec3 local((i & 1u) ? half.x : -half.x,
280 (i & 2u) ? half.y : -half.y,
281 (i & 4u) ? half.z : -half.z);
282 const glm::vec4 clip = view_projection_ * glm::vec4(centre + basis * local, 1.0f);
283 if (clip.w <= kMinW) return false;
284 const glm::vec3 ndc = glm::vec3(clip) / clip.w;
285 // Behind the near plane in the convention every camera projection here
286 // is built in (near = -1). A depth-zero-to-one projection simply never
287 // trips it, which costs culling and never correctness.
288 if (ndc.z < -1.0f) return false;
289 out[i] = {(ndc.x + 1.0f) * 0.5f * static_cast<f32>(size_),
290 (ndc.y + 1.0f) * 0.5f * static_cast<f32>(size_), ndc.z};
291 }
292 return true;
293 }
294
297 static bool buildFace(const glm::vec3 (&corners)[8], const u32 (&quad)[4], Face& out) {
298 const glm::vec3 v[4] = {corners[quad[0]], corners[quad[1]],
299 corners[quad[2]], corners[quad[3]]};
300 // Signed area decides the orientation, so the inside test below is the same
301 // expression for a face pointing at the eye and one pointing away.
302 f32 area = 0.0f;
303 for (u32 i = 0; i < 4; ++i) {
304 const glm::vec3& a = v[i];
305 const glm::vec3& b = v[(i + 1) % 4];
306 area += a.x * b.y - b.x * a.y;
307 }
308 if (std::fabs(area) < 1e-3f) return false;
309 const f32 sign = area > 0.0f ? 1.0f : -1.0f;
310
311 for (u32 i = 0; i < 4; ++i) {
312 const glm::vec3& a = v[i];
313 const glm::vec3& b = v[(i + 1) % 4];
314 const f32 ex = -(b.y - a.y) * sign;
315 const f32 ey = (b.x - a.x) * sign;
316 out.edges[i] = {ex, ey, -(ex * a.x + ey * a.y)};
317 // Half a texel each way: the test is then "covers this texel WHOLE",
318 // which is the difference between an occluder that may hide something
319 // and one that only touches the pixels at its own silhouette.
320 out.bias[i] = 0.5f * (std::fabs(ex) + std::fabs(ey));
321 }
322
323 const glm::vec2 d1(v[1].x - v[0].x, v[1].y - v[0].y);
324 const glm::vec2 d2(v[2].x - v[0].x, v[2].y - v[0].y);
325 const f32 det = d1.x * d2.y - d1.y * d2.x;
326 if (std::fabs(det) < 1e-6f) return false;
327 const f32 dz1 = v[1].z - v[0].z;
328 const f32 dz2 = v[2].z - v[0].z;
329 out.zx = (dz1 * d2.y - dz2 * d1.y) / det;
330 out.zy = (d1.x * dz2 - d2.x * dz1) / det;
331 out.z0 = v[0].z - out.zx * v[0].x - out.zy * v[0].y;
332 return true;
333 }
334
336 static constexpr usize kCells = (kSize * kSize * 4) / 3 + 1;
337
338 f32* levelData(u32 level) { return base_.data() + offsetOf(level); }
339 const f32* levelData(u32 level) const { return base_.data() + offsetOf(level); }
340
341 usize offsetOf(u32 level) const {
342 usize offset = 0;
343 for (u32 i = 0; i < level; ++i) offset += static_cast<usize>(size_ >> i) * (size_ >> i);
344 return offset;
345 }
346
347 glm::mat4 view_projection_{1.0f};
348 std::array<f32, kCells> base_{};
349 u32 boxes_ = 0;
350 u32 size_ = kSize;
351 u32 levels_ = kLevels;
352};
353
354} // namespace esengine
Core type definitions and utilities for ESEngine.
The depths this view is blocked at, and the test a bound asks it.
static constexpr f32 kOpen
Depth of a texel nothing covers: no bound is ever farther.
void begin(const glm::mat4 &viewProjection)
Opens a view looking through viewProjection. Nothing is blocked until a box is taken,...
bool addBox(const glm::vec3 &centre, const glm::quat &rotation, const glm::vec3 &half)
Takes one solid box — half world half-extents about centre, turned by rotation — as something sight d...
bool hidden(const glm::vec3 &centre, const glm::vec3 &half) const
Whether nothing of a box bounded by centre / half can be seen, because every texel it covers is block...
void finish()
Closes the view: reduces the grid by MAXIMUM into a pyramid, so a bound of any size on screen costs f...
u32 boxes() const
How many declared boxes this view took.
static constexpr f32 kMinW
Smallest clip w a corner may have. Anything at or behind the eye plane makes the projection meaningle...
static constexpr u32 kTestSpan
Texels a side a bound is tested over: sixteen reads, whatever its size on screen.
bool empty() const
Whether this view blocks nothing, so every bound is visible to it.
static constexpr u32 kLevels
64, 32, 16, 8, 4, 2, 1 — down to one texel, so an object covering the whole screen still takes a boun...
static constexpr u32 kSize
Grid resolution of the coarsest useful answer. A texel is ~1.5% of the screen, which is what an occlu...
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
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
float f32
32-bit floating point
Definition Types.hpp:59