8#if defined(__SSE2__) || defined(_M_X64)
9#define SLEAK_CULL_SSE2 1
12#define SLEAK_CULL_SSE2 0
18constexpr float kWEps = 1e-4f;
19constexpr float kZBias = 1e-4f;
20constexpr int kLanes = 4;
31 uint32_t triStart = 0;
32 uint32_t triCount = 0;
38 bool frustumEnabled =
true;
39 bool occlusionEnabled =
true;
42 uint32_t maxOccluders = 192;
44 std::vector<float> depth;
45 std::vector<OccluderEntry> occluders;
46 std::vector<Math::Vector3D> triVerts;
48 ViewFrustum frustum{};
50 Math::Vector3D cameraPos{};
52 bool hasFrame =
false;
53 bool rasterizedThisFrame =
false;
54 bool everRasterized =
false;
56 bool adaptiveEnabled =
true;
57 uint32_t probeInterval = 20;
58 uint32_t skipFrames = 0;
60 CullingSystem::Stats stats{};
70inline ClipVert ToClip(
const Math::Vector3D& p,
const Math::Matrix4& m) {
71 float x = p.GetX(), y = p.GetY(), z = p.GetZ();
73 c.x = x * m(0, 0) + y * m(1, 0) + z * m(2, 0) + m(3, 0);
74 c.y = x * m(0, 1) + y * m(1, 1) + z * m(2, 1) + m(3, 1);
75 c.z = x * m(0, 2) + y * m(1, 2) + z * m(2, 2) + m(3, 2);
76 c.w = x * m(0, 3) + y * m(1, 3) + z * m(2, 3) + m(3, 3);
81inline void ToScreen(
const ClipVert& c,
float w,
float h,
float& sx,
82 float& sy,
float& sz) {
83 float inv = 1.0f / c.w;
84 float ndcx = c.x * inv;
85 float ndcy = c.y * inv;
87 sx = (ndcx * 0.5f + 0.5f) * w;
88 sy = (0.5f - ndcy * 0.5f) * h;
92int ClipNear(
const ClipVert* in,
int n, ClipVert* out) {
94 for (
int i = 0; i < n; ++i) {
95 const ClipVert& A = in[i];
96 const ClipVert& B = in[(i + 1) % n];
97 bool inA = A.w >= kWEps;
98 bool inB = B.w >= kWEps;
99 if (inA) out[m++] = A;
101 float t = (kWEps - A.w) / (B.w - A.w);
103 I.x = A.x + t * (B.x - A.x);
104 I.y = A.y + t * (B.y - A.y);
105 I.z = A.z + t * (B.z - A.z);
106 I.w = A.w + t * (B.w - A.w);
116 int minX, maxX, minY, maxY;
117 float w0Row, w1Row, w2Row;
127template <
bool kPositive>
128inline __m128 EdgeMask(__m128 w0, __m128 w1, __m128 w2) {
129 const __m128 zero = _mm_setzero_ps();
130 if constexpr (kPositive) {
132 _mm_and_ps(_mm_cmpge_ps(w0, zero), _mm_cmpge_ps(w1, zero)),
133 _mm_cmpge_ps(w2, zero));
136 _mm_and_ps(_mm_cmple_ps(w0, zero), _mm_cmple_ps(w1, zero)),
137 _mm_cmple_ps(w2, zero));
142inline void MinStorePartial(
float* dst, __m128 v,
int n) {
143 alignas(16)
float tmp[kLanes];
144 _mm_store_ps(tmp, v);
145 for (
int i = 0; i < n; ++i)
146 if (tmp[i] < dst[i]) dst[i] = tmp[i];
151template <
bool kPositive>
152void RasterTriSse2(
const TriSetup& t,
float* depth,
int W) {
153 const __m128 a0 = _mm_set1_ps(t.A0);
154 const __m128 a1 = _mm_set1_ps(t.A1);
155 const __m128 a2 = _mm_set1_ps(t.A2);
156 const __m128 zv0 = _mm_set1_ps(t.z0);
157 const __m128 zv1 = _mm_set1_ps(t.z1);
158 const __m128 zv2 = _mm_set1_ps(t.z2);
159 const __m128 inv = _mm_set1_ps(t.invArea);
160 const __m128 zero = _mm_setzero_ps();
161 const __m128 one = _mm_set1_ps(1.0f);
162 const __m128 untouched =
163 _mm_set1_ps(std::numeric_limits<float>::infinity());
165 float w0Row = t.w0Row, w1Row = t.w1Row, w2Row = t.w2Row;
166 for (
int y = t.minY; y <= t.maxY; y += kLanes) {
167 alignas(16)
float r0[kLanes], r1[kLanes], r2[kLanes];
168 for (
int i = 0; i < kLanes; ++i) {
176 const int rows = std::min(kLanes, t.maxY - y + 1);
177 __m128 e0 = _mm_load_ps(r0);
178 __m128 e1 = _mm_load_ps(r1);
179 __m128 e2 = _mm_load_ps(r2);
180 float* rowBase = depth + y * W;
182 for (
int x = t.minX; x <= t.maxX; x += kLanes) {
183 __m128 s0 = e0, s1 = e1, s2 = e2;
186 for (
int k = 0; k < kLanes; ++k) {
187 m[k] = EdgeMask<kPositive>(e0, e1, e2);
188 any = _mm_or_ps(any, m[k]);
189 e0 = _mm_add_ps(e0, a0);
190 e1 = _mm_add_ps(e1, a1);
191 e2 = _mm_add_ps(e2, a2);
193 if (_mm_movemask_ps(any) == 0)
continue;
196 for (
int k = 0; k < kLanes; ++k) {
197 __m128 z = _mm_add_ps(
198 _mm_add_ps(_mm_mul_ps(s0, zv0), _mm_mul_ps(s1, zv1)),
199 _mm_mul_ps(s2, zv2));
200 z = _mm_min_ps(one, _mm_mul_ps(z, inv));
201 zc[k] = _mm_max_ps(_mm_andnot_ps(m[k], untouched), z);
202 s0 = _mm_add_ps(s0, a0);
203 s1 = _mm_add_ps(s1, a1);
204 s2 = _mm_add_ps(s2, a2);
206 _MM_TRANSPOSE4_PS(zc[0], zc[1], zc[2], zc[3]);
208 float* p = rowBase + x;
209 const int cols = std::min(kLanes, t.maxX - x + 1);
210 if (cols == kLanes) {
211 for (
int r = 0; r < rows; ++r) {
212 float* q = p + r * W;
213 _mm_storeu_ps(q, _mm_min_ps(zc[r], _mm_loadu_ps(q)));
216 for (
int r = 0; r < rows; ++r)
217 MinStorePartial(p + r * W, zc[r], cols);
224void RasterTriScalar(
const TriSetup& t,
float* depth,
int W) {
225 float w0Row = t.w0Row, w1Row = t.w1Row, w2Row = t.w2Row;
226 for (
int y = t.minY; y <= t.maxY; ++y) {
227 float w0 = w0Row, w1 = w1Row, w2 = w2Row;
229 for (
int x = t.minX; x <= t.maxX; ++x) {
230 bool inside = t.positive ? (w0 >= 0.0f && w1 >= 0.0f && w2 >= 0.0f)
231 : (w0 <= 0.0f && w1 <= 0.0f && w2 <= 0.0f);
233 float z = (w0 * t.z0 + w1 * t.z1 + w2 * t.z2) * t.invArea;
234 if (z < 0.0f) z = 0.0f;
235 if (z > 1.0f) z = 1.0f;
237 if (z < depth[idx]) depth[idx] = z;
251void RasterScreenTri(
float x0,
float y0,
float z0,
float x1,
float y1,
252 float z1,
float x2,
float y2,
float z2) {
253 CullState& s = State();
254 int W =
static_cast<int>(s.width);
255 int H =
static_cast<int>(s.height);
257 float area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0);
258 if (std::fabs(area) < 1e-4f)
return;
259 float invArea = 1.0f / area;
261 float fminX = std::min(x0, std::min(x1, x2));
262 float fmaxX = std::max(x0, std::max(x1, x2));
263 float fminY = std::min(y0, std::min(y1, y2));
264 float fmaxY = std::max(y0, std::max(y1, y2));
266 int minX =
static_cast<int>(std::floor(fminX));
267 int maxX =
static_cast<int>(std::ceil(fmaxX));
268 int minY =
static_cast<int>(std::floor(fminY));
269 int maxY =
static_cast<int>(std::ceil(fmaxY));
270 if (minX < 0) minX = 0;
271 if (minY < 0) minY = 0;
272 if (maxX > W - 1) maxX = W - 1;
273 if (maxY > H - 1) maxY = H - 1;
274 if (minX > maxX || minY > maxY)
return;
276 float px0 = minX + 0.5f;
277 float py0 = minY + 0.5f;
283 t.w0Row = (x2 - x1) * (py0 - y1) - (y2 - y1) * (px0 - x1);
284 t.w1Row = (x0 - x2) * (py0 - y2) - (y0 - y2) * (px0 - x2);
285 t.w2Row = (x1 - x0) * (py0 - y0) - (y1 - y0) * (px0 - x0);
296 t.positive = area > 0.0f;
300 RasterTriSse2<true>(t, s.depth.data(), W);
302 RasterTriSse2<false>(t, s.depth.data(), W);
304 RasterTriScalar(t, s.depth.data(), W);
309void RasterClipTri(
const ClipVert& a,
const ClipVert& b,
const ClipVert& c) {
310 ClipVert in[3] = {a, b, c};
312 int n = ClipNear(in, 3, out);
315 CullState& s = State();
316 float w =
static_cast<float>(s.width);
317 float h =
static_cast<float>(s.height);
320 ToScreen(out[0], w, h, sx0, sy0, sz0);
321 for (
int i = 1; i + 1 < n; ++i) {
322 float sx1, sy1, sz1, sx2, sy2, sz2;
323 ToScreen(out[i], w, h, sx1, sy1, sz1);
324 ToScreen(out[i + 1], w, h, sx2, sy2, sz2);
325 RasterScreenTri(sx0, sy0, sz0, sx1, sy1, sz1, sx2, sy2, sz2);
330void RasterWorldTri(
const Math::Vector3D& p0,
const Math::Vector3D& p1,
332 RasterClipTri(ToClip(p0, vp), ToClip(p1, vp), ToClip(p2, vp));
336void RasterBox(
const Math::AABB& box,
const Math::Matrix4& vp,
337 const Math::Vector3D& cam) {
338 float mnx = box.min.GetX(), mny = box.min.GetY(), mnz = box.min.GetZ();
339 float mxx = box.max.GetX(), mxy = box.max.GetY(), mxz = box.max.GetZ();
340 using V = Math::Vector3D;
341 V c000(mnx, mny, mnz), c100(mxx, mny, mnz);
342 V c010(mnx, mxy, mnz), c110(mxx, mxy, mnz);
343 V c001(mnx, mny, mxz), c101(mxx, mny, mxz);
344 V c011(mnx, mxy, mxz), c111(mxx, mxy, mxz);
346 auto quad = [&](
const V& a,
const V& b,
const V& c,
const V& d) {
347 RasterWorldTri(a, b, c, vp);
348 RasterWorldTri(a, c, d, vp);
351 if (cam.GetX() < mnx) quad(c000, c001, c011, c010);
352 if (cam.GetX() > mxx) quad(c100, c110, c111, c101);
353 if (cam.GetY() < mny) quad(c000, c100, c101, c001);
354 if (cam.GetY() > mxy) quad(c010, c011, c111, c110);
355 if (cam.GetZ() < mnz) quad(c000, c010, c110, c100);
356 if (cam.GetZ() > mxz) quad(c001, c101, c111, c011);
360bool AnyDepthAtOrBehind(
const float* depth,
int W,
int minX,
int maxX,
int minY,
361 int maxY,
float thresh) {
363 if (maxX - minX + 1 >= kLanes) {
364 const __m128 t = _mm_set1_ps(thresh);
365 const int lastX = maxX - kLanes + 1;
366 for (
int y = minY; y <= maxY; ++y) {
367 const float* row = depth + y * W;
368 __m128 hit = _mm_cmpge_ps(_mm_loadu_ps(row + lastX), t);
369 for (
int x = minX; x < lastX; x += kLanes)
370 hit = _mm_or_ps(hit, _mm_cmpge_ps(_mm_loadu_ps(row + x), t));
371 if (_mm_movemask_ps(hit) != 0)
return true;
376 for (
int y = minY; y <= maxY; ++y) {
377 const float* row = depth + y * W;
378 for (
int x = minX; x <= maxX; ++x) {
379 if (row[x] >= thresh)
return true;
387bool DepthRectVisible(
const Math::AABB& box) {
388 CullState& s = State();
389 float w =
static_cast<float>(s.width);
390 float h =
static_cast<float>(s.height);
391 float mnx = 1e30f, mny = 1e30f, mxx = -1e30f, mxy = -1e30f;
392 float boxMinZ = 1e30f;
393 for (
int i = 0; i < 8; ++i) {
394 ClipVert c = ToClip(box.Corner(i), s.viewProj);
395 if (c.w <= kWEps)
return true;
397 ToScreen(c, w, h, sx, sy, sz);
398 mnx = std::min(mnx, sx);
399 mxx = std::max(mxx, sx);
400 mny = std::min(mny, sy);
401 mxy = std::max(mxy, sy);
402 boxMinZ = std::min(boxMinZ, sz);
405 int W =
static_cast<int>(s.width);
406 int H =
static_cast<int>(s.height);
407 int minX =
static_cast<int>(std::floor(mnx)) - 1;
408 int maxX =
static_cast<int>(std::ceil(mxx)) + 1;
409 int minY =
static_cast<int>(std::floor(mny)) - 1;
410 int maxY =
static_cast<int>(std::ceil(mxy)) + 1;
411 if (minX < 0) minX = 0;
412 if (minY < 0) minY = 0;
413 if (maxX > W - 1) maxX = W - 1;
414 if (maxY > H - 1) maxY = H - 1;
415 if (minX > maxX || minY > maxY)
return true;
417 return AnyDepthAtOrBehind(s.depth.data(), W, minX, maxX, minY, maxY,
422bool ProjectedTooSmall(
const Math::AABB& b,
const Math::Matrix4& vp) {
423 CullState& s = State();
424 float w =
static_cast<float>(s.width);
425 float h =
static_cast<float>(s.height);
426 float mnx = 1e30f, mny = 1e30f, mxx = -1e30f, mxy = -1e30f;
427 for (
int i = 0; i < 8; ++i) {
428 ClipVert c = ToClip(b.Corner(i), vp);
429 if (c.w <= kWEps)
return false;
431 ToScreen(c, w, h, sx, sy, sz);
432 mnx = std::min(mnx, sx);
433 mxx = std::max(mxx, sx);
434 mny = std::min(mny, sy);
435 mxy = std::max(mxy, sy);
437 return (mxx - mnx) < 2.0f || (mxy - mny) < 2.0f;
443 State().frustumEnabled = enabled;
447 State().occlusionEnabled = enabled;
451 return State().frustumEnabled;
455 return State().occlusionEnabled;
459 CullState& s = State();
465 State().maxOccluders = count;
469 uint32_t probeInterval) {
470 CullState& s = State();
471 s.adaptiveEnabled = enabled;
472 s.probeInterval = probeInterval > 0 ? probeInterval : 1;
473 if (!enabled) s.skipFrames = 0;
479 CullState& s = State();
480 if (s.width == 0) s.width = 1;
481 if (s.height == 0) s.height = 1;
484 if (s.adaptiveEnabled && s.rasterizedThisFrame &&
485 s.stats.occlusionCulled == 0)
486 s.skipFrames = s.probeInterval;
488 size_t need =
static_cast<size_t>(s.width) * s.height;
489 if (s.depth.size() != need) s.depth.assign(need, 1.0f);
494 s.viewProj = viewProj;
495 s.cameraPos = cameraPos;
497 s.rasterizedThisFrame =
false;
502 CullState& s = State();
503 if (!s.hasFrame || !s.occlusionEnabled)
return;
505 if (!s.frustum.IsAABBVisible(box.
min, box.
max))
return;
511 s.occluders.push_back(e);
512 ++s.stats.occludersSubmitted;
516 uint32_t vertexCount,
517 const uint32_t* indices,
518 uint32_t indexCount) {
519 CullState& s = State();
520 if (!s.hasFrame || !s.occlusionEnabled)
return;
521 if (!vertices || vertexCount == 0)
return;
522 if (!indices || indexCount < 3)
return;
523 indexCount -= indexCount % 3;
526 for (uint32_t i = 1; i < vertexCount; ++i)
528 if (!s.frustum.IsAABBVisible(bounds.
min, bounds.
max))
return;
530 uint32_t start =
static_cast<uint32_t
>(s.triVerts.size());
531 for (uint32_t i = 0; i < indexCount; ++i) {
532 uint32_t idx = indices[i];
533 if (idx >= vertexCount) {
534 s.triVerts.resize(start);
537 s.triVerts.push_back(vertices[idx]);
544 e.triCount = indexCount;
546 s.occluders.push_back(e);
547 ++s.stats.occludersSubmitted;
551 CullState& s = State();
552 if (!s.hasFrame)
return;
554 if (s.skipFrames > 0) {
558 s.rasterizedThisFrame =
false;
559 s.stats.occlusionSkipped =
true;
563 auto t0 = std::chrono::high_resolution_clock::now();
565 std::fill(s.depth.begin(), s.depth.end(), 1.0f);
567 std::sort(s.occluders.begin(), s.occluders.end(),
568 [](
const OccluderEntry& a,
const OccluderEntry& b) {
569 return a.distSq < b.distSq;
572 uint32_t rasterized = 0;
573 for (
const auto& e : s.occluders) {
574 if (rasterized >= s.maxOccluders)
break;
575 if (ProjectedTooSmall(e.bounds, s.viewProj))
continue;
577 if (rasterized > 0 && !DepthRectVisible(e.bounds))
continue;
579 RasterBox(e.bounds, s.viewProj, s.cameraPos);
581 for (uint32_t i = 0; i + 2 < e.triCount; i += 3) {
582 RasterWorldTri(s.triVerts[e.triStart + i],
583 s.triVerts[e.triStart + i + 1],
584 s.triVerts[e.triStart + i + 2], s.viewProj);
590 s.stats.occludersRasterized = rasterized;
591 s.rasterizedThisFrame = rasterized > 0;
592 if (rasterized > 0) s.everRasterized =
true;
594 auto t1 = std::chrono::high_resolution_clock::now();
595 s.stats.rasterizeMs =
596 std::chrono::duration<float, std::milli>(t1 - t0).count();
600 CullState& s = State();
602 if (!s.hasFrame)
return true;
604 if (s.frustumEnabled) {
605 if (!s.frustum.IsAABBVisible(box.
min, box.
max)) {
606 ++s.stats.frustumCulled;
611 if (!s.occlusionEnabled || !s.rasterizedThisFrame)
return true;
613 if (DepthRectVisible(box))
return true;
615 ++s.stats.occlusionCulled;
620 CullState& s = State();
622 if (!s.hasFrame)
return true;
623 if (s.frustumEnabled) {
624 if (!s.frustum.IsAABBVisible(box.
min, box.
max)) {
625 ++s.stats.frustumCulled;
633 return State().stats;
637 CullState& s = State();
638 if (!s.everRasterized || s.depth.empty()) {
645 return s.depth.data();
649 CullState& s = State();
651 s.depth.shrink_to_fit();
653 s.occluders.shrink_to_fit();
655 s.triVerts.shrink_to_fit();
657 s.rasterizedThisFrame =
false;
658 s.everRasterized =
false;
static bool IsVisibleFrustumOnly(const Math::AABB &box)
Frustum-only visibility test, skipping the occlusion buffer entirely.
static const Stats & GetStats()
static void SetAdaptiveOcclusion(bool enabled, uint32_t probeInterval)
static void SetOcclusionBufferSize(uint32_t width, uint32_t height)
Occlusion depth buffer resolution (default 256x144).
static void SetOcclusionCullingEnabled(bool enabled)
static const float * GetDepthBuffer(uint32_t &width, uint32_t &height)
static void SubmitOccluderTriangles(const Math::Vector3D *vertices, uint32_t vertexCount, const uint32_t *indices, uint32_t indexCount)
World-space triangle occluder; same fully-solid-volume requirement as SubmitOccluderBox.
static void SubmitOccluderBox(const Math::AABB &box)
World-space occluders. Boxes must be fully solid volumes.
static void BeginFrame(const ViewFrustum &frustum, const Math::Matrix4 &viewProj, const Math::Vector3D &cameraPos)
static bool IsVisible(const Math::AABB &box)
static void FinalizeOccluders()
Sorts submitted occluders by distance and rasterizes them into the depth buffer up to the max-occlude...
static bool IsFrustumCullingEnabled()
static bool IsOcclusionCullingEnabled()
static void SetMaxOccluders(uint32_t count)
static void SetFrustumCullingEnabled(bool enabled)
Matrix< float, 4, 4 > Matrix4
Root namespace for everything the engine exposes.
Per-frame counters for the last completed culling pass.
void Merge(const AABB &o)
Grows this box to also cover o.
bool IsValid() const
True if min is componentwise <= max.
float DistanceSq(const Vector3D &p) const