[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
+164 -64
View File
@@ -1,90 +1,190 @@
---
id: wiki-2026-0508-computational-geometry
title: Computational Geometry
title: Computational Geometry (Frontend)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-053]
aliases: [2D Geometry, Geometric Algorithms]
duplicate_of: none
source_trust_level: A
confidence_score: 0.97
tags: [geometry, computational geometry, 3d, rendering]
confidence_score: 0.9
verification_status: applied
tags: [geometry, algorithms, canvas, frontend, math]
raw_sources: []
last_reinforced: 2026-06-XX
github_commit: "[P-Reinforce] Processed Computational Geometry."
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: TypeScript
framework: Canvas / SVG / WebGL
---
# [[Computational Geometry|Computational Geometry]] (계산 기하학)
# Computational Geometry (Frontend)
## 📌 한 줄 통찰 (The Karpathy Summary)
> 수학적 알고리즘을 사용하여 컴퓨터가 점, 곡선, 다각형 같은 기하학적 객체들 사이의 관계와 공간 구조를 효율적으로 분석하고 조작하는 기술 분야이다.
## 한 줄
> **"매 pixel 의 math 가 geometry 다"**. Hit-testing, polygon clipping, convex hull, spatial index — 매 canvas/SVG/Figma-style editor 의 core, 매 numerical robustness + spatial accel structure 가 핵심.
## 📖 구조화된 지식 (Synthesized Content)
- **정의:** 수학과 컴퓨터 과학이 만나는 영역으로, 현실 세계의 형태(건축물, 인체 모델, 게임 오브젝트 등)를 디지털로 표현하고 이를 바탕으로 물리적/시각적 시뮬레이션을 수행하는 기반 기술이다.
- **핵심 알고리즘 및 구조:**
1. **메쉬 데이터 구조:** 3D 객체를 삼각형(Tri[[ANGLE|ANGLE]])의 집합으로 근사화하여 저장하고 처리한다. (Vertices, Edges, Faces).
2. **공간 분할 기법:** 대규모 데이터를 효율적으로 검색하기 위해 공간을 나누는 방법들 (예: Octree, BVH - Bounding Volume Hierarchy). 이는 렌더링의 성능(Culling)에 필수적이다.
3. **좌표 변환 및 근사화:** 카메라 위치나 오브젝트 이동에 따른 좌표계 변환(Transformation Matrix), 그리고 복잡한 곡선을 단순화하는 과정이 포함된다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 기하학적 모델링은 단순히 형태를 만드는 것을 넘어, 물리 엔진과의 결합을 통해 '물리 법칙'을 시뮬레이션하고 그 결과를 예측하는 데 사용된다.
- **정책 변화:** 최신 트렌드는 하드웨어 가속(GPU)과 연동하여 복잡한 기하학적 계산(예: Ray Tracing)을 실시간으로 처리하는 방향으로 진화하고 있다.
### 매 fundamental ops
- Point-in-polygon (ray casting / winding number).
- Line-line / segment-segment intersection.
- Polygon-polygon clipping (Sutherland-Hodgman, Weiler-Atherton).
- Convex hull (Graham scan, Andrew's monotone chain).
- Bounding box / sphere.
- Distance: point-segment, point-polygon.
## 🔗 지식 연결 (Graph)
- Parent: [[Computational Geometry|Computational Geometry]]
- Related: Bounding Volume Hierarchy (BVH) , [[Three.js 렌더링 최적화|Three.js 렌더링 최적화]] , [[Physics|Physics]]-Based-Simulation
### 매 spatial accel
- Quadtree — 2D static/dynamic.
- R-tree — bbox-based, dynamic insert/delete (rbush lib).
- Spatial hash — uniform grid.
- BVH — for raycasting in 2D/3D.
---
### 매 numerical pitfalls
- Floating-point cross product near zero → epsilon checks.
- Robust orientation predicates (Shewchuk).
- 매 SVG path parsing → degenerate cubic 처리.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Figma-style hit-testing.
2. Map polygon labeling / clipping.
3. Drag-select rectangle vs many shapes.
4. Snap-to-grid / snap-to-edge.
5. Boolean ops on shapes (union/intersect/difference).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Point-in-polygon (ray casting)
```ts
type Pt = { x: number; y: number };
## 🧪 검증 상태 (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
export function pointInPolygon(p: Pt, poly: Pt[]): boolean {
let inside = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const a = poly[i], b = poly[j];
const intersect =
(a.y > p.y) !== (b.y > p.y) &&
p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y) + a.x;
if (intersect) inside = !inside;
}
return inside;
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Segment-segment intersection
```ts
export function segIntersect(p1: Pt, p2: Pt, p3: Pt, p4: Pt): Pt | null {
const d = (p2.x - p1.x) * (p4.y - p3.y) - (p2.y - p1.y) * (p4.x - p3.x);
if (Math.abs(d) < 1e-10) return null; // parallel
const t = ((p3.x - p1.x) * (p4.y - p3.y) - (p3.y - p1.y) * (p4.x - p3.x)) / d;
const u = ((p3.x - p1.x) * (p2.y - p1.y) - (p3.y - p1.y) * (p2.x - p1.x)) / d;
if (t < 0 || t > 1 || u < 0 || u > 1) return null;
return { x: p1.x + t * (p2.x - p1.x), y: p1.y + t * (p2.y - p1.y) };
}
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Convex hull (Andrew's monotone chain)
```ts
export function convexHull(pts: Pt[]): Pt[] {
const p = [...pts].sort((a, b) => a.x - b.x || a.y - b.y);
const cross = (o: Pt, a: Pt, b: Pt) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
const lower: Pt[] = [];
for (const pt of p) {
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], pt) <= 0) lower.pop();
lower.push(pt);
}
const upper: Pt[] = [];
for (let i = p.length - 1; i >= 0; i--) {
const pt = p[i];
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], pt) <= 0) upper.pop();
upper.push(pt);
}
upper.pop(); lower.pop();
return lower.concat(upper);
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Bounding box
```ts
export function bbox(pts: Pt[]): { min: Pt; max: Pt } {
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const { x, y } of pts) {
if (x < minX) minX = x; if (y < minY) minY = y;
if (x > maxX) maxX = x; if (y > maxY) maxY = y;
}
return { min: { x: minX, y: minY }, max: { x: maxX, y: maxY } };
}
```
**기본값:**
> *(TODO)*
### R-tree spatial index (rbush)
```ts
import RBush from 'rbush';
## ❌ 안티패턴 (Anti-Patterns)
type Item = { minX: number; minY: number; maxX: number; maxY: number; id: string };
const tree = new RBush<Item>();
tree.load(items);
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
const hits = tree.search({ minX: 0, minY: 0, maxX: 100, maxY: 100 });
```
### Point-segment distance
```ts
export function distPtSeg(p: Pt, a: Pt, b: Pt): number {
const dx = b.x - a.x, dy = b.y - a.y;
const lenSq = dx * dx + dy * dy;
if (lenSq === 0) return Math.hypot(p.x - a.x, p.y - a.y);
let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / lenSq;
t = Math.max(0, Math.min(1, t));
return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));
}
```
### Polygon clipping (using martinez-polygon-clipping)
```ts
import * as martinez from 'martinez-polygon-clipping';
const subject = [[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]];
const clip = [[[5, 5], [15, 5], [15, 15], [5, 15], [5, 5]]];
const intersection = martinez.intersection(subject, clip);
```
### Snap-to-grid
```ts
export const snap = (v: number, grid: number) => Math.round(v / grid) * grid;
export const snapPt = (p: Pt, g: number): Pt => ({ x: snap(p.x, g), y: snap(p.y, g) });
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 1k+ shape hit-test | R-tree (rbush) |
| Static map polygons | Quadtree pre-built |
| Boolean ops on polygons | martinez-polygon-clipping |
| Hull / triangulation | d3-delaunay, earcut |
| Robust numerics | Shewchuk predicates |
**기본값**: bbox pre-filter → exact test. Spatial index 매 N>500.
## 🔗 Graph
- 부모: [[Algorithms]] · [[Graphics]]
- 변형: [[Computer-Graphics]] · [[GIS]]
- 응용: [[Canvas-API]] · [[SVG]] · [[WebGL]] · [[Map-Rendering]]
- Adjacent: [[Spatial-Indexing]] · [[Collision-Detection]]
## 🤖 LLM 활용
**언제**: canvas editor, map UI, drag-select, snapping, boolean ops on shapes.
**언제 X**: 매 trivial fixed UI — 매 CSS layout 으로 충분.
## ❌ 안티패턴
- **Naive O(N) hit-test on 10k shapes**: 매 lag — spatial index 필수.
- **No epsilon in cross product**: 매 collinear 매 wrong branch.
- **Re-building spatial tree per frame**: 매 only on data change, drag 매 incremental update.
## 🧪 검증 / 중복
- Verified (CGAL docs / "Computational Geometry: Algorithms and Applications" — de Berg et al.).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 2D geometry algorithms + spatial index patterns |