[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,98 +2,198 @@
id: wiki-2026-0508-frustum-culling
title: Frustum Culling
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-7A315B]
aliases: [View Frustum Culling, VFC, Camera Culling]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [graphics, rendering, culling, optimization, gpu]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Frustum Culling"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: cpp
framework: opengl-vulkan-unity
---
# [[Frustum Culling|Frustum Culling]]
# Frustum Culling
## 📌 한 줄 통찰 (The Karpathy Summary)
> 시야 절두체 컬링(Frustum Culling)은 카메라의 시야(View Frustum) 밖으로 벗어난 객체를 렌더링 연산에서 제외하여 불필요한 GPU 자원 소모를 방지하는 최적화 기법이다 [1]. 하지만 [[InstancedMesh|InstancedMesh]]를 적용할 경우 엔진 수준에서 전체를 단일 객체로 취급하므로, 모든 인스턴스를 포함하는 거대한 바운딩 볼륨을 기준으로 한 번만 컬링이 수행되는 '전부 아니면 전무(All-or-Nothing)' 방식으로 작동한다 [2]. 이로 인해 화면에 극히 일부의 인스턴스만 노출되더라도 보이지 않는 나머지 모든 인스턴스의 정점 변환 연산을 GPU가 강제로 수행해야 하는 구조적 한계를 야기한다 [2].
## 한 줄
> **"매 carmera 의 view volume (frustum) 밖 object 의 매 draw skip"**. 매 가장 기본적이고 가장 효과적인 매 visibility culling — 매 30-90% draw call 감소가 일반적. 매 modern engine (Unreal 5 Nanite, Unity HDRP, bevy) 은 매 GPU-driven culling 으로 매 millions of objects 를 매 compute shader 안에서 매 frame 마다 cull.
## 📖 구조화된 지식 (Synthesized Content)
- **InstancedMesh에서의 구조적 비효율성**
Three.js는 기본적으로 카메라 시야 밖의 객체를 자동으로 컬링해 드로우 콜 생성을 방지한다 [3]. 그러나 InstancedMesh를 사용하면 개별 인스턴스 단위의 네이티브 시야 절두체 컬링 기능이 상실된다 [4]. 엔진은 전체 인스턴스의 바운딩 볼륨만을 검사하기 때문에, 10,000개의 객체 중 단 1개만 시야에 들어와도 GPU는 9,999개의 보이지 않는 객체에 대한 정점 셰이더([[Vertex Shader|Vertex Shader]]) 행렬 곱셈 연산을 처리해야 한다 [2]. 이는 특히 저사양 모바일 기기나 통합 GPU 환경에서 치명적인 GPU 점유율 상승 및 프레임 드랍을 유발한다 [2, 5].
## 매 핵심
- **수동 CPU 컬링의 병목 현상**
GPU 낭비를 막기 위해 자바스크립트(CPU) 수준에서 각 인스턴스의 위치를 카메라 평면과 대조하여 가시성을 판단하고 렌더링할 버퍼를 매 프레임 재구성(Reordering)할 수 있다 [5, 6]. 하지만 단일 스레드 특성을 갖는 자바스크립트에서 대규모 배열을 매번 순회하고 조작하는 것은 치명적인 CPU 메인 스레드 병목과 가비지 컬렉션(GC) 부하를 일으킨다 [5].
### 매 frustum 표현
- **6 planes**: near, far, left, right, top, bottom.
- 매 plane equation: `ax + by + cz + d = 0` with `(a,b,c)` = inward normal.
- 매 view-projection matrix 의 매 row combo 로 6 planes extract (Gribb-Hartmann).
- **한계 극복을 위한 대안 전략**
1. **공간 분할 기반 그룹화 전략**: 수만 개의 인스턴스를 하나의 거대한 InstancedMesh로 묶는 대신, 공간적으로 인접한 객체들을 100~500개 단위의 소규모 InstancedMesh로 분할 관리하는 방법이다. 이 경우 드로우 콜 횟수는 다소 증가하지만 시야 절두체 컬링 정밀도가 크게 향상되어 GPU의 무의미한 정점 연산을 극적으로 줄일 수 있다 [7].
2. **GPU 컴퓨트 컬링 및 간접 그리기([[Indirect Draw|Indirect Draw]])**: WebGPU 환경의 컴퓨트 셰이더([[Compute Shader|Compute Shader]])를 활용해 GPU가 직접 인스턴스의 가시성을 판별하도록 처리하는 방식이다 [8, 9]. 판별 결과는 GPU 내부 버퍼에 저장되어 `drawIndirect` 명령으로 즉각 렌더링되므로, CPU 연산 및 CPU-GPU 간 데이터 전송 병목을 완벽히 회피할 수 있다 [9].
3. **확장 라이브러리 도입**: BVH(Bounding Volume Hierarchy)를 이용한 고속 공간 쿼리와 `Instanced[[BufferAttribute|BufferAttribute]]`를 활용한 간접 참조(Indirection) 방식을 통해 기존 InstancedMesh를 확장하여 효율적인 개별 컬링을 제공하는 `[[InstancedMesh2|InstancedMesh2]]`와 같은 외부 라이브러리 활용이 대안이 될 수 있다 [10-12].
### 매 bounding volume choice
- **AABB (axis-aligned)**: 매 cheapest, 매 conservative — 매 large rotated objects 매 over-conservative.
- **OBB (oriented)**: 매 tighter, 매 더 expensive.
- **Sphere**: 매 cheapest test (single dot product), 매 loosest.
- **Plane mask (frustum culling with masks)**: 매 children inherit parent 의 "fully inside" plane.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
### 매 알고리즘 흐름
1. View-projection matrix → 6 frustum planes.
2. 매 object 의 BV 와 매 6 planes test.
3. **Outside** any plane → cull.
4. **Inside** all → render.
5. **Intersect** → render (or recurse children if hierarchy).
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[InstancedMesh|InstancedMesh]], Draw Call, [[WebGPU|WebGPU]], Bounding Volume Hierarchy (BVH)
- **Projects/Contexts:** Three.js, [[InstancedMesh2|InstancedMesh2]]
- **Contradictions/Notes:** InstancedMesh 기술은 드로우 콜 감소를 통해 CPU 병목을 획기적으로 해결할 수 있도록 설계되었으나, 동시에 개별 시야 절두체 컬링을 무력화시킴으로써 결과적으로 GPU 측면에 새로운 정점 연산 병목을 유발하는 모순적인 절충(Trade-off)을 요구한다 [5, 13].
### 매 modern (GPU-driven)
- **Compute shader** 가 매 draw arguments buffer 를 build (`DrawIndirect`).
- 매 millions of objects 도 매 sub-millisecond.
- 매 hierarchical Z-buffer occlusion + frustum 결합 (Nanite).
---
*Last updated: 2026-04-19*
## 💻 패턴
---
### Extract frustum planes from VP matrix (Gribb-Hartmann)
```cpp
struct Plane { glm::vec3 n; float d; };
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
void extractPlanes(const glm::mat4& vp, Plane out[6]) {
auto m = glm::transpose(vp); // row-major helper
out[0] = { glm::vec3(m[3]+m[0]), m[3].w + m[0].w }; // left
out[1] = { glm::vec3(m[3]-m[0]), m[3].w - m[0].w }; // right
out[2] = { glm::vec3(m[3]+m[1]), m[3].w + m[1].w }; // bottom
out[3] = { glm::vec3(m[3]-m[1]), m[3].w - m[1].w }; // top
out[4] = { glm::vec3(m[3]+m[2]), m[3].w + m[2].w }; // near
out[5] = { glm::vec3(m[3]-m[2]), m[3].w - m[2].w }; // far
for (int i = 0; i < 6; i++) {
float len = glm::length(out[i].n);
out[i].n /= len; out[i].d /= len;
}
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Sphere vs frustum (cheapest)
```cpp
bool sphereInFrustum(const Plane planes[6], const glm::vec3& c, float r) {
for (int i = 0; i < 6; i++)
if (glm::dot(planes[i].n, c) + planes[i].d < -r) return false;
return true;
}
```
**선택 A를 써야 할 때:**
- *(TODO)*
### AABB vs frustum (positive vertex / p-vertex test)
```cpp
bool aabbInFrustum(const Plane planes[6], const glm::vec3& mn, const glm::vec3& mx) {
for (int i = 0; i < 6; i++) {
glm::vec3 p = {
planes[i].n.x >= 0 ? mx.x : mn.x,
planes[i].n.y >= 0 ? mx.y : mn.y,
planes[i].n.z >= 0 ? mx.z : mn.z
};
if (glm::dot(planes[i].n, p) + planes[i].d < 0) return false;
}
return true;
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### BVH-based hierarchical culling
```cpp
void cullBVH(const BVHNode& node, const Plane planes[6], std::vector<int>& visible) {
auto r = aabbVsFrustumIntersect(planes, node.aabb);
if (r == OUTSIDE) return;
if (r == INSIDE) { addAll(node, visible); return; }
if (node.isLeaf) {
for (int idx : node.objects)
if (aabbInFrustum(planes, objs[idx].mn, objs[idx].mx))
visible.push_back(idx);
return;
}
cullBVH(*node.left, planes, visible);
cullBVH(*node.right, planes, visible);
}
```
**기본값:**
> *(TODO)*
### GPU compute culling (HLSL)
```hlsl
// CullCS.hlsl
StructuredBuffer<ObjectData> objects : register(t0);
ConstantBuffer<FrustumCB> frustum : register(b0);
RWStructuredBuffer<DrawArgs> drawArgs : register(u0);
RWByteAddressBuffer counter : register(u1);
## ❌ 안티패턴 (Anti-Patterns)
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID) {
if (id.x >= objects.Length) return;
ObjectData o = objects[id.x];
bool visible = true;
[unroll] for (int i = 0; i < 6; i++) {
float4 p = frustum.planes[i];
if (dot(p.xyz, o.center) + p.w < -o.radius) { visible = false; break; }
}
if (visible) {
uint slot;
counter.InterlockedAdd(0, 1, slot);
drawArgs[slot].vertexCount = o.indexCount;
drawArgs[slot].instanceCount = 1;
drawArgs[slot].firstIndex = o.firstIndex;
drawArgs[slot].baseInstance = id.x;
}
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Unity (Burst) culling job
```csharp
[BurstCompile]
struct FrustumCullJob : IJobParallelFor {
[ReadOnly] public NativeArray<float4> planes; // 6 planes
[ReadOnly] public NativeArray<float4> bounds; // xyz=center, w=radius
[WriteOnly] public NativeArray<bool> visible;
public void Execute(int i) {
float4 b = bounds[i];
for (int p = 0; p < 6; p++) {
float4 pl = planes[p];
if (math.dot(pl.xyz, b.xyz) + pl.w < -b.w) {
visible[i] = false;
return;
}
}
visible[i] = true;
}
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| <1k objects, CPU | per-object sphere/AABB test |
| 1k-100k, hierarchical | BVH / Octree + frustum |
| 100k+ static, GPU | compute shader + DrawIndirect |
| Massive (Nanite-class) | GPU-driven + HZB occlusion |
| Animated skeletal | use skinned bounds (loose) |
**기본값**: 매 modern engine — GPU compute culling + BVH for spatial queries.
## 🔗 Graph
- 부모: [[Visibility Culling]] · [[Real-Time Rendering]]
- 변형: [[Occlusion Culling]] · [[Portal Culling]] · [[Backface Culling]]
- 응용: [[GPU-Driven Rendering]] · [[Nanite]] · [[LOD Systems]]
- Adjacent: [[BVH]] · [[Octree]] · [[Hierarchical Z-Buffer]]
## 🤖 LLM 활용
**언제**: plane extraction code 검토, false-cull bug 디버깅 (e.g., flipped normal), GPU shader skeleton.
**언제 X**: 매 actual rendering decision 의 runtime correctness — unit test + visual verification.
## ❌ 안티패턴
- **No bounding volume cache**: 매 frame 마다 매 mesh 의 bound 재계산 — pre-compute.
- **Sphere only for everything**: 매 long thin object 매 over-conservative.
- **Plane normalization 누락**: 매 distance comparison 부정확.
- **Cull camera == render camera 가정**: 매 shadow camera, planar reflection 시 매 잘못.
- **Animated bound 무시**: 매 skinned mesh 의 bound 가 매 outdated → pop in/out.
## 🧪 검증 / 중복
- Verified (Real-Time Rendering 4th ed, Gribb-Hartmann 2001, Unreal Nanite docs 2026).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — frustum extraction + BV tests + GPU-driven |