# Performance Guard - Performans Koruma Direktifleri

## KRITIK KURAL: HER FIRSATTA PERFORMANS IYILESTIR

```
┌─────────────────────────────────────────────────────────────────┐
│  HEDEF: Catia, SolidWorks, Tebis'ten DAHA PERFORMANSLI olmak   │
│                                                                 │
│  Her kod degisikliginde:                                        │
│  1. Mevcut performansi KORU                                     │
│  2. Firsat varsa IYILESTIR                                      │
│  3. Asla GERILETEMEZSIN                                         │
└─────────────────────────────────────────────────────────────────┘
```

## FikoSecililer Performans Korumasi

### KORUNMASI GEREKEN YAPILAR

```typescript
// 1. Vector3 Pool - ASLA KALDIR
class Vector3Pool {
    private pool: THREE.Vector3[] = [];
    private maxPoolSize = Math.max(50, navigator.hardwareConcurrency * 10);

    acquire(): THREE.Vector3 { /* ... */ }
    release(vec: THREE.Vector3): void { /* ... */ }

    // Health check - %60-80 hedef
    getPoolHealth(): number { /* ... */ }
}

// 2. Geometry Cache (500ms TTL) - ASLA KALDIR
private geometryCache: Map<string, {
    geometry: THREE.BufferGeometry,
    timestamp: number
}> = new Map();

// 3. Clipping Plane Filter - ASLA KALDIR
private isPointBehindClippingPlanes(point: THREE.Vector3): boolean { /* ... */ }

// 4. GPU Picking API - ASLA KALDIR
public setGPUPicking(enabled: boolean): void { /* ... */ }
public getGPUPickingStatus(): GPUPickingStatus { /* ... */ }
```

### PERFORMANS HEDEFLERI

| Metrik | Minimum | Hedef | Maksimum |
|--------|---------|-------|----------|
| Edge selection | 10ms | <5ms | 2ms |
| GPU raycast | 1ms | <0.5ms | 0.2ms |
| Color picking | 3ms | <2ms | 1ms |
| Frame rate | 30 FPS | 60 FPS | 120 FPS |
| Allocation/frame | 20 | <10 | 0 |
| GPU memory | 512MB | <256MB | 128MB |
| Pool health | 50% | 60-80% | 90% |

## Render Performans Korumasi

### KORUNMASI GEREKEN YAPILAR

```typescript
// 1. Frustum Culling - ASLA DEVRE DISI BIRAKMA
renderer.frustumCulling = true;

// 2. LOD System - ASLA KALDIR
const LOD_DISTANCES = [0, 50, 150, 300, 500];
const LOD_LEVELS = ['ultra', 'high', 'medium', 'low', 'billboard'];

// 3. Instanced Rendering - ASLA KALDIR
class FikoInstancedEdgeRenderer {
    // 10,000+ edge'i tek draw call'da ciz
}

// 4. Occlusion Culling (500ms cache) - ASLA KALDIR
const OCCLUSION_CACHE_TTL = 500;
```

### RENDER LOOP KURALLARI

```typescript
// DOGRU - Performansli render loop
private animate = (): void => {
    this.animationId = requestAnimationFrame(this.animate);

    // 1. Frame budget check
    const frameStart = performance.now();

    // 2. Frustum culling (her 2 frame'de bir)
    if (this.frameCount % 2 === 0) {
        this.updateFrustumCulling();
    }

    // 3. LOD update (her 5 frame'de bir)
    if (this.frameCount % 5 === 0) {
        this.updateLOD();
    }

    // 4. Render
    this.renderer.render(this.scene, this.camera);

    // 5. Frame budget kontrol
    const frameTime = performance.now() - frameStart;
    if (frameTime > 16.67) {
        console.warn('Frame budget exceeded:', frameTime.toFixed(2), 'ms');
    }

    this.frameCount++;
};
```

## Zero-Allocation Kurallari

### YASAK PATTERNLER

```typescript
// ❌ YASAK - Loop icinde allocation
for (let i = 0; i < items.length; i++) {
    const vec = new Vector3(x, y, z);     // ALLOCATION!
    const mat = new Matrix4();             // ALLOCATION!
    const arr = items.slice(i, i + 10);   // ALLOCATION!
    const str = `Item ${i}`;              // ALLOCATION!
}

// ❌ YASAK - Spread operator hot path'te
const merged = [...arr1, ...arr2];        // ALLOCATION!
const copy = { ...obj };                  // ALLOCATION!

// ❌ YASAK - Array methods hot path'te
items.map(x => x * 2);                    // ALLOCATION!
items.filter(x => x > 0);                 // ALLOCATION!
items.reduce((a, b) => a + b, 0);         // Her frame'de YASAK!
```

### DOGRU PATTERNLER

```typescript
// ✅ DOGRU - Pre-allocated buffers
private readonly _tempVec = new Vector3();
private readonly _tempMat = new Matrix4();
private readonly _resultBuffer = new Float32Array(16);

processItems(): void {
    for (let i = 0; i < items.length; i++) {
        this._tempVec.set(items[i].x, items[i].y, items[i].z);
        // Use _tempVec
    }
}

// ✅ DOGRU - Object pool kullan
const vec = this.vector3Pool.acquire();
try {
    vec.set(x, y, z);
    // Use vec
} finally {
    this.vector3Pool.release(vec);
}

// ✅ DOGRU - Inline hesaplama
function distanceSquaredFast(a: Vector3, b: Vector3): number {
    const dx = a.x - b.x;
    const dy = a.y - b.y;
    const dz = a.z - b.z;
    return dx * dx + dy * dy + dz * dz;
}
```

## Memory Leak Onleme

### DISPOSAL CHECKLIST

```typescript
// Her component destroy'da MUTLAKA calistir
ngOnDestroy(): void {
    // 1. Animation loop durdur
    cancelAnimationFrame(this.animationId);

    // 2. Event listener'lari kaldir
    this.canvas.removeEventListener('mousemove', this.onMouseMove);
    this.canvas.removeEventListener('click', this.onClick);

    // 3. Three.js resources dispose et
    this.scene.traverse(child => {
        if (child instanceof THREE.Mesh) {
            child.geometry?.dispose();
            this.disposeMaterial(child.material);
        }
    });

    // 4. Renderer dispose
    this.renderer.dispose();
    this.renderer.forceContextLoss();

    // 5. GPU buffers temizle
    this.gpuPicker?.dispose();
    this.webGPU?.dispose();

    // 6. WASM memory serbest birak
    this.wasmBridge?.cleanup();

    // 7. Pools temizle
    this.vector3Pool.clear();
    this.geometryCache.clear();
}
```

## GPU Memory Yonetimi

### BUFFER REUSE

```typescript
// ✅ Buffer pool kullan
class BufferPool {
    private pools: Map<number, GPUBuffer[]> = new Map();

    acquire(size: number): GPUBuffer {
        const pool = this.pools.get(size);
        if (pool && pool.length > 0) {
            return pool.pop()!;
        }
        return this.createBuffer(size);
    }

    release(buffer: GPUBuffer, size: number): void {
        let pool = this.pools.get(size);
        if (!pool) {
            pool = [];
            this.pools.set(size, pool);
        }
        if (pool.length < 10) {
            pool.push(buffer);
        } else {
            buffer.destroy();
        }
    }
}
```

## Performance Monitor Integration

### RUNTIME KONTROL

```typescript
class PerformanceGuard {
    private metrics = {
        fps: 0,
        frameTime: 0,
        gpuMemory: 0,
        allocationsPerFrame: 0,
        poolHealth: 0
    };

    check(): PerformanceReport {
        const warnings: string[] = [];

        if (this.metrics.fps < 30) {
            warnings.push('CRITICAL: FPS below 30');
        }
        if (this.metrics.frameTime > 33) {
            warnings.push('WARNING: Frame time > 33ms');
        }
        if (this.metrics.allocationsPerFrame > 20) {
            warnings.push('WARNING: Too many allocations');
        }
        if (this.metrics.poolHealth < 50) {
            warnings.push('WARNING: Pool health low');
        }

        return { metrics: this.metrics, warnings };
    }
}
```

## Debug Console

```javascript
// Performans metrikleri
const perf = window.__fikoPerformance__;

// FPS
console.log("FPS:", perf?.fps);

// Frame time
console.log("Frame time:", perf?.frameTime, "ms");

// Memory
console.log("GPU Memory:", renderer.info.memory);
console.log("Geometries:", renderer.info.memory.geometries);
console.log("Textures:", renderer.info.memory.textures);

// Pool health
console.log("Pool health:", fikoSecim?.vector3Pool?.getPoolHealth(), "%");

// Draw calls
console.log("Draw calls:", renderer.info.render.calls);
console.log("Triangles:", renderer.info.render.triangles);
```

## Performans Iyilestirme Firsatlari

```
HER KOD DEGISIKLIGINDE KONTROL ET:

1. [ ] Loop'ta allocation var mi? → Pool kullan
2. [ ] Array method kullaniliyor mu? → for loop'a cevir
3. [ ] Spread operator var mi? → Manual copy yap
4. [ ] String concatenation var mi? → Template literal cache'le
5. [ ] Object creation var mi? → Reuse et
6. [ ] Event listener ekleniyor mu? → Cleanup ekle
7. [ ] GPU buffer olusturuluyor mu? → Pool'a ekle
8. [ ] Geometry clone ediliyor mu? → Share et
9. [ ] Material clone ediliyor mu? → Share et
10. [ ] Texture yukleniyor mu? → Cache'le
```

## KURAL: PERFORMANS ASLA GERILETEMEZ

```
Eger bir degisiklik performansi dusuruyorsa:
1. YAPMA
2. Alternatif bul
3. Optimize et
4. Test et
5. Benchmark ile dogrula

Catia, SolidWorks, Tebis'ten DAHA IYI olmak ZORUNLU!
```
