commit b3b4188216cf7ef519c70a0f8f39f80ce8339278 Author: CRT Date: Thu Aug 20 23:15:58 2026 +0000 Initial commit: @medieval-kit registry and viewer A lowpoly medieval procedural model library for Vibe3D, plus the model inspector used to build it. Registry (@medieval-kit, published as @medieval-kit/registry): - core: deterministic mulberry32 RNG, slot-based vertex-coloured materials, a geometry vocabulary (box, prism, stave, band, head, flip), and the stable-anchor part slots the Vibe3D protocol requires - wooden-barrel: 806 tris, 13 separate staves, iron hoops, recessed heads - wooden-crate: 360 tris, plank rows on corner posts, forged straps - iron-brazier: 423 tris, typed actions, per-frame flame flicker, own light The kit declares no renderer capabilities, so it runs on WebGLRenderer as well as WebGPURenderer. Colour variation lives in vertex attributes rather than in materials, so each model keeps one draw call per material. Verification (bun run verify) covers 64 checks without a browser: geometry validity, winding by two measures (radial alignment for bodies of revolution, signed volume for closed solids), coplanar-face detection for z-fighting, stable root and anchor identity across configure(), deterministic seeding, material ownership, and idempotent disposal. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6a3ccb5 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,12 @@ +# Depoda her zaman LF sakla, checkout'ta platformun yerel biçimini ver. +# Bu olmadan Windows'ta yapılan commit'ler CRLF ile girer ve Linux/macOS'taki +# katkıcılar dosyaların tamamını değişmiş görür. +* text=auto eol=lf + +# İkili dosyalar dönüştürülmemeli. +*.png binary +*.jpg binary +*.webp binary +*.glb binary +*.gltf binary +*.woff2 binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..aadcaba --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +node_modules/ + +# Derleme çıktıları. `my-registry/dist/registry.json` build script'inden üretilir; +# depoya konmaz, `bun run registry:build` ile yeniden kurulur. +dist/ +dist-viewer/ + +*.log +*.tgz +*.tsbuildinfo +.DS_Store + +# Ajan/araç durumu +.omc/ +.claude/settings.local.json + +# models.lock.json KASITLI OLARAK dahil edilir: kurulu kaynağın hangi sürümden +# geldiğini kaydeder ve `vibe3d diff` onunla yerel değişiklikleri bulur. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2e4bee1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 CRTkafa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b91242f --- /dev/null +++ b/README.md @@ -0,0 +1,84 @@ +# medieval-kit + +A lowpoly medieval model library for [Vibe3D](https://github.com/vibe-stack/vibe3d), +plus the viewer used to build it. + +Vibe3D is a source-first model registry for Three.js: you install the +TypeScript that *generates* a model into your own project rather than depending +on an opaque package. This repository holds one such registry. + +- **[`my-registry/`](my-registry/)** — the `@medieval-kit` registry, published + to npm as [`@medieval-kit/registry`](my-registry/README.md). +- **`src/`** — a demo app that installs from both `@medieval-kit` and the + first-party `@scifi-kit`, so the two can be inspected side by side. + +## Run the viewer + +Requires [Bun](https://bun.sh) and a browser with WebGPU (the `@scifi-kit` model +in the demo uses TSL node materials; the medieval kit itself does not). + +```sh +bun install +bun run registry:build +bun run dev +``` + +Open `/viewer.html` for the model inspector: registry-grouped catalogue, live +triangle counts, configuration sliders wired to `configure()`, and a wireframe +overlay. + +## Use the kit in your own project + +```sh +bunx vibe3d init +bunx vibe3d add @medieval-kit/wooden-barrel +``` + +See [`my-registry/README.md`](my-registry/README.md) for the model list, +configuration fields, and runtime contract. + +## Verify + +```sh +bun run typecheck +bun run verify +``` + +`verify` runs 64 checks against the installed sources without a browser: +geometry validity, winding, coplanar-face (z-fighting) detection, stable root +and anchor identity across `configure()`, deterministic seeding, material +ownership, and idempotent disposal. + +Two of those deserve a note, because both were written after a real bug: + +- **Winding** is checked two ways, because two kinds of geometry need two + measures. Bodies of revolution use radial alignment — every radial face on the + outer shell must point away from the axis. Closed solids use signed volume: + `Σ a·(b×c)/6` is positive only when the winding faces outward. +- **Z-fighting** is checked by looking for triangles that share a plane, share a + normal direction, and overlap in area. Edge contact between neighbouring boards + is fine and is not flagged; genuine coplanar overlap is. + +## Layout + +```text +my-registry/ + models/core/ shared palette, RNG, geometry vocabulary, part slots + models// one procedural model per folder + build.ts compiles models/ into dist/registry.json +src/ + viewer.ts the model inspector + lib/vibe3d/ Vibe3D contracts installed by `vibe3d init` + models/ installed model source (owned, editable) +scripts/ + verify-model.ts browser-free conformance checks + zfight.ts coplanar overlap detection +models.json which registries this project resolves +models.lock.json install receipt; `vibe3d diff` compares against it +``` + +`src/models/` is generated by `vibe3d add` but committed on purpose: it is the +demo's own source, and keeping it in the tree is what makes `vibe3d diff` +meaningful. + +Released under the MIT License. diff --git a/REFERENCE.md b/REFERENCE.md new file mode 100644 index 0000000..92204f6 --- /dev/null +++ b/REFERENCE.md @@ -0,0 +1,534 @@ +# vibe3d — çalışma notları + +Bu klasördeki her şeyin ne işe yaradığı, vibe3d'nin nasıl çalıştığı ve kendi +asset pack'inizi nasıl üreteceğiniz. + +Üst kaynak: · Dokümanlar: + · Lisans: MIT + +--- + +## 1. vibe3d ne DEĞİL, ne + +**Değil:** bir 3D model kütüphanesi, bir AI model üreteci, bir motor. + +**Ne:** shadcn/ui'ın 3D karşılığı — bir *kaynak dağıtım protokolü*. Model +indirmiyorsunuz; **modeli üreten TypeScript kodunu** kendi projenize kopyalıyor +ve sahipleniyorsunuz. `node_modules` sınırı yok, patch'lemek yok; dosya sizin, +açıp değiştirirsiniz. + +Sistem dört katmandan oluşuyor: + +| Katman | Paket | Sorumluluk | +| --- | --- | --- | +| Protokol | `@vibe3djs/schema` | `models.json`, `registry.json`, lock şemaları (Zod) | +| Çözümleme | `@vibe3djs/registry` | kaynak sağlayıcılar, bağımlılık grafiği, güvenli kurulum | +| Doğrulama | `@vibe3djs/conformance` | şema + yol güvenliği + hash denetimi | +| Arayüz | `vibe3d` (CLI) | `init`, `add`, `view`, `list`, `diff`, `remove`, `doctor` | + +`@scifi-kit` bunların hiçbiri değil — **protokolün ilk referans registry'si**. +Yani sci-fi olması bir tesadüf; platform stil hakkında hiçbir varsayım yapmıyor. + +### Adresleme + +``` +@scifi-kit/pressure-gauge +| └── registry item (model) +└───────────── registry namespace +``` + +Namespace **npm paket adı değildir**. Fiziksel kaynağa `models.json` üzerinden +bağlanır: + +```json +"registries": { + "@scifi-kit": { "source": "npm:@scifi-kit/registry", "version": "latest" }, + "@medieval-kit":{ "source": "file:my-registry/dist/registry.json", "version": "workspace" } +} +``` + +Bu ayrım sayesinde yayıncı depolamayı değiştirebilir (npm → başka scope → shard'lı +paketler) ve tüketicinin kullandığı adres aynı kalır. Desteklenen kaynaklar: +`npm:`, `file:`, `https://`. (`github:` şemada var ama henüz "planned but not +available yet" hatası veriyor.) + +### Güvenlik modeli + +CLI, registry npm paketini `node_modules`'a **kurmaz** ve lifecycle script'lerini +**çalıştırmaz**. `pacote` ile tarball'ı geçici bir dizine açar, manifest'i Zod ile +doğrular, mutlak yol / `..` sızmasını reddeder, sadece çözümlenmiş item'ların +bildirdiği dosyaları yazar, sonra geçici dizini siler. + +--- + +## 2. Bu klasörde ne var + +``` +models.json sizin yapılandırmanız (elle düzenlenir) +models.lock.json CLI'ın makbuzu (elle düzenlenmez) +index.html · vite.config.ts oyun alanı uygulaması +src/main.ts sahne + renderer + render döngüsü (SİZE ait) +src/lib/vibe3d/ `init`in kurduğu evrensel sözleşmeler + model.ts ModelInstance, PartHandle, MaterialBindings + ownership.ts ResourceScope (kaynak sahipliği) + materials.ts MaterialSource arayüzü +src/lib/vibe3d/scifi-kit/generator/ @scifi-kit/core — 2.100 satır prosedürel araç +src/models/scifi-kit/pressure-gauge/ kurulu sci-fi modeli +src/models/medieval-kit/wooden-barrel/ kurulu KENDİ modeliniz +my-registry/ kendi registry'nizin kaynağı + build script'i +scripts/verify-model.ts tarayıcısız conformance doğrulaması +``` + +`models.json` ↔ `models.lock.json` ayrımı kasıtlı: birincisi **yapılandırma** +(sizin), ikincisi **kurulum durumu** (CLI'ın). Lock her dosyanın kurulum anındaki +sha256'sını tutar; `vibe3d diff` bununla yerel değişikliklerinizi tespit eder ve +`add`/`update` düzenlediğiniz dosyaların **üzerine yazmaz** (`--overwrite` demedikçe). + +### Çalıştırma + +```bash +bun run dev # oyun alanı — iki registry, tek proje +bun run typecheck # kurulu kaynak gerçekten derleniyor mu +bun scripts/verify-model.ts # geometri, kimlik kararlılığı, sahiplik, dispose +``` + +> **WebGPU gerekir.** `@scifi-kit` modelleri TSL düğüm materyalleri (`colorNode`, +> `attribute(...)`) kullanıyor, bu yüzden `WebGPURenderer` şart. Kendi +> `@medieval-kit` modeliniz düz `MeshStandardMaterial` kullanıyor — WebGL yeter. + +> **`three` vs `three/webgpu` tuzağı.** Bunlar ayrı bundle'lar ve her ikisi de +> çekirdek sınıfların kendi kopyasını içerir. Karıştırırsanız "Multiple instances +> of Three.js" uyarısı alır, `instanceof` kontrolleri iki kopya arasında bozulur. +> `vite.config.ts` içinde `three` → `three/webgpu` takma adıyla çözdük. Regex +> (`/^three$/`) şart; düz string önek eşleşmesi yapıp `three/addons/...` yolunu da +> bozardı. + +--- + +## 3. Modeller nasıl üretiliyor + +Kısa cevap: **prosedürel TypeScript**. GLB/FBX indirilmiyor, mesh runtime'da +koddan doğuyor. GLB sadece *çıktı* (dışa aktarım), *girdi* değil. + +### 3.1 Boru hattı + +`@scifi-kit/core` (`src/lib/vibe3d/scifi-kit/generator/`) beş aşamalı bir hat: + +1. **`primitives.ts`** (867 satır) — `prism`, `extrudeProfile`, `filletRing`, + `flatPlate`, `groove`, `cylinder`. Bunlar Three.js'in kutu/silindirinden farklı: + köşe pahları (chamfer), teğetsel fileto halkaları ve pah bantları boyunca + paylaşılan normaller üretiyorlar. "AI ürünü gibi durmayan" hard-surface + görünümü buradan geliyor. +2. **`profile.ts`** — 2B profil üretimi: `rect`, `octagon`, `stepEdge`, + `offsetProfile`, `mirrorProfile`. Önce kesit çizilir, sonra extrude edilir. +3. **`materials.ts`** — `MaterialLibrary` + `mountMaterialSource`. Materyaller + `MAT-03/GRAPHITE-800` gibi semantik kimliklerle alınır, projede override edilebilir. +4. **`wear.ts`** (524 satır) — işin sırrı burada. `bakeOcclusion` ve + `bakeSurfaceAttributes`, parçalar hâlâ ayrıyken komşuluk ve yüzey kimliğini + **vertex attribute'larına** (`aMask`, `aColor`, `aSurface`, `aWearDir`, `aPlane`) + yazar. Sonra `createWearMaterial` tek bir TSL düğüm grafiğiyle boya + dökülmesi, çizik ve kir üretir. Koddaki yorum niyeti net anlatıyor: fraktal + gürültü kasıtlı olarak kullanılmamış, çünkü izotropik gürültü yumuşak bulut + verir ve bulut hasar değil sis gibi okunur. +5. **`batching.ts` + `glb.ts`** — `mergeStaticByMaterial` statik parçaları + materyal başına tek çizime indirir; `exportStaticGlb` prosedürel aşınmayı + standart PBR verisine *bake* ederek taşınabilir GLB üretir. + +Sıra kritik ve `modeling-rules.md`'de kural 9 olarak yazılı: **kur, bake et, +sonra birleştir.** Komşuluk verisi ancak nesneler ayrıyken türetilebilir. + +### 3.2 Bir modelin anatomisi + +`src/models/scifi-kit/pressure-gauge/model.ts` (539 satır) tipik bir örnek: + +```ts +export function createModel() { + const { materials, handles, profiles } = acquireMaterials() + const root = new Group(); root.name = 'pressure-gauge' + + addMount(root, materials); addHousing(root, materials) + const needlePivot = addFace(root, materials) // hareketli parça + addSideIndicator(root, materials); addConnector(root, materials) + + bakeOcclusion(root) // 1) komşuluk → attribute + bakeSurfaceAttributes(root, profiles) + const wearMaterial = createWearMaterial(...) // 2) tek TSL materyali + + root.remove(needlePivot) // 3) hareketli parçayı batch dışına al + mergeStaticByMaterial(root, ...) // statik olanı düzleştir + root.add(needlePivot) + + return { root, update, triggerPressureTest, dispose } +} +``` + +Ölçüm sonucu (`bun scripts/verify-model.ts`): **10 mesh, 10.830 üçgen**, 8 materyal, +5.7 × 7.4 × 2.71 m. `update()` tam **bir** düğümü döndürüyor (ibre pivotu). + +### 3.3 Runtime sözleşmesi + +`src/lib/vibe3d/model.ts` küçük ve kasıtlı olarak öyle: + +- **`root` kimliği ömür boyu sabit.** `configure()` topolojiyi yeniden kurabilir + ama kökü değiştiremez — sahne ebeveynliği, editör seçimi, dış referanslar + hayatta kalsın diye. +- **Semantik `parts`** — anonim mesh sırasına bağımlılık yok. `anchor` sabit, + `content` yeniden kurulabilir. Tüketicinin `anchor`'a eklediği ışık/etiket + rebuild'i atlatır. +- **`materials.get/override/reset`** — çözümleme sırası: örnek override → proje + override → kit varsayılanı. +- **Sahiplik**: model kendi kaynağını tam bir kez dispose eder, **tüketicinin + verdiği materyale asla dokunmaz**, `dispose()` idempotenttir. +- **Sahne, renderer, kamera ve render döngüsü SİZE ait.** `src/main.ts`'e bakın. + +`configure()` pahalıdır — kullanıcı ayarı içindir, kare başına animasyon için +değil. Sürekli hareket `actions` + `update(dt)` ile yapılır. + +### 3.4 Modeller nasıl *yazılıyor* (asıl "generate" kısmı) + +Elle. Ama yapılandırılmış bir AI döngüsüyle: **`vibe-model` skill'i**. + +```bash +bunx vibe-model # .agents/skills/vibe-model kurar +``` + +Döngü: + +``` +model kaynağı → deterministik preview → bağımsız görsel kritik + ▲ │ + └──────────── en yüksek etkili düzeltme ─┘ +``` + +Kurallar (`.agents/skills/vibe-model/SKILL.md`): kritik eden ajana **sadece** +brief, referans görseli ve mevcut render verilir (kodu görmez). Ajan bir benzerlik +skoru ve **en fazla üç** öncelikli düzeltme döndürür. Sırasıyla siluet ve oranlar, +ana kütleler ve negatif alan, ayırt edici işaretler, materyal/değer okunuşu +puanlanır. **85'te dur**; iki kez plato yaparsa ya da 10 iterasyonu geçerse dur — +plato, temsili ya da referansı değiştirmek gerektiğinin kanıtıdır. + +`references/modeling-rules.md` 17 sert kural içeriyor. En pahalı olanlar: + +- Pahları algısal role göre bütçele — varsayılan **tek** faset; ikinciyi sadece + silueti taşıyan kütlelere ver. +- Halka içe doğru inset edildiğinde **sarım yönünün değiştiğini varsay**; + ilk üçgenin kenar çapraz çarpımını beklenen normalle karşılaştır. +- Pahları etkilenen yarı-boyutun ~%60'ının altında tut. +- Fiziksel özellikleri **dünya biriminde** boyutlandır — pah, dikiş, cıvata, + boşluk. Bunları host parçanın yüzdesi olarak ölçekleme. +- Uygulanan her katman için boşluk hesapla; bu metre ölçekli kitte en az + **0.015 birim** ve gerçek kameradan doğrula (z-fighting). + +--- + +## 4. Kendi asset pack'inizi üretmek + +**Bu klasörde bunu zaten yaptık.** `my-registry/` çalışan, doğrulanmış bir örnek. + +Bir registry, sonuçta **tek bir JSON dosyası**. Bağımlılık gerekmez. + +### Adımlar + +**1) Kaynağı yaz** — `my-registry/models//model.ts` + +Kanonik import'ları kullanın; kurulum sırasında yeniden yazılırlar: + +| Yazdığınız | Kurulunca olur | +| --- | --- | +| `@vibe3d/model.ts` | `@/lib/vibe3d/model.ts` | +| `@models/...` | `@/models/...` | + +Bu yüzden registry, tüketicinin klasör düzenini varsaymak zorunda kalmaz. + +**2) Manifest'i derle** — `my-registry/build.ts` + +Her dosya için `{ path, target, content, hash }`. `target` içinde `{models}` ve +`{vibe3d}` yer tutucuları tüketicinin `models.json`'ındaki `paths` ile değişir. +`defaultItem` zorunlu ve var olmalı. + +```bash +bun my-registry/build.ts +``` + +**3) Doğrula** — resmi conformance denetimi + +```bash +bunx vibe3d registry validate my-registry/dist/registry.json +# Conformant @medieval-kit · 2 items · 1 files · MIT +``` + +Şema, bağımlılık kapanışı, güvenli hedef yolları, çift yazım ve hash tazeliği +kontrol edilir. + +**4) Bağla ve kur** + +```jsonc +// models.json +"@medieval-kit": { "source": "file:my-registry/dist/registry.json", "version": "workspace" } +``` + +```bash +bunx vibe3d add @medieval-kit/wooden-barrel --dry-run # önce göster +bunx vibe3d add @medieval-kit/wooden-barrel +``` + +**5) Yayınla** — `package.json`'a `vibe3d.registry` alanını koyup npm'e gönderin: + +```json +{ + "name": "@medieval-kit/registry", + "keywords": ["vibe3d", "vibe3d-registry", "threejs"], + "vibe3d": { "registry": "./dist/registry.json" }, + "files": ["dist", "README.md", "LICENSE"] +} +``` + +Kullanıcılar `models.json`'a `"source": "npm:@medieval-kit/registry"` yazıp aynı +CLI ile kurar. **Kimseden izin almanıza gerek yok** — vibe3d deposuna dokunmadan +kendi registry'nizi yayınlayabilirsiniz. Mimari doküman bunu açık bir hedef olarak +yazıyor. + +### Boyut uyarısı + +`registry.json` tüm kaynağı gömülü tutar. `@scifi-kit/registry@0.0.1` → **1.8 MB +JSON**, 404 KB tarball. npm tek item için bile tarball'ın tamamını indirir. Mimari +doküman ilerisi için koleksiyon bazlı shard'lamayı öngörüyor +(`@scifi-kit/industrial`, `@scifi-kit/medical`…) — adres aynı kalır, fiziksel +paket değişir. + +--- + +## 5. Lowpoly medieval — evet, sorunsuz + +Bu bir varsayım değil; `@medieval-kit` çalışıyor ve doğrulandı. Dört item var: + +| Item | Tür | İçerik | +| --- | --- | --- | +| `@medieval-kit/core` | `vibe3d:lib` | deterministik rastgelelik, slot bazlı materyaller, geometri sözlüğü, parça yuvaları | +| `@medieval-kit/wooden-barrel` | `vibe3d:model` | 3 mesh, 806 üçgen, 0.82 × 1.05 × 0.81 m | +| `@medieval-kit/wooden-crate` | `vibe3d:model` | 3 mesh, 360 üçgen, 0.67 × 0.52 × 0.53 m | +| `@medieval-kit/iron-brazier` | `vibe3d:model` | 9 mesh, 423 üçgen, 0.53 × 0.90 × 0.53 m · **hareketli** | + +### core'un sözlüğü + +`geometry.ts` beş üreteç veriyor — hepsi indekssiz, hepsi vertex renkli: +`boxGeometry` (tahta, kiriş, kayış, ayak), `prismGeometry` (kesik koni: kâse, +alev dili; isteğe bağlı dikey renk geçişiyle), `staveGeometry` (fıçı tahtası), +`bandGeometry` (demir çember), `headGeometry` (kapak diski). Ayrıca +`flipGeometry` sarımı ters çevirir — içi görünen kaplar için gerekli: kâsenin +dış yüzeyi dışa, iç yüzeyi içe bakmalı, ikisi de aynı koniden üretiliyor. + +`materials.ts` slot bazlı: `createMedievalMaterials(scope, ['iron','ember'])` +yalnızca istenenleri üretir. Mangalın meşeye, fıçının emissive materyale +ihtiyacı yok; kullanılmayan materyal üretmek hem boşuna GPU kaynağı hem de +modelin `materialSlots` bildirimiyle çelişen bir yalan olurdu. + +`ember` yuvası bilinçli olarak **MeshBasicMaterial**. MeshStandardMaterial +burada yanlış araç olurdu: `emissive` tek bir Color'dır, vertex renklerinden +beslenmez — yani alevin dibinden ucuna renk geçişi yapılamazdı. + +Model, core'a `registryDependencies` ile bağlı ve build script'i bunu +**kaynaktan türetiyor** — `from '../core/'` içeren her import otomatik +bağımlılık oluyor, elle tutulan liste yok. `vibe3d add @medieval-kit/wooden-barrel` +core'u kendiliğinden getiriyor. + +### Fıçı nasıl kurulu + +Gerçek fıçı tek parça değildir, o yüzden model de tek parça değil: 13 ayrı +tahta (stave), uçlara doğru daralan bir profil (`taper`), gövdeye gömülü +kapaklar ve tahtaların kapak üstünde bıraktığı bilezik (chime), dört demir +çember (uçtakiler daha geniş — en çok zorlanan yer orası). + +İki teknik burada öğrenmeye değer: + +**Vertex renkleri.** 13 tahtanın 13 ayrı tonu var ama **tek materyal** +kullanılıyor. Renk varyasyonu materyalde değil geometride taşınıyor +(`vertexColors: true`), böylece hepsi tek çizim çağrısını paylaşıyor. Bu, +scifi-kit'in aşınma boru hattındaki fikrin küçük hâli: yüzey kimliğini vertex +attribute'una yaz, sonra birleştir. Ekranda ölçüldü: **61 farklı ahşap tonu**. + +**Deterministik rastgelelik.** `Math.random()` yok; `seed`'e bağlı bir +mulberry32. Aynı tohum her zaman aynı fıçıyı verir — yoksa ne önizleme, ne +test, ne sanat yönetimi tutar. `seed` yapılandırılabilir bir alan, yani aynı +modelden istediğiniz kadar farklı fıçı çıkarabilirsiniz. + +**Indekssiz geometri.** `computeVertexNormals()` indekssiz geometride her +üçgene kendi normalini verir — düz gölgeleme materyal bayrağı olmadan, +geometrinin doğal sonucu olarak gelir. Lowpoly'de istenen tam olarak bu. + +Neden hiçbir engel yok: + +- Şema stil hakkında hiçbir şey bilmiyor. Namespace, item adı, dosya, hash. O kadar. +- `capabilities: []` bildirebilirsiniz — `@scifi-kit` `["webgpu","tsl"]` istiyor, + sizinki istemiyor, ikisi aynı projede yan yana yaşıyor. +- `@scifi-kit/core`'a bağımlı **değilsiniz**. Fıçı sadece düz `three` ve + `init`in kurduğu evrensel sözleşmeleri kullanıyor. +- Mimari dokümanın "non-goals" bölümü bunu açıkça yazıyor: *"Requiring all + registries to use the sci-fi kit's material library, visual language, geometry + helpers, or authoring pipeline."* + +Bu desen `@scifi-kit`'in `axiom-cargo-kit` item'ıyla aynı: 50 model tek bir +destek item'ını paylaşıyor, böylece tek tek kurulan bir sandık bile yanındaki +konteynerle aynı katalogdan gelmiş gibi duruyor. Kite yeni model eklerken +kural basit: **ortak olan her şey `core`'a, sadece o modele ait olan model +dosyasına.** + +### anchor / content ayrımı — protokolün en kolay kaçırılan yeri + +`PartHandle` iki ayrı nesne bildirir ve ikisi **aynı olamaz**: + +- `anchor` — modelin ömrü boyunca aynı nesne. Tüketici ışığını, etiketini, + çarpışma gövdesini buraya takar. +- `content` — `configure()` her çağrıldığında atılıp yeniden kurulan geometri. + +İkisini aynı Group yapıp rebuild'de `clear()` çağırmak tüketicinin taktığı her +şeyi de sessizce siler. Model çalışmaya devam eder, ama protokolün asıl vaadi +bozulmuştur — ve bunu fark etmek zordur. + +İlk üç modeli de bu hatayla yazdım; `scripts/verify-model.ts` yakaladı. Doğru +yapı artık `core/parts.ts` içinde `createPart()` olarak duruyor, yani sonraki +modeller aynı hataya düşemez. Mangalın ateş ışığı da bu sayede `anchor`'da +yaşıyor ve `configure()` ateşi söndürmüyor. + +### Statik ve hareketli modeller + +Fıçı ve sandık statik. Mangal protokolün onların hiç dokunmadığı iki parçasını +kullanıyor: + +- **tipli `actions`** — `setLit(boolean)` / `isLit()` +- **`update(dt)`** — alev titremesi ve ışık dalgalanması + +Ayrım önemli ve mimari dokümanda yazılı: `configure()` topolojiyi yeniden kurar +ve **pahalıdır**, kullanıcı ayarı içindir. Kare başına değişen her şey +`update()` içinde olmalı. + +Alev titremesi iki farklı frekansın toplamı; tek sinüs fazla düzenli okunuyor, +ateş öyle yanmaz. `update()` ayrıca adımı 0.05 s ile sınırlıyor ki sekme arka +plandan dönünce alev fırlamasın. + +### Z-fighting: hizalı yüz yapma, kasıtlı içiçe geç + +İki yüzey aynı düzlemde, aynı yöne bakıyor ve alanları örtüşüyorsa hangisinin +önde olduğu derinlik tamponunun kayan nokta hassasiyetine kalır. Kamera +oynadıkça kazanan değişir ve yüzey titrer. + +Sandığın ilk hâli tam bu hataya düşmüştü: dikmeler, yan tahtalar ve kapak +tahtalarının hepsi dış yüzeyini `±width/2` düzlemine koyuyordu — **96 çakışan +yüz.** (Fıçı ve mangalda 0'dı, çünkü onlar dönel ve yüzeyleri doğal olarak +farklı yarıçaplarda.) + +Çözüm bir "epsilon kaydırma" değil, gerçek marangozluk: + +- **Dikmeler tahtalardan dışarı taşıyor** (`postProud`) — yan tahtalar + dikmelerin arkasına çekili, dış yüzleri farklı düzlemde. +- **Kapak ve taban çerçeveden sarkıyor** (`overhang`) — yan yüzleri dikmelerin + yüzleriyle hizalanmıyor. +- **Dikmeler kapak ve tabanın içine giriyor**, uçları katı parçanın içinde + kaldığı için görünmüyor ve hiçbir düzlemle hizalanmıyor. +- **Tahtalar birbirine küt ekleniyor** (butt joint) — değiyorlar ama + örtüşmüyorlar. Kenar teması z-fighting üretmez. +- **Ön/arka kayışlar köşede dışa taşıyor, yan kayışlar onlara varmadan + bitiyor** — dört parçanın üst yüzü köşede üst üste binmiyor. + +`scripts/zfight.ts` bunu ölçüyor ve `verify-model.ts` her modelde, sandıkta ise +birkaç farklı yapılandırmada birden çağırıyor. Ölçüt bounding box değil gerçek +alan örtüşmesi: bir üçgenin ağırlık merkezi diğerinin içinde mi. Böylece +bitişik tahtalar yanlış alarm vermiyor. + +### Sarım denetimi + +Elle yazılan geometride en sinsi hata ters sarım: yüz içten görünür hâle gelir +ve bu ancak belirli bir kamera açısında fark edilir. `scripts/verify-model.ts` +bunu iki ayrı ölçütle denetliyor, çünkü iki ayrı geometri türü var: + +**Dönel gövdeler** (fıçı, mangal kâsesi) için radyal hizalama — dış kabuktaki +her **radyal** yüzün normali eksenden dışa bakmalı. + +**Kapalı katılar** (sandık: tamamen kutulardan kurulu) için işaretli hacim. +Kapalı bir yüzeyin hacmi Σ a·(b×c)/6 ile bulunur; sarım dışa bakıyorsa pozitif, +içe bakıyorsa negatif çıkar. Sandıkta bu ölçüt radyal testten daha keskin, +çünkü kutunun "radyal" yönü diye bir şey yok. + +Önemli incelik: tahtaların yan (boşluk) yüzeyleri teğetseldir, yani bu çarpım +onlar için tanımı gereği ~0'dır ve işareti sadece kayan nokta gürültüsüdür. +Radyal bir test onları yargılayamaz, o yüzden ayıklanıyor ve **kaç tane +ayıklandığı raporlanıyor** — sessizce elenmiyorlar. + +Test mutasyonla doğrulandı: dış yüz dörtgeninin sarımı kasten ters çevrildiğinde +104 radyal yüzün 52'si yakalandı; geri alınınca sıfır. + +--- + +## 6. Katkı + +Depo MIT ve Bun workspace'i. `apps/*`, `packages/*`, `registries/*`. + +```bash +git clone https://github.com/vibe-stack/vibe3d +cd vibe3d && bun install +bun run dev # docs kataloğu — her modelin canlı önizlemesi +``` + +Sürümleme **Changesets** ile: + +```bash +bun run changeset # değişiklik niyetini yaz +bun run build && bun run typecheck && bun test # release:check ile aynı +``` + +Release workflow bir version PR'ı tutuyor ve merge sonrası paketleri bağımlılık +sırasına göre yayınlıyor. + +### Katkı yolları, en kolaydan zora + +1. **Kendi registry'nizi yayınlayın.** Depoya dokunmaz, izin gerekmez, ekosistemi + büyütür. `@scifi-kit` sadece *referans* registry. +2. **`@scifi-kit`'e model ekleyin.** `assets/prototypes//model.ts` + ekleyin — `registries/scifi-kit/src/build.ts` `model.ts` içeren her klasörü + **otomatik keşfeder**, kayıt listesi yok. `vibe-model` döngüsünü izleyin, + `docs/templates/asset-spec-template.md` sözleşmesini doldurun. +3. **Protokol boşluklarını kapatın.** Mimari dokümanda yazılı ama henüz + olmayanlar, doğrudan katkıya açık: + - `github:` sağlayıcısı (`source.ts` bugün açıkça "planned but not available + yet" fırlatıyor); + - `vibe3d registry init` / `build` / `test` komutları (mimaride var, CLI'da + sadece `validate` mevcut); + - üç yollu birleştirmesiz güvenli `update` çakışma akışı; + - runtime conformance (mevcut `checkRegistry` statik; "temiz fixture'a kur, + TypeScript derle, geçerli model örneği doğrula" adımları henüz yok). + +Not: mimari dokümanın başlığı hâlâ *"Status: proposed architecture; not yet +implemented"* diyor ama çekirdek büyük ölçüde gerçek. Bu boşluk da bir katkı +fırsatı. + +### Şu anki durum + +npm'de yayınlanan `@scifi-kit/registry@0.0.1`: **110 model** (Industrial 76, +Architecture 12, Streets 9, Military 7, Medical 6) + 2 lib + 1 kit. GitHub `main` +daha ileride — `assets/prototypes/` altında ~180 klasör var (kargo/lojistik +dalgası henüz yayınlanmamış). Tüm paketler `0.0.1`, 2026-08-11'de yayınlanmış; +proje çok erken aşamada, yani katkı için zamanlama iyi. + +--- + +## 7. Komut özeti + +```bash +# tüketici +bunx vibe3d init +bunx vibe3d list [sorgu] # katalog, alias: search +bunx vibe3d view @scifi-kit/modular-wall # kurmadan incele +bunx vibe3d add @scifi-kit/modular-wall [--dry-run] [--overwrite] +bunx vibe3d add @scifi-kit # defaultItem = tüm kit +bunx vibe3d diff # yerel değişikliklerim ne +bunx vibe3d update @scifi-kit/modular-wall +bunx vibe3d remove @scifi-kit/modular-wall [--force] +bunx vibe3d doctor + +# registry yazarı +bunx vibe3d registry validate ./dist/registry.json + +# yazarlık skill'leri +bunx vibe-model [--global] [doctor] [--force] +bunx vibe-terrain +``` diff --git a/bun.lock b/bun.lock new file mode 100644 index 0000000..0e1a7c6 --- /dev/null +++ b/bun.lock @@ -0,0 +1,361 @@ +{ + "lockfileVersion": 1, + "configVersion": 1, + "workspaces": { + "": { + "name": "vibe3d-playground", + "dependencies": { + "three": "^0.185.1", + }, + "devDependencies": { + "@types/node": "^22.15.3", + "@types/three": "^0.185.4", + "@webgpu/types": "^0.1.72", + "typescript": "^5.9.2", + "vibe3d": "^0.0.1", + "vite": "^7.1.5", + }, + }, + }, + "packages": { + "@dimforge/rapier3d-compat": ["@dimforge/rapier3d-compat@0.12.0", "", {}, "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow=="], + + "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="], + + "@esbuild/android-arm": ["@esbuild/android-arm@0.28.2", "", { "os": "android", "cpu": "arm" }, "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg=="], + + "@esbuild/android-arm64": ["@esbuild/android-arm64@0.28.2", "", { "os": "android", "cpu": "arm64" }, "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A=="], + + "@esbuild/android-x64": ["@esbuild/android-x64@0.28.2", "", { "os": "android", "cpu": "x64" }, "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q=="], + + "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.28.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw=="], + + "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.28.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw=="], + + "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.28.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw=="], + + "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.28.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg=="], + + "@esbuild/linux-arm": ["@esbuild/linux-arm@0.28.2", "", { "os": "linux", "cpu": "arm" }, "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w=="], + + "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.28.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug=="], + + "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.28.2", "", { "os": "linux", "cpu": "ia32" }, "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ=="], + + "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ=="], + + "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA=="], + + "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.28.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ=="], + + "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA=="], + + "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.28.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg=="], + + "@esbuild/linux-x64": ["@esbuild/linux-x64@0.28.2", "", { "os": "linux", "cpu": "x64" }, "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ=="], + + "@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw=="], + + "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.28.2", "", { "os": "none", "cpu": "x64" }, "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw=="], + + "@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.28.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ=="], + + "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.28.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw=="], + + "@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q=="], + + "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.28.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g=="], + + "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.28.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ=="], + + "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.28.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA=="], + + "@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.2", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="], + + "@gar/promise-retry": ["@gar/promise-retry@1.0.3", "", {}, "sha512-GmzA9ckNokPypTg10pgpeHNQe7ph+iIKKmhKu3Ob9ANkswreCx7R3cKmY781K8QK3AqVL3xVh9A42JvIAbkkSA=="], + + "@isaacs/fs-minipass": ["@isaacs/fs-minipass@4.0.1", "", { "dependencies": { "minipass": "^7.0.4" } }, "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w=="], + + "@napi-rs/lzma-linux-x64-gnu": ["@napi-rs/lzma-linux-x64-gnu@1.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ=="], + + "@npmcli/agent": ["@npmcli/agent@4.0.2", "", { "dependencies": { "agent-base": "^7.1.0", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.1", "lru-cache": "^11.2.1", "socks-proxy-agent": "^8.0.3" } }, "sha512-EUEuWAxnL07Sp5/iC/1X6Xj+XThUvnbei9zfRWZdEXa7lss9RTHMhAHBeg+MZ5To9s/gGaSI+UwZTPdYMvKSeg=="], + + "@npmcli/fs": ["@npmcli/fs@5.0.0", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-7OsC1gNORBEawOa5+j2pXN9vsicaIOH5cPXxoR6fJOmH6/EXpJB2CajXOu1fPRFun2m1lktEFX11+P89hqO/og=="], + + "@npmcli/git": ["@npmcli/git@7.0.2", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@npmcli/promise-spawn": "^9.0.0", "ini": "^6.0.0", "lru-cache": "^11.2.1", "npm-pick-manifest": "^11.0.1", "proc-log": "^6.0.0", "semver": "^7.3.5", "which": "^6.0.0" } }, "sha512-oeolHDjExNAJAnlYP2qzNjMX/Xi9bmu78C9dIGr4xjobrSKbuMYCph8lTzn4vnW3NjIqVmw/f8BCfouqyJXlRg=="], + + "@npmcli/installed-package-contents": ["@npmcli/installed-package-contents@4.0.0", "", { "dependencies": { "npm-bundled": "^5.0.0", "npm-normalize-package-bin": "^5.0.0" }, "bin": { "installed-package-contents": "bin/index.js" } }, "sha512-yNyAdkBxB72gtZ4GrwXCM0ZUedo9nIbOMKfGjt6Cu6DXf0p8y1PViZAKDC8q8kv/fufx0WTjRBdSlyrvnP7hmA=="], + + "@npmcli/node-gyp": ["@npmcli/node-gyp@5.0.0", "", {}, "sha512-uuG5HZFXLfyFKqg8QypsmgLQW7smiRjVc45bqD/ofZZcR/uxEjgQU8qDPv0s9TEeMUiAAU/GC5bR6++UdTirIQ=="], + + "@npmcli/package-json": ["@npmcli/package-json@7.0.5", "", { "dependencies": { "@npmcli/git": "^7.0.0", "glob": "^13.0.0", "hosted-git-info": "^9.0.0", "json-parse-even-better-errors": "^5.0.0", "proc-log": "^6.0.0", "semver": "^7.5.3", "spdx-expression-parse": "^4.0.0" } }, "sha512-iVuTlG3ORq2iaVa1IWUxAO/jIp77tUKBhoMjuzYW2kL4MLN1bi/ofqkZ7D7OOwh8coAx1/S2ge0rMdGv8sLSOQ=="], + + "@npmcli/promise-spawn": ["@npmcli/promise-spawn@9.0.1", "", { "dependencies": { "which": "^6.0.0" } }, "sha512-OLUaoqBuyxeTqUvjA3FZFiXUfYC1alp3Sa99gW3EUDz3tZ3CbXDdcZ7qWKBzicrJleIgucoWamWH1saAmH/l2Q=="], + + "@npmcli/redact": ["@npmcli/redact@4.0.0", "", {}, "sha512-gOBg5YHMfZy+TfHArfVogwgfBeQnKbbGo3pSUyK/gSI0AVu+pEiDVcKlQb0D8Mg1LNRZILZ6XG8I5dJ4KuAd9Q=="], + + "@npmcli/run-script": ["@npmcli/run-script@10.0.4", "", { "dependencies": { "@npmcli/node-gyp": "^5.0.0", "@npmcli/package-json": "^7.0.0", "@npmcli/promise-spawn": "^9.0.0", "node-gyp": "^12.1.0", "proc-log": "^6.0.0" } }, "sha512-mGUWr1uMnf0le2TwfOZY4SFxZGXGfm4Jtay/nwAa2FLNAKXUoUwaGwBMNH36UHPtinWfTSJ3nqFQr0091CxVGg=="], + + "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.62.5", "", { "os": "android", "cpu": "arm" }, "sha512-jfkGfTwhQpsiSckPF8r9bU3pn3vyd72NlWaO+TgEO6WPSDnUhXzrNYCHBMOYj0ACaUgjm6eERLF+XV9a6RstoA=="], + + "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.62.5", "", { "os": "android", "cpu": "arm64" }, "sha512-oGVqyQlxnrz9/ty89oHpU857VUHEl5/Xu4R2lS+aivCTrNnSsbiENzTnNaBsjxH0CNWGPhzHArOLFwo+oKXveA=="], + + "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.62.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-bW7B8xMEq8n99Q3ieEcPRGuphurdZAaFzQc9Efyyw3FL6DZO6pMy9xhdN+kBoD7Sy05xNXSr4OyPPnpkYriS/A=="], + + "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.62.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-YSwBS86QeHOGlrxJ1PSOIZSkzRL/JmKeunhc+lV6M1a6En8QuVCD/T/qIA0J4Gd2Y86RIOBYrLcOUtqGh9+/1w=="], + + "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.62.5", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-2fST8lILgl7cKbme/1KDdPCmbXbG+gqoV3bHp19L0ypX/3akYMBVdOunPleRCwonoLnXOZ/0F+Mt/v8POFmfcQ=="], + + "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.62.5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-cpIxQCP9J+EVad0a6LO1kY3ZGODlk80VlI+2I96B8xMcdHZ4pLVhfQ49JFpYqjPF91FFkQWftf57YlDcTiw9yQ=="], + + "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.62.5", "", { "os": "linux", "cpu": "arm" }, "sha512-r9fGh3eFs3e/udWh5ZjXQtxiYK/xoFxQaYR/cELxac/Udkl5Th+IsFm0CX3Kl9hmUH/we7EoMpjJgeQNnE0+IA=="], + + "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.62.5", "", { "os": "linux", "cpu": "arm" }, "sha512-xdvFdp7OM6KLJviJT2g/YuRSUjnZgGHk4RNgwIbN7X6cPugOucV60DdHXWzsBVCUdrGb6qSXnJQrrAKMmQuj3Q=="], + + "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.62.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-rRqILAndyzHzP7T9NFQrq+4HFWNhqkqkKur7eiBpfLmz01PO0JKx5Vchu3YllE4YXI/Ftgq/szrDWg5GJ0mI8g=="], + + "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.62.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-Gf4X3qVMucayUvux6aXXPgXovocSFUC0rrffDuPI/S2nHhNMhjcZxsrAFYCOF350PRreW1XwzFj3CT/3bKsWCw=="], + + "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.62.5", "", { "os": "linux", "cpu": "none" }, "sha512-+s5qA0TNM0qm8PK/a5gt/1Hpx+NV08uSuCncvhziIlQzT6AEV2fnUQo7eBtFTFO0nA9scauvoR2HusfXmQnO4w=="], + + "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.62.5", "", { "os": "linux", "cpu": "none" }, "sha512-ybb6QvWwWJCbBWqERpc8K3pYVGIrXlG8MEQ8IIuJY6Y9KdHQxoFoNyfkAOtKn1VHu3KuLidXvwrvGR1mEjeWCw=="], + + "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.62.5", "", { "os": "linux", "cpu": "ppc64" }, "sha512-nZb1DtnOyhCmYvsC8A2CwOkopVg+IS1+fPUa7rMOAXtNw5+lLCLLPqd6XAiNrGtoQKsbvIBOwsHnBH/3wnb4HQ=="], + + "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.62.5", "", { "os": "linux", "cpu": "ppc64" }, "sha512-yMbj63Sp89ryrXLWyz+sy+fYD2HpOnMCLGbe4Oa1smclFSUukdtD/BgdiHaAetJNb74URD8U4hM+qG5KVzMEkg=="], + + "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.62.5", "", { "os": "linux", "cpu": "none" }, "sha512-mhoan3OJw2kYV/e1jtIdmvUZgyBFeA6zGWsOswmR0Tg19TQbowZuR+JMLID6spbbBN7Zee2ejrgmy3+FxGrIdA=="], + + "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.62.5", "", { "os": "linux", "cpu": "none" }, "sha512-5ZTLmjWbb1VZdjuyhe83K/8QO0/h11midQCBP+X5OYn32ra7eOBoM0ZqtaY4nkgNsYgmdVhMYPoyVPTjUpHf3w=="], + + "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.62.5", "", { "os": "linux", "cpu": "s390x" }, "sha512-m53kG+br6PGxOTmgBEM2DHSDs9RVjsyEbUwjJPJGTFm1grWOG8EKJggDCTb60unD4Tjby8fi7/m9XfkEWasVWg=="], + + "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.62.5", "", { "os": "linux", "cpu": "x64" }, "sha512-6RHPJR1g/uvdYU8uXBnfq3nlqyZCP82Fr6NHgfGoaIeSh0YEqnX/x6uA9MmJJbnSH7swqX4F+CkGdUF+6doiQA=="], + + "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.62.5", "", { "os": "linux", "cpu": "x64" }, "sha512-xs+OXQtEXgpXT0DmA5+U3qnRZHdCST/5HRQxS8wSPZTUZN/EMWeHuSIod32LQklTBZBV9DyfncKBQ8n5V3eFdw=="], + + "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.62.5", "", { "os": "openbsd", "cpu": "x64" }, "sha512-e7hD+sl3s+mcLQDZ8pbudBVsdG6r5yN4w3LqG2TJ8sQHDpblWj5lrJs/3m01Cvlxbt4x13zu5thLjgypgtkYzw=="], + + "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.62.5", "", { "os": "none", "cpu": "arm64" }, "sha512-GiyJaCf+WpMub/17aPcKk27QMl5W6f+KhdPTjlFOn5akH5Wa/DCM9Stdx5cDfmasyKB08MqpVQ1uJE2RkkpbXg=="], + + "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.62.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-+OQ8U2DdoEfXl8T4Fb18AjmEwbXMerKDKCL8yCPAYhKCEEKoul7rkbeGCBFCbAlaGaa7pmtRTpkAJM2LE/i5FA=="], + + "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.62.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-KanvAZrPKbDBFwrgiU9yEVpQoox9QPV1WZOXX7HudJQY+eSlu82CtWxDU8WtuRRvtN5EGkLczkd6Y6DTcvm9wA=="], + + "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.62.5", "", { "os": "win32", "cpu": "x64" }, "sha512-1aC3UEWTtRl3RK3VpDJ/Tqk1XI4SLTmXIthAq6wRWo8XiSXJNd+VprJM4/1P4+i6HIaFEFlVi9sTTziniD2tOQ=="], + + "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.62.5", "", { "os": "win32", "cpu": "x64" }, "sha512-/gDJaRs4gl0NPIwqCz+6PkpmhhjRAD2j6P4rSNHBzUkO3naEx2mIU0pRle1vUNRQ7mE/+8OOeXLTv/J56FKiQg=="], + + "@sigstore/bundle": ["@sigstore/bundle@4.0.0", "", { "dependencies": { "@sigstore/protobuf-specs": "^0.5.0" } }, "sha512-NwCl5Y0V6Di0NexvkTqdoVfmjTaQwoLM236r89KEojGmq/jMls8S+zb7yOwAPdXvbwfKDlP+lmXgAL4vKSQT+A=="], + + "@sigstore/core": ["@sigstore/core@3.2.1", "", {}, "sha512-qRsxPnCrbC/puegGxKuynfnxgLiHqWStrSjxkoB4YKqq3Z3s4cyZyj42ZdWFAEblNP65C+rBH8EuREHIXoi83g=="], + + "@sigstore/protobuf-specs": ["@sigstore/protobuf-specs@0.5.1", "", {}, "sha512-/ScWUhhoFasJsSRGTVBwId1loQjjnjAfE4djL6ZhrXRpNCmPTnUKF5Jokd58ILseOMjzET3UrMOtJPS9sYeI0g=="], + + "@sigstore/sign": ["@sigstore/sign@4.1.1", "", { "dependencies": { "@gar/promise-retry": "^1.0.2", "@sigstore/bundle": "^4.0.0", "@sigstore/core": "^3.2.0", "@sigstore/protobuf-specs": "^0.5.0", "make-fetch-happen": "^15.0.4", "proc-log": "^6.1.0" } }, "sha512-Hf4xglukg0XXQ2RiD5vSoLjdPe8OBUPA8XeVjUObheuDcWdYWrnH/BNmxZCzkAy68MzmNCxXLeurJvs6hcP2OQ=="], + + "@sigstore/tuf": ["@sigstore/tuf@4.0.2", "", { "dependencies": { "@sigstore/protobuf-specs": "^0.5.0", "tuf-js": "^4.1.0" } }, "sha512-TCAzTy0xzdP79EnxSjq9KQ3eaR7+FmudLC6eRKknVKZbV7ZNlGLClAAQb/HMNJ5n2OBNk2GT1tEmU0xuPr+SLQ=="], + + "@sigstore/verify": ["@sigstore/verify@3.1.1", "", { "dependencies": { "@sigstore/bundle": "^4.0.0", "@sigstore/core": "^3.2.1", "@sigstore/protobuf-specs": "^0.5.0" } }, "sha512-qv7+G3J2cc6wwFj3yKvXOamzqhMwSk1ogPGmhpS8iXllcPrJaIIBA+4HbttlHVu1pqWTdmaCH/WE7UOC51kdoA=="], + + "@tufjs/canonical-json": ["@tufjs/canonical-json@2.0.0", "", {}, "sha512-yVtV8zsdo8qFHe+/3kw81dSLyF7D576A5cCFCi4X7B39tWT7SekaEFUnvnWJHz+9qO7qJTah1JbrDjWKqFtdWA=="], + + "@tufjs/models": ["@tufjs/models@4.1.0", "", { "dependencies": { "@tufjs/canonical-json": "2.0.0", "minimatch": "^10.1.1" } }, "sha512-Y8cK9aggNRsqJVaKUlEYs4s7CvQ1b1ta2DVPyAimb0I2qhzjNk+A+mxvll/klL0RlfuIUei8BF7YWiua4kQqww=="], + + "@tweenjs/tween.js": ["@tweenjs/tween.js@23.1.3", "", {}, "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA=="], + + "@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + + "@types/node": ["@types/node@22.20.1", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q=="], + + "@types/stats.js": ["@types/stats.js@0.17.4", "", {}, "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA=="], + + "@types/three": ["@types/three@0.185.4", "", { "dependencies": { "@dimforge/rapier3d-compat": "~0.12.0", "@tweenjs/tween.js": "~23.1.3", "@types/stats.js": "*", "@types/webxr": ">=0.5.17", "fflate": "~0.8.2", "meshoptimizer": "~1.1.1" } }, "sha512-gAsBIC07NIFrxjbf7tH2t71c38uulFfk/RFoC7FNBSjMRAQ8J1x/RBvusX0N5PJouaYFJawXQqfCQ0RKUx/1nA=="], + + "@types/webxr": ["@types/webxr@0.5.24", "", {}, "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg=="], + + "@vibe3djs/conformance": ["@vibe3djs/conformance@0.0.1", "", { "dependencies": { "@vibe3djs/registry": "^0.0.1", "@vibe3djs/schema": "^0.0.1" } }, "sha512-2edpScRmY7K1Gd7WV/JHHFKtHCg0G9xDbdvNzXKlmLxjduUWR5DZ617qhVNVd+22p8+XWU78leC7lHAA8lUE7w=="], + + "@vibe3djs/registry": ["@vibe3djs/registry@0.0.1", "", { "dependencies": { "@vibe3djs/schema": "^0.0.1", "pacote": "^21.0.0" } }, "sha512-eYMfkR4/9aKpV8s54nubVKJGiYjQa8Gwswj2mbclyOyXoGIF/9FGBm9L9oM1AW01Dmng1NRBSrfqiBfCA/C9FA=="], + + "@vibe3djs/schema": ["@vibe3djs/schema@0.0.1", "", { "dependencies": { "zod": "^4.0.0" } }, "sha512-+uD3K7OxMpkYm/VKHdvauOX8irWi9FQ99OOKu7Pg0eMlTwg8Etd4X9HgieTtsweQl//q9RPg9mofUrNczrkoSw=="], + + "@webgpu/types": ["@webgpu/types@0.1.72", "", {}, "sha512-0cF7RFM2edNoiIS1ODJp0/Gzv4/xSXhwoR0YCza+OWpJWtn4wmo9DvK91aLlH9+uUnwIriP7ZiC3WitmyhuzBw=="], + + "abbrev": ["abbrev@4.0.0", "", {}, "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA=="], + + "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], + + "balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], + + "brace-expansion": ["brace-expansion@5.0.9", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg=="], + + "cacache": ["cacache@20.0.4", "", { "dependencies": { "@npmcli/fs": "^5.0.0", "fs-minipass": "^3.0.0", "glob": "^13.0.0", "lru-cache": "^11.1.0", "minipass": "^7.0.3", "minipass-collect": "^2.0.1", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "p-map": "^7.0.2", "ssri": "^13.0.0" } }, "sha512-M3Lab8NPYlZU2exsL3bMVvMrMqgwCnMWfdZbK28bn3pK6APT/Te/I8hjRPNu1uwORY9a1eEQoifXbKPQMfMTOA=="], + + "chownr": ["chownr@3.0.0", "", {}, "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g=="], + + "commander": ["commander@14.0.3", "", {}, "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw=="], + + "content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "env-paths": ["env-paths@2.2.1", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="], + + "esbuild": ["esbuild@0.28.2", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="], + + "exponential-backoff": ["exponential-backoff@3.1.3", "", {}, "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA=="], + + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], + + "fflate": ["fflate@0.8.3", "", {}, "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="], + + "fs-minipass": ["fs-minipass@3.0.3", "", { "dependencies": { "minipass": "^7.0.3" } }, "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw=="], + + "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + + "glob": ["glob@13.0.6", "", { "dependencies": { "minimatch": "^10.2.2", "minipass": "^7.1.3", "path-scurry": "^2.0.2" } }, "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw=="], + + "graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="], + + "hosted-git-info": ["hosted-git-info@9.0.3", "", { "dependencies": { "lru-cache": "^11.1.0" } }, "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg=="], + + "http-cache-semantics": ["http-cache-semantics@4.2.0", "", {}, "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ=="], + + "http-proxy-agent": ["http-proxy-agent@7.0.2", "", { "dependencies": { "agent-base": "^7.1.0", "debug": "^4.3.4" } }, "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig=="], + + "https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], + + "iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="], + + "ignore-walk": ["ignore-walk@8.0.0", "", { "dependencies": { "minimatch": "^10.0.3" } }, "sha512-FCeMZT4NiRQGh+YkeKMtWrOmBgWjHjMJ26WQWrRQyoyzqevdaGSakUaJW5xQYmjLlUVk2qUnCjYVBax9EKKg8A=="], + + "ini": ["ini@6.0.0", "", {}, "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ=="], + + "ip-address": ["ip-address@10.5.0", "", {}, "sha512-R5SnVLJmgYYvf2F2ZgwSBnelz5G4q5AxIC277GDfUaNbrZKNANcBC7RHqYYePlszf4kBolVkJauG0ZjHHFh55g=="], + + "isexe": ["isexe@4.0.0", "", {}, "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw=="], + + "json-parse-even-better-errors": ["json-parse-even-better-errors@5.0.0", "", {}, "sha512-ZF1nxZ28VhQouRWhUcVlUIN3qwSgPuswK05s/HIaoetAoE/9tngVmCHjSxmSQPav1nd+lPtTL0YZ/2AFdR/iYQ=="], + + "jsonparse": ["jsonparse@1.3.1", "", {}, "sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg=="], + + "lru-cache": ["lru-cache@11.5.2", "", {}, "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g=="], + + "make-fetch-happen": ["make-fetch-happen@15.0.6", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@npmcli/agent": "^4.0.0", "@npmcli/redact": "^4.0.0", "cacache": "^20.0.1", "http-cache-semantics": "^4.1.1", "minipass": "^7.0.2", "minipass-fetch": "^5.0.0", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "negotiator": "^1.0.0", "proc-log": "^6.0.0", "ssri": "^13.0.0" } }, "sha512-Je0fLJ0F5atA7F+eIlLzk+Wkcl57JDf4kf+EW8xiP5E31xOQxkIxTbgf1Oi1Lw9tRI9UEMRdI5Vz2xTzoNU1Jw=="], + + "meshoptimizer": ["meshoptimizer@1.1.1", "", {}, "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g=="], + + "minimatch": ["minimatch@10.2.6", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="], + + "minipass": ["minipass@7.1.3", "", {}, "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A=="], + + "minipass-collect": ["minipass-collect@2.0.1", "", { "dependencies": { "minipass": "^7.0.3" } }, "sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw=="], + + "minipass-fetch": ["minipass-fetch@5.0.2", "", { "dependencies": { "minipass": "^7.0.3", "minipass-sized": "^2.0.0", "minizlib": "^3.0.1" }, "optionalDependencies": { "iconv-lite": "^0.7.2" } }, "sha512-2d0q2a8eCi2IRg/IGubCNRJoYbA1+YPXAzQVRFmB45gdGZafyivnZ5YSEfo3JikbjGxOdntGFvBQGqaSMXlAFQ=="], + + "minipass-flush": ["minipass-flush@1.0.7", "", { "dependencies": { "minipass": "^3.0.0" } }, "sha512-TbqTz9cUwWyHS2Dy89P3ocAGUGxKjjLuR9z8w4WUTGAVgEj17/4nhgo2Du56i0Fm3Pm30g4iA8Lcqctc76jCzA=="], + + "minipass-pipeline": ["minipass-pipeline@1.2.4", "", { "dependencies": { "minipass": "^3.0.0" } }, "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A=="], + + "minipass-sized": ["minipass-sized@2.0.0", "", { "dependencies": { "minipass": "^7.1.2" } }, "sha512-zSsHhto5BcUVM2m1LurnXY6M//cGhVaegT71OfOXoprxT6o780GZd792ea6FfrQkuU4usHZIUczAQMRUE2plzA=="], + + "minizlib": ["minizlib@3.1.0", "", { "dependencies": { "minipass": "^7.1.2" } }, "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "nanoid": ["nanoid@3.3.18", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w=="], + + "negotiator": ["negotiator@1.1.0", "", { "dependencies": { "content-type": "^2.1.0" } }, "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg=="], + + "node-gyp": ["node-gyp@12.4.0", "", { "dependencies": { "env-paths": "^2.2.0", "exponential-backoff": "^3.1.1", "graceful-fs": "^4.2.6", "nopt": "^9.0.0", "proc-log": "^6.0.0", "semver": "^7.3.5", "tar": "^7.5.4", "tinyglobby": "^0.2.12", "undici": "^6.25.0", "which": "^6.0.0" }, "bin": { "node-gyp": "bin/node-gyp.js" } }, "sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw=="], + + "nopt": ["nopt@9.0.0", "", { "dependencies": { "abbrev": "^4.0.0" }, "bin": { "nopt": "bin/nopt.js" } }, "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw=="], + + "npm-bundled": ["npm-bundled@5.0.0", "", { "dependencies": { "npm-normalize-package-bin": "^5.0.0" } }, "sha512-JLSpbzh6UUXIEoqPsYBvVNVmyrjVZ1fzEFbqxKkTJQkWBO3xFzFT+KDnSKQWwOQNbuWRwt5LSD6HOTLGIWzfrw=="], + + "npm-install-checks": ["npm-install-checks@8.0.0", "", { "dependencies": { "semver": "^7.1.1" } }, "sha512-ScAUdMpyzkbpxoNekQ3tNRdFI8SJ86wgKZSQZdUxT+bj0wVFpsEMWnkXP0twVe1gJyNF5apBWDJhhIbgrIViRA=="], + + "npm-normalize-package-bin": ["npm-normalize-package-bin@5.0.0", "", {}, "sha512-CJi3OS4JLsNMmr2u07OJlhcrPxCeOeP/4xq67aWNai6TNWWbTrlNDgl8NcFKVlcBKp18GPj+EzbNIgrBfZhsag=="], + + "npm-package-arg": ["npm-package-arg@13.0.2", "", { "dependencies": { "hosted-git-info": "^9.0.0", "proc-log": "^6.0.0", "semver": "^7.3.5", "validate-npm-package-name": "^7.0.0" } }, "sha512-IciCE3SY3uE84Ld8WZU23gAPPV9rIYod4F+rc+vJ7h7cwAJt9Vk6TVsK60ry7Uj3SRS3bqRRIGuTp9YVlk6WNA=="], + + "npm-packlist": ["npm-packlist@10.0.4", "", { "dependencies": { "ignore-walk": "^8.0.0", "proc-log": "^6.0.0" } }, "sha512-uMW73iajD8hiH4ZBxEV3HC+eTnppIqwakjOYuvgddnalIw2lJguKviK1pcUJDlIWm1wSJkchpDZDSVVsZEYRng=="], + + "npm-pick-manifest": ["npm-pick-manifest@11.0.3", "", { "dependencies": { "npm-install-checks": "^8.0.0", "npm-normalize-package-bin": "^5.0.0", "npm-package-arg": "^13.0.0", "semver": "^7.3.5" } }, "sha512-buzyCfeoGY/PxKqmBqn1IUJrZnUi1VVJTdSSRPGI60tJdUhUoSQFhs0zycJokDdOznQentgrpf8LayEHyyYlqQ=="], + + "npm-registry-fetch": ["npm-registry-fetch@19.1.1", "", { "dependencies": { "@npmcli/redact": "^4.0.0", "jsonparse": "^1.3.1", "make-fetch-happen": "^15.0.0", "minipass": "^7.0.2", "minipass-fetch": "^5.0.0", "minizlib": "^3.0.1", "npm-package-arg": "^13.0.0", "proc-log": "^6.0.0" } }, "sha512-TakBap6OM1w0H73VZVDf44iFXsOS3h+L4wVMXmbWOQroZgFhMch0juN6XSzBNlD965yIKvWg2dfu7NSiaYLxtw=="], + + "p-map": ["p-map@7.0.6", "", {}, "sha512-I4Prw6ivkd6p8PiYR1tXASOAOBzIJwu0TB7fqaX0c/8c3QAehNYmX57EijyGGGBt3c/BIowGwV03RVBtXvHEVg=="], + + "pacote": ["pacote@21.5.1", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@npmcli/git": "^7.0.0", "@npmcli/installed-package-contents": "^4.0.0", "@npmcli/package-json": "^7.0.0", "@npmcli/promise-spawn": "^9.0.0", "@npmcli/run-script": "^10.0.0", "cacache": "^20.0.0", "fs-minipass": "^3.0.0", "minipass": "^7.0.2", "npm-package-arg": "^13.0.0", "npm-packlist": "^10.0.1", "npm-pick-manifest": "^11.0.1", "npm-registry-fetch": "^19.0.0", "proc-log": "^6.0.0", "sigstore": "^4.0.0", "ssri": "^13.0.0", "tar": "^7.4.3" }, "bin": { "pacote": "bin/index.js" } }, "sha512-KvcJ9iy3crysCsgqc4+PknH/w6jkrp8JN36mpZBPwNaDRwTfMZD37YzRazNstiZUOhuF5pno9f78n9mEJBavwg=="], + + "path-scurry": ["path-scurry@2.0.2", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg=="], + + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], + + "picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], + + "postcss": ["postcss@8.5.26", "", { "dependencies": { "nanoid": "^3.3.17", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ=="], + + "proc-log": ["proc-log@6.1.0", "", {}, "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ=="], + + "rollup": ["rollup@4.62.5", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@napi-rs/lzma-linux-x64-gnu": "1.5.1", "@rollup/rollup-android-arm-eabi": "4.62.5", "@rollup/rollup-android-arm64": "4.62.5", "@rollup/rollup-darwin-arm64": "4.62.5", "@rollup/rollup-darwin-x64": "4.62.5", "@rollup/rollup-freebsd-arm64": "4.62.5", "@rollup/rollup-freebsd-x64": "4.62.5", "@rollup/rollup-linux-arm-gnueabihf": "4.62.5", "@rollup/rollup-linux-arm-musleabihf": "4.62.5", "@rollup/rollup-linux-arm64-gnu": "4.62.5", "@rollup/rollup-linux-arm64-musl": "4.62.5", "@rollup/rollup-linux-loong64-gnu": "4.62.5", "@rollup/rollup-linux-loong64-musl": "4.62.5", "@rollup/rollup-linux-ppc64-gnu": "4.62.5", "@rollup/rollup-linux-ppc64-musl": "4.62.5", "@rollup/rollup-linux-riscv64-gnu": "4.62.5", "@rollup/rollup-linux-riscv64-musl": "4.62.5", "@rollup/rollup-linux-s390x-gnu": "4.62.5", "@rollup/rollup-linux-x64-gnu": "4.62.5", "@rollup/rollup-linux-x64-musl": "4.62.5", "@rollup/rollup-openbsd-x64": "4.62.5", "@rollup/rollup-openharmony-arm64": "4.62.5", "@rollup/rollup-win32-arm64-msvc": "4.62.5", "@rollup/rollup-win32-ia32-msvc": "4.62.5", "@rollup/rollup-win32-x64-gnu": "4.62.5", "@rollup/rollup-win32-x64-msvc": "4.62.5", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-/tqMfgP7GPA3PHhCmuiS4vIjrSVhHLgY++i+dhbG462euyAj7FpM4D9uq1X3BgjlqRdpcOrYhcQtfiQLNc8tqw=="], + + "safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="], + + "semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], + + "sigstore": ["sigstore@4.1.1", "", { "dependencies": { "@sigstore/bundle": "^4.0.0", "@sigstore/core": "^3.2.1", "@sigstore/protobuf-specs": "^0.5.0", "@sigstore/sign": "^4.1.1", "@sigstore/tuf": "^4.0.2", "@sigstore/verify": "^3.1.1" } }, "sha512-endqECJkfhozrXMK5ngu/UAA0xVcVEFdnHJCElGaExypjW+HK5i6zu3NteLoaX/iFbRUbC3+DjttQs0GARr+5w=="], + + "smart-buffer": ["smart-buffer@4.2.0", "", {}, "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg=="], + + "socks": ["socks@2.8.9", "", { "dependencies": { "ip-address": "^10.1.1", "smart-buffer": "^4.2.0" } }, "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw=="], + + "socks-proxy-agent": ["socks-proxy-agent@8.0.5", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "^4.3.4", "socks": "^2.8.3" } }, "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw=="], + + "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], + + "spdx-exceptions": ["spdx-exceptions@2.5.0", "", {}, "sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w=="], + + "spdx-expression-parse": ["spdx-expression-parse@4.0.0", "", { "dependencies": { "spdx-exceptions": "^2.1.0", "spdx-license-ids": "^3.0.0" } }, "sha512-Clya5JIij/7C6bRR22+tnGXbc4VKlibKSVj2iHvVeX5iMW7s1SIQlqu699JkODJJIhh/pUu8L0/VLh8xflD+LQ=="], + + "spdx-license-ids": ["spdx-license-ids@3.0.23", "", {}, "sha512-CWLcCCH7VLu13TgOH+r8p1O/Znwhqv/dbb6lqWy67G+pT1kHmeD/+V36AVb/vq8QMIQwVShJ6Ssl5FPh0fuSdw=="], + + "ssri": ["ssri@13.0.1", "", { "dependencies": { "minipass": "^7.0.3" } }, "sha512-QUiRf1+u9wPTL/76GTYlKttDEBWV1ga9ZXW8BG6kfdeyyM8LGPix9gROyg9V2+P0xNyF3X2Go526xKFdMZrHSQ=="], + + "tar": ["tar@7.5.22", "", { "dependencies": { "@isaacs/fs-minipass": "^4.0.0", "chownr": "^3.0.0", "minipass": "^7.1.2", "minizlib": "^3.1.0", "yallist": "^5.0.0" } }, "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA=="], + + "three": ["three@0.185.1", "", {}, "sha512-5aojFCXKwnjBRZvUnt3WFfEcvUJgkN5LlijRFN95hMy8WVkG4I0QNcJE+OuWvuJ0bOdStrbfXn0pkd6/QyiAlg=="], + + "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], + + "tuf-js": ["tuf-js@4.1.0", "", { "dependencies": { "@tufjs/models": "4.1.0", "debug": "^4.4.3", "make-fetch-happen": "^15.0.1" } }, "sha512-50QV99kCKH5P/Vs4E2Gzp7BopNV+KzTXqWeaxrfu5IQJBOULRsTIS9seSsOVT8ZnGXzCyx55nYWAi4qJzpZKEQ=="], + + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + + "undici": ["undici@6.28.0", "", {}, "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA=="], + + "undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="], + + "validate-npm-package-name": ["validate-npm-package-name@7.0.2", "", {}, "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A=="], + + "vibe3d": ["vibe3d@0.0.1", "", { "dependencies": { "@vibe3djs/conformance": "^0.0.1", "@vibe3djs/registry": "^0.0.1", "@vibe3djs/schema": "^0.0.1", "commander": "^14.0.0", "picocolors": "^1.1.1" }, "bin": { "vibe3d": "dist/index.js" } }, "sha512-TXLr+uZ/EOFjctM24T8yIbfWgLt0qPd3GeCF1YMYqdfzxxGuZlhpgy1d/MJB3/QRixdwylQ/rgwJPbMPvHcdaQ=="], + + "vite": ["vite@7.3.6", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg=="], + + "which": ["which@6.0.1", "", { "dependencies": { "isexe": "^4.0.0" }, "bin": { "node-which": "bin/which.js" } }, "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg=="], + + "yallist": ["yallist@5.0.0", "", {}, "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw=="], + + "zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="], + + "minipass-flush/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], + + "minipass-pipeline/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], + + "minipass-flush/minipass/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], + + "minipass-pipeline/minipass/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], + } +} diff --git a/index.html b/index.html new file mode 100644 index 0000000..01642db --- /dev/null +++ b/index.html @@ -0,0 +1,47 @@ + + + + + + vibe3d · iki registry, tek proje + + + + +
+
+ + +
+ +

başlatılıyor…

+
+ + + diff --git a/models.json b/models.json new file mode 100644 index 0000000..f57b89f --- /dev/null +++ b/models.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://vibe3d.dev/schema/models.json", + "engine": "three", + "typescript": true, + "paths": { + "vibe3d": "src/lib/vibe3d", + "models": "src/models" + }, + "aliases": { + "vibe3d": "@/lib/vibe3d", + "models": "@/models" + }, + "registries": { + "@scifi-kit": { + "source": "npm:@scifi-kit/registry", + "version": "latest" + }, + "@medieval-kit": { + "source": "file:my-registry/dist/registry.json", + "version": "workspace" + } + } +} diff --git a/models.lock.json b/models.lock.json new file mode 100644 index 0000000..57400b1 --- /dev/null +++ b/models.lock.json @@ -0,0 +1,151 @@ +{ + "schemaVersion": 1, + "items": { + "@scifi-kit/core": { + "address": "@scifi-kit/core", + "source": "npm:@scifi-kit/registry", + "version": "latest", + "installedAt": "2026-08-20T20:26:13.607Z", + "files": [ + { + "path": "src\\lib\\vibe3d\\scifi-kit\\generator\\batching.ts", + "sourceHash": "c27ddd60cb9f72aec413e3a67132640aba0288d2c0e7fada96e8da67f063a965" + }, + { + "path": "src\\lib\\vibe3d\\scifi-kit\\generator\\effects.ts", + "sourceHash": "d735ab630899d296ffb0b5e68f326c3cf411c50225937699bed1bd5eb9b7ffd9" + }, + { + "path": "src\\lib\\vibe3d\\scifi-kit\\generator\\generator.test.ts", + "sourceHash": "28f0ca98e97a19532eacbc400a7a8465d306276342ab1c95bd95d750f51c97bc" + }, + { + "path": "src\\lib\\vibe3d\\scifi-kit\\generator\\glb.ts", + "sourceHash": "5f1f37136f9f92209f62e5d75321da59cad3e3a30f602e3745f4b315b997ad5b" + }, + { + "path": "src\\lib\\vibe3d\\scifi-kit\\generator\\index.ts", + "sourceHash": "cbc02a3372d44895058eaeb161e1be9f69fdca01b710c827f2990a20075f58dc" + }, + { + "path": "src\\lib\\vibe3d\\scifi-kit\\generator\\materials.ts", + "sourceHash": "a9462fdb3282620c97db02438bae620be6adb3c977f6502cee96a16f258d8e7f" + }, + { + "path": "src\\lib\\vibe3d\\scifi-kit\\generator\\primitives.ts", + "sourceHash": "ae7b8d8d8f154150cd3aa0111aafbee13039d03eb8b078ecae082a337500664b" + }, + { + "path": "src\\lib\\vibe3d\\scifi-kit\\generator\\profile.ts", + "sourceHash": "0ee3734762beddb5cc3316261c4633540a2e04d5497a8b4ed161116ee2acee95" + }, + { + "path": "src\\lib\\vibe3d\\scifi-kit\\generator\\wear.ts", + "sourceHash": "b9452449e13b3fdb2d4eee8ecc8318eb28a07470b5fe1ab4ddfd5f2a394f99e4" + } + ], + "dependencies": [ + "three@>=0.185.0" + ] + }, + "@scifi-kit/pressure-gauge": { + "address": "@scifi-kit/pressure-gauge", + "source": "npm:@scifi-kit/registry", + "version": "latest", + "installedAt": "2026-08-20T20:26:13.609Z", + "files": [ + { + "path": "src\\models\\scifi-kit\\pressure-gauge\\model.ts", + "sourceHash": "7e79976cc1dcf86bcf5abe25cfd4c143f84ae215c95ccd60a43f9df01a0fb1e5" + } + ], + "dependencies": [ + "three@>=0.185.0" + ] + }, + "@medieval-kit/wooden-barrel": { + "address": "@medieval-kit/wooden-barrel", + "source": "file:my-registry/dist/registry.json", + "version": "workspace", + "installedAt": "2026-08-20T22:57:15.724Z", + "files": [ + { + "path": "src\\models\\medieval-kit\\wooden-barrel\\model.ts", + "sourceHash": "52e73d497b7026f7f14748b23c41bf7e8be84dc7c8dcd52e867fea68ca6c56a1" + } + ], + "dependencies": [ + "three@>=0.185.0" + ] + }, + "@medieval-kit/core": { + "address": "@medieval-kit/core", + "source": "file:my-registry/dist/registry.json", + "version": "workspace", + "installedAt": "2026-08-20T22:57:15.720Z", + "files": [ + { + "path": "src\\models\\medieval-kit\\core\\geometry.ts", + "sourceHash": "70a44cbd731ac822b6103b601f1a00b9798130ef64533928b1c57a0817218176" + }, + { + "path": "src\\models\\medieval-kit\\core\\index.ts", + "sourceHash": "c18ab8ecdc97bea92ad32eae2c925115bf41014393af72068b6f85591c607f32" + }, + { + "path": "src\\models\\medieval-kit\\core\\materials.ts", + "sourceHash": "4d75182ad96ebfd90d1f776248b8bc37817e55b6826b96ce54b84862cd37b422" + }, + { + "path": "src\\models\\medieval-kit\\core\\random.ts", + "sourceHash": "de4e57736755b39b355a24a3b3df0cd79f31191343891502e7e5353417c0b3f2" + }, + { + "path": "src\\models\\medieval-kit\\core\\parts.ts", + "sourceHash": "73abd39c264a1d5ede9506b7818a7bb4386b6d93b2e4ac4c87b5ca7439cab3e3" + } + ], + "dependencies": [ + "three@>=0.185.0" + ] + }, + "@medieval-kit/iron-brazier": { + "address": "@medieval-kit/iron-brazier", + "source": "file:my-registry/dist/registry.json", + "version": "workspace", + "installedAt": "2026-08-20T22:57:15.723Z", + "files": [ + { + "path": "src\\models\\medieval-kit\\iron-brazier\\model.ts", + "sourceHash": "906b3e0b20aca546d1188b4f88f598d55d1bed9555a60547911d2db272ea14da" + } + ], + "dependencies": [ + "three@>=0.185.0" + ] + }, + "@medieval-kit/wooden-crate": { + "address": "@medieval-kit/wooden-crate", + "source": "file:my-registry/dist/registry.json", + "version": "workspace", + "installedAt": "2026-08-20T22:57:15.726Z", + "files": [ + { + "path": "src\\models\\medieval-kit\\wooden-crate\\model.ts", + "sourceHash": "1036c1652d84ba82401d520331b841f9e8391b6a4035bf9ebcbb3faefb787233" + } + ], + "dependencies": [ + "three@>=0.185.0" + ] + }, + "@medieval-kit/kit": { + "address": "@medieval-kit/kit", + "source": "file:my-registry/dist/registry.json", + "version": "workspace", + "installedAt": "2026-08-20T22:57:15.726Z", + "files": [], + "dependencies": [] + } + } +} diff --git a/my-registry/LICENSE b/my-registry/LICENSE new file mode 100644 index 0000000..2e4bee1 --- /dev/null +++ b/my-registry/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 CRTkafa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/my-registry/README.md b/my-registry/README.md new file mode 100644 index 0000000..32e38fd --- /dev/null +++ b/my-registry/README.md @@ -0,0 +1,110 @@ +# Medieval Kit + +A lowpoly medieval model library for [Vibe3D](https://github.com/vibe-stack/vibe3d) +and Three.js. Install a prop and you own its source: readable TypeScript in your +own tree, not an opaque package boundary. + +```sh +bunx vibe3d add @medieval-kit/wooden-barrel +bunx vibe3d add @medieval-kit +``` + +Configure `models.json` first so the namespace resolves: + +```json +{ + "registries": { + "@medieval-kit": { + "source": "npm:@medieval-kit/registry", + "version": "latest" + } + } +} +``` + +## Models + +| Address | Triangles | Size | Notes | +| --- | --- | --- | --- | +| `@medieval-kit/wooden-barrel` | 806 | 0.82 × 1.05 × 0.81 m | 13 separate staves, iron hoops, recessed heads | +| `@medieval-kit/wooden-crate` | 360 | 0.67 × 0.52 × 0.53 m | Plank rows on corner posts, forged straps | +| `@medieval-kit/iron-brazier` | 423 | 0.53 × 0.90 × 0.53 m | Animated flame, glowing coals, carries its own light | + +Every model depends on `@medieval-kit/core`, a shared support item holding the +palette, deterministic randomness, and the geometry vocabulary. Pulling a single +prop brings it along, so an individually installed crate still looks like it +came from the same catalogue as the barrel beside it. + +## Plain WebGL + +This kit does **not** require WebGPU. It declares `capabilities: []` and builds +on `MeshStandardMaterial` and `MeshBasicMaterial`, so it renders on +`WebGLRenderer` as well as `WebGPURenderer`. + +## Configuration + +Models are procedural, not baked. Every prop exposes typed fields: + +```ts +import { createModel } from '@/models/medieval-kit/wooden-barrel/model.ts' + +const barrel = createModel({ staveCount: 17, taper: 0.22, seed: 42 }) +scene.add(barrel.root) + +barrel.configure({ hoopCount: 6 }) // rebuilds geometry inside a stable root +barrel.dispose() +``` + +`seed` is a real field, not a debug knob. Variation is deterministic: the same +seed always produces the same prop, so previews, tests, and art direction stay +reproducible. Change the seed to get a different barrel from the same model. + +## Runtime anatomy + +Each model follows the Vibe3D protocol: + +- **`root`** keeps its object identity for the model's whole lifetime. +- **`parts`** expose stable semantic anchors. Attach your own lights, labels, or + gameplay objects to `part.anchor` — they survive `configure()`, because only + `part.content` is rebuilt. +- **`materials`** resolve per slot and can be overridden. Materials you supply + are borrowed: the model never disposes them. +- **`actions`** and **`update(delta)`** carry interactive state. `iron-brazier` + uses both: + +```ts +const brazier = createModel() +brazier.actions.setLit(false) +brazier.update(deltaSeconds) // flame flicker and light modulation +``` + +Reach for `configure()` when a user changes a setting; it rebuilds topology and +is not cheap. Anything that changes per frame belongs in `update()`. + +## Material slots + +| Slot | Used by | Type | +| --- | --- | --- | +| `oak` | barrel, crate | `MeshStandardMaterial`, vertex-coloured | +| `iron` | barrel, crate, brazier | `MeshStandardMaterial`, vertex-coloured | +| `char` | brazier | `MeshStandardMaterial`, vertex-coloured | +| `ember` | brazier | `MeshBasicMaterial`, unlit and not tone-mapped | + +Colour variation lives in the geometry, not in the materials: each of the +barrel's 13 staves carries its own tone as vertex colours, and all of them share +one material and therefore one draw call. + +## Building from source + +```sh +bun build.ts # emit dist/registry.json +bunx vibe3d registry validate dist/registry.json +``` + +The build walks `models/`. A folder containing `model.ts` becomes a +`vibe3d:model`; any other folder becomes a `vibe3d:lib`. Registry dependencies +are derived from the source — an import from `../core/` makes +`@medieval-kit/core` a dependency automatically, so there is no hand-maintained +list to go stale. + +Released under the MIT License. diff --git a/my-registry/build.ts b/my-registry/build.ts new file mode 100644 index 0000000..a5aa670 --- /dev/null +++ b/my-registry/build.ts @@ -0,0 +1,259 @@ +/** + * Kendi registry'nizi derleyen script. + * + * `models/` altındaki her klasörü tarar: + * - `model.ts` içeriyorsa -> vibe3d:model + * - içermiyorsa -> vibe3d:lib (paylaşılan destek item'ı) + * + * Bağımlılıklar kaynaktan türetilir: bir model `../core/` altından import + * ediyorsa `@medieval-kit/core` otomatik bağımlılık olur. Elle tutulan bir + * liste yok, dolayısıyla listenin bayatlaması da mümkün değil. + * + * Çalıştır: bun my-registry/build.ts + * Doğrula: bunx vibe3d registry validate my-registry/dist/registry.json + */ +import { createHash } from 'node:crypto' +import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises' +import { dirname, join, relative, resolve, sep } from 'node:path' +import { fileURLToPath } from 'node:url' + +const registryRoot = dirname(fileURLToPath(import.meta.url)) +const sourceRoot = join(registryRoot, 'models') +const outputRoot = join(registryRoot, 'dist') + +const NAMESPACE = '@medieval-kit' +const THREE_RANGE = 'three@>=0.185.0' + +/** Model başına katalog verisi. Kaynak dosyalar diskten okunur. */ +const MODEL_META: Record + materialSlots: string[] + parts: string[] +}> = { + 'wooden-barrel': { + title: 'Wooden Barrel', + description: + 'Ayrı meşe tahtalardan kurulmuş, demir çemberli, kapağı gömülü lowpoly fıçı.', + category: 'Props', + tags: ['medieval', 'lowpoly', 'props', 'procedural'], + controls: { + height: { type: 'number', label: 'Yükseklik', min: 0.4, max: 2, step: 0.02, unit: 'm' }, + radius: { type: 'number', label: 'Yarıçap', min: 0.15, max: 0.9, step: 0.01, unit: 'm' }, + taper: { type: 'number', label: 'Uç daralması', min: 0, max: 0.34, step: 0.01 }, + staveCount: { type: 'number', label: 'Tahta sayısı', min: 6, max: 28, step: 1 }, + hoopCount: { type: 'number', label: 'Çember sayısı', min: 0, max: 6, step: 1 }, + seed: { type: 'number', label: 'Varyasyon tohumu', min: 1, max: 64, step: 1 }, + }, + materialSlots: ['oak', 'iron'], + parts: ['staves', 'heads', 'hoops'], + }, + 'wooden-crate': { + title: 'Wooden Crate', + description: + 'Köşe dikmelerine çakılmış yatay tahta sıraları ve dövme demir kayışlar.', + category: 'Props', + tags: ['medieval', 'lowpoly', 'props', 'procedural'], + controls: { + width: { type: 'number', label: 'Genişlik', min: 0.3, max: 1.4, step: 0.02, unit: 'm' }, + height: { type: 'number', label: 'Yükseklik', min: 0.25, max: 1.2, step: 0.02, unit: 'm' }, + depth: { type: 'number', label: 'Derinlik', min: 0.3, max: 1.4, step: 0.02, unit: 'm' }, + plankRows: { type: 'number', label: 'Tahta sırası', min: 1, max: 6, step: 1 }, + strapCount: { type: 'number', label: 'Demir kayış', min: 0, max: 4, step: 1 }, + seed: { type: 'number', label: 'Varyasyon tohumu', min: 1, max: 64, step: 1 }, + }, + materialSlots: ['oak', 'iron'], + parts: ['posts', 'planks', 'straps'], + }, + 'iron-brazier': { + title: 'Iron Brazier', + description: + 'Üç ayaklı dövme demir mangal; titreyen alev, kor kömürler ve taşıdığı ateş ışığı.', + category: 'Lighting', + tags: ['medieval', 'lowpoly', 'lighting', 'animated', 'procedural'], + controls: { + height: { type: 'number', label: 'Yükseklik', min: 0.4, max: 1.6, step: 0.02, unit: 'm' }, + bowlRadius: { type: 'number', label: 'Kâse yarıçapı', min: 0.12, max: 0.5, step: 0.01, unit: 'm' }, + bowlSegments: { type: 'number', label: 'Kâse köşesi', min: 5, max: 20, step: 1 }, + legCount: { type: 'number', label: 'Ayak sayısı', min: 3, max: 6, step: 1 }, + flameCount: { type: 'number', label: 'Alev dili', min: 0, max: 9, step: 1 }, + seed: { type: 'number', label: 'Varyasyon tohumu', min: 1, max: 64, step: 1 }, + }, + materialSlots: ['iron', 'char', 'ember'], + parts: ['bowl', 'legs', 'coals', 'flame'], + }, +} + +const LIB_DESCRIPTION: Record = { + core: { + title: 'Medieval Kit Core', + description: + 'Kitin paylaşılan temeli: deterministik rastgelelik, vertex-renkli materyaller ' + + 've stave/band/head geometri üreticileri.', + }, +} + +function sha256(content: string): string { + return createHash('sha256').update(content).digest('hex') +} + +function posix(path: string): string { + return path.split(sep).join('/') +} + +async function collectTypeScript(root: string): Promise { + const files: string[] = [] + const visit = async (directory: string): Promise => { + for (const entry of await readdir(directory, { withFileTypes: true })) { + const path = join(directory, entry.name) + if (entry.isDirectory()) await visit(path) + else if (entry.isFile() && entry.name.endsWith('.ts')) files.push(path) + } + } + await visit(root) + return files.sort() +} + +async function registryFiles(itemId: string, paths: readonly string[]) { + const directory = join(sourceRoot, itemId) + return Promise.all(paths.map(async (path) => { + const content = await readFile(path, 'utf8') + return { + path: posix(relative(registryRoot, path)), + // {models} ve {vibe3d}, tüketicinin models.json'ındaki paths ile + // değiştirilir — registry onun klasör düzenini varsaymak zorunda değil. + target: `{models}/medieval-kit/${itemId}/${posix(relative(directory, path))}`, + content, + hash: sha256(content), + } + })) +} + +/** `from '..//'` biçimindeki her import bir registry bağımlılığıdır. */ +function dependenciesFrom(contents: readonly string[], selfId: string): string[] { + const found = new Set() + const pattern = /from\s+['"]\.\.\/([a-z0-9][a-z0-9-]*)\//g + for (const content of contents) { + for (const match of content.matchAll(pattern)) { + const id = match[1] + if (id && id !== selfId) found.add(`${NAMESPACE}/${id}`) + } + } + return [...found].sort() +} + +async function main(): Promise { + const entries = await readdir(sourceRoot, { withFileTypes: true }) + const models: string[] = [] + const libs: string[] = [] + + for (const entry of entries) { + if (!entry.isDirectory()) continue + // Nokta ile başlayan klasörler item değildir. Araçlar (editör, VCS, ajan + // durumu) buraya klasör bırakabilir; registry adları ise `[a-z0-9-]+` + // olmak zorunda, yani böyle bir klasör derlemeyi kırardı. + if (entry.name.startsWith('.')) continue + const paths = await collectTypeScript(join(sourceRoot, entry.name)) + if (paths.some((path) => path.endsWith(`${sep}model.ts`))) models.push(entry.name) + else libs.push(entry.name) + } + models.sort() + libs.sort() + + const items: unknown[] = [] + + for (const id of libs) { + const paths = await collectTypeScript(join(sourceRoot, id)) + const contents = await Promise.all(paths.map((path) => readFile(path, 'utf8'))) + const meta = LIB_DESCRIPTION[id] ?? { title: id, description: 'Paylaşılan kit kaynağı.' } + items.push({ + name: id, + type: 'vibe3d:lib', + title: meta.title, + description: meta.description, + dependencies: [THREE_RANGE], + registryDependencies: dependenciesFrom(contents, id), + files: await registryFiles(id, paths), + }) + } + + for (const id of models) { + const paths = await collectTypeScript(join(sourceRoot, id)) + const contents = await Promise.all(paths.map((path) => readFile(path, 'utf8'))) + const meta = MODEL_META[id] + if (!meta) throw new Error(`${id} için MODEL_META girdisi yok`) + items.push({ + name: id, + type: 'vibe3d:model', + title: meta.title, + description: meta.description, + dependencies: [THREE_RANGE], + registryDependencies: dependenciesFrom(contents, id), + files: await registryFiles(id, paths), + meta: { + title: meta.title, + description: meta.description, + category: meta.category, + tags: meta.tags, + controls: meta.controls, + materialSlots: meta.materialSlots, + parts: meta.parts, + sockets: [], + }, + }) + } + + // defaultItem şart: `vibe3d add @medieval-kit` (item adı vermeden) bunu kurar. + items.push({ + name: 'kit', + type: 'vibe3d:kit', + title: 'Medieval Kit', + description: 'Lowpoly medieval kitin tamamı.', + dependencies: [], + registryDependencies: models.map((id) => `${NAMESPACE}/${id}`), + files: [], + }) + + const registry = { + $schema: 'https://vibe3d.dev/schema/registry.json', + schemaVersion: 1, + namespace: NAMESPACE, + name: 'Medieval Kit', + description: 'Three.js için lowpoly medieval prosedürel model kütüphanesi.', + license: 'MIT', + defaultItem: 'kit', + compatibility: { + vibe3d: '^0.0.1', + engine: 'three', + three: '>=0.185.0', + // scifi-kit ['webgpu','tsl'] ister; bu kit klasik WebGL ile çalışır. + capabilities: [], + }, + items, + } + + await mkdir(outputRoot, { recursive: true }) + await writeFile( + resolve(outputRoot, 'registry.json'), + `${JSON.stringify(registry, null, 2)}\n`, + 'utf8', + ) + + const fileCount = items.reduce( + (total, item) => total + (item as { files: unknown[] }).files.length, + 0, + ) + console.log(`${items.length} item derlendi · ${models.length} model · ${libs.length} lib · ${fileCount} dosya`) + for (const id of [...libs, ...models]) { + const item = items.find((candidate) => (candidate as { name: string }).name === id) as { + registryDependencies: string[] + } + const deps = item.registryDependencies.length > 0 ? ` -> ${item.registryDependencies.join(', ')}` : '' + console.log(` ${NAMESPACE}/${id}${deps}`) + } +} + +await main() diff --git a/my-registry/models/core/geometry.ts b/my-registry/models/core/geometry.ts new file mode 100644 index 0000000..043e4f7 --- /dev/null +++ b/my-registry/models/core/geometry.ts @@ -0,0 +1,292 @@ +import { BufferAttribute, BufferGeometry, Color } from 'three' +import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js' + +/** + * Kitin geometri dili. + * + * Hepsi INDEKSSİZ üretiliyor. Sebep: indekssiz geometride + * computeVertexNormals() her üçgene kendi normalini verir, yani düz gölgeleme + * (flat shading) geometrinin doğal sonucu olur — materyal bayrağına gerek + * kalmaz. Lowpoly'de istediğimiz tam olarak bu. + * + * Konum çerçevesi: point(a, r, y) = (sin a · r, y, cos a · r) + * Yani a = 0 → +Z yönü; a büyüdükçe +X'e doğru. + * + * Sarımlar elle çözüldü ve `scripts/verify-model.ts` içindeki denetim onları + * mutasyonla sınıyor: dış kabuktaki radyal yüzler eksenden dışa bakmalı. + */ + +export type Vec3 = readonly [number, number, number] + +export interface Level { + /** Dikey konum (metre). */ + readonly y: number + /** O yükseklikteki DIŞ yarıçap (metre). */ + readonly radius: number +} + +function point(angle: number, radius: number, y: number): Vec3 { + return [Math.sin(angle) * radius, y, Math.cos(angle) * radius] +} + +interface Sink { + readonly position: number[] + readonly color: number[] +} + +function tri(sink: Sink, a: Vec3, b: Vec3, c: Vec3, colour: Color): void { + sink.position.push(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2]) + for (let i = 0; i < 3; i += 1) sink.color.push(colour.r, colour.g, colour.b) +} + +/** Üç köşesi ayrı renkli üçgen — dikey renk geçişleri için. */ +function triShaded(sink: Sink, a: Vec3, b: Vec3, c: Vec3, ca: Color, cb: Color, cc: Color): void { + sink.position.push(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2]) + sink.color.push(ca.r, ca.g, ca.b, cb.r, cb.g, cb.b, cc.r, cc.g, cc.b) +} + +/** Dörtgeni (a,b,c,d) sırasıyla iki üçgene böler. Normal a→b→c sarımından çıkar. */ +function quad(sink: Sink, a: Vec3, b: Vec3, c: Vec3, d: Vec3, colour: Color): void { + tri(sink, a, b, c, colour) + tri(sink, a, c, d, colour) +} + +function finish(sink: Sink): BufferGeometry { + const geometry = new BufferGeometry() + geometry.setAttribute('position', new BufferAttribute(new Float32Array(sink.position), 3)) + geometry.setAttribute('color', new BufferAttribute(new Float32Array(sink.color), 3)) + return geometry +} + +/** + * Eksen hizalı kutu. Kitin en çok kullanılan parçası: tahta, kiriş, demir + * kayış, ayak — hepsi bu. + */ +export function boxGeometry( + size: Vec3, + centre: Vec3, + colour: Color, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const [hx, hy, hz] = [size[0] / 2, size[1] / 2, size[2] / 2] + const [cx, cy, cz] = centre + const v = (sx: number, sy: number, sz: number): Vec3 => [cx + sx * hx, cy + sy * hy, cz + sz * hz] + + quad(sink, v(-1, -1, 1), v(1, -1, 1), v(1, 1, 1), v(-1, 1, 1), colour) // +Z + quad(sink, v(1, -1, -1), v(-1, -1, -1), v(-1, 1, -1), v(1, 1, -1), colour) // -Z + quad(sink, v(1, -1, 1), v(1, -1, -1), v(1, 1, -1), v(1, 1, 1), colour) // +X + quad(sink, v(-1, -1, -1), v(-1, -1, 1), v(-1, 1, 1), v(-1, 1, -1), colour) // -X + quad(sink, v(-1, 1, 1), v(1, 1, 1), v(1, 1, -1), v(-1, 1, -1), colour) // +Y + quad(sink, v(-1, -1, -1), v(1, -1, -1), v(1, -1, 1), v(-1, -1, 1), colour) // -Y + + return finish(sink) +} + +/** + * Kesik koni / prizma: ayak, sap, kâse, alev dili. + * + * `colourTop` verilirse renk yüksekliğe göre geçiş yapar — alev için gerekli, + * çünkü alevin dibi ile ucu aynı renk değildir. + */ +export function prismGeometry( + radiusBottom: number, + radiusTop: number, + height: number, + segments: number, + centre: Vec3, + colour: Color, + options: { readonly capTop?: boolean; readonly capBottom?: boolean; readonly colourTop?: Color } = {}, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const { capTop = true, capBottom = true } = options + const top = options.colourTop ?? colour + const [cx, cy, cz] = centre + const low = cy - height / 2 + const high = cy + height / 2 + const stepAngle = (Math.PI * 2) / segments + const shift = (p: Vec3): Vec3 => [p[0] + cx, p[1], p[2] + cz] + + for (let i = 0; i < segments; i += 1) { + const a0 = i * stepAngle + const a1 = (i + 1) * stepAngle + const l0 = shift(point(a0, radiusBottom, low)) + const l1 = shift(point(a1, radiusBottom, low)) + const h0 = shift(point(a0, radiusTop, high)) + const h1 = shift(point(a1, radiusTop, high)) + + // Yan yüz: dışa bakar. + triShaded(sink, l0, l1, h1, colour, colour, top) + triShaded(sink, l0, h1, h0, colour, top, top) + + if (capTop && radiusTop > 0) tri(sink, [cx, high, cz], h0, h1, top) + if (capBottom && radiusBottom > 0) tri(sink, [cx, low, cz], l1, l0, colour) + } + + return finish(sink) +} + +/** + * Bir fıçı tahtası (stave): halkanın bir dilimi, kalınlığı olan kapalı bir katı. + * + * Her seviyede dört köşe var: + * A = dış/başlangıç açısı B = dış/bitiş açısı + * C = iç/bitiş açısı D = iç/başlangıç açısı + */ +export function staveGeometry( + levels: readonly Level[], + angleStart: number, + angleEnd: number, + thickness: number, + colour: Color, +): BufferGeometry { + if (levels.length < 2) throw new Error('staveGeometry en az iki seviye ister') + + const sink: Sink = { position: [], color: [] } + + const corners = levels.map((level) => { + // Kalınlık, en ince yarıçapın yarısını geçemez; yoksa iç yüzey dışa taşar. + const inner = Math.max(level.radius * 0.5, level.radius - thickness) + return { + a: point(angleStart, level.radius, level.y), + b: point(angleEnd, level.radius, level.y), + c: point(angleEnd, inner, level.y), + d: point(angleStart, inner, level.y), + } + }) + + for (let i = 0; i < corners.length - 1; i += 1) { + const low = corners[i]! + const high = corners[i + 1]! + quad(sink, low.a, low.b, high.b, high.a, colour) // dış yüz → dışa bakar + quad(sink, low.c, low.d, high.d, high.c, colour) // iç yüz → eksene bakar + quad(sink, low.d, low.a, high.a, high.d, colour) // başlangıç kenarı + quad(sink, low.b, low.c, high.c, high.b, colour) // bitiş kenarı + } + + const top = corners.at(-1)! + const bottom = corners[0]! + quad(sink, top.a, top.b, top.c, top.d, colour) // üst kapak → +Y + quad(sink, bottom.d, bottom.c, bottom.b, bottom.a, colour) // alt kapak → -Y + + return finish(sink) +} + +/** + * Demir çember: dikdörtgen kesitli bir halka. + * + * İç yüzey kasten üretilmiyor — yaslandığı gövde onu her kameradan gizler. + * Üçgen bütçesinin dörtte biri buradan kazanılıyor. + */ +export function bandGeometry( + radius: number, + y: number, + height: number, + thickness: number, + segments: number, + colour: Color, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const half = height / 2 + const inner = radius - thickness + const stepAngle = (Math.PI * 2) / segments + + for (let i = 0; i < segments; i += 1) { + const a0 = i * stepAngle + const a1 = (i + 1) * stepAngle + + const outerLow0 = point(a0, radius, y - half) + const outerLow1 = point(a1, radius, y - half) + const outerHigh0 = point(a0, radius, y + half) + const outerHigh1 = point(a1, radius, y + half) + const innerHigh0 = point(a0, inner, y + half) + const innerHigh1 = point(a1, inner, y + half) + const innerLow0 = point(a0, inner, y - half) + const innerLow1 = point(a1, inner, y - half) + + quad(sink, outerLow0, outerLow1, outerHigh1, outerHigh0, colour) // dış → dışa + quad(sink, outerHigh0, outerHigh1, innerHigh1, innerHigh0, colour) // üst → +Y + quad(sink, innerLow0, innerLow1, outerLow1, outerLow0, colour) // alt → -Y + } + + return finish(sink) +} + +/** + * Yelpaze disk: fıçı kapağı, kâse dibi. + * + * Tek parça ahşap değil, birkaç tahtadan kurulmuş gibi okunması için her + * üçgen, merkezinin X konumuna göre bir "tahta bandına" düşer ve o bandın tonu + * vertex color'a yazılır. Geometri maliyeti sıfır. + */ +export function headGeometry( + radius: number, + y: number, + segments: number, + facing: 'up' | 'down', + colour: Color, + plankCount: number, + plankShade: number, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const centre: Vec3 = [0, y, 0] + const stepAngle = (Math.PI * 2) / segments + const plankWidth = (radius * 2) / Math.max(1, plankCount) + const tint = new Color() + + for (let i = 0; i < segments; i += 1) { + const p0 = point(i * stepAngle, radius, y) + const p1 = point((i + 1) * stepAngle, radius, y) + + // Tahtalar X ekseni boyunca dilimlenmiş şeritler; üçgenin ağırlık + // merkezinin X'i hangi şeride düşüyorsa onun tonunu alır. + const centroidX = (p0[0] + p1[0]) / 3 + const band = Math.floor((centroidX + radius) / plankWidth) + tint.copy(colour).multiplyScalar(1 + (band % 2 === 0 ? plankShade : -plankShade)) + + if (facing === 'up') tri(sink, centre, p0, p1, tint) + else tri(sink, centre, p1, p0, tint) + } + + return finish(sink) +} + +/** + * Her üçgenin sarımını ters çevirir, yani tüm normalleri döndürür. + * + * İçi görünen kaplar için gerekli: bir kâsenin dış yüzeyi dışa, iç yüzeyi içe + * bakmalı. İkisini ayrı ayrı yazmak yerine aynı koniyi üretip birini + * çeviriyoruz. + */ +export function flipGeometry(geometry: BufferGeometry): BufferGeometry { + for (const name of ['position', 'color'] as const) { + const attribute = geometry.getAttribute(name) + if (!attribute) continue + const array = attribute.array as Float32Array + const stride = attribute.itemSize + // Üçgenin 2. ve 3. köşesini takas etmek sarımı ters çevirir. + for (let i = 0; i < attribute.count; i += 3) { + for (let k = 0; k < stride; k += 1) { + const b = (i + 1) * stride + k + const c = (i + 2) * stride + k + const swap = array[b]! + array[b] = array[c]! + array[c] = swap + } + } + attribute.needsUpdate = true + } + return geometry +} + +/** + * Aynı materyali paylaşan parçaları tek geometriye indirger — materyal başına + * tek çizim çağrısı. Normaller birleştirmeden SONRA hesaplanır: indekssiz + * geometride bu her üçgene kendi normalini verir, yani düz gölgeleme. + */ +export function mergeColoured(geometries: readonly BufferGeometry[]): BufferGeometry { + const merged = mergeGeometries(geometries as BufferGeometry[], false) + if (!merged) throw new Error('Geometriler birleştirilemedi: attribute setleri uyuşmuyor') + for (const geometry of geometries) geometry.dispose() + merged.computeVertexNormals() + return merged +} diff --git a/my-registry/models/core/index.ts b/my-registry/models/core/index.ts new file mode 100644 index 0000000..7b20fd9 --- /dev/null +++ b/my-registry/models/core/index.ts @@ -0,0 +1,15 @@ +export { createRandom, jitter } from './random.ts' +export { + bandGeometry, + boxGeometry, + flipGeometry, + headGeometry, + mergeColoured, + prismGeometry, + staveGeometry, +} from './geometry.ts' +export type { Level, Vec3 } from './geometry.ts' +export { createPart } from './parts.ts' +export type { PartSlot } from './parts.ts' +export { MEDIEVAL_PALETTE, createMedievalMaterials } from './materials.ts' +export type { MedievalPalette, MedievalSlot } from './materials.ts' diff --git a/my-registry/models/core/materials.ts b/my-registry/models/core/materials.ts new file mode 100644 index 0000000..fdbc861 --- /dev/null +++ b/my-registry/models/core/materials.ts @@ -0,0 +1,121 @@ +import { Color, MeshBasicMaterial, MeshStandardMaterial } from 'three' + +import type { ResourceScope } from '@vibe3d/ownership.ts' + +/** + * Kitin paylaşılan materyal seti. + * + * Kritik tercih: her materyal `vertexColors: true`. Renk varyasyonu materyalde + * değil GEOMETRİDE taşınıyor. Böylece 13 tahtanın 13 ayrı tonu olabiliyor ama + * hepsi tek materyali, dolayısıyla tek çizim çağrısını paylaşıyor. + * + * Bu, scifi-kit'in aşınma boru hattındaki fikrin küçük hâli: yüzey kimliğini + * vertex attribute'una yaz, sonra birleştir. + */ +export type MedievalSlot = 'oak' | 'iron' | 'ember' | 'char' + +/** + * Her yuvanın materyal TİPİ farklı olabilir. `ember` aydınlatılmayan bir + * MeshBasicMaterial; diğerleri PBR. Bu eşleme sayesinde model kodu hangi tipi + * aldığını derleme zamanında biliyor. + */ +export interface SlotMaterial { + readonly oak: MeshStandardMaterial + readonly iron: MeshStandardMaterial + readonly ember: MeshBasicMaterial + readonly char: MeshStandardMaterial +} + +export interface MedievalPalette { + /** Meşe gövde tonu. */ + readonly oak: Color + /** Kapak tahtası — gövdeden biraz daha soğuk ve açık (damar ucu). */ + readonly oakEnd: Color + /** Dövme demir. */ + readonly iron: Color + /** Alev dibi — sıcak ve parlak. */ + readonly ember: Color + /** Alev ucu — daha doygun, daha kırmızı. */ + readonly emberTip: Color + /** Sönmüş kömür. */ + readonly char: Color + /** Kor hâlindeki kömür. */ + readonly charHot: Color +} + +/** + * Renkler sRGB olarak yazılır; three, ColorManagement açıkken bunları içeride + * lineer uzayda saklar. Vertex color attribute'u lineer beklediği için + * `color.r/g/b` doğrudan yazılabilir — ekstra dönüşüm gerekmez. + */ +export const MEDIEVAL_PALETTE: MedievalPalette = { + oak: new Color(0x8a5a34), + oakEnd: new Color(0x9a7350), + iron: new Color(0x40464d), + ember: new Color(0xffd27a), + emberTip: new Color(0xd8571b), + char: new Color(0x241f1c), + charHot: new Color(0xc4441a), +} + +/** + * İstenen yuvalar için materyal üretir. + * + * Slot listesi bilerek zorunlu: mangalın meşeye, fıçının emissive materyale + * ihtiyacı yok. Kullanılmayan materyal üretmek hem boşuna GPU kaynağı hem de + * modelin `materialSlots` bildirimiyle çelişen bir yalan olur. + * + * Dönüş tipi istenen yuvalara daraltılır, yani `materials.ember` sadece onu + * isteyen modelde derlenir. + */ +export function createMedievalMaterials( + scope: ResourceScope, + slots: readonly S[], +): Pick { + const build: { [K in MedievalSlot]: () => SlotMaterial[K] } = { + oak: () => new MeshStandardMaterial({ + name: 'medieval-kit / oak', + // Beyaz taban: tüm renk bilgisi vertex color'dan geliyor, materyal onu + // çarpmasın diye. + color: 0xffffff, + vertexColors: true, + roughness: 0.82, + metalness: 0, + }), + iron: () => new MeshStandardMaterial({ + name: 'medieval-kit / wrought iron', + color: 0xffffff, + vertexColors: true, + roughness: 0.52, + metalness: 0.8, + }), + // Alev ışık ALMAZ, yayar. MeshStandardMaterial burada yanlış araç olurdu: + // `emissive` tek bir Color'dır, vertex renklerinden beslenmez — yani + // alevin dibinden ucuna renk geçişi yapılamaz. MeshBasicMaterial + // aydınlatmayı tamamen atlar ve vertex rengini olduğu gibi gösterir; + // toneMapped kapalı ki sahne pozlaması alevi söndürmesin. + ember: () => new MeshBasicMaterial({ + name: 'medieval-kit / ember', + color: 0xffffff, + vertexColors: true, + toneMapped: false, + }), + char: () => new MeshStandardMaterial({ + name: 'medieval-kit / charcoal', + color: 0xffffff, + vertexColors: true, + roughness: 0.95, + metalness: 0, + }), + } + + const materials = {} as { [K in S]: SlotMaterial[K] } + for (const slot of slots) { + // TypeScript ilişkili birleşimleri (correlated unions) takip edemiyor: + // `build[slot]` bir fonksiyon birleşimine genişliyor, dolayısıyla dönüşün + // tam olarak SlotMaterial[slot] olduğunu bilemiyor. Eşleme yukarıda elle + // kurulduğu için dönüşüm güvenli. + materials[slot] = scope.ownMaterial(build[slot]()) as SlotMaterial[S] + } + return materials +} diff --git a/my-registry/models/core/parts.ts b/my-registry/models/core/parts.ts new file mode 100644 index 0000000..7416cde --- /dev/null +++ b/my-registry/models/core/parts.ts @@ -0,0 +1,46 @@ +import { Group } from 'three' + +import type { PartHandle } from '@vibe3d/model.ts' + +/** + * Semantik parça yuvası: sabit anchor + değiştirilebilir içerik. + * + * vibe3d'nin en kolay yanlış anlaşılan sözleşmesi bu. `PartHandle` iki ayrı + * nesne bildirir ve ikisi AYNI OLAMAZ: + * + * anchor modelin ömrü boyunca aynı nesne. Tüketici ışığını, etiketini, + * çarpışma gövdesini, gameplay nesnesini buraya takar. + * content configure() her çağrıldığında atılıp yeniden kurulan geometri. + * + * İkisini aynı Group yapıp rebuild'de `clear()` çağırmak, tüketicinin taktığı + * her şeyi de sessizce siler — model çalışmaya devam eder, ama protokolün asıl + * vaadi bozulmuştur. `scripts/verify-model.ts` bunu ayrıca test ediyor. + */ +export interface PartSlot extends PartHandle { + readonly anchor: Group + readonly content: Group + /** İçeriği taze bir Group ile değiştirir ve onu döndürür. Anchor'a dokunmaz. */ + reset(): Group +} + +export function createPart(name: string): PartSlot { + const anchor = new Group() + anchor.name = name + let content = new Group() + content.name = `${name}/content` + anchor.add(content) + + return { + anchor, + get content(): Group { + return content + }, + reset(): Group { + anchor.remove(content) + content = new Group() + content.name = `${name}/content` + anchor.add(content) + return content + }, + } +} diff --git a/my-registry/models/core/random.ts b/my-registry/models/core/random.ts new file mode 100644 index 0000000..f7750e1 --- /dev/null +++ b/my-registry/models/core/random.ts @@ -0,0 +1,26 @@ +/** + * Deterministik rastgelelik. + * + * Prosedürel bir kitte varyasyon şart — mükemmel simetri "üretilmiş" gibi + * okunur. Ama varyasyon tekrarlanabilir olmalı: aynı seed her zaman aynı + * modeli vermeli, yoksa ne önizleme, ne test, ne de sanat yönetimi tutar. + * Math.random() bu yüzden kullanılmıyor. + * + * mulberry32: 32-bit durum, hızlı, kriptografik değil ama görsel varyasyon + * için fazlasıyla yeterli. + */ +export function createRandom(seed: number): () => number { + let state = seed >>> 0 + return () => { + state = (state + 0x6d2b79f5) >>> 0 + let t = state + t = Math.imul(t ^ (t >>> 15), t | 1) + t ^= t + Math.imul(t ^ (t >>> 7), t | 61) + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +/** -amount .. +amount aralığında simetrik sapma. */ +export function jitter(random: () => number, amount: number): number { + return (random() * 2 - 1) * amount +} diff --git a/my-registry/models/iron-brazier/model.ts b/my-registry/models/iron-brazier/model.ts new file mode 100644 index 0000000..ec55bbc --- /dev/null +++ b/my-registry/models/iron-brazier/model.ts @@ -0,0 +1,396 @@ +/** + * @medieval-kit/iron-brazier + * + * Kitin ilk HAREKETLİ modeli. Fıçı ve sandık statik: kurulurlar ve öyle + * kalırlar. Mangal, vibe3d protokolünün onların hiç dokunmadığı iki parçasını + * çalıştırıyor: + * + * - tipli `actions` → yak / söndür + * - `update(dt)` → alev titremesi ve ışık dalgalanması + * + * Ayrım önemli: `configure()` topolojiyi yeniden kurar ve pahalıdır, kullanıcı + * ayarı içindir. Kare başına değişen her şey `update()` içinde olmalı. + * + * Model ayrıca bir PointLight taşıyor. Işık `flame` anchor'ına takılı, yani + * configure() geometriyi yeniden kursa bile ışık hayatta kalıyor. + */ +import { + Color, + Group, + Mesh, + PointLight, + type BufferGeometry, + type Material, +} from 'three' + +import type { ConfigureResult, MaterialBindings, ModelInstance, PartHandle } from '@vibe3d/model.ts' +import { ResourceScope } from '@vibe3d/ownership.ts' + +import { + MEDIEVAL_PALETTE, + bandGeometry, + boxGeometry, + createMedievalMaterials, + createPart, + createRandom, + flipGeometry, + jitter, + mergeColoured, + prismGeometry, +} from '../core/index.ts' + +export interface IronBrazierConfig { + /** Ayak dâhil toplam yükseklik (metre). */ + readonly height: number + /** Kâsenin üst ağız yarıçapı (metre). */ + readonly bowlRadius: number + /** Kâse çevresindeki köşe sayısı. Düşük tut — lowpoly silueti bu belirler. */ + readonly bowlSegments: number + /** Ayak sayısı. */ + readonly legCount: number + /** Alev dili sayısı. 0 = alev yok, sadece kömür. */ + readonly flameCount: number + /** Varyasyon tohumu. */ + readonly seed: number +} + +export const ironBrazierDefaults: IronBrazierConfig = { + height: 0.86, + bowlRadius: 0.26, + bowlSegments: 12, + legCount: 3, + flameCount: 5, + seed: 11, +} + +export interface IronBrazierParts { + /** Kâse ve ağız çemberi. */ + readonly bowl: PartHandle + /** Ayaklar ve pabuçlar. */ + readonly legs: PartHandle + /** Sönmüş kömürler. */ + readonly coals: PartHandle + /** Alev dilleri, kor kömürler ve ışık. Söndürülünce gizlenir. */ + readonly flame: PartHandle +} + +export interface IronBrazierActions { + /** Ateşi yakar ya da söndürür. */ + setLit(lit: boolean): void + /** Şu anda yanıyor mu. */ + isLit(): boolean +} + +const SLOTS = ['iron', 'char', 'ember'] as const +type Slot = (typeof SLOTS)[number] + +interface Blade { + readonly mesh: Group + readonly phase: number + readonly speed: number + readonly reach: number +} + +export function createModel( + overrides: Partial = {}, +): ModelInstance { + let config: IronBrazierConfig = { ...ironBrazierDefaults, ...overrides } + + const scope = new ResourceScope() + const defaults = createMedievalMaterials(scope, SLOTS) + const overridesBySlot = new Map() + const resolve = (slot: Slot): Material => overridesBySlot.get(slot) ?? defaults[slot] + + const root = new Group() + root.name = 'iron-brazier' + const bowl = createPart('iron-brazier/bowl') + const legs = createPart('iron-brazier/legs') + const coals = createPart('iron-brazier/coals') + const flame = createPart('iron-brazier/flame') + root.add(bowl.anchor, legs.anchor, coals.anchor, flame.anchor) + + // Işık ANCHOR'a takılı, üretilen içeriğe değil. Anchor rebuild'de + // değişmediği için configure() ateşi söndürmüyor — tüketicinin kendi + // eklediği nesneler de aynı sebeple hayatta kalıyor. + const light = new PointLight(0xffa04d, 0, 6, 2) + light.name = 'iron-brazier/firelight' + flame.anchor.add(light) + + let owned: BufferGeometry[] = [] + let blades: Blade[] = [] + let lit = true + let elapsed = 0 + + /** Kâsenin üst ağzının dünya yüksekliği. */ + const bowlTop = (): number => config.height * 0.5 + const bowlDepth = (): number => config.bowlRadius * 0.78 + + function buildBowl(random: () => number): BufferGeometry { + const tint = new Color() + const shade = (): Color => { + tint.copy(MEDIEVAL_PALETTE.iron) + tint.offsetHSL(0, jitter(random, 0.02), jitter(random, 0.055)) + return tint + } + + const depth = bowlDepth() + const centreY = bowlTop() - depth / 2 + const outerBottom = config.bowlRadius * 0.56 + const wall = config.bowlRadius * 0.055 + + // Dış kabuk ve iç kabuk aynı koni; içteki ters çevrilmiş, çünkü kâsenin + // içine bakıldığında yüzeyler bize dönük olmalı. + const outer = prismGeometry( + outerBottom, config.bowlRadius, depth, config.bowlSegments, + [0, centreY, 0], shade(), { capTop: false, capBottom: true }, + ) + const inner = flipGeometry(prismGeometry( + outerBottom - wall, config.bowlRadius - wall, depth, config.bowlSegments, + [0, centreY + wall, 0], shade(), { capTop: false, capBottom: true }, + )) + // Ağız çemberi dış ve iç kabuğun arasındaki boşluğu kapatır ve dövme bir + // dudak izlenimi verir. + const rim = bandGeometry( + config.bowlRadius + wall * 0.4, bowlTop(), wall * 2.6, wall * 1.6, + config.bowlSegments, shade(), + ) + + return mergeColoured([outer, inner, rim]) + } + + function buildLegs(random: () => number): BufferGeometry { + const tint = new Color() + const pieces: BufferGeometry[] = [] + const attachY = bowlTop() - bowlDepth() + const legLength = attachY * 1.16 + const thickness = config.bowlRadius * 0.1 + const tilt = 0.24 + + for (let i = 0; i < Math.max(1, config.legCount); i += 1) { + const angle = (i / Math.max(1, config.legCount)) * Math.PI * 2 + tint.copy(MEDIEVAL_PALETTE.iron) + tint.offsetHSL(0, jitter(random, 0.02), jitter(random, 0.05)) + + // Önce origin'in ALTINA sarkan bir çubuk kur, sonra dışa yatır, sonra + // yerine döndür. Sıra önemli: rotate her zaman origin etrafında döner. + const leg = boxGeometry([thickness, legLength, thickness], [0, -legLength / 2, 0], tint) + leg.rotateZ(tilt) + leg.rotateY(angle) + leg.translate(0, attachY, 0) + pieces.push(leg) + + // Pabuç: ayağın yere bastığı yassı taban. + const spread = Math.sin(tilt) * legLength + const foot = boxGeometry( + [thickness * 2.1, thickness * 0.7, thickness * 2.1], + [0, 0, 0], + tint, + ) + foot.rotateY(angle) + foot.translate( + Math.sin(angle) * spread, + attachY - Math.cos(tilt) * legLength + thickness * 0.35, + Math.cos(angle) * spread, + ) + pieces.push(foot) + } + + return mergeColoured(pieces) + } + + /** Kâsenin içine dağılmış kömür parçaları. `hot` olanlar ışıldar. */ + function coalPieces(random: () => number, hot: boolean): BufferGeometry[] { + const tint = new Color() + const pieces: BufferGeometry[] = [] + const floor = bowlTop() - bowlDepth() + config.bowlRadius * 0.06 + const count = hot ? 4 : 7 + + for (let i = 0; i < count; i += 1) { + const angle = random() * Math.PI * 2 + const radius = Math.sqrt(random()) * config.bowlRadius * 0.62 + const size = config.bowlRadius * (0.13 + random() * 0.1) + tint.copy(hot ? MEDIEVAL_PALETTE.charHot : MEDIEVAL_PALETTE.char) + tint.offsetHSL(jitter(random, 0.02), jitter(random, 0.08), jitter(random, hot ? 0.09 : 0.05)) + + const coal = boxGeometry( + [size, size * 0.62, size * 0.86], + [0, 0, 0], + tint, + ) + coal.rotateY(random() * Math.PI) + coal.rotateX(jitter(random, 0.25)) + coal.translate( + Math.sin(angle) * radius, + floor + size * 0.31 + (hot ? size * 0.12 : 0), + Math.cos(angle) * radius, + ) + pieces.push(coal) + } + + return pieces + } + + /** + * Alev dilleri. Her biri ayrı bir Group içinde, çünkü update() onları tek + * tek ölçekleyip döndürecek — birleştirilmiş tek geometri kıpırdayamazdı. + */ + function buildFlame(random: () => number, target: Group): { geometries: BufferGeometry[]; blades: Blade[] } { + const geometries: BufferGeometry[] = [] + const madeBlades: Blade[] = [] + const base = bowlTop() - bowlDepth() * 0.35 + const material = resolve('ember') + const hot = new Color() + const tip = new Color() + + for (let i = 0; i < config.flameCount; i += 1) { + const angle = (i / Math.max(1, config.flameCount)) * Math.PI * 2 + jitter(random, 0.4) + const radius = config.bowlRadius * (0.1 + random() * 0.42) + const reach = config.bowlRadius * (0.85 + random() * 1.15) + const width = config.bowlRadius * (0.16 + random() * 0.13) + + hot.copy(MEDIEVAL_PALETTE.ember).offsetHSL(0, jitter(random, 0.04), jitter(random, 0.05)) + tip.copy(MEDIEVAL_PALETTE.emberTip).offsetHSL(jitter(random, 0.02), 0, jitter(random, 0.05)) + + // Uç yarıçapı sıfır: koni. Renk dipten uca geçiş yapıyor, alevin dibi ile + // ucu aynı renk değildir. + const blade = prismGeometry( + width, 0, reach, 5, + [0, reach / 2, 0], hot, + { capBottom: true, capTop: false, colourTop: tip }, + ) + geometries.push(blade) + + const holder = new Group() + holder.name = `iron-brazier/flame-${i}` + holder.position.set(Math.sin(angle) * radius, base, Math.cos(angle) * radius) + const mesh = new Mesh(blade, material) + mesh.name = `iron-brazier/flame-${i}/blade` + mesh.userData.vibe3d = { model: '@medieval-kit/iron-brazier', part: 'flame', materialSlot: 'ember' } + holder.add(mesh) + target.add(holder) + + madeBlades.push({ + mesh: holder, + phase: random() * Math.PI * 2, + speed: 2.6 + random() * 2.9, + reach, + }) + } + + return { geometries, blades: madeBlades } + } + + function attach(target: Group, geometry: BufferGeometry, part: string, slot: Slot): void { + owned.push(geometry) + const mesh = new Mesh(geometry, resolve(slot)) + mesh.name = `iron-brazier/${part}` + mesh.userData.vibe3d = { model: '@medieval-kit/iron-brazier', part, materialSlot: slot } + target.add(mesh) + } + + function build(): void { + for (const geometry of owned) geometry.dispose() + owned = [] + blades = [] + // reset() sadece üretilmiş içeriği değiştirir; anchor'lar ve onlara + // takılanlar (ışık dâhil) yerinde kalır. + const random = createRandom(config.seed) + attach(bowl.reset(), buildBowl(random), 'bowl', 'iron') + attach(legs.reset(), buildLegs(random), 'legs', 'iron') + attach(coals.reset(), mergeColoured(coalPieces(random, false)), 'coals', 'char') + + const flameTarget = flame.reset() + const glowing = coalPieces(random, true) + const built = buildFlame(random, flameTarget) + owned.push(...built.geometries) + blades = built.blades + + const hotCoals = mergeColoured(glowing) + owned.push(hotCoals) + const hotMesh = new Mesh(hotCoals, resolve('ember')) + hotMesh.name = 'iron-brazier/hot-coals' + hotMesh.userData.vibe3d = { model: '@medieval-kit/iron-brazier', part: 'flame', materialSlot: 'ember' } + flameTarget.add(hotMesh) + + applyLit() + } + + function applyLit(): void { + // Üretilen alev içeriği content'te; ışık anchor'da. İkisi de sönmeli. + flame.content.visible = lit + light.visible = lit + light.position.y = bowlTop() + if (!lit) light.intensity = 0 + } + + build() + + const materials: MaterialBindings = { + get: (slot) => (SLOTS.includes(slot as Slot) ? resolve(slot as Slot) : undefined), + override: (slot, material) => { + if (!SLOTS.includes(slot as Slot)) return + overridesBySlot.set(slot as Slot, material) + build() + }, + reset: (slot) => { + if (!overridesBySlot.delete(slot as Slot)) return + build() + }, + } + + return { + root, + parts: { bowl, legs, coals, flame }, + actions: { + setLit: (next: boolean) => { + if (next === lit) return + lit = next + applyLit() + }, + isLit: () => lit, + }, + materials, + getConfig: () => config, + configure: (patch): ConfigureResult => { + const next = { ...config, ...patch } + const changed = (Object.keys(next) as Array) + .some((keyName) => next[keyName] !== config[keyName]) + if (!changed) return { rebuilt: false } + config = next + build() + return { rebuilt: true } + }, + update: (deltaSeconds: number) => { + if (!lit) return + // Kare atlamalarında alevin fırlamaması için adımı sınırla. + elapsed += Math.min(Math.max(deltaSeconds, 0), 0.05) + + let brightness = 0 + for (const blade of blades) { + // İki farklı frekansın toplamı: tek sinüs fazla düzenli, "nefes alan" + // bir ritim veriyor; ateş öyle yanmaz. + const wave = + Math.sin(elapsed * blade.speed + blade.phase) * 0.6 + + Math.sin(elapsed * blade.speed * 2.7 + blade.phase * 1.9) * 0.4 + blade.mesh.scale.y = 1 + wave * 0.22 + blade.mesh.scale.x = 1 - wave * 0.07 + blade.mesh.scale.z = blade.mesh.scale.x + blade.mesh.rotation.z = wave * 0.09 + brightness += wave + } + + const average = blades.length > 0 ? brightness / blades.length : 0 + light.intensity = 2.4 + average * 0.9 + }, + dispose: () => { + for (const geometry of owned) geometry.dispose() + owned = [] + blades = [] + bowl.reset() + legs.reset() + coals.reset() + flame.reset() + scope.dispose() + }, + } +} diff --git a/my-registry/models/wooden-barrel/model.ts b/my-registry/models/wooden-barrel/model.ts new file mode 100644 index 0000000..7321462 --- /dev/null +++ b/my-registry/models/wooden-barrel/model.ts @@ -0,0 +1,275 @@ +/** + * @medieval-kit/wooden-barrel + * + * Gerçek bir fıçı tek parça değildir: uçlara doğru daralan ayrı tahtalardan + * (stave) kurulur, demir çemberlerle sıkıştırılır, kapağı gövdenin içine + * gömülür ve tahtalar kapağın üstünde bir bilezik (chime) bırakır. Bu model + * onu böyle kuruyor — şişirilmiş bir silindir olarak değil. + * + * Bağımlılıklar: düz `three` ve `@medieval-kit/core`. scifi-kit'in + * primitive/aşınma boru hattına hiç dokunmuyor; WebGL yeterli. + */ +import { Color, Group, Mesh, type BufferGeometry, type Material } from 'three' + +import type { ConfigureResult, MaterialBindings, ModelInstance, PartHandle } from '@vibe3d/model.ts' +import { ResourceScope } from '@vibe3d/ownership.ts' + +import { + MEDIEVAL_PALETTE, + bandGeometry, + createMedievalMaterials, + createPart, + createRandom, + headGeometry, + jitter, + mergeColoured, + staveGeometry, + type Level, +} from '../core/index.ts' + +export interface WoodenBarrelConfig { + /** Toplam yükseklik (metre). */ + readonly height: number + /** Göbekteki (bilge) dış yarıçap (metre). */ + readonly radius: number + /** Uçların göbeğe göre ne kadar daraldığı. 0.16 = uçlar %84 genişlikte. */ + readonly taper: number + /** Tahta sayısı. Tek sayı, mükemmel simetriyi kırdığı için varsayılan. */ + readonly staveCount: number + /** Demir çember sayısı. */ + readonly hoopCount: number + /** Varyasyon tohumu. Aynı tohum her zaman aynı fıçıyı verir. */ + readonly seed: number +} + +export const woodenBarrelDefaults: WoodenBarrelConfig = { + height: 1.04, + radius: 0.41, + taper: 0.17, + staveCount: 13, + hoopCount: 4, + seed: 7, +} + +export interface WoodenBarrelParts { + /** Duvar tahtaları. */ + readonly staves: PartHandle + /** Üst ve alt kapaklar. */ + readonly heads: PartHandle + /** Demir çemberler. */ + readonly hoops: PartHandle +} + +const SLOTS = ['oak', 'iron'] as const +type Slot = (typeof SLOTS)[number] + +/** Fıçı profili: t ∈ [-1,1], uçlarda dar, göbekte geniş. */ +function profileAt(t: number, taper: number): number { + return 1 - taper * t * t +} + +/** + * Çemberler uçtan içe doğru simetrik yerleşir: en dıştakiler "chime" (uç) + * çemberi, içtekiler "bilge" (göbek) çemberi. + */ +function hoopPositions(count: number): number[] { + if (count <= 0) return [] + if (count === 1) return [0] + const outer = 0.87 + const inner = count <= 2 ? 0.87 : 0.33 + const pairs = Math.floor(count / 2) + const positions: number[] = [] + for (let i = 0; i < pairs; i += 1) { + const t = pairs === 1 ? outer : outer - (outer - inner) * (i / (pairs - 1)) + positions.push(t, -t) + } + if (count % 2 === 1) positions.push(0) + return positions +} + +export function createModel( + overrides: Partial = {}, +): ModelInstance { + let config: WoodenBarrelConfig = { ...woodenBarrelDefaults, ...overrides } + + // Modelin sahip olduğu kaynaklar. Tüketicinin verdiği materyaller buraya + // girmez, dolayısıyla dispose() onlara dokunmaz. + const scope = new ResourceScope() + const defaults = createMedievalMaterials(scope, SLOTS) + const overridesBySlot = new Map() + const resolve = (slot: Slot): Material => overridesBySlot.get(slot) ?? defaults[slot] + + // Kök ve anchor'lar modelin ömrü boyunca aynı NESNE kalır. configure() sadece + // içlerini yeniden kurar, böylece tüketicinin anchor'a taktığı ışık, etiket + // veya gameplay nesnesi rebuild'i atlatır. + const root = new Group() + root.name = 'wooden-barrel' + const staves = createPart('wooden-barrel/staves') + const heads = createPart('wooden-barrel/heads') + const hoops = createPart('wooden-barrel/hoops') + root.add(staves.anchor, heads.anchor, hoops.anchor) + + let owned: BufferGeometry[] = [] + + function buildStaves(random: () => number, half: number, levels: number[]): BufferGeometry { + const wallThickness = config.radius * 0.13 + const step = (Math.PI * 2) / config.staveCount + // Tahtalar arasında ince bir boşluk — "tek parça" değil "monte edilmiş" + // okunmasını sağlayan tek detay bu. + const gap = step * 0.055 + const tint = new Color() + const pieces: BufferGeometry[] = [] + + for (let index = 0; index < config.staveCount; index += 1) { + // Her tahta kendi ufak sapmalarını taşır: yarıçap, uç yüksekliği, ton. + // Mükemmel tekrar "üretilmiş" gibi okunur; kural: aynaları kır. + const radiusBias = 1 + jitter(random, 0.014) + const topBias = jitter(random, 0.006) + const bottomBias = jitter(random, 0.006) + + const shaped: Level[] = levels.map((t, level) => { + const edge = level === 0 ? bottomBias : level === levels.length - 1 ? topBias : 0 + return { + y: t * half + edge, + radius: config.radius * profileAt(t, config.taper) * radiusBias, + } + }) + + tint.copy(MEDIEVAL_PALETTE.oak) + tint.offsetHSL(jitter(random, 0.014), jitter(random, 0.05), jitter(random, 0.055)) + + pieces.push(staveGeometry( + shaped, + index * step + gap / 2, + (index + 1) * step - gap / 2, + wallThickness, + tint, + )) + } + + return mergeColoured(pieces) + } + + function buildHeads(random: () => number, half: number): BufferGeometry { + const wallThickness = config.radius * 0.13 + const endRadius = config.radius * profileAt(1, config.taper) + // Kapak gövdenin İÇİNE oturur ve uçtan biraz geride kalır; tahtaların + // üstte bıraktığı bilezik (chime) fıçıyı fıçı yapan siluet detayı. + const seatRadius = endRadius - wallThickness * 0.9 + const inset = config.height * 0.055 + const tint = new Color(MEDIEVAL_PALETTE.oakEnd) + tint.offsetHSL(0, jitter(random, 0.03), jitter(random, 0.03)) + + return mergeColoured([ + headGeometry(seatRadius, half - inset, config.staveCount, 'up', tint, 3, 0.06), + headGeometry(seatRadius, -half + inset, config.staveCount, 'down', tint, 3, 0.06), + ]) + } + + function buildHoops(random: () => number, half: number): BufferGeometry | undefined { + const positions = hoopPositions(config.hoopCount) + if (positions.length === 0) return undefined + + const tint = new Color() + const pieces: BufferGeometry[] = [] + + for (const t of positions) { + const seat = config.radius * profileAt(t, config.taper) + // Uç çemberleri daha geniştir: en çok zorlanan yer orası. + const bandHeight = config.height * (0.045 + 0.03 * Math.abs(t)) + tint.copy(MEDIEVAL_PALETTE.iron) + tint.offsetHSL(0, jitter(random, 0.02), jitter(random, 0.05)) + + pieces.push(bandGeometry( + seat + config.radius * 0.022, + t * half, + bandHeight, + config.radius * 0.05, + config.staveCount, + tint, + )) + } + + return mergeColoured(pieces) + } + + function build(): void { + for (const geometry of owned) geometry.dispose() + owned = [] + // reset() sadece üretilmiş içeriği değiştirir; anchor ve ona takılanlar kalır. + const staveTarget = staves.reset() + const headTarget = heads.reset() + const hoopTarget = hoops.reset() + + const random = createRandom(config.seed) + const half = config.height / 2 + // Beş seviye: uçlar, çeyrekler ve göbek. Lowpoly bir fıçı eğrisi için + // yeterli; altıncı seviye siluete ölçülebilir bir şey katmıyor. + const levels = [-1, -0.58, 0, 0.58, 1] + + const staveGeometryData = buildStaves(random, half, levels) + owned.push(staveGeometryData) + const staveMesh = new Mesh(staveGeometryData, resolve('oak')) + staveMesh.name = 'wooden-barrel/staves' + staveMesh.userData.vibe3d = { model: '@medieval-kit/wooden-barrel', part: 'staves', materialSlot: 'oak' } + staveTarget.add(staveMesh) + + const headGeometryData = buildHeads(random, half) + owned.push(headGeometryData) + const headMesh = new Mesh(headGeometryData, resolve('oak')) + headMesh.name = 'wooden-barrel/heads' + headMesh.userData.vibe3d = { model: '@medieval-kit/wooden-barrel', part: 'heads', materialSlot: 'oak' } + headTarget.add(headMesh) + + const hoopGeometryData = buildHoops(random, half) + if (hoopGeometryData) { + owned.push(hoopGeometryData) + const hoopMesh = new Mesh(hoopGeometryData, resolve('iron')) + hoopMesh.name = 'wooden-barrel/hoops' + hoopMesh.userData.vibe3d = { model: '@medieval-kit/wooden-barrel', part: 'hoops', materialSlot: 'iron' } + hoopTarget.add(hoopMesh) + } + } + + build() + + const materials: MaterialBindings = { + get: (slot) => (SLOTS.includes(slot as Slot) ? resolve(slot as Slot) : undefined), + override: (slot, material) => { + if (!SLOTS.includes(slot as Slot)) return + overridesBySlot.set(slot as Slot, material) + build() + }, + reset: (slot) => { + if (!overridesBySlot.delete(slot as Slot)) return + build() + }, + } + + return { + root, + parts: { staves, heads, hoops }, + actions: {}, + materials, + getConfig: () => config, + configure: (patch): ConfigureResult => { + const next = { ...config, ...patch } + const changed = (Object.keys(next) as Array) + .some((keyName) => next[keyName] !== config[keyName]) + if (!changed) return { rebuilt: false } + config = next + build() + return { rebuilt: true } + }, + update: () => undefined, + dispose: () => { + for (const geometry of owned) geometry.dispose() + owned = [] + staves.reset() + heads.reset() + hoops.reset() + // Sadece modelin kendi materyallerini siler; override edilenlere dokunmaz. + scope.dispose() + }, + } +} diff --git a/my-registry/models/wooden-crate/model.ts b/my-registry/models/wooden-crate/model.ts new file mode 100644 index 0000000..8e45048 --- /dev/null +++ b/my-registry/models/wooden-crate/model.ts @@ -0,0 +1,273 @@ +/** + * @medieval-kit/wooden-crate + * + * Sandık, kutu değildir: dört köşe dikmesine çakılmış yatay tahta sıralarıdır. + * Aradaki ince boşluklar ve dikmelerin dışa taşması, siluete "monte edilmiş" + * okunuşunu veren şey. Bu model onu böyle kuruyor. + * + * Fıçıyla aynı core'u paylaşıyor: aynı meşe tonu, aynı deterministik + * rastgelelik, aynı vertex-renk tekniği. Yan yana koyduğunuzda aynı + * katalogdan gelmiş gibi durmalarının sebebi bu. + */ +import { Color, Group, Mesh, type BufferGeometry, type Material } from 'three' + +import type { ConfigureResult, MaterialBindings, ModelInstance, PartHandle } from '@vibe3d/model.ts' +import { ResourceScope } from '@vibe3d/ownership.ts' + +import { + MEDIEVAL_PALETTE, + boxGeometry, + createMedievalMaterials, + createPart, + createRandom, + jitter, + mergeColoured, + type Vec3, +} from '../core/index.ts' + +export interface WoodenCrateConfig { + /** Genişlik (X ekseni, metre). */ + readonly width: number + /** Yükseklik (metre). */ + readonly height: number + /** Derinlik (Z ekseni, metre). */ + readonly depth: number + /** Her yüzdeki yatay tahta sırası sayısı. */ + readonly plankRows: number + /** Demir kayış sayısı. 0 = sade ahşap sandık. */ + readonly strapCount: number + /** Varyasyon tohumu. */ + readonly seed: number +} + +export const woodenCrateDefaults: WoodenCrateConfig = { + width: 0.66, + height: 0.52, + depth: 0.52, + plankRows: 3, + strapCount: 2, + seed: 3, +} + +export interface WoodenCrateParts { + /** Köşe dikmeleri. */ + readonly posts: PartHandle + /** Yan, üst ve alt tahtalar. */ + readonly planks: PartHandle + /** Demir kayışlar. */ + readonly straps: PartHandle +} + +const SLOTS = ['oak', 'iron'] as const +type Slot = (typeof SLOTS)[number] + +export function createModel( + overrides: Partial = {}, +): ModelInstance { + let config: WoodenCrateConfig = { ...woodenCrateDefaults, ...overrides } + + const scope = new ResourceScope() + const defaults = createMedievalMaterials(scope, SLOTS) + const overridesBySlot = new Map() + const resolve = (slot: Slot): Material => overridesBySlot.get(slot) ?? defaults[slot] + + const root = new Group() + root.name = 'wooden-crate' + const posts = createPart('wooden-crate/posts') + const planks = createPart('wooden-crate/planks') + const straps = createPart('wooden-crate/straps') + root.add(posts.anchor, planks.anchor, straps.anchor) + + let owned: BufferGeometry[] = [] + + /** + * Ölçü sözleşmesi. + * + * Z-FIGHTING KURALI: hiçbir iki yüzey aynı düzlemde, aynı yöne bakarak + * örtüşmemeli. Gerçek marangozlukta parçalar birbirine geçer; burada da öyle + * yapıyoruz. Dikmeler tahtalardan dışarı taşıyor, kapak ve taban çerçeveden + * biraz sarkıyor, tahtalar birbirine küt ekleniyor. Böylece her yüzey kendi + * düzleminde tek başına. + */ + const dims = () => { + const post = Math.min(config.width, config.depth) * 0.11 + const board = post * 0.5 + return { + post, + board, + /** Dikmelerin tahta yüzeyinden ne kadar dışarı taştığı. */ + postProud: board * 0.45, + /** Kapak ve tabanın çerçeveden sarkması. */ + overhang: board * 0.6, + half: config.height / 2, + } + } + + function buildPosts(random: () => number): BufferGeometry { + const { post, board, half } = dims() + const tint = new Color() + const pieces: BufferGeometry[] = [] + const x = config.width / 2 - post / 2 + const z = config.depth / 2 - post / 2 + // Dikmeler kapak ve tabanın İÇİNE giriyor; uçları o katı parçaların + // içinde kaldığı için görünmez ve hiçbir yüzeyle hizalanmaz. + const reach = half - board * 0.3 + + for (const [sx, sz] of [[-1, -1], [1, -1], [1, 1], [-1, 1]] as const) { + tint.copy(MEDIEVAL_PALETTE.oak) + // Dikmeler gövdeden biraz daha koyu: farklı kesim, daha çok yıpranma. + tint.offsetHSL(jitter(random, 0.01), jitter(random, 0.04), -0.045 + jitter(random, 0.02)) + pieces.push(boxGeometry([post, reach * 2, post], [sx * x, 0, sz * z], tint)) + } + + return mergeColoured(pieces) + } + + function buildPlanks(random: () => number): BufferGeometry { + const { board, postProud, overhang, half } = dims() + const tint = new Color() + const pieces: BufferGeometry[] = [] + + // Yan tahtalar dikmelerin ARKASINA çekili: dış yüzleri ±width/2 değil, + // ±(width/2 - postProud). Dikmelerle aynı düzleme oturmamalarının sebebi bu. + const faceX = config.width / 2 - postProud - board / 2 + const faceZ = config.depth / 2 - postProud - board / 2 + // Küt ek (butt joint): ön/arka tahtalar yan tahtaların iç yüzüne dayanır. + // Değiyorlar ama örtüşmüyorlar — kenar teması z-fighting üretmez. + const spanX = (config.width / 2 - postProud - board) * 2 + const spanZ = (config.depth / 2 - postProud - board) * 2 + + // Sıralar kapak ve tabanın içine girecek kadar uzanıyor, ama dikmelerin + // uçlarından FARKLI bir yükseklikte bitiyor. + const wallTop = half - board * 0.65 + const rows = Math.max(1, config.plankRows) + const gap = config.height * 0.012 + const rowHeight = (wallTop * 2 - gap * (rows - 1)) / rows + + for (let row = 0; row < rows; row += 1) { + const y = -wallTop + rowHeight / 2 + row * (rowHeight + gap) + for (const side of [-1, 1] as const) { + tint.copy(MEDIEVAL_PALETTE.oak) + tint.offsetHSL(jitter(random, 0.012), jitter(random, 0.05), jitter(random, 0.06)) + pieces.push(boxGeometry([spanX, rowHeight, board], [0, y, side * faceZ], tint)) + + tint.copy(MEDIEVAL_PALETTE.oak) + tint.offsetHSL(jitter(random, 0.012), jitter(random, 0.05), jitter(random, 0.06)) + pieces.push(boxGeometry([board, rowHeight, spanZ], [side * faceX, y, 0], tint)) + } + } + + // Kapak ve taban: çerçevenin üstüne/altına oturan, biraz sarkan tahta + // levhalar. Sarkma sayesinde yan yüzleri dikmelerin yüzleriyle hizalanmıyor. + const slabWidth = config.width + overhang * 2 + const slabDepth = config.depth + overhang * 2 + const slabBoards = 3 + const slabGap = slabDepth * 0.014 + const boardDepth = (slabDepth - slabGap * (slabBoards - 1)) / slabBoards + + for (const [y, shade] of [[half - board / 2, 0.03], [-half + board / 2, -0.05]] as const) { + for (let i = 0; i < slabBoards; i += 1) { + tint.copy(MEDIEVAL_PALETTE.oakEnd) + tint.offsetHSL(jitter(random, 0.01), jitter(random, 0.04), shade + jitter(random, 0.05)) + pieces.push(boxGeometry( + [slabWidth, board, boardDepth], + [0, y, -slabDepth / 2 + boardDepth / 2 + i * (boardDepth + slabGap)], + tint, + )) + } + } + + return mergeColoured(pieces) + } + + function buildStraps(random: () => number): BufferGeometry | undefined { + if (config.strapCount <= 0) return undefined + + const { post } = dims() + const tint = new Color() + const pieces: BufferGeometry[] = [] + const bandHeight = config.height * 0.07 + const proud = post * 0.3 + + for (let i = 0; i < config.strapCount; i += 1) { + // Kayışlar üstten ve alttan içe doğru simetrik yerleşir. + const t = config.strapCount === 1 + ? 0 + : 0.6 - (1.2 * i) / (config.strapCount - 1) + const y = (t * config.height) / 2 + tint.copy(MEDIEVAL_PALETTE.iron) + tint.offsetHSL(0, jitter(random, 0.02), jitter(random, 0.06)) + + // Ön/arka kayışlar köşelerde dışa taşıyor; yan kayışlar onlara VARMADAN + // bitiyor. Böylece dört parçanın üst yüzleri köşede üst üste binmiyor. + pieces.push( + boxGeometry([config.width + proud * 2, bandHeight, proud], [0, y, config.depth / 2], tint), + boxGeometry([config.width + proud * 2, bandHeight, proud], [0, y, -config.depth / 2], tint), + boxGeometry([proud, bandHeight, config.depth - proud], [config.width / 2, y, 0], tint), + boxGeometry([proud, bandHeight, config.depth - proud], [-config.width / 2, y, 0], tint), + ) + } + + return mergeColoured(pieces) + } + + function attach(target: Group, geometry: BufferGeometry | undefined, part: string, slot: Slot): void { + if (!geometry) return + owned.push(geometry) + const mesh = new Mesh(geometry, resolve(slot)) + mesh.name = `wooden-crate/${part}` + mesh.userData.vibe3d = { model: '@medieval-kit/wooden-crate', part, materialSlot: slot } + target.add(mesh) + } + + function build(): void { + for (const geometry of owned) geometry.dispose() + owned = [] + // reset() sadece üretilmiş içeriği değiştirir; anchor ve ona takılanlar kalır. + const random = createRandom(config.seed) + attach(posts.reset(), buildPosts(random), 'posts', 'oak') + attach(planks.reset(), buildPlanks(random), 'planks', 'oak') + attach(straps.reset(), buildStraps(random), 'straps', 'iron') + } + + build() + + const materials: MaterialBindings = { + get: (slot) => (SLOTS.includes(slot as Slot) ? resolve(slot as Slot) : undefined), + override: (slot, material) => { + if (!SLOTS.includes(slot as Slot)) return + overridesBySlot.set(slot as Slot, material) + build() + }, + reset: (slot) => { + if (!overridesBySlot.delete(slot as Slot)) return + build() + }, + } + + return { + root, + parts: { posts, planks, straps }, + actions: {}, + materials, + getConfig: () => config, + configure: (patch): ConfigureResult => { + const next = { ...config, ...patch } + const changed = (Object.keys(next) as Array) + .some((keyName) => next[keyName] !== config[keyName]) + if (!changed) return { rebuilt: false } + config = next + build() + return { rebuilt: true } + }, + update: () => undefined, + dispose: () => { + for (const geometry of owned) geometry.dispose() + owned = [] + posts.reset() + planks.reset() + straps.reset() + scope.dispose() + }, + } +} diff --git a/my-registry/package.json b/my-registry/package.json new file mode 100644 index 0000000..6c9aba8 --- /dev/null +++ b/my-registry/package.json @@ -0,0 +1,46 @@ +{ + "name": "@medieval-kit/registry", + "version": "0.1.0", + "description": "A lowpoly medieval procedural model library for Vibe3D and Three.js.", + "type": "module", + "license": "MIT", + "author": "CRTkafa", + "homepage": "https://github.com/CRTkafa/medieval-kit#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/CRTkafa/medieval-kit.git", + "directory": "my-registry" + }, + "bugs": { + "url": "https://github.com/CRTkafa/medieval-kit/issues" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "keywords": [ + "vibe3d", + "vibe3d-registry", + "threejs", + "3d-models", + "medieval", + "lowpoly", + "procedural" + ], + "vibe3d": { + "registry": "./dist/registry.json" + }, + "files": [ + "dist", + "README.md", + "LICENSE" + ], + "scripts": { + "build": "bun build.ts", + "validate": "vibe3d registry validate dist/registry.json", + "prepublishOnly": "bun build.ts && vibe3d registry validate dist/registry.json" + }, + "peerDependencies": { + "three": ">=0.185.0" + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..41cc759 --- /dev/null +++ b/package.json @@ -0,0 +1,26 @@ +{ + "name": "medieval-kit-workspace", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview", + "typecheck": "tsc --noEmit", + "verify": "bun scripts/verify-model.ts", + "registry:build": "bun my-registry/build.ts", + "registry:validate": "vibe3d registry validate my-registry/dist/registry.json", + "viewer:build": "vite build --config vite.viewer.config.ts && bun scripts/build-artifact.ts" + }, + "dependencies": { + "three": "^0.185.1" + }, + "devDependencies": { + "@types/node": "^22.15.3", + "@types/three": "^0.185.4", + "@webgpu/types": "^0.1.72", + "typescript": "^5.9.2", + "vibe3d": "^0.0.1", + "vite": "^7.1.5" + } +} diff --git a/scripts/build-artifact.ts b/scripts/build-artifact.ts new file mode 100644 index 0000000..d79783d --- /dev/null +++ b/scripts/build-artifact.ts @@ -0,0 +1,49 @@ +/** + * dist-viewer/ çıktısını tek dosyalık, kendi kendine yeten bir HTML'e indirger. + * + * Artifact sayfaları katı bir CSP altında çalışır: harici host'a istek yok. + * Tek istisna Google Fonts. Bu yüzden JS ve CSS gömülü olmak zorunda. + * + * Çalıştır: + * bunx vite build --config vite.viewer.config.ts + * bun scripts/build-artifact.ts + */ +import { readFile, writeFile } from 'node:fs/promises' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const projectRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const distRoot = join(projectRoot, 'dist-viewer') + +// Sadece gerçekten kullanılan ağırlıklar. Google Fonts her ağırlığı tembel +// yükler; istemediğiniz ağırlıkları istemek boşuna CSS büyütür. +const FONTS = + 'https://fonts.googleapis.com/css2?family=Archivo:wght@400;700' + + '&family=IBM+Plex+Mono:wght@400;500;600&display=swap' + +const css = await readFile(join(distRoot, 'viewer.css'), 'utf8') +const js = await readFile(join(distRoot, 'viewer.js'), 'utf8') + +// Gömülü script içindeki bir `vibe3d Model Tezgahı + + + + +
+ +` + +const output = join(distRoot, 'artifact.html') +await writeFile(output, html, 'utf8') + +const kb = (value: number) => `${(value / 1024).toFixed(0)} KB` +console.log(`dist-viewer/artifact.html yazıldı`) +console.log(` CSS ${kb(css.length)} · JS ${kb(js.length)} · toplam ${kb(html.length)}`) diff --git a/scripts/verify-model.ts b/scripts/verify-model.ts new file mode 100644 index 0000000..38fca58 --- /dev/null +++ b/scripts/verify-model.ts @@ -0,0 +1,400 @@ +/** + * Kurulan modelleri tarayıcı olmadan doğrular. + * + * vibe3d'nin conformance listesinden gerçekten test edilebilir olanlar: + * sonlu geometri ve geçerli sınırlar, configure() sonrası kök nesnenin + * kimliğini koruması, materyal sahipliği ve idempotent dispose(). + * + * Buna ek olarak kendi kitimiz için sarım (winding) denetimi var — elle + * yazılmış geometride yanlış sarım sessizce içten görünen yüzler bırakır ve + * bu ancak belirli bir kamera açısında fark edilir. İki ayrı ölçüt kullanılıyor + * çünkü iki ayrı geometri türü var: dönel gövdeler için radyal hizalama, + * kapalı katılar için işaretli hacim. + * + * Çalıştır: bun scripts/verify-model.ts + */ +import { Box3, Mesh, MeshStandardMaterial, PointLight, Vector3, type Object3D } from 'three/webgpu' + +import { findZFighting } from './zfight.ts' +import { createModel as createGauge } from '@/models/scifi-kit/pressure-gauge/model.ts' +import { createModel as createBarrel } from '@/models/medieval-kit/wooden-barrel/model.ts' +import { createModel as createCrate } from '@/models/medieval-kit/wooden-crate/model.ts' +import { createModel as createBrazier } from '@/models/medieval-kit/iron-brazier/model.ts' + +const failures: string[] = [] +function expect(label: string, condition: boolean): void { + console.log(` ${condition ? 'PASS' : 'FAIL'} ${label}`) + if (!condition) failures.push(label) +} + +/* ------------------------------------------------------------------ ölçüm */ + +interface GeometryReport { + meshes: number + triangles: number + nonFinitePositions: number + sizeMetres: [number, number, number] +} + +function inspect(root: Object3D): GeometryReport { + let meshes = 0 + let triangles = 0 + let nonFinitePositions = 0 + + root.traverse((object) => { + if (!(object instanceof Mesh)) return + meshes += 1 + const position = object.geometry.getAttribute('position') + const index = object.geometry.getIndex() + triangles += (index ? index.count : position.count) / 3 + const array = position.array as ArrayLike + for (let i = 0; i < array.length; i += 1) { + if (!Number.isFinite(array[i])) nonFinitePositions += 1 + } + }) + + const size = new Box3().setFromObject(root).getSize(new Vector3()) + return { + meshes, + triangles, + nonFinitePositions, + sizeMetres: [+size.x.toFixed(2), +size.y.toFixed(2), +size.z.toFixed(2)], + } +} + +/** + * Bir parçanın altındaki ilk Mesh. + * + * Anchor'ın doğrudan çocuğu artık mesh DEĞİL, değiştirilebilir content + * Group'u — protokolün gerektirdiği yapı bu. Test de o yüzden aşağı iniyor. + */ +function firstMesh(part: { anchor: Object3D }): Mesh { + let found: Mesh | undefined + part.anchor.traverse((object) => { + if (!found && object instanceof Mesh) found = object + }) + if (!found) throw new Error(`${part.anchor.name} altında mesh yok`) + return found +} + +/** Dünya uzayındaki tüm üçgenleri toplar. */ +function worldTriangles(root: Object3D): Array<[Vector3, Vector3, Vector3]> { + const triangles: Array<[Vector3, Vector3, Vector3]> = [] + root.updateWorldMatrix(true, true) + root.traverse((object) => { + if (!(object instanceof Mesh)) return + const position = object.geometry.getAttribute('position') + const index = object.geometry.getIndex() + const count = index ? index.count : position.count + for (let i = 0; i < count; i += 3) { + const corners = [0, 1, 2].map((k) => { + const vertex = index ? index.getX(i + k) : i + k + return object.localToWorld(new Vector3().fromBufferAttribute(position, vertex)) + }) as [Vector3, Vector3, Vector3] + triangles.push(corners) + } + }) + return triangles +} + +/** + * Dönel gövdeler için: dış kabuğun RADYAL yüzeyleri eksenden dışa bakmalı. + * + * Ölçüt: yüzey normali · (eksenden ağırlık merkezine birim vektör). + * Dışa bakanda +1'e, ters sarımda -1'e yakın. + * + * Kritik ayrım: tahtaların yan (boşluk) yüzeyleri teğetseldir, yani bu çarpım + * onlar için tanımı gereği ~0'dır ve işareti sadece kayan nokta gürültüsüdür. + * Radyal bir test onları yargılayamaz, o yüzden ayıklanır ve kaç tane + * ayıklandığı raporlanır — sessizce elenmezler. + */ +const RADIAL_THRESHOLD = 0.5 + +function radialWinding(root: Object3D, shellRatio = 0.94): { + radialFaces: number + inwardFaces: number + tangentialSkipped: number +} { + const triangles = worldTriangles(root) + let maxRadius = 0 + for (const [a, b, c] of triangles) { + const centroid = a.clone().add(b).add(c).divideScalar(3) + maxRadius = Math.max(maxRadius, Math.hypot(centroid.x, centroid.z)) + } + + let radialFaces = 0 + let inwardFaces = 0 + let tangentialSkipped = 0 + + for (const [a, b, c] of triangles) { + const centroid = a.clone().add(b).add(c).divideScalar(3) + if (Math.hypot(centroid.x, centroid.z) < maxRadius * shellRatio) continue + + const normal = new Vector3() + .crossVectors(b.clone().sub(a), c.clone().sub(a)) + if (normal.lengthSq() === 0) continue + normal.normalize() + if (Math.abs(normal.y) > 0.7) continue + + const outward = new Vector3(centroid.x, 0, centroid.z).normalize() + const alignment = normal.dot(outward) + + if (Math.abs(alignment) < RADIAL_THRESHOLD) { + tangentialSkipped += 1 + continue + } + radialFaces += 1 + if (alignment < 0) inwardFaces += 1 + } + + return { radialFaces, inwardFaces, tangentialSkipped } +} + +/** + * Kapalı katılar için: işaretli hacim. + * + * Kapalı bir yüzeyin hacmi Σ a·(b×c)/6 ile bulunur. Sarım dışa bakıyorsa + * pozitif, içe bakıyorsa negatif çıkar. Sandık tamamen kapalı kutulardan + * kurulu olduğu için bu ölçüt orada radyal testten daha keskin. + */ +function signedVolume(root: Object3D): number { + let volume = 0 + for (const [a, b, c] of worldTriangles(root)) { + volume += a.dot(new Vector3().crossVectors(b, c)) / 6 + } + return volume +} + +/** + * Eş düzlemli çakışma denetimi. + * + * Aynı düzlemde, aynı yöne bakan ve alanları örtüşen iki yüzey, kamera + * oynadıkça sırayla kazanır ve yüzey titrer. Kenardan değen yüzeyler sorun + * değildir, o yüzden ölçüt gerçek alan örtüşmesi. + * + * Bu kontrol gözle bulunan bir hatadan sonra eklendi: sandığın dikmeleri, yan + * tahtaları ve kapağı dış yüzeylerini aynı düzleme koyuyordu. + */ +function checkNoZFighting(label: string, root: Object3D): void { + const report = findZFighting(root) + console.log(` ${label}: ${report.faces} yüz · eş düzlem grubu ${report.coplanarGroups} · çakışma ${report.overlaps}`) + for (const sample of report.samples) console.log(` ${sample}`) + expect(`${label} eş düzlemli çakışma yok`, report.overlaps === 0) +} + +/* ----------------------------------------------------- ortak protokol testi */ + +interface ProtocolModel { + root: Object3D + parts: Record + materials: { get(slot: string): unknown; override(slot: string, material: never): void } + configure(patch: Record): { rebuilt: boolean } + dispose(): void +} + +function checkOwnership(model: ProtocolModel, ownSlot: string, borrowSlot: string): void { + let ownDisposed = false + ;(model.materials.get(ownSlot) as MeshStandardMaterial) + .addEventListener('dispose', () => { ownDisposed = true }) + + let borrowedDisposed = false + const borrowed = new MeshStandardMaterial({ name: 'consumer-owned' }) + borrowed.addEventListener('dispose', () => { borrowedDisposed = true }) + model.materials.override(borrowSlot, borrowed as never) + expect('override materyali geri okunuyor', model.materials.get(borrowSlot) === borrowed) + + model.dispose() + model.dispose() + expect('modelin kendi materyali dispose edildi', ownDisposed) + expect('ödünç materyale dokunulmadı', !borrowedDisposed) + expect('dispose() idempotent (iki kez çağrıldı, hata yok)', true) +} + +function checkStableIdentity( + model: ProtocolModel, + anchorName: string, + patch: Record, +): void { + const rootBefore = model.root + const anchorBefore = model.parts[anchorName]!.anchor + const result = model.configure(patch) + expect('configure() rebuilt=true bildiriyor', result.rebuilt) + expect('kök nesne kimliği korundu', model.root === rootBefore) + expect('anchor nesne kimliği korundu', model.parts[anchorName]!.anchor === anchorBefore) + expect('değişmeyen patch rebuilt=false', model.configure(patch).rebuilt === false) +} + +/* ------------------------------------------------------------------ testler */ + +console.log('\n@scifi-kit/pressure-gauge') +{ + const gauge = createGauge() + const report = inspect(gauge.root) + console.log(` ${report.meshes} mesh · ${report.triangles} üçgen · ${report.sizeMetres.join(' x ')} m`) + + expect('geometri üretildi', report.meshes > 0 && report.triangles > 0) + expect('NaN/Infinity vertex yok', report.nonFinitePositions === 0) + expect('sınırlar sonlu', report.sizeMetres.every(Number.isFinite)) + + const before = new Map() + gauge.root.traverse((object) => before.set(object, object.rotation.z)) + gauge.triggerPressureTest() + for (let i = 0; i < 30; i += 1) gauge.update(1 / 60) + let animated = 0 + gauge.root.traverse((object) => { + if (Math.abs(object.rotation.z - (before.get(object) ?? 0)) > 1e-6) animated += 1 + }) + expect('update() ibreyi hareket ettiriyor', animated === 1) + + gauge.dispose() + gauge.dispose() + expect('dispose() idempotent (iki kez çağrıldı, hata yok)', true) +} + +console.log('\n@medieval-kit/wooden-barrel') +{ + const barrel = createBarrel() + const report = inspect(barrel.root) + console.log(` ${report.meshes} mesh · ${report.triangles} üçgen · ${report.sizeMetres.join(' x ')} m`) + + expect('geometri üretildi', report.meshes > 0 && report.triangles > 0) + expect('NaN/Infinity vertex yok', report.nonFinitePositions === 0) + expect('üç semantik parça (tahtalar, kapaklar, çemberler)', report.meshes === 3) + expect('lowpoly bütçesinde (< 1500 üçgen)', report.triangles < 1500) + + checkNoZFighting('z-fight', barrel.root) + + const winding = radialWinding(barrel.root) + console.log( + ` radyal dış yüz: ${winding.radialFaces} · ters sarım: ${winding.inwardFaces}` + + ` · teğetsel (yargılanamaz, atlandı): ${winding.tangentialSkipped}`, + ) + expect('dış kabukta ters sarım yok', winding.inwardFaces === 0) + expect('test anlamlı sayıda radyal yüz gördü', winding.radialFaces >= 50) + + const colour = firstMesh(barrel.parts.staves).geometry.getAttribute('color') + const distinct = new Set() + for (let i = 0; i < colour.count; i += 1) { + distinct.add(`${colour.getX(i).toFixed(3)},${colour.getY(i).toFixed(3)},${colour.getZ(i).toFixed(3)}`) + } + expect(`tahta başına ayrı ton (${distinct.size} farklı renk)`, distinct.size >= 10) + + const twinA = createBarrel({ seed: 21 }) + const twinB = createBarrel({ seed: 21 }) + const other = createBarrel({ seed: 22 }) + const firstVertex = (model: ReturnType): string => { + const position = firstMesh(model.parts.staves).geometry.getAttribute('position') + return `${position.getX(0)},${position.getY(0)},${position.getZ(0)}` + } + expect('aynı tohum aynı geometri', firstVertex(twinA) === firstVertex(twinB)) + expect('farklı tohum farklı geometri', firstVertex(twinA) !== firstVertex(other)) + twinA.dispose(); twinB.dispose(); other.dispose() + + checkStableIdentity(barrel as unknown as ProtocolModel, 'staves', { staveCount: 22, hoopCount: 6 }) + expect('yeni topoloji üretildi', inspect(barrel.root).triangles > report.triangles) + checkOwnership(barrel as unknown as ProtocolModel, 'iron', 'oak') +} + +console.log('\n@medieval-kit/wooden-crate') +{ + const crate = createCrate() + const report = inspect(crate.root) + console.log(` ${report.meshes} mesh · ${report.triangles} üçgen · ${report.sizeMetres.join(' x ')} m`) + + expect('geometri üretildi', report.meshes > 0 && report.triangles > 0) + expect('NaN/Infinity vertex yok', report.nonFinitePositions === 0) + expect('üç semantik parça (dikmeler, tahtalar, kayışlar)', report.meshes === 3) + expect('lowpoly bütçesinde (< 1500 üçgen)', report.triangles < 1500) + + // Sandık tamamen kapalı kutulardan kurulu, yani işaretli hacmi pozitif olmalı. + const volume = signedVolume(crate.root) + const boundingVolume = report.sizeMetres[0] * report.sizeMetres[1] * report.sizeMetres[2] + console.log(` işaretli hacim: ${volume.toFixed(4)} m³ · sınır kutusu: ${boundingVolume.toFixed(4)} m³`) + expect('işaretli hacim pozitif (sarım dışa bakıyor)', volume > 0) + expect('hacim sınır kutusundan küçük (içi boş sandık)', volume < boundingVolume * 0.6) + + // Üretilen içerik content'te; anchor her zaman o content Group'unu taşır. + expect('kayışsız yapılandırma çalışıyor', + createCrate({ strapCount: 0 }).parts.straps.content.children.length === 0) + + // Sandık tamamen kutulardan kurulu, yani z-fighting'e en açık model. + // Birkaç yapılandırmada birden denetleniyor. + checkNoZFighting('z-fight (varsayılan)', crate.root) + for (const variant of [{ plankRows: 1 }, { plankRows: 6 }, { strapCount: 4 }]) { + const sample = createCrate(variant) + checkNoZFighting(`z-fight ${JSON.stringify(variant)}`, sample.root) + sample.dispose() + } + + checkStableIdentity(crate as unknown as ProtocolModel, 'planks', { plankRows: 5, strapCount: 3 }) + checkOwnership(crate as unknown as ProtocolModel, 'iron', 'oak') +} + +console.log('\n@medieval-kit/iron-brazier') +{ + const brazier = createBrazier() + const report = inspect(brazier.root) + console.log(` ${report.meshes} mesh · ${report.triangles} üçgen · ${report.sizeMetres.join(' x ')} m`) + + expect('geometri üretildi', report.meshes > 0 && report.triangles > 0) + expect('NaN/Infinity vertex yok', report.nonFinitePositions === 0) + expect('lowpoly bütçesinde (< 1500 üçgen)', report.triangles < 1500) + + // Kâsenin dış kabuğu dönel; ayaklar ve kömürler dış yarıçapın altında kaldığı + // için bu filtre onları zaten eliyor. + checkNoZFighting('z-fight', brazier.root) + + const winding = radialWinding(brazier.root, 0.97) + console.log( + ` radyal dış yüz: ${winding.radialFaces} · ters sarım: ${winding.inwardFaces}` + + ` · teğetsel (atlandı): ${winding.tangentialSkipped}`, + ) + expect('kâse dış kabuğunda ters sarım yok', winding.inwardFaces === 0) + + // Ateş ışığı modelin kendi parçası ve flame anchor'ında yaşıyor. + const light = brazier.parts.flame.anchor.children.find((child) => child instanceof PointLight) + expect('model bir PointLight taşıyor', light instanceof PointLight) + + // Tipli actions — fıçı ve sandıkta olmayan protokol parçası. + expect('varsayılan olarak yanıyor', brazier.actions.isLit()) + + const bladeScales = (): number[] => brazier.parts.flame.content.children + .filter((child) => child.name.startsWith('iron-brazier/flame-')) + .map((child) => child.scale.y) + + const restScales = bladeScales() + expect('alev dilleri var', restScales.length === 5) + for (let i = 0; i < 40; i += 1) brazier.update(1 / 60) + const movedScales = bladeScales() + const moved = movedScales.some((value, i) => Math.abs(value - restScales[i]!) > 1e-4) + expect('update() alevi titretiyor', moved) + expect('ışık şiddeti sıfırdan büyük', (light as PointLight).intensity > 0) + + // Söndür: alev gizlenmeli, ışık kapanmalı, update() bir şey yapmamalı. + brazier.actions.setLit(false) + expect('setLit(false) sonrası isLit() false', !brazier.actions.isLit()) + expect('ışık kapandı', (light as PointLight).intensity === 0) + expect('alev ve kor kömürler gizlendi', !brazier.parts.flame.content.visible) + const beforeIdle = bladeScales() + for (let i = 0; i < 40; i += 1) brazier.update(1 / 60) + expect('sönükken update() hiçbir şeyi kıpırdatmıyor', + bladeScales().every((value, i) => value === beforeIdle[i])) + + brazier.actions.setLit(true) + expect('tekrar yakılabiliyor', brazier.actions.isLit()) + + // Tüketici eklentisi rebuild'i atlatmalı — protokolün asıl vaadi bu. + const marker = new PointLight(0x00ff00, 1) + marker.name = 'consumer-marker' + brazier.parts.bowl.anchor.add(marker) + brazier.configure({ bowlSegments: 8 }) + expect('tüketicinin taktığı nesne rebuild sonrası duruyor', + brazier.parts.bowl.anchor.children.includes(marker)) + expect('modelin ışığı rebuild sonrası duruyor', + brazier.parts.flame.anchor.children.includes(light as PointLight)) + + checkOwnership(brazier as unknown as ProtocolModel, 'iron', 'char') +} + +console.log(failures.length === 0 ? '\nTüm kontroller geçti.' : `\n${failures.length} kontrol BAŞARISIZ.`) +if (failures.length > 0) process.exitCode = 1 diff --git a/scripts/zfight.ts b/scripts/zfight.ts new file mode 100644 index 0000000..2f325c1 --- /dev/null +++ b/scripts/zfight.ts @@ -0,0 +1,137 @@ +/** + * Eş düzlemli çakışma (z-fighting) denetimi. + * + * İki yüzey tam olarak aynı düzlemde, aynı yöne bakıyor ve alanları + * örtüşüyorsa, hangisinin önde olduğu derinlik tamponunun kayan nokta + * hassasiyetine kalır. Kamera oynadıkça kazanan değişir ve yüzey titrer. + * + * Kenardan değen yüzeyler (bitişik tahtalar) sorun DEĞİLDİR — örtüşme yoktur. + * O yüzden test bounding box'a değil, gerçek alan örtüşmesine bakıyor: + * bir üçgenin ağırlık merkezi diğerinin İÇİNDE mi? + * + * Çalıştır: bun scripts/zfight.ts + */ +import { Mesh, Vector3, type Object3D } from 'three/webgpu' + +interface Face { + readonly a: Vector3 + readonly b: Vector3 + readonly c: Vector3 + readonly centroid: Vector3 + readonly mesh: string +} + +export interface ZFightReport { + faces: number + coplanarGroups: number + overlaps: number + samples: string[] +} + +/** Düzlem kimliği: yuvarlanmış normal + orijine uzaklık. */ +function planeKey(normal: Vector3, offset: number): string { + const r = (value: number): string => (Math.round(value * 1000) / 1000).toFixed(3) + return `${r(normal.x)},${r(normal.y)},${r(normal.z)}|${r(offset)}` +} + +/** Düzlemin baskın eksenini atarak 2B'ye indir. */ +function project(point: Vector3, axis: 'x' | 'y' | 'z'): [number, number] { + if (axis === 'x') return [point.y, point.z] + if (axis === 'y') return [point.x, point.z] + return [point.x, point.y] +} + +function insideTriangle( + p: [number, number], + a: [number, number], + b: [number, number], + c: [number, number], +): boolean { + const sign = (p1: [number, number], p2: [number, number], p3: [number, number]): number => + (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1]) + const d1 = sign(p, a, b) + const d2 = sign(p, b, c) + const d3 = sign(p, c, a) + const negative = d1 < 0 || d2 < 0 || d3 < 0 + const positive = d1 > 0 || d2 > 0 || d3 > 0 + // Kenarda olmak yeterli değil; kesin olarak içeride olmalı. + return !(negative && positive) +} + +export function findZFighting(root: Object3D): ZFightReport { + const faces: Face[] = [] + root.updateWorldMatrix(true, true) + root.traverse((object) => { + if (!(object instanceof Mesh)) return + const position = object.geometry.getAttribute('position') + const index = object.geometry.getIndex() + const count = index ? index.count : position.count + for (let i = 0; i < count; i += 3) { + const [a, b, c] = [0, 1, 2].map((k) => { + const vertex = index ? index.getX(i + k) : i + k + return object.localToWorld(new Vector3().fromBufferAttribute(position, vertex)) + }) as [Vector3, Vector3, Vector3] + faces.push({ + a, b, c, + centroid: a.clone().add(b).add(c).divideScalar(3), + mesh: object.name, + }) + } + }) + + // Aynı düzlem + aynı bakış yönü olanları grupla. + const groups = new Map() + for (const face of faces) { + const normal = new Vector3() + .crossVectors(face.b.clone().sub(face.a), face.c.clone().sub(face.a)) + if (normal.lengthSq() === 0) continue + normal.normalize() + const key = planeKey(normal, normal.dot(face.a)) + const bucket = groups.get(key) + if (bucket) bucket.push(face) + else groups.set(key, [face]) + } + + let overlaps = 0 + let coplanarGroups = 0 + const samples: string[] = [] + + for (const [key, group] of groups) { + if (group.length < 2) continue + coplanarGroups += 1 + const normal = key.split('|')[0]!.split(',').map(Number) + const dominant = Math.abs(normal[0]!) > Math.abs(normal[1]!) + ? (Math.abs(normal[0]!) > Math.abs(normal[2]!) ? 'x' : 'z') + : (Math.abs(normal[1]!) > Math.abs(normal[2]!) ? 'y' : 'z') + + for (let i = 0; i < group.length; i += 1) { + for (let j = i + 1; j < group.length; j += 1) { + const first = group[i]! + const second = group[j]! + // Aynı mesh içindeki komşu üçgenler zaten aynı yüzeyi döşüyor. + const pa = project(first.a, dominant) + const pb = project(first.b, dominant) + const pc = project(first.c, dominant) + const qa = project(second.a, dominant) + const qb = project(second.b, dominant) + const qc = project(second.c, dominant) + + if ( + insideTriangle(project(second.centroid, dominant), pa, pb, pc) || + insideTriangle(project(first.centroid, dominant), qa, qb, qc) + ) { + overlaps += 1 + if (samples.length < 6) { + const p = first.centroid + samples.push( + `${first.mesh} ↔ ${second.mesh} @ ` + + `(${p.x.toFixed(3)}, ${p.y.toFixed(3)}, ${p.z.toFixed(3)}) düzlem ${key}`, + ) + } + } + } + } + } + + return { faces: faces.length, coplanarGroups, overlaps, samples } +} diff --git a/src/lib/vibe3d/materials.ts b/src/lib/vibe3d/materials.ts new file mode 100644 index 0000000..144decb --- /dev/null +++ b/src/lib/vibe3d/materials.ts @@ -0,0 +1,20 @@ +import type { Material } from 'three' + +export interface MaterialRequest { + readonly slot: string + readonly model: string + readonly variant?: string +} + +export interface MaterialHandle { + readonly material: T + release(): void +} + +export interface MaterialSource { + acquire(request: MaterialRequest): MaterialHandle +} + +export function borrowedMaterial(material: T): MaterialHandle { + return { material, release: () => undefined } +} diff --git a/src/lib/vibe3d/model.ts b/src/lib/vibe3d/model.ts new file mode 100644 index 0000000..c080c32 --- /dev/null +++ b/src/lib/vibe3d/model.ts @@ -0,0 +1,31 @@ +import type { Group, Material, Object3D } from 'three' + +export interface PartHandle { + readonly anchor: T + readonly content: Object3D +} + +export interface ConfigureResult { + readonly rebuilt: boolean +} + +export interface ModelInstance< + Config extends object, + Parts extends object = Record, + Actions extends object = Record, +> { + readonly root: Group + readonly parts: Parts + readonly actions: Actions + readonly materials: MaterialBindings + getConfig(): Readonly + configure(patch: Partial): ConfigureResult + update(deltaSeconds: number): void + dispose(): void +} + +export interface MaterialBindings { + get(slot: string): Material | undefined + override(slot: string, material: Material): void + reset(slot: string): void +} diff --git a/src/lib/vibe3d/ownership.ts b/src/lib/vibe3d/ownership.ts new file mode 100644 index 0000000..353d5df --- /dev/null +++ b/src/lib/vibe3d/ownership.ts @@ -0,0 +1,31 @@ +import type { BufferGeometry, Material, Texture } from 'three' + +export class ResourceScope { + readonly #geometries = new Set() + readonly #materials = new Set() + readonly #textures = new Set() + #disposed = false + + ownGeometry(geometry: T): T { + this.#geometries.add(geometry) + return geometry + } + + ownMaterial(material: T): T { + this.#materials.add(material) + return material + } + + ownTexture(texture: T): T { + this.#textures.add(texture) + return texture + } + + dispose(): void { + if (this.#disposed) return + this.#disposed = true + for (const texture of this.#textures) texture.dispose() + for (const material of this.#materials) material.dispose() + for (const geometry of this.#geometries) geometry.dispose() + } +} diff --git a/src/lib/vibe3d/scifi-kit/generator/batching.ts b/src/lib/vibe3d/scifi-kit/generator/batching.ts new file mode 100644 index 0000000..2e03480 --- /dev/null +++ b/src/lib/vibe3d/scifi-kit/generator/batching.ts @@ -0,0 +1,101 @@ +import { + Float32BufferAttribute, + Matrix4, + Mesh, + type BufferGeometry, + type Group, + type Material, +} from 'three/webgpu' +import { mergeGeometries, mergeVertices } from 'three/addons/utils/BufferGeometryUtils.js' + +export interface StaticBatchOptions { + /** Maps a source material to the material used by its merged batch. */ + readonly resolveMaterial?: (source: Material) => Material + /** Extra vertex attributes to retain for a resolved material. */ + readonly retainedAttributes?: ( + resolved: Material, + source: Material, + ) => readonly string[] + /** Names the merged mesh created for a material batch. */ + readonly meshName?: (material: Material) => string +} + +/** + * Collapses the static meshes below `root` into one mesh per resolved material. + * Transforms are baked relative to `root`, so the resulting group remains safe + * to animate as one assembly. Source geometries are disposed after the merge. + */ +export function mergeStaticByMaterial( + root: Group, + options: StaticBatchOptions = {}, +): BufferGeometry[] { + root.updateMatrixWorld(true) + const rootInverse = new Matrix4().copy(root.matrixWorld).invert() + const batches = new Map() + const sourceGeometries = new Set() + + root.traverse((object) => { + if (!(object instanceof Mesh) || Array.isArray(object.material)) return + const source = object.geometry as BufferGeometry + const sourceMaterial = object.material as Material + const material = options.resolveMaterial?.(sourceMaterial) ?? sourceMaterial + const retained = new Set([ + 'position', + 'normal', + 'uv', + ...(options.retainedAttributes?.(material, sourceMaterial) ?? []), + ]) + + sourceGeometries.add(source) + const geometry = source.index ? source.toNonIndexed() : source.clone() + geometry.applyMatrix4(object.matrixWorld).applyMatrix4(rootInverse) + if (!geometry.getAttribute('normal')) geometry.computeVertexNormals() + if (!geometry.getAttribute('uv')) addPlanarUv(geometry) + for (const name of Object.keys(geometry.attributes)) { + if (!retained.has(name)) geometry.deleteAttribute(name) + } + + const geometries = batches.get(material) ?? [] + geometries.push(geometry) + batches.set(material, geometries) + }) + + root.clear() + const mergedGeometries: BufferGeometry[] = [] + for (const [material, geometries] of batches) { + const merged = mergeGeometries(geometries, false) + for (const geometry of geometries) geometry.dispose() + if (!merged) throw new Error(`Failed to merge static batch for material ${material.name || '(unnamed)'}`) + // Sources are expanded before merging so independently-authored meshes can + // carry different attribute sets safely. Re-index the finished batch once + // those attributes have been normalized: mergeVertices hashes every + // retained attribute (normal, UV, wear data, etc.), so only vertices that + // are visually identical are shared. This removes the 3-vertices-per- + // triangle expansion without smoothing hard edges or changing shaders. + const indexed = mergeVertices(merged, 1e-6) + merged.dispose() + indexed.computeBoundingSphere() + const mesh = new Mesh(indexed, material) + mesh.name = options.meshName?.(material) ?? material.name + root.add(mesh) + mergedGeometries.push(indexed) + } + for (const geometry of sourceGeometries) geometry.dispose() + return mergedGeometries +} + +function addPlanarUv(geometry: BufferGeometry): void { + geometry.computeBoundingBox() + const bounds = geometry.boundingBox! + const sizeX = Math.max(bounds.max.x - bounds.min.x, 0.001) + const sizeY = Math.max(bounds.max.y - bounds.min.y, 0.001) + const positions = geometry.getAttribute('position') + const uvs: number[] = [] + for (let index = 0; index < positions.count; index += 1) { + uvs.push( + (positions.getX(index) - bounds.min.x) / sizeX, + (positions.getY(index) - bounds.min.y) / sizeY, + ) + } + geometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2)) +} diff --git a/src/lib/vibe3d/scifi-kit/generator/effects.ts b/src/lib/vibe3d/scifi-kit/generator/effects.ts new file mode 100644 index 0000000..6092f06 --- /dev/null +++ b/src/lib/vibe3d/scifi-kit/generator/effects.ts @@ -0,0 +1,129 @@ +import { + DataTexture, + LinearFilter, + LinearMipmapLinearFilter, + RepeatWrapping, + RGBAFormat, + SRGBColorSpace, + UnsignedByteType, +} from 'three/webgpu' + +const DEFAULT_SMOKE_TEXTURE_SIZE = 48 + +function smokeSmoothstep(edge0: number, edge1: number, value: number): number { + const t = Math.min(1, Math.max(0, (value - edge0) / (edge1 - edge0))) + return t * t * (3 - 2 * t) +} + +function smokeEllipse( + px: number, + py: number, + centreX: number, + centreY: number, + radiusX: number, + radiusY: number, +): number { + const distance = Math.hypot((px - centreX) / radiusX, (py - centreY) / radiusY) + return 1 - smokeSmoothstep(0.52, 1.05, distance) +} + +function smokeWisp( + px: number, + py: number, + phase: number, + amplitude: number, + width: number, +): number { + const lift = (py + 1) * 0.5 + const centreX = Math.sin((py + phase) * 5.2) * amplitude + + Math.sin((py + phase) * 10.7) * 0.045 + const taper = width * (0.72 + lift * 0.55) + const lateral = 1 - smokeSmoothstep(0.38, 1.0, Math.abs(px - centreX) / taper) + const ends = 1 - smokeSmoothstep(0.84, 1.03, Math.abs(py)) + return lateral * ends +} + +function smokeHash(x: number, y: number): number { + const value = Math.sin(x * 127.1 + y * 311.7) * 43758.5453 + return value - Math.floor(value) +} + +function smokeValueNoise(u: number, v: number, frequency: number): number { + const x = u * frequency + const y = v * frequency + const x0 = Math.floor(x) + const y0 = Math.floor(y) + const x1 = (x0 + 1) % frequency + const y1 = (y0 + 1) % frequency + const tx = x - x0 + const ty = y - y0 + const sx = tx * tx * (3 - 2 * tx) + const sy = ty * ty * (3 - 2 * ty) + const low = smokeHash(x0, y0) * (1 - sx) + smokeHash(x1, y0) * sx + const high = smokeHash(x0, y1) * (1 - sx) + smokeHash(x1, y1) * sx + return low * (1 - sy) + high * sy +} + +function tileableFbm(u: number, v: number): number { + let total = 0 + let amplitude = 0.5 + let weight = 0 + for (const frequency of [3, 6, 12, 24]) { + total += smokeValueNoise(u, v, frequency) * amplitude + weight += amplitude + amplitude *= 0.5 + } + return total / weight +} + +export interface SmokeTextureOptions { + /** Square texture resolution. Defaults to 48 pixels. */ + readonly size?: number +} + +/** + * CPU-baked once per model, then sampled by every smoke card. DataTexture keeps + * this usable by the headless asset renderer as well as the browser preview; + * there is no DOM canvas dependency and no per-frame texture work. + */ +export function createSmokeTexture(options: SmokeTextureOptions = {}): DataTexture { + const size = Math.max(2, Math.round(options.size ?? DEFAULT_SMOKE_TEXTURE_SIZE)) + const data = new Uint8Array(size * size * 4) + const centre = (size - 1) * 0.5 + for (let y = 0; y < size; y += 1) { + for (let x = 0; x < size; x += 1) { + const u = x / size + const v = y / size + const px = (x - centre) / centre + const py = (y - centre) / centre + const noise = tileableFbm(u, v) + const fineWisp = smokeWisp(px, py, 0.08, 0.2, 0.24) + const splitWisp = smokeWisp(px, py, 0.41, -0.16, 0.18) * 0.72 + const highWisp = smokeWisp(px, py, 0.73, 0.12, 0.15) * 0.62 + const billow = Math.max( + smokeEllipse(px, py, -0.14, -0.18, 0.42, 0.55) * 0.34, + smokeEllipse(px, py, 0.13, 0.28, 0.36, 0.48) * 0.28, + ) + const envelope = Math.max(fineWisp, splitWisp, highWisp, billow) + const density = Math.min(1, Math.max(0, envelope * (0.3 + noise * 0.95) - 0.08)) + const alpha = Math.floor(255 * density ** 1.12) + const lift = Math.min(1, Math.max(0, 0.52 - px * 0.24 + py * 0.34)) + const shade = Math.floor(150 + (240 - 150) * lift * (1 - density * 0.4)) + const index = (y * size + x) * 4 + data[index] = shade + data[index + 1] = shade + data[index + 2] = shade + data[index + 3] = alpha + } + } + + const textureMap = new DataTexture(data, size, size, RGBAFormat, UnsignedByteType) + textureMap.colorSpace = SRGBColorSpace + textureMap.wrapS = RepeatWrapping + textureMap.wrapT = RepeatWrapping + textureMap.magFilter = LinearFilter + textureMap.minFilter = LinearMipmapLinearFilter + textureMap.generateMipmaps = true + textureMap.needsUpdate = true + return textureMap +} diff --git a/src/lib/vibe3d/scifi-kit/generator/generator.test.ts b/src/lib/vibe3d/scifi-kit/generator/generator.test.ts new file mode 100644 index 0000000..07772bb --- /dev/null +++ b/src/lib/vibe3d/scifi-kit/generator/generator.test.ts @@ -0,0 +1,211 @@ +import assert from 'node:assert/strict' +import { describe, test } from 'node:test' +import { + Float32BufferAttribute, + Group, + InstancedMesh, + Matrix4, + Mesh, + MeshPhysicalMaterial, + SphereGeometry, +} from 'three/webgpu' +import { + createWearMaterial, + createSmokeTexture, + createStaticGlbSnapshot, + bakeSurfaceAttributes, + filletRing, + flatPlate, + mergeStaticByMaterial, + MaterialLibrary, + mountMaterialSource, + prism, + tuneMaterial, + type MaterialHandle, +} from './index.ts' + +describe('generator primitives', () => { + test('prism authors the geometry and wear attributes expected by the shared helpers', () => { + const material = new MeshPhysicalMaterial() + const mesh = prism(material, [2, 1, 0.5], [1, 2, 3], { + chamfer: [0.2, 0.1, 0.05, 0], + fillet: 0.04, + bevel: 0.03, + }) + + assert.deepEqual(mesh.position.toArray(), [1, 2, 3]) + assert.ok(mesh.geometry.getAttribute('position').count > 0) + assert.equal(mesh.geometry.getAttribute('normal').count, + mesh.geometry.getAttribute('position').count, + ) + assert.equal(mesh.geometry.getAttribute('aEdge').itemSize, 1) + assert.equal(mesh.geometry.getAttribute('aPlane').itemSize, 2) + + mesh.geometry.dispose() + material.dispose() + }) + + test('filletRing and flatPlate expose reusable authoring metadata', () => { + const ring = filletRing([[1, 1], [-1, 1], [-1, -1], [1, -1]], 0.1, 2) + assert.equal(ring.length, 12) + assert.ok(ring.every((point) => Number.isFinite(point.nx + point.ny))) + + const material = new MeshPhysicalMaterial() + const engraved = flatPlate(material, [2, 0.25], [0, 0, 0]) + const painted = flatPlate(material, [2, 0.25], [0, 0, 0], [0, 0, 0], false) + assert.equal(engraved.userData.grooveCross, 'y') + assert.equal(painted.userData.grooveCross, undefined) + engraved.geometry.dispose() + painted.geometry.dispose() + material.dispose() + }) +}) + +describe('generator assembly helpers', () => { + test('static GLB snapshots bake wear and omit explicitly excluded effects', () => { + const root = new Group() + const sourceMaterial = new MeshPhysicalMaterial({ color: 0x8b9294, roughness: 0.5, metalness: 0.3 }) + const worn = prism(sourceMaterial, [2, 1, 0.5], [0, 0, 0]) + const smoke = new Group() + smoke.name = 'preview smoke' + smoke.userData.excludeFromExport = true + const orbGeometry = new SphereGeometry(0.1, 8, 6) + const orbMaterial = new MeshPhysicalMaterial({ color: 0x55ffff }) + const orbs = new InstancedMesh(orbGeometry, orbMaterial, 2) + const instanceMatrix = new Matrix4() + orbs.setMatrixAt(0, instanceMatrix.makeTranslation(-0.2, 0, 0)) + orbs.setMatrixAt(1, instanceMatrix.makeTranslation(0.2, 0, 0)) + root.add(worn, smoke, orbs) + const wornUv = worn.geometry.getAttribute('uv') + wornUv.setXY(0, 0.5, 0.5) + wornUv.setXY(1, 0.5, 0.5) + wornUv.setXY(2, 0.5, 0.5) + bakeSurfaceAttributes(root, new Map([ + [sourceMaterial, { rub: 1, grime: 0.8, scratch: 0.9 }], + ])) + + const snapshot = createStaticGlbSnapshot(root, { textureSize: 32 }) + assert.equal(snapshot.root.getObjectByName('preview smoke'), undefined) + assert.equal(snapshot.root.getObjectByProperty('isInstancedMesh', true), undefined) + let bakedMeshes = 0 + let bakedSurface: Mesh | undefined + snapshot.root.traverse((object) => { + if (!(object instanceof Mesh)) return + bakedMeshes += 1 + if (object.name.includes('baked surface')) bakedSurface = object + assert.ok(object.material instanceof MeshPhysicalMaterial) + const material = object.material as MeshPhysicalMaterial + assert.equal(object.geometry.getAttribute('aMask'), undefined) + if (material.normalMap) { + const tangent = object.geometry.getAttribute('tangent') + assert.ok(tangent) + for (let index = 0; index < tangent.count; index += 1) { + const length = Math.hypot(tangent.getX(index), tangent.getY(index), tangent.getZ(index)) + assert.ok(Math.abs(length - 1) < 1e-5, `tangent ${index} has length ${length}`) + assert.equal(Math.abs(tangent.getW(index)), 1) + } + } + if (!material.map && !material.normalMap && !material.roughnessMap && !material.metalnessMap) { + assert.equal(object.geometry.getAttribute('uv'), undefined) + } + }) + assert.ok(bakedMeshes >= 3) + const bakedMaterial = bakedSurface?.material as MeshPhysicalMaterial | undefined + assert.ok(bakedSurface?.geometry.getAttribute('color')) + assert.ok(bakedMaterial?.map) + assert.ok(bakedMaterial?.normalMap) + assert.ok(bakedMaterial?.roughnessMap) + assert.ok(worn.geometry.getAttribute('aMask'), 'the live model must remain unchanged') + + snapshot.dispose() + worn.geometry.dispose() + sourceMaterial.dispose() + orbGeometry.dispose() + orbMaterial.dispose() + }) + + test('smoke textures are deterministic and do not require a DOM canvas', () => { + const first = createSmokeTexture({ size: 16 }) + const second = createSmokeTexture({ size: 16 }) + assert.equal(first.image.width, 16) + assert.equal(first.image.height, 16) + assert.deepEqual(first.image.data, second.image.data) + assert.ok((first.image.data as Uint8Array).some((value, index) => index % 4 === 3 && value > 0)) + first.dispose() + second.dispose() + }) + + test('mergeStaticByMaterial remaps batches and retains requested attributes', () => { + const root = new Group() + const sourceA = new MeshPhysicalMaterial({ name: 'source-a' }) + const sourceB = new MeshPhysicalMaterial({ name: 'source-b' }) + const resolved = new MeshPhysicalMaterial({ name: 'resolved' }) + const first = prism(sourceA, [1, 1, 1], [-1, 0, 0]) + const second = prism(sourceB, [1, 1, 1], [1, 0, 0]) + const tag = (mesh: Mesh) => { + const count = mesh.geometry.getAttribute('position').count + mesh.geometry.setAttribute('batchTag', new Float32BufferAttribute(new Float32Array(count), 1)) + } + tag(first) + tag(second) + root.add(first, second) + + const geometries = mergeStaticByMaterial(root, { + resolveMaterial: () => resolved, + retainedAttributes: () => ['aEdge', 'aPlane', 'batchTag'], + meshName: () => 'merged-test-batch', + }) + + assert.equal(geometries.length, 1) + assert.equal(root.children.length, 1) + const merged = root.children[0] as Mesh + assert.equal(merged.material, resolved) + assert.equal(merged.name, 'merged-test-batch') + assert.ok(merged.geometry.getAttribute('batchTag')) + assert.ok(merged.geometry.index, 'merged batches should be re-indexed after attribute normalization') + assert.ok( + merged.geometry.getAttribute('position').count < (merged.geometry.index?.count ?? 0), + 're-indexing should share visually identical triangle vertices', + ) + merged.geometry.computeBoundingBox() + assert.ok((merged.geometry.boundingBox?.min.x ?? 0) < -1.4) + assert.ok((merged.geometry.boundingBox?.max.x ?? 0) > 1.4) + + merged.geometry.dispose() + sourceA.dispose() + sourceB.dispose() + resolved.dispose() + }) + + test('material helpers are configurable without asset-specific names', () => { + const material = new MeshPhysicalMaterial() + const handle: MaterialHandle = { key: 'test', material, release: () => undefined } + tuneMaterial(handle, 0x123456, 0.7, 0.4, { clearcoat: 0.2, emissive: 1.5 }) + assert.equal(material.color.getHex(), 0x123456) + assert.equal(material.roughness, 0.7) + assert.equal(material.metalness, 0.4) + assert.equal(material.emissiveIntensity, 1.5) + + const wear = createWearMaterial({ name: 'generator-test / wear', clearcoat: 0.1 }) + assert.equal(wear.name, 'generator-test / wear') + assert.equal(wear.clearcoat, 0.1) + wear.dispose() + material.dispose() + }) + + test('material sources can be mounted and restored', () => { + const material = new MeshPhysicalMaterial() + let acquired = 0 + const restore = mountMaterialSource({ + acquire(_options, key) { + acquired += 1 + return { key, material, release: () => undefined } + }, + }) + const handle = new MaterialLibrary().acquire({ recipeId: 'paint', palette: 'blue' }) + assert.equal(handle.material, material) + assert.equal(acquired, 1) + restore() + material.dispose() + }) +}) diff --git a/src/lib/vibe3d/scifi-kit/generator/glb.ts b/src/lib/vibe3d/scifi-kit/generator/glb.ts new file mode 100644 index 0000000..d38885a --- /dev/null +++ b/src/lib/vibe3d/scifi-kit/generator/glb.ts @@ -0,0 +1,913 @@ +import { + BufferGeometry, + Color, + DataTexture, + Float32BufferAttribute, + Group, + InstancedMesh, + LinearFilter, + LinearMipmapLinearFilter, + Matrix4, + Mesh, + MeshPhysicalMaterial, + RepeatWrapping, + RGBAFormat, + SRGBColorSpace, + Texture, + UnsignedByteType, + type BufferAttribute, + type InterleavedBufferAttribute, + type Object3D, +} from 'three/webgpu' +import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js' + +export interface StaticGlbOptions { + /** Resolution of each embedded baked wear texture. */ + readonly textureSize?: number + /** Additional objects to omit from the static snapshot. */ + readonly exclude?: (object: Object3D) => boolean +} + +export interface StaticGlbSnapshot { + readonly root: Object3D + dispose(): void +} + +interface SurfaceProfile { + readonly colour: readonly [number, number, number] + readonly roughness: number + readonly metalness: number + readonly rub: number + readonly grime: number + readonly scratch: number +} + +interface GeometryBucket { + readonly profile: SurfaceProfile + readonly positions: number[] + readonly normals: number[] + readonly uvs: number[] + readonly colours: number[] +} + +interface BakeContext { + readonly textureSize: number + readonly materials: Map + readonly standardMaterials: Map + readonly ownedGeometries: Set + readonly ownedMaterials: Set + readonly ownedTextures: Set + readonly geometryVariants: Map> + readonly preparedNormalMaterials: Set +} + +type ReadableAttribute = BufferAttribute | InterleavedBufferAttribute + +const WEAR_ATTRIBUTE_NAMES = ['aMask', 'aColor', 'aSurface', 'aWearDir'] as const + +/** + * Clones a model into a static, glTF-safe hierarchy. Preview-only node + * materials are replaced without mutating the live model. + */ +export function createStaticGlbSnapshot( + source: Object3D, + options: StaticGlbOptions = {}, +): StaticGlbSnapshot { + const root = source.clone(true) + root.name = source.name || 'static-model' + root.userData = { + ...root.userData, + staticGlb: true, + animations: 'omitted', + proceduralWear: 'baked to vertex colors and PBR textures', + } + + const context: BakeContext = { + textureSize: Math.max(32, Math.round(options.textureSize ?? 512)), + materials: new Map(), + standardMaterials: new Map(), + ownedGeometries: new Set(), + ownedMaterials: new Set(), + ownedTextures: new Set(), + geometryVariants: new Map(), + preparedNormalMaterials: new Set(), + } + + const excluded: Object3D[] = [] + const wornMeshes: Mesh[] = [] + root.traverse((object) => { + if (object !== root && (object.userData.excludeFromExport === true || options.exclude?.(object))) { + excluded.push(object) + return + } + if (object instanceof Mesh && hasWearAttributes(object.geometry)) wornMeshes.push(object) + }) + for (const object of excluded) object.removeFromParent() + expandInstancedMeshes(root) + + for (const mesh of wornMeshes) { + if (!mesh.parent) continue + const replacement = bakeWearMesh(mesh, context) + mesh.parent.add(replacement) + mesh.removeFromParent() + } + prepareStandardMaterials(root, context) + prepareGeometryForExport(root, context) + + return { + root, + dispose: () => { + for (const geometry of context.ownedGeometries) geometry.dispose() + for (const material of context.ownedMaterials) material.dispose() + for (const texture of context.ownedTextures) texture.dispose() + }, + } +} + +function prepareStandardMaterials(root: Object3D, context: BakeContext): void { + root.traverse((object) => { + if (!(object instanceof Mesh)) return + const sources = Array.isArray(object.material) ? object.material : [object.material] + const materials = sources.map((source) => { + if (!(source instanceof MeshPhysicalMaterial) || context.ownedMaterials.has(source)) return source + const existing = context.standardMaterials.get(source) + if (existing) return existing + const material = source.clone() + packDataTextureOrm(material, context) + context.standardMaterials.set(source, material) + context.ownedMaterials.add(material) + return material + }) + object.material = Array.isArray(object.material) ? materials : materials[0]! + }) +} + +function expandInstancedMeshes(root: Object3D): void { + const instances: InstancedMesh[] = [] + root.traverse((object) => { + if (object instanceof InstancedMesh) instances.push(object) + }) + const matrix = new Matrix4() + for (const source of instances) { + if (!source.parent) continue + const group = new Group() + group.name = source.name + group.position.copy(source.position) + group.quaternion.copy(source.quaternion) + group.scale.copy(source.scale) + group.visible = source.visible + group.userData = { ...source.userData, gpuInstances: 'expanded for portable glTF' } + for (let index = 0; index < source.count; index += 1) { + source.getMatrixAt(index, matrix) + const mesh = new Mesh(source.geometry, source.material) + mesh.name = `${source.name} / instance ${String(index + 1).padStart(2, '0')}` + matrix.decompose(mesh.position, mesh.quaternion, mesh.scale) + mesh.castShadow = source.castShadow + mesh.receiveShadow = source.receiveShadow + group.add(mesh) + } + source.parent.add(group) + source.removeFromParent() + } +} + +function prepareGeometryForExport(root: Object3D, context: BakeContext): void { + root.traverse((object) => { + if (!(object instanceof Mesh)) return + const materials = Array.isArray(object.material) ? object.material : [object.material] + const usesUv = materials.some(materialUsesUv) + const usesNormalMap = materials.some((material) => ( + material instanceof MeshPhysicalMaterial && material.normalMap !== null + )) + const variantKey = `${usesUv ? 'uv' : 'no-uv'}/${usesNormalMap ? 'tangent' : 'no-tangent'}` + object.geometry = geometryVariant(object.geometry, variantKey, context, (geometry) => { + stripNonGltfAttributes(geometry) + if (!usesUv) geometry.deleteAttribute('uv') + if (usesNormalMap) { + if (!geometry.getAttribute('uv')) { + throw new Error(`Cannot export normal-mapped mesh without UVs: ${object.name}`) + } + computePortableTangents(geometry) + } else { + geometry.deleteAttribute('tangent') + } + geometry.computeBoundingSphere() + }) + for (const material of materials) { + if (!(material instanceof MeshPhysicalMaterial) || context.preparedNormalMaterials.has(material)) continue + prepareDataTextureNormal(material, usesNormalMap, context) + context.preparedNormalMaterials.add(material) + } + }) +} + +/** + * Computes explicit glTF tangent frames and supplies a normalized fallback + * when a triangle's UVs collapse to a point or line. Three's built-in tangent + * builder leaves those vertices at (0, 0, 0), which glTF correctly rejects. + */ +function computePortableTangents(geometry: BufferGeometry): void { + const position = geometry.getAttribute('position') + const normal = geometry.getAttribute('normal') + const uv = geometry.getAttribute('uv') + const index = geometry.index + const tangentSum = new Float64Array(position.count * 3) + const bitangentSum = new Float64Array(position.count * 3) + const triangleIndices = index?.count ?? position.count + + for (let offset = 0; offset < triangleIndices; offset += 3) { + const ia = index?.getX(offset) ?? offset + const ib = index?.getX(offset + 1) ?? offset + 1 + const ic = index?.getX(offset + 2) ?? offset + 2 + const edge1: [number, number, number] = [ + position.getX(ib) - position.getX(ia), + position.getY(ib) - position.getY(ia), + position.getZ(ib) - position.getZ(ia), + ] + const edge2: [number, number, number] = [ + position.getX(ic) - position.getX(ia), + position.getY(ic) - position.getY(ia), + position.getZ(ic) - position.getZ(ia), + ] + const du1 = uv.getX(ib) - uv.getX(ia) + const dv1 = uv.getY(ib) - uv.getY(ia) + const du2 = uv.getX(ic) - uv.getX(ia) + const dv2 = uv.getY(ic) - uv.getY(ia) + const determinant = du1 * dv2 - du2 * dv1 + let tangent: [number, number, number] + let bitangent: [number, number, number] + + if (Number.isFinite(determinant) && Math.abs(determinant) > 1e-10) { + const inverse = 1 / determinant + tangent = [ + (edge1[0] * dv2 - edge2[0] * dv1) * inverse, + (edge1[1] * dv2 - edge2[1] * dv1) * inverse, + (edge1[2] * dv2 - edge2[2] * dv1) * inverse, + ] + bitangent = [ + (edge2[0] * du1 - edge1[0] * du2) * inverse, + (edge2[1] * du1 - edge1[1] * du2) * inverse, + (edge2[2] * du1 - edge1[2] * du2) * inverse, + ] + } else { + tangent = squaredLength(edge1) >= squaredLength(edge2) ? edge1 : edge2 + const averageNormal = normalize3([ + normal.getX(ia) + normal.getX(ib) + normal.getX(ic), + normal.getY(ia) + normal.getY(ib) + normal.getY(ic), + normal.getZ(ia) + normal.getZ(ib) + normal.getZ(ic), + ], [0, 1, 0]) + tangent = orthogonalize(tangent, averageNormal) + if (squaredLength(tangent) < 1e-20) tangent = fallbackTangent(averageNormal) + bitangent = cross3(averageNormal, tangent) + } + + for (const vertex of [ia, ib, ic]) { + const target = vertex * 3 + tangentSum[target] += tangent[0] + tangentSum[target + 1] += tangent[1] + tangentSum[target + 2] += tangent[2] + bitangentSum[target] += bitangent[0] + bitangentSum[target + 1] += bitangent[1] + bitangentSum[target + 2] += bitangent[2] + } + } + + const tangents = new Float32Array(position.count * 4) + for (let vertex = 0; vertex < position.count; vertex += 1) { + const source = vertex * 3 + const target = vertex * 4 + const n = normalize3([ + normal.getX(vertex), + normal.getY(vertex), + normal.getZ(vertex), + ], [0, 1, 0]) + let tangent = orthogonalize([ + tangentSum[source], + tangentSum[source + 1], + tangentSum[source + 2], + ], n) + tangent = normalize3(tangent, fallbackTangent(n)) + const bitangent: [number, number, number] = [ + bitangentSum[source], + bitangentSum[source + 1], + bitangentSum[source + 2], + ] + const handedness = dot3(cross3(n, tangent), bitangent) < 0 ? -1 : 1 + tangents[target] = tangent[0] + tangents[target + 1] = tangent[1] + tangents[target + 2] = tangent[2] + tangents[target + 3] = handedness + } + geometry.setAttribute('tangent', new Float32BufferAttribute(tangents, 4)) +} + +function orthogonalize( + vector: [number, number, number], + normal: [number, number, number], +): [number, number, number] { + const projection = dot3(vector, normal) + return [ + vector[0] - normal[0] * projection, + vector[1] - normal[1] * projection, + vector[2] - normal[2] * projection, + ] +} + +function fallbackTangent(normal: [number, number, number]): [number, number, number] { + const absolute = normal.map(Math.abs) + const helper: [number, number, number] = absolute[0] <= absolute[1] && absolute[0] <= absolute[2] + ? [1, 0, 0] + : absolute[1] <= absolute[2] + ? [0, 1, 0] + : [0, 0, 1] + return normalize3(cross3(helper, normal), [1, 0, 0]) +} + +function normalize3( + vector: [number, number, number], + fallback: [number, number, number], +): [number, number, number] { + const length = Math.sqrt(squaredLength(vector)) + return Number.isFinite(length) && length > 1e-10 + ? [vector[0] / length, vector[1] / length, vector[2] / length] + : fallback +} + +function cross3( + left: [number, number, number], + right: [number, number, number], +): [number, number, number] { + return [ + left[1] * right[2] - left[2] * right[1], + left[2] * right[0] - left[0] * right[2], + left[0] * right[1] - left[1] * right[0], + ] +} + +function dot3(left: [number, number, number], right: [number, number, number]): number { + return left[0] * right[0] + left[1] * right[1] + left[2] * right[2] +} + +function squaredLength(vector: [number, number, number]): number { + return dot3(vector, vector) +} + +function geometryVariant( + source: BufferGeometry, + key: string, + context: BakeContext, + prepare: (geometry: BufferGeometry) => void, +): BufferGeometry { + if (context.ownedGeometries.has(source)) { + prepare(source) + return source + } + const variants = context.geometryVariants.get(source) ?? new Map() + const existing = variants.get(key) + if (existing) return existing + const geometry = source.clone() + prepare(geometry) + variants.set(key, geometry) + context.geometryVariants.set(source, variants) + context.ownedGeometries.add(geometry) + return geometry +} + +const GLTF_ATTRIBUTES = new Set([ + 'position', + 'normal', + 'tangent', + 'uv', + 'uv1', + 'color', + 'skinIndex', + 'skinWeight', +]) + +function stripNonGltfAttributes(geometry: BufferGeometry): void { + for (const name of Object.keys(geometry.attributes)) { + if (!GLTF_ATTRIBUTES.has(name)) geometry.deleteAttribute(name) + } +} + +const UV_TEXTURE_PROPERTIES = [ + 'map', + 'normalMap', + 'roughnessMap', + 'metalnessMap', + 'aoMap', + 'emissiveMap', + 'alphaMap', + 'lightMap', + 'bumpMap', + 'displacementMap', + 'clearcoatMap', + 'clearcoatNormalMap', + 'clearcoatRoughnessMap', + 'sheenColorMap', + 'sheenRoughnessMap', + 'transmissionMap', + 'thicknessMap', +] as const + +function materialUsesUv(material: unknown): boolean { + if (typeof material !== 'object' || material === null) return false + const values = material as Record + return UV_TEXTURE_PROPERTIES.some((property) => values[property] instanceof Texture) +} + +function prepareDataTextureNormal( + material: MeshPhysicalMaterial, + hasTangents: boolean, + context: BakeContext, +): void { + const normal = material.normalMap + if (!isDataTexture(normal)) return + const flipX = material.normalScale.x < 0 + const flipY = hasTangents ? material.normalScale.y < 0 : material.normalScale.y > 0 + if (flipX || flipY) { + const width = normal.image.width + const height = normal.image.height + const output = new Uint8Array(width * height * 4) + for (let y = 0; y < height; y += 1) { + for (let x = 0; x < width; x += 1) { + const offset = (y * width + x) * 4 + const red = sampleTextureChannel(normal, x, y, width, height, 0, 128) + const green = sampleTextureChannel(normal, x, y, width, height, 1, 128) + output[offset] = flipX ? 255 - red : red + output[offset + 1] = flipY ? 255 - green : green + output[offset + 2] = sampleTextureChannel(normal, x, y, width, height, 2, 255) + output[offset + 3] = sampleTextureChannel(normal, x, y, width, height, 3, 255) + } + } + const prepared = dataTexture(output, width, height, false, `${material.name} / gltf normal`) + material.normalMap = prepared + context.ownedTextures.add(prepared) + } + material.normalScale.set(Math.abs(material.normalScale.x), hasTangents + ? Math.abs(material.normalScale.y) + : -Math.abs(material.normalScale.y)) +} + +function packDataTextureOrm(material: MeshPhysicalMaterial, context: BakeContext): void { + if (material.metalnessMap === material.roughnessMap) return + const metalness = material.metalnessMap + const roughness = material.roughnessMap + if (!isDataTexture(metalness) && !isDataTexture(roughness)) return + const width = Math.max(textureWidth(metalness), textureWidth(roughness), 1) + const height = Math.max(textureHeight(metalness), textureHeight(roughness), 1) + const packed = new Uint8Array(width * height * 4) + for (let y = 0; y < height; y += 1) { + for (let x = 0; x < width; x += 1) { + const offset = (y * width + x) * 4 + packed[offset] = 255 + packed[offset + 1] = sampleTextureChannel(roughness, x, y, width, height, 1, 255) + packed[offset + 2] = sampleTextureChannel(metalness, x, y, width, height, 2, 255) + packed[offset + 3] = 255 + } + } + const orm = dataTexture(packed, width, height, false, `${material.name} / packed orm`) + material.roughnessMap = orm + material.metalnessMap = orm + context.ownedTextures.add(orm) +} + +function isDataTexture(texture: Texture | null): texture is DataTexture { + return texture instanceof DataTexture && texture.image?.data !== undefined +} + +function textureWidth(texture: Texture | null): number { + return isDataTexture(texture) ? texture.image.width : 0 +} + +function textureHeight(texture: Texture | null): number { + return isDataTexture(texture) ? texture.image.height : 0 +} + +function sampleTextureChannel( + texture: Texture | null, + x: number, + y: number, + width: number, + height: number, + channel: number, + fallback: number, +): number { + if (!isDataTexture(texture)) return fallback + const sourceX = Math.min(texture.image.width - 1, Math.floor(x * texture.image.width / width)) + const sourceY = Math.min(texture.image.height - 1, Math.floor(y * texture.image.height / height)) + const source = texture.image.data as ArrayLike + const channels = Math.max(1, Math.round(source.length / (texture.image.width * texture.image.height))) + return source[(sourceY * texture.image.width + sourceX) * channels + Math.min(channel, channels - 1)] ?? fallback +} + +/** Exports one binary, animation-free GLB with all textures embedded. */ +export async function exportStaticGlb( + source: Object3D, + options: StaticGlbOptions = {}, +): Promise { + const snapshot = createStaticGlbSnapshot(source, options) + try { + const output = await new GLTFExporter().parseAsync(snapshot.root, { + binary: true, + animations: [], + onlyVisible: false, + includeCustomExtensions: true, + maxTextureSize: options.textureSize ?? 512, + }) + if (!(output instanceof ArrayBuffer)) throw new Error('GLTFExporter did not return binary GLB data') + assertPortableGlb(output) + return new Blob([output], { type: 'model/gltf-binary' }) + } finally { + snapshot.dispose() + } +} + +interface GltfJson { + readonly accessors?: readonly { + readonly bufferView?: number + readonly byteOffset?: number + readonly componentType?: number + readonly count?: number + readonly type?: string + }[] + readonly animations?: readonly unknown[] + readonly bufferViews?: readonly { + readonly byteOffset?: number + readonly byteStride?: number + }[] + readonly extensionsUsed?: readonly string[] + readonly materials?: readonly Record[] + readonly meshes?: readonly { + readonly primitives?: readonly { + readonly attributes?: Readonly> + readonly indices?: number + readonly material?: number + }[] + }[] +} + +function assertPortableGlb(buffer: ArrayBuffer): void { + const view = new DataView(buffer) + if (view.getUint32(0, true) !== 0x46546c67 || view.getUint32(4, true) !== 2) { + throw new Error('GLTFExporter returned an invalid GLB header') + } + const jsonLength = view.getUint32(12, true) + const jsonType = view.getUint32(16, true) + if (jsonType !== 0x4e4f534a) throw new Error('GLB does not begin with a JSON chunk') + const json = JSON.parse( + new TextDecoder().decode(new Uint8Array(buffer, 20, jsonLength)).trim(), + ) as GltfJson + const binaryChunkHeader = 20 + jsonLength + const binaryType = view.getUint32(binaryChunkHeader + 4, true) + if (binaryType !== 0x004e4942) throw new Error('GLB does not contain a BIN chunk after JSON') + const binaryDataOffset = binaryChunkHeader + 8 + if (json.extensionsUsed?.includes('EXT_mesh_gpu_instancing')) { + throw new Error('Portable GLB unexpectedly contains EXT_mesh_gpu_instancing') + } + if ((json.animations?.length ?? 0) > 0) { + throw new Error('Static GLB unexpectedly contains animations') + } + + const usedAccessors = new Set() + for (const [meshIndex, mesh] of (json.meshes ?? []).entries()) { + for (const [primitiveIndex, primitive] of (mesh.primitives ?? []).entries()) { + const material = primitive.material === undefined ? undefined : json.materials?.[primitive.material] + const attributes = primitive.attributes ?? {} + if (material?.normalTexture !== undefined && attributes.TANGENT === undefined) { + throw new Error(`Normal-mapped primitive ${meshIndex}/${primitiveIndex} has no tangent attribute`) + } + if (attributes.TANGENT !== undefined) { + assertUnitTangents(view, binaryDataOffset, json, attributes.TANGENT, meshIndex, primitiveIndex) + } + if (!jsonValueUsesTexture(material) && attributes.TEXCOORD_0 !== undefined) { + throw new Error(`Untextured primitive ${meshIndex}/${primitiveIndex} contains an unused TEXCOORD_0`) + } + for (const accessor of Object.values(attributes)) usedAccessors.add(accessor) + if (primitive.indices !== undefined) usedAccessors.add(primitive.indices) + } + } + for (let accessor = 0; accessor < (json.accessors?.length ?? 0); accessor += 1) { + if (!usedAccessors.has(accessor)) throw new Error(`GLB contains unused accessor ${accessor}`) + } +} + +function assertUnitTangents( + view: DataView, + binaryDataOffset: number, + json: GltfJson, + accessorIndex: number, + meshIndex: number, + primitiveIndex: number, +): void { + const accessor = json.accessors?.[accessorIndex] + const bufferView = accessor?.bufferView === undefined ? undefined : json.bufferViews?.[accessor.bufferView] + if (!accessor || !bufferView || accessor.componentType !== 5126 || accessor.type !== 'VEC4') { + throw new Error(`Tangent accessor ${accessorIndex} is not a float VEC4`) + } + const stride = bufferView.byteStride ?? 16 + const start = binaryDataOffset + (bufferView.byteOffset ?? 0) + (accessor.byteOffset ?? 0) + for (let index = 0; index < (accessor.count ?? 0); index += 1) { + const offset = start + index * stride + const x = view.getFloat32(offset, true) + const y = view.getFloat32(offset + 4, true) + const z = view.getFloat32(offset + 8, true) + const w = view.getFloat32(offset + 12, true) + const length = Math.hypot(x, y, z) + if (!Number.isFinite(length) || Math.abs(length - 1) > 1e-4 || Math.abs(Math.abs(w) - 1) > 1e-4) { + throw new Error( + `Primitive ${meshIndex}/${primitiveIndex} has invalid tangent ${index}: ` + + `[${x}, ${y}, ${z}, ${w}]`, + ) + } + } +} + +function jsonValueUsesTexture(value: unknown, key = ''): boolean { + if (value === null || typeof value !== 'object') return false + if (key.toLowerCase().endsWith('texture')) return true + return Object.entries(value).some(([childKey, child]) => jsonValueUsesTexture(child, childKey)) +} + +function hasWearAttributes(geometry: BufferGeometry): boolean { + return WEAR_ATTRIBUTE_NAMES.every((name) => geometry.getAttribute(name) !== undefined) +} + +function bakeWearMesh(source: Mesh, context: BakeContext): Group { + const geometry = source.geometry.index ? source.geometry.toNonIndexed() : source.geometry + const position = geometry.getAttribute('position') + const normal = geometry.getAttribute('normal') + const uv = geometry.getAttribute('uv') + const mask = geometry.getAttribute('aMask') + const colour = geometry.getAttribute('aColor') + const surface = geometry.getAttribute('aSurface') + const wearDirection = geometry.getAttribute('aWearDir') + const buckets = new Map() + + for (let triangle = 0; triangle < position.count; triangle += 3) { + const profile = readProfile(colour, surface, wearDirection, triangle) + const key = profileKey(profile) + const bucket = buckets.get(key) ?? { + profile, + positions: [], + normals: [], + uvs: [], + colours: [], + } + buckets.set(key, bucket) + + for (let corner = 0; corner < 3; corner += 1) { + const index = triangle + corner + bucket.positions.push(position.getX(index), position.getY(index), position.getZ(index)) + bucket.normals.push(normal.getX(index), normal.getY(index), normal.getZ(index)) + bucket.uvs.push(uv?.getX(index) ?? 0, uv?.getY(index) ?? 0) + bucket.colours.push(...bakeVertexColour(position, normal, mask, profile, index)) + } + } + if (geometry !== source.geometry) geometry.dispose() + + const group = new Group() + group.name = source.name + group.position.copy(source.position) + group.quaternion.copy(source.quaternion) + group.scale.copy(source.scale) + group.visible = source.visible + group.renderOrder = source.renderOrder + group.userData = { ...source.userData, surfaceBake: 'standard-pbr' } + + let part = 0 + for (const [key, bucket] of buckets) { + const bakedGeometry = new BufferGeometry() + bakedGeometry.setAttribute('position', new Float32BufferAttribute(bucket.positions, 3)) + bakedGeometry.setAttribute('normal', new Float32BufferAttribute(bucket.normals, 3)) + bakedGeometry.setAttribute('uv', new Float32BufferAttribute(bucket.uvs, 2)) + bakedGeometry.setAttribute('color', new Float32BufferAttribute(bucket.colours, 3)) + bakedGeometry.computeBoundingSphere() + context.ownedGeometries.add(bakedGeometry) + + const baked = new Mesh(bakedGeometry, materialForProfile(key, bucket.profile, context)) + baked.name = `${source.name} / baked surface ${String(part + 1).padStart(2, '0')}` + baked.castShadow = source.castShadow + baked.receiveShadow = source.receiveShadow + group.add(baked) + part += 1 + } + return group +} + +function readProfile( + colour: ReadableAttribute, + surface: ReadableAttribute, + wearDirection: ReadableAttribute, + index: number, +): SurfaceProfile { + return { + colour: [colour.getX(index), colour.getY(index), colour.getZ(index)], + roughness: surface.getX(index), + metalness: surface.getY(index), + rub: surface.getZ(index), + grime: surface.getW(index), + scratch: wearDirection.getX(index), + } +} + +function profileKey(profile: SurfaceProfile): string { + return [ + ...profile.colour, + profile.roughness, + profile.metalness, + profile.rub, + profile.grime, + profile.scratch, + ].map((value) => value.toFixed(4)).join('/') +} + +function bakeVertexColour( + position: ReadableAttribute, + normal: ReadableAttribute, + mask: ReadableAttribute, + profile: SurfaceProfile, + index: number, +): [number, number, number] { + const px = position.getX(index) + const py = position.getY(index) + const pz = position.getZ(index) + const edge = mask.getX(index) + const occlusion = mask.getY(index) + const flakeScale = mask.getW(index) + const flake = smoothstep(0.52, 0.36, valueNoise3(px * flakeScale * 22, py * flakeScale * 22, pz * flakeScale * 22)) + const cluster = smoothstep(0.36, 0.56, valueNoise3(px * flakeScale * 3.4, py * flakeScale * 3.4, pz * flakeScale * 3.4)) + const rub = clamp01(edge ** 3 * flake * cluster * (1 - occlusion * 0.85) * profile.rub) + const down = clamp01(-normal.getY(index)) + const up = clamp01(normal.getY(index)) + const splash = smoothstep(1.05, 0.12, py) + const streak = valueNoise3(px * 9, py * 0.9, pz * 9) + const grime = clamp01(occlusion * 1.15 + down * 0.24 + splash * 0.3) + * (streak * 0.4 + 0.7) * profile.grime + const dust = up * 0.26 * (streak * 0.5 + 0.5) * (1 - rub) * profile.grime + + const base = new Color(...profile.colour) + base.lerp(new Color(0.16, 0.15, 0.13), clamp01(grime * 0.6)) + base.lerp(new Color(0.47, 0.46, 0.42), clamp01(dust * 0.28)) + base.lerp(new Color(0.56, 0.575, 0.59), clamp01(rub * 0.55)) + return [base.r, base.g, base.b] +} + +function materialForProfile( + key: string, + profile: SurfaceProfile, + context: BakeContext, +): MeshPhysicalMaterial { + const existing = context.materials.get(key) + if (existing) return existing + const { albedo, orm, normal } = createWearTextureSet(profile, context.textureSize) + const material = new MeshPhysicalMaterial({ + name: `baked worn surface / ${context.materials.size + 1}`, + color: 0xffffff, + vertexColors: true, + roughness: 1, + metalness: 1, + clearcoat: 0.3, + clearcoatRoughness: 0.3, + map: albedo, + roughnessMap: orm, + metalnessMap: orm, + normalMap: normal, + }) + material.normalScale.set(0.42, 0.42) + material.userData = { + surfaceBake: 'toolbox-wear-v1', + baseRoughness: profile.roughness, + baseMetalness: profile.metalness, + } + context.materials.set(key, material) + context.ownedMaterials.add(material) + context.ownedTextures.add(albedo) + context.ownedTextures.add(orm) + context.ownedTextures.add(normal) + return material +} + +function createWearTextureSet( + profile: SurfaceProfile, + size: number, +): { albedo: DataTexture; orm: DataTexture; normal: DataTexture } { + const albedoData = new Uint8Array(size * size * 4) + const ormData = new Uint8Array(size * size * 4) + const normalData = new Uint8Array(size * size * 4) + for (let y = 0; y < size; y += 1) { + for (let x = 0; x < size; x += 1) { + const u = x / size + const v = y / size + const grain = valueNoise2(u * 18, v * 96) + const broad = valueNoise2(u * 7, v * 7) + const primaryPhase = u * 11 + v * 3 + const crossPhase = u * 4 - v * 13 + const primaryDistance = Math.abs(Math.sin(Math.PI * primaryPhase)) + const crossDistance = Math.abs(Math.sin(Math.PI * crossPhase)) + const broken = smoothstep(0.72, 0.94, Math.sin((u * 5 + v * 7) * Math.PI * 2) * 0.5 + 0.5) + const scratch = clamp01( + smoothstep(0.09, 0.015, primaryDistance) * broken + + smoothstep(0.055, 0.012, crossDistance) * (1 - broken) * 0.55, + ) * profile.scratch + const chips = smoothstep(0.7, 0.84, broad) * profile.rub + const dirt = smoothstep(0.38, 0.7, valueNoise2(u * 5 + 2.7, v * 5 - 1.3)) * profile.grime + const multiplier = clamp01(0.98 + (grain - 0.5) * 0.08 - dirt * 0.16 - scratch * 0.3) + const roughness = clamp01(profile.roughness + dirt * 0.2 - scratch * 0.34 - chips * 0.12) + const metalness = clamp01(profile.metalness + (scratch * 0.7 + chips * 0.45) * (1 - profile.metalness)) + const wall = Math.sign(Math.sin(Math.PI * primaryPhase)) * scratch * 0.34 + const wallCross = Math.sign(Math.sin(Math.PI * crossPhase)) * scratch * 0.18 + const nx = -wall * 0.96 - wallCross * 0.3 + const ny = -wall * 0.26 + wallCross * 0.95 + const nz = Math.sqrt(Math.max(0, 1 - nx * nx - ny * ny)) + const offset = (y * size + x) * 4 + const albedo = Math.round(multiplier * 255) + albedoData.set([albedo, albedo, albedo, 255], offset) + ormData.set([255, Math.round(roughness * 255), Math.round(metalness * 255), 255], offset) + normalData.set([ + Math.round((nx * 0.5 + 0.5) * 255), + Math.round((ny * 0.5 + 0.5) * 255), + Math.round((nz * 0.5 + 0.5) * 255), + 255, + ], offset) + } + } + return { + albedo: dataTexture(albedoData, size, true, 'baked wear / albedo'), + orm: dataTexture(ormData, size, false, 'baked wear / orm'), + normal: dataTexture(normalData, size, false, 'baked wear / normal'), + } +} + +function dataTexture(data: Uint8Array, size: number, srgb: boolean, name: string): DataTexture +function dataTexture(data: Uint8Array, width: number, height: number, srgb: boolean, name: string): DataTexture +function dataTexture( + data: Uint8Array, + width: number, + heightOrSrgb: number | boolean, + srgbOrName: boolean | string, + maybeName?: string, +): DataTexture { + const height = typeof heightOrSrgb === 'number' ? heightOrSrgb : width + const srgb = typeof heightOrSrgb === 'boolean' ? heightOrSrgb : srgbOrName as boolean + const name = typeof heightOrSrgb === 'boolean' ? srgbOrName as string : maybeName! + const texture = new DataTexture(data, width, height, RGBAFormat, UnsignedByteType) + texture.name = name + texture.wrapS = RepeatWrapping + texture.wrapT = RepeatWrapping + texture.magFilter = LinearFilter + texture.minFilter = LinearMipmapLinearFilter + texture.generateMipmaps = true + if (srgb) texture.colorSpace = SRGBColorSpace + texture.needsUpdate = true + return texture +} + +function valueNoise2(x: number, y: number): number { + const ix = Math.floor(x) + const iy = Math.floor(y) + const fx = x - ix + const fy = y - iy + const ux = fx * fx * (3 - 2 * fx) + const uy = fy * fy * (3 - 2 * fy) + return mix(mix(hash2(ix, iy), hash2(ix + 1, iy), ux), mix(hash2(ix, iy + 1), hash2(ix + 1, iy + 1), ux), uy) +} + +function valueNoise3(x: number, y: number, z: number): number { + const ix = Math.floor(x) + const iy = Math.floor(y) + const iz = Math.floor(z) + const fx = x - ix + const fy = y - iy + const fz = z - iz + const ux = fx * fx * (3 - 2 * fx) + const uy = fy * fy * (3 - 2 * fy) + const uz = fz * fz * (3 - 2 * fz) + const corner = (dx: number, dy: number, dz: number) => hash2( + ix + dx * 37 + (iz + dz) * 17, + iy + dy * 53 + (iz + dz) * 29, + ) + return mix( + mix(mix(corner(0, 0, 0), corner(1, 0, 0), ux), mix(corner(0, 1, 0), corner(1, 1, 0), ux), uy), + mix(mix(corner(0, 0, 1), corner(1, 0, 1), ux), mix(corner(0, 1, 1), corner(1, 1, 1), ux), uy), + uz, + ) +} + +function hash2(x: number, y: number): number { + const value = Math.sin(x * 127.1 + y * 311.7) * 43758.5453 + return value - Math.floor(value) +} + +function smoothstep(edge0: number, edge1: number, value: number): number { + const t = clamp01((value - edge0) / (edge1 - edge0)) + return t * t * (3 - 2 * t) +} + +function mix(a: number, b: number, amount: number): number { + return a * (1 - amount) + b * amount +} + +function clamp01(value: number): number { + return Math.min(1, Math.max(0, value)) +} diff --git a/src/lib/vibe3d/scifi-kit/generator/index.ts b/src/lib/vibe3d/scifi-kit/generator/index.ts new file mode 100644 index 0000000..5fdf3f8 --- /dev/null +++ b/src/lib/vibe3d/scifi-kit/generator/index.ts @@ -0,0 +1,50 @@ +export { mergeStaticByMaterial } from './batching.ts' +export type { StaticBatchOptions } from './batching.ts' +export { createSmokeTexture } from './effects.ts' +export type { SmokeTextureOptions } from './effects.ts' +export { createStaticGlbSnapshot, exportStaticGlb } from './glb.ts' +export type { StaticGlbOptions, StaticGlbSnapshot } from './glb.ts' +export { MaterialLibrary, mountMaterialSource, tuneMaterial } from './materials.ts' +export type { + MaterialHandle, + MaterialSource, + MaterialSourceOptions, + PhysicalMaterialTuning, +} from './materials.ts' +export { mirrorProfile, octagon, offsetProfile, rect, stepEdge } from './profile.ts' +export type { Side } from './profile.ts' +export { + WEAR_BAND, + WEAR_FLOOR, + cylinder, + downTriangle, + extrudeProfile, + filletRing, + flatPlate, + groove, + orientRing, + prism, + signedArea, +} from './primitives.ts' +export type { + CapChamfer, + Corners, + PrismOptions, + ProfileOptions, + RingPoint, + Vec2, + Vec3, +} from './primitives.ts' +export { + WEAR_ATTRIBUTES, + bakeOcclusion, + bakeSurfaceAttributes, + createWearMaterial, + wearOutputs, +} from './wear.ts' +export type { + OcclusionBakeOptions, + WearMaterialOptions, + WearOutputs, + WearProfile, +} from './wear.ts' diff --git a/src/lib/vibe3d/scifi-kit/generator/materials.ts b/src/lib/vibe3d/scifi-kit/generator/materials.ts new file mode 100644 index 0000000..65b6982 --- /dev/null +++ b/src/lib/vibe3d/scifi-kit/generator/materials.ts @@ -0,0 +1,97 @@ +import { MeshPhysicalMaterial } from 'three/webgpu' + +export interface MaterialSourceOptions { + readonly recipeId?: string + readonly palette?: string + readonly condition?: string + readonly wear?: number + readonly dirt?: number + readonly seed?: number + readonly uvScale?: readonly [number, number] +} + +export interface MaterialHandle { + readonly key: string + readonly material: MeshPhysicalMaterial + release(): void +} + +export interface MaterialSource { + acquire(options: MaterialSourceOptions, key: string): MaterialHandle +} + +let mountedMaterialSource: MaterialSource | undefined + +/** + * Sets the application-level material source used by subsequently-created + * libraries. The returned function restores the previous source, which makes + * kit mounting safe across previews, tests, and hot reloads. + */ +export function mountMaterialSource(source: MaterialSource): () => void { + const previous = mountedMaterialSource + mountedMaterialSource = source + return () => { + if (mountedMaterialSource === source) mountedMaterialSource = previous + } +} + +/** + * Tiny ownership helper for model-local PBR materials. It deliberately has no + * registry, schema, hashing, or compiler dependency; generators can create and + * release materials without adopting a production pipeline. + */ +export class MaterialLibrary { + readonly #source: MaterialSource | undefined + + constructor(source: MaterialSource | undefined = mountedMaterialSource) { + this.#source = source + } + + acquire(options: MaterialSourceOptions = {}): MaterialHandle { + const key = [options.recipeId, options.palette, options.seed].filter(Boolean).join('/') || 'material' + if (this.#source) return this.#source.acquire(options, key) + const material = new MeshPhysicalMaterial({ name: key }) + material.userData.source = { ...options } + let released = false + return { + key, + material, + release() { + if (released) return + released = true + material.dispose() + }, + } + } +} + +export interface PhysicalMaterialTuning { + readonly clearcoat?: number + readonly clearcoatRoughness?: number + readonly emissive?: number +} + +/** Applies generator-local art direction to an owned material handle. */ +export function tuneMaterial( + handle: MaterialHandle, + hex: number, + roughness: number, + metalness: number, + tuning: PhysicalMaterialTuning = {}, +): MeshPhysicalMaterial { + const material = handle.material as MeshPhysicalMaterial + material.color.setHex(hex) + material.roughness = roughness + material.metalness = metalness + material.clearcoat = tuning.clearcoat ?? 0 + material.clearcoatRoughness = tuning.clearcoatRoughness ?? 0.3 + if (tuning.emissive !== undefined) { + material.emissive.setHex(hex) + material.emissiveIntensity = tuning.emissive + material.toneMapped = false + } else { + material.emissive.setHex(0x000000) + material.emissiveIntensity = 0 + } + return material +} diff --git a/src/lib/vibe3d/scifi-kit/generator/primitives.ts b/src/lib/vibe3d/scifi-kit/generator/primitives.ts new file mode 100644 index 0000000..718603f --- /dev/null +++ b/src/lib/vibe3d/scifi-kit/generator/primitives.ts @@ -0,0 +1,867 @@ +import { + BufferGeometry, + CylinderGeometry, + Float32BufferAttribute, + Mesh, + ShapeUtils, + Vector2, + type MeshPhysicalMaterial, +} from 'three/webgpu' + +export const WEAR_BAND = 0.075 +/** Edge value on clean interior surface, so nothing is ever perfectly pristine. */ +export const WEAR_FLOOR = 0.08 + +export type Vec3 = [number, number, number] +export type Vec2 = [number, number] +/** Corner clip sizes in ring order: top-right, top-left, bottom-left, bottom-right. */ +export type Corners = [number, number, number, number] + +export interface RingPoint { + x: number + y: number + nx: number + ny: number +} + +/** Twice the enclosed area; positive when the ring is wound counter-clockwise. */ +export function signedArea(polygon: Vec2[]): number { + let total = 0 + for (let i = 0; i < polygon.length; i += 1) { + const [ax, ay] = polygon[i] + const [bx, by] = polygon[(i + 1) % polygon.length] + total += ax * by - bx * ay + } + return total +} + +/** Returns the ring wound the requested way, copying only when it has to flip. */ +export function orientRing(polygon: Vec2[], counterClockwise: boolean): Vec2[] { + const isCounterClockwise = signedArea(polygon) > 0 + return isCounterClockwise === counterClockwise ? polygon : [...polygon].reverse() +} + +/** + * Rounds every corner of an XY polygon into a tangent arc. The tangent points + * inherit the arc normal, which is identical to the adjacent edge normal, so + * straight runs stay perfectly flat while corners shade smoothly. + * + * Reflex corners are filleted too. The arc centre already lands on the correct + * side for them - it is only the outward normal that inverts, because the + * material is on the far side of the bisector. Concave silhouettes (an L-shaped + * upright, a notched bracket, a recessed shoulder) therefore round exactly like + * convex ones, which is what lets a whole part be one ring instead of a stack. + */ +export function filletRing(polygon: Vec2[], fillet: number, arcSegments: number): RingPoint[] { + const count = polygon.length + const points: RingPoint[] = [] + const winding = signedArea(polygon) > 0 ? 1 : -1 + for (let i = 0; i < count; i += 1) { + const previous = polygon[(i - 1 + count) % count] + const vertex = polygon[i] + const next = polygon[(i + 1) % count] + + const toPrevious: Vec2 = [previous[0] - vertex[0], previous[1] - vertex[1]] + const toNext: Vec2 = [next[0] - vertex[0], next[1] - vertex[1]] + const previousLength = Math.hypot(...toPrevious) + const nextLength = Math.hypot(...toNext) + const u1: Vec2 = [toPrevious[0] / previousLength, toPrevious[1] / previousLength] + const u2: Vec2 = [toNext[0] / nextLength, toNext[1] / nextLength] + + const interior = Math.acos(Math.min(1, Math.max(-1, u1[0] * u2[0] + u1[1] * u2[1]))) + const half = interior * 0.5 + // A degenerate corner (collinear edges) contributes a single flat point. + if (!Number.isFinite(half) || half < 1e-3 || Math.abs(Math.PI - interior) < 1e-3) { + const nx = u2[1] * winding + const ny = -u2[0] * winding + points.push({ x: vertex[0], y: vertex[1], nx, ny }) + continue + } + + // The bisector points into the corner's narrow side. On a convex vertex that + // is the material, so the surface normal runs from the arc centre outward; + // on a reflex vertex it is the void, and the normal inverts. + const convex = (u1[0] * u2[1] - u1[1] * u2[0]) * winding < 0 + const facing = convex ? 1 : -1 + + const radius = Math.min(fillet, previousLength * 0.49 * Math.tan(half), nextLength * 0.49 * Math.tan(half)) + const tangent = radius / Math.tan(half) + const bisector: Vec2 = [u1[0] + u2[0], u1[1] + u2[1]] + const bisectorLength = Math.hypot(...bisector) || 1 + const centre: Vec2 = [ + vertex[0] + (bisector[0] / bisectorLength) * (radius / Math.sin(half)), + vertex[1] + (bisector[1] / bisectorLength) * (radius / Math.sin(half)), + ] + + const start: Vec2 = [vertex[0] + u1[0] * tangent, vertex[1] + u1[1] * tangent] + const end: Vec2 = [vertex[0] + u2[0] * tangent, vertex[1] + u2[1] * tangent] + const startAngle = Math.atan2(start[1] - centre[1], start[0] - centre[0]) + const endAngle = Math.atan2(end[1] - centre[1], end[0] - centre[0]) + let sweep = endAngle - startAngle + while (sweep > Math.PI) sweep -= Math.PI * 2 + while (sweep < -Math.PI) sweep += Math.PI * 2 + + for (let s = 0; s <= arcSegments; s += 1) { + const angle = startAngle + (sweep * s) / arcSegments + const nx = Math.cos(angle) + const ny = Math.sin(angle) + points.push({ + x: centre[0] + nx * radius, + y: centre[1] + ny * radius, + nx: nx * facing, + ny: ny * facing, + }) + } + } + return points +} + +/** + * Depth-axis corner cut, the counterpart to the profile-plane `chamfer`. + * + * A number cuts both ends; a pair cuts the front and back independently. Give a + * part both a `chamfer` and a `capChamfer` and every one of its twelve edges is + * a real 45-degree facet - which is the difference between a machined block and + * an extruded slab whose ends were left square. + */ +export type CapChamfer = number | [number, number] + +export interface PrismOptions { + /** Large 45-degree corner cuts. A single number applies to all four corners. */ + chamfer?: number | Corners + /** Large 45-degree cuts on the depth axis: `number` or `[front, back]`. */ + capChamfer?: CapChamfer + /** Small radius softening every ring corner, including the chamfer's own. */ + fillet?: number + /** Radius rolling the front and back face edges into the side walls. */ + bevel?: number + /** Inner rings cut clean through the part. Real openings, not floated quads. */ + holes?: Vec2[][] + rotation?: Vec3 + arcSegments?: number + bevelSegments?: number +} + +export interface ProfileOptions { + /** Small radius softening every polygon corner. */ + fillet?: number + /** Radius rolling the front and back face edges into the side walls. On a + * profile extrusion this band is the part's corner facet in the extruded + * plane, so hero masses want it large rather than hairline. */ + bevel?: number + /** Large 45-degree cuts on the depth axis: `number` or `[front, back]`. */ + capChamfer?: CapChamfer + /** + * Inner rings cut clean through the extrusion. Each hole gets its own filleted + * rim, its own bevel roll, and walls that face into the opening, so a screen + * well, a vent mouth, or a cable pass-through is subtracted from the part + * rather than faked with a dark quad floated on top of it. + */ + holes?: Vec2[][] + rotation?: Vec3 + arcSegments?: number + bevelSegments?: number +} + +/** One ring of the depth cross-section: where it sits, and which way it faces. */ +interface Band { + z: number + inset: number + nz: number + nScale: number + edge: number +} + +/** + * Builds the depth cross-section as a closed polygon in (inset, z) and fillets + * it with the very same routine that rounds the profile plane. + * + * That symmetry is the point. The old cross-section was hard-coded to a single + * quarter-round, so the depth axis could only ever receive a hairline roll no + * matter what the caller asked for - a part could be chamfered across its face + * and never through its thickness. Expressing depth as a profile means a cap + * chamfer is just another corner, its own creases get the same bevel, and the + * two axes finally have equal expressive power. + */ +function depthBands( + halfDepth: number, + front: number, + back: number, + bevel: number, + bevelSegments: number, +): Band[] { + // The section is closed off far inside the part; those corners are discarded + // after filleting, so their only job is to make the ring a valid polygon. + const far = halfDepth * 4 + Math.max(front, back) + bevel * 4 + 1 + const section: Vec2[] = [[far, halfDepth]] + if (front > 0) section.push([front, halfDepth], [0, halfDepth - front]) + else section.push([0, halfDepth]) + if (back > 0) section.push([0, -(halfDepth - back)], [back, -halfDepth]) + else section.push([0, -halfDepth]) + section.push([far, -halfDepth]) + + const bands: Band[] = [] + for (const point of filletRing(section, bevel, bevelSegments)) { + if (point.x > far * 0.5) continue + // Section +x runs into the part, so its normal component is the ring normal + // inverted; section +y is world z. + bands.push({ z: point.y, inset: point.x, nz: point.ny, nScale: -point.nx, edge: 1 }) + } + + // A deep side wall gets two interior rings so its middle can read as clean + // metal. Without them the wear band would stretch across the whole wall. + const wall = bands.findIndex((band, index) => + index + 1 < bands.length + && Math.abs(band.inset) < 1e-6 && Math.abs(band.nz) < 1e-6 + && Math.abs(bands[index + 1].inset) < 1e-6 && Math.abs(bands[index + 1].nz) < 1e-6) + if (wall >= 0 && bands[wall].z - bands[wall + 1].z > WEAR_BAND * 3) { + bands.splice(wall + 1, 0, + { z: bands[wall].z - WEAR_BAND, inset: 0, nz: 0, nScale: 1, edge: WEAR_FLOOR }, + { z: bands[wall + 1].z + WEAR_BAND, inset: 0, nz: 0, nScale: 1, edge: WEAR_FLOOR }) + } + return bands +} + +function resolveCapChamfer(value: CapChamfer | undefined, limit: number): [number, number] { + const pair: [number, number] = typeof value === 'number' ? [value, value] : value ?? [0, 0] + return [ + Math.max(0, Math.min(pair[0], limit)), + Math.max(0, Math.min(pair[1], limit)), + ] +} + +/** + * The tightest arc `filletRing` will actually produce on a convex corner of this + * polygon, which is the hard ceiling on how far the ring can be inset. + * + * A cap chamfer is built by drawing the ring inset from itself, and pushing a + * rounded corner inward by more than its own radius turns it inside out. Reflex + * corners only ever open up under the same inset, so they impose no limit. + */ +function minConvexRadius(polygon: Vec2[], fillet: number): number { + const count = polygon.length + const winding = signedArea(polygon) > 0 ? 1 : -1 + let smallest = Infinity + for (let i = 0; i < count; i += 1) { + const previous = polygon[(i - 1 + count) % count] + const vertex = polygon[i] + const next = polygon[(i + 1) % count] + const toPrevious: Vec2 = [previous[0] - vertex[0], previous[1] - vertex[1]] + const toNext: Vec2 = [next[0] - vertex[0], next[1] - vertex[1]] + const previousLength = Math.hypot(...toPrevious) + const nextLength = Math.hypot(...toNext) + const u1: Vec2 = [toPrevious[0] / previousLength, toPrevious[1] / previousLength] + const u2: Vec2 = [toNext[0] / nextLength, toNext[1] / nextLength] + const interior = Math.acos(Math.min(1, Math.max(-1, u1[0] * u2[0] + u1[1] * u2[1]))) + const half = interior * 0.5 + if (!Number.isFinite(half) || half < 1e-3 || Math.abs(Math.PI - interior) < 1e-3) continue + if ((u1[0] * u2[1] - u1[1] * u2[0]) * winding >= 0) continue + smallest = Math.min( + smallest, + fillet, + previousLength * 0.49 * Math.tan(half), + nextLength * 0.49 * Math.tan(half), + ) + } + return smallest +} + +/** + * The single building block for the whole case. Corners and face edges carry a + * real bevel, but at the segment count a hand modeller would actually use: one + * facet, with the normals shared across it so it reads as a soft highlight + * rather than a razor edge. Only the hero masses opt into a second segment. + */ +export function prism( + material: MeshPhysicalMaterial, + size: Vec3, + position: Vec3, + options: PrismOptions = {}, +): Mesh { + const [width, height, depth] = size + const hx = width * 0.5 + const hy = height * 0.5 + + const raw = options.chamfer ?? 0 + const clips: Corners = typeof raw === 'number' ? [raw, raw, raw, raw] : raw + // Leave real straight edge between clips. At 0.85 a thin prism's side collapses + // to a few thou, and filleting both ends of that produces zero-area slivers. + const [ctr, ctl, cbl, cbr] = clips.map((clip) => Math.min(clip, hx * 0.6, hy * 0.6)) as Corners + + // Counter-clockwise ring beginning at the top-right corner. + const polygon: Vec2[] = [] + if (ctr > 0) polygon.push([hx, hy - ctr], [hx - ctr, hy]) + else polygon.push([hx, hy]) + if (ctl > 0) polygon.push([-hx + ctl, hy], [-hx, hy - ctl]) + else polygon.push([-hx, hy]) + if (cbl > 0) polygon.push([-hx, -hy + cbl], [-hx + cbl, -hy]) + else polygon.push([-hx, -hy]) + if (cbr > 0) polygon.push([hx - cbr, -hy], [hx, -hy + cbr]) + else polygon.push([hx, -hy]) + + return extrudeProfile(material, polygon, depth, position, options) +} + +/** Rings are authored counter-clockwise; a hole's wall faces into the opening. */ +function ringOf(polygon: Vec2[], fillet: number, arcSegments: number, hole: boolean): RingPoint[] { + const ring = filletRing(orientRing(polygon, true), fillet, arcSegments) + if (!hole) return ring + return ring.map((point) => ({ ...point, nx: -point.nx, ny: -point.ny })) +} + +/** + * Ear-clips a cap, honouring concave outlines and any number of openings. + * + * The triangulator wants a counter-clockwise contour and clockwise holes, but + * the caller has already emitted its vertices in ring order, so any ring flipped + * on the way in has its indices flipped back on the way out. + */ +function capIndices(outer: Vec2[], holes: Vec2[][]): number[] { + const toVectors = (ring: Vec2[], counterClockwise: boolean) => { + const flipped = signedArea(ring) > 0 !== counterClockwise + const ordered = flipped ? [...ring].reverse() : ring + return { points: ordered.map(([x, y]) => new Vector2(x, y)), flipped } + } + + const contour = toVectors(outer, true) + const rings = holes.map((hole) => toVectors(hole, false)) + + // Offsets into the concatenated [outer, ...holes] list the triangulator indexes. + const spans = [{ start: 0, count: outer.length, flipped: contour.flipped }] + for (const [index, hole] of holes.entries()) { + const previous = spans[spans.length - 1] + spans.push({ start: previous.start + previous.count, count: hole.length, flipped: rings[index].flipped }) + } + const restore = (index: number): number => { + const span = spans.findLast((candidate) => index >= candidate.start)! + const local = index - span.start + return span.start + (span.flipped ? span.count - 1 - local : local) + } + + const faces = ShapeUtils.triangulateShape(contour.points, rings.map((ring) => ring.points)) + + // An ear-clipper handed a hole it cannot bridge drops it and returns a cap + // with no opening - geometry that still renders, still passes a volume check + // on its walls, and reads as a solid face. A dropped hole contributes no + // vertices at all, which is exact; comparing triangle counts instead would + // cry wolf every time a collinear corner collapsed. + const used = new Set() + for (const triangle of faces) used.add(triangle[0]).add(triangle[1]).add(triangle[2]) + for (let hole = 1; hole < spans.length; hole += 1) { + const { start, count } = spans[hole] + let reached = false + for (let i = start; i < start + count && !reached; i += 1) reached = used.has(i) + if (!reached) { + console.warn( + `extrudeProfile: cap triangulation dropped hole ${hole} - it is too close to the ` + + 'outline or to another hole to bridge, and the face will render solid.', + ) + } + } + + const indices: number[] = [] + for (const triangle of faces) { + indices.push(restore(triangle[0]), restore(triangle[1]), restore(triangle[2])) + } + return indices +} + +/** + * Extrudes an arbitrary profile along z with the same bevel, normal, and + * wear-attribute treatment `prism` gets. The outline may be concave, and + * `options.holes` cuts real openings clean through it. + * + * Reach for this whenever the silhouette is not a clipped rectangle. Stacking + * boxes to approximate a stepped or tapering mass leaves coincident interior + * faces, a bevel that restarts at every joint, and a hard seam wherever two + * blocks meet - the profile has to be one ring for the outline to be one edge. + */ +export function extrudeProfile( + material: MeshPhysicalMaterial, + profile: Vec2[], + depth: number, + position: Vec3, + options: ProfileOptions = {}, +): Mesh { + const hz = depth * 0.5 + const arcSegments = options.arcSegments ?? 1 + const bevelSegments = options.bevelSegments ?? 1 + + let minX = Infinity + let maxX = -Infinity + let minY = Infinity + let maxY = -Infinity + for (const [x, y] of profile) { + minX = Math.min(minX, x) + maxX = Math.max(maxX, x) + minY = Math.min(minY, y) + maxY = Math.max(maxY, y) + } + const width = maxX - minX + const height = maxY - minY + const hx = width * 0.5 + const hy = height * 0.5 + + // Callers author profiles and holes in one shared coordinate system, and + // `position` is an offset applied on top of the profile's own centre; mesh + // rotation then pivots about that centre, which is what an angled return + // plate wants. + const centreX = (minX + maxX) * 0.5 + const centreY = (minY + maxY) * 0.5 + const recentre = (ring: Vec2[]): Vec2[] => + centreX === 0 && centreY === 0 + ? ring + : ring.map(([x, y]): Vec2 => [x - centreX, y - centreY]) + const polygon = recentre(profile) + const holePolygons = (options.holes ?? []).map(recentre) + minX -= centreX + maxX -= centreX + minY -= centreY + maxY -= centreY + + const capLimit = Math.min(hz * 0.9, Math.min(hx, hy) * 0.9) + const requested = resolveCapChamfer(options.capChamfer, capLimit) + const chamfered = requested[0] > 0 || requested[1] > 0 + + // A cap chamfer needs a corner round enough to carry it, so when the caller + // has not pinned the profile fillet it opens up to match. That is what a hand + // modeller does too: a deep 45 on the ends implies the vertical edges are not + // razor sharp either. + const autoFillet = Math.max(Math.min(hx, hy) * 0.18, chamfered ? Math.max(...requested) * 1.25 : 0) + const fillet = Math.max(1e-4, Math.min(options.fillet ?? autoFillet, hx * 0.9, hy * 0.9)) + + // Without a cap chamfer the depth axis only carries the legacy hairline roll, + // whose radius stays tied to the profile fillet. A part that asked for a real + // depth chamfer has creases of its own to soften, and `filletRing` already + // clamps a radius that will not fit, so that tie is dropped. + const rings = [ + ringOf(polygon, fillet, arcSegments, false), + ...holePolygons.map((hole) => { + let holeSpan = Infinity + for (const [ax, ay] of hole) { + for (const [bx, by] of hole) holeSpan = Math.min(holeSpan, Math.hypot(ax - bx, ay - by) || Infinity) + } + const holeFillet = Math.max(1e-4, Math.min(options.fillet ?? holeSpan * 0.24, holeSpan * 0.32)) + return ringOf(hole, holeFillet, arcSegments, true) + }), + ] + + // Everything that draws the cap ring inward shares one budget. Overrun it and + // a corner arc turns inside out, or a hole's mouth opens wider than the + // outline enclosing it - and an ear-clipper handed either one gives up and + // returns a cap with no hole in it at all. + const clearance = ringClearance(rings) + const insetLimit = Math.min(minConvexRadius(polygon, fillet) * 0.85, clearance * 0.42) + + const defaultBevel = Math.min(0.028, hz * 0.6) + const bevel = Math.max(1e-4, Math.min( + options.bevel ?? defaultBevel, + hz * 0.9, + insetLimit, + // Without a cap chamfer the roll is the whole depth-axis treatment, and its + // radius has always been tied to the profile fillet. + chamfered ? Infinity : fillet * 1.6, + )) + const insetCeiling = Math.max(0, insetLimit - bevel * 0.4143) + const [frontChamfer, backChamfer] = [ + Math.min(requested[0], insetCeiling), + Math.min(requested[1], insetCeiling), + ] + + const bands = depthBands(hz, frontChamfer, backChamfer, bevel, bevelSegments) + + const positions: number[] = [] + const normals: number[] = [] + const uvs: number[] = [] + const edges: number[] = [] + const planes: number[] = [] + const indices: number[] = [] + + const pushVertex = ( + x: number, y: number, z: number, + nx: number, ny: number, nz: number, + edge: number, planeU: number, planeV: number, + ): void => { + positions.push(x, y, z) + normals.push(nx, ny, nz) + uvs.push((x - minX) / width, (y - minY) / height) + edges.push(edge) + planes.push(planeU, planeV) + } + + // Side walls, one strip per ring. Cumulative arc length is the surface + // parameter the wear is evaluated in: projecting world position onto an axis + // plane instead smears the pattern into stripes wherever the surface turns + // edge-on to the projection, which is exactly what a bevel does. + for (const [ringIndex, ring] of rings.entries()) { + const ringCount = ring.length + const arc: number[] = [] + let travelled = 0 + for (let i = 0; i < ringCount; i += 1) { + arc.push(travelled) + const next = ring[(i + 1) % ringCount] + travelled += Math.hypot(next.x - ring[i].x, next.y - ring[i].y) + } + + const base = positions.length / 3 + for (const band of bands) { + for (const [i, point] of ring.entries()) { + pushVertex( + point.x - point.nx * band.inset, point.y - point.ny * band.inset, band.z, + point.nx * band.nScale, point.ny * band.nScale, band.nz, + band.edge, arc[i], band.z, + ) + } + } + for (let s = 0; s < bands.length - 1; s += 1) { + const a = base + s * ringCount + const b = base + (s + 1) * ringCount + for (let i = 0; i < ringCount; i += 1) { + const j = (i + 1) % ringCount + // A hole's wall faces the opening, so its strip winds the other way. + if (ringIndex === 0) indices.push(a + i, b + i, b + j, a + i, b + j, a + j) + else indices.push(a + i, b + j, b + i, a + i, a + j, b + j) + } + } + } + + // Caps. A face broad enough to have a clean middle gets an inset rim ring, so + // the rub band stays a constant width instead of scaling with the panel. A + // small greeble has no clean middle and stays worn all over. Offsetting a ring + // inward is only safe while it stays convex, so a concave outline skips the + // rim band rather than risk folding its own cap inside out. + const halfMin = Math.min(hx, hy) + const convex = rings.every((ring, index) => index === 0 ? isConvexRing(ring) : true) + // Each ring's rub band eats WEAR_BAND of face on its way inward, so two rings + // separated by less than two bands would offset straight through each other + // and hand the triangulator a hole wider than its own contour. + const broad = halfMin > WEAR_BAND * 3.2 && convex + && clearance > WEAR_BAND * 2.4 + && rings.every((ring) => ringSpan(ring) > WEAR_BAND * 3.2) + + for (const [index, band] of [bands[0], bands[bands.length - 1]].entries()) { + // Each cap gets its own copy of the rim ring. It has to be parameterised in + // the face plane, and the wall's copy is parameterised as arc length for the + // bevel - one vertex cannot carry both. The seam lands on the hard edge, + // which is where an unwrap would put it anyway. + const capBase = positions.length / 3 + const offsetRing = (ring: RingPoint[], inset: number): Vec2[] => + ring.map((point): Vec2 => [point.x - point.nx * inset, point.y - point.ny * inset]) + const rims = rings.map((ring) => offsetRing(ring, band.inset)) + + // The rub band is measured from the profile itself, not from the rim, so a + // hairline bevel does not eat into it. A cap chamfer can push the rim past + // that, in which case the band follows the rim inward instead. + const wearInset = Math.max(WEAR_BAND, band.inset + WEAR_BAND * 0.5) + const wears = rings.map((ring) => offsetRing(ring, wearInset)) + // Offsetting a ring inward by more than a corner's fillet radius turns that + // corner inside out. Reversed segments are the exact symptom, and a cap that + // cannot hold a clean band is better off without one than folded. + const safe = wears.every((wear, index) => wear.every((point, i) => { + const next = wear[(i + 1) % wear.length] + const ring = rings[index] + const source = ring[i] + const sourceNext = ring[(i + 1) % ring.length] + const dot = (next[0] - point[0]) * (sourceNext.x - source.x) + + (next[1] - point[1]) * (sourceNext.y - source.y) + return dot >= 0 + })) + + let fanRings = rims + if (broad && safe) { + for (const rim of rims) { + for (const [x, y] of rim) pushVertex(x, y, band.z, 0, 0, band.nz, 1, x, y) + } + const wearBase = positions.length / 3 + for (const wear of wears) { + for (const [x, y] of wear) pushVertex(x, y, band.z, 0, 0, band.nz, WEAR_FLOOR, x, y) + } + let cursor = 0 + for (const [ringIndex, ring] of rings.entries()) { + const count = ring.length + const rimStart = capBase + cursor + const wearStart = wearBase + cursor + cursor += count + for (let i = 0; i < count; i += 1) { + const j = (i + 1) % count + // The inset ring runs inward from the rim, reversing the winding + // relative to the outward-facing wall bands; a hole reverses again. + const flip = (index === 0) === (ringIndex === 0) + if (flip) { + indices.push(rimStart + i, wearStart + j, wearStart + i, rimStart + i, rimStart + j, wearStart + j) + } else { + indices.push(rimStart + j, wearStart + i, wearStart + j, rimStart + j, rimStart + i, wearStart + i) + } + } + } + fanRings = wears + } else { + const edge = halfMin > WEAR_BAND * 3.2 ? WEAR_FLOOR : Math.max(0, 1 - halfMin / (WEAR_BAND * 2.2)) + for (const rim of rims) { + for (const [x, y] of rim) pushVertex(x, y, band.z, 0, 0, band.nz, edge, x, y) + } + } + + const fanBase = fanRings === rims + ? capBase + : positions.length / 3 - fanRings.reduce((total, ring) => total + ring.length, 0) + const face = capIndices(fanRings[0], fanRings.slice(1)) + for (let t = 0; t < face.length; t += 3) { + // Triangulation is authored for a counter-clockwise contour seen from +z. + if (index === 0) indices.push(fanBase + face[t], fanBase + face[t + 1], fanBase + face[t + 2]) + else indices.push(fanBase + face[t + 2], fanBase + face[t + 1], fanBase + face[t]) + } + } + + const geometry = new BufferGeometry() + geometry.setAttribute('position', new Float32BufferAttribute(positions, 3)) + geometry.setAttribute('normal', new Float32BufferAttribute(normals, 3)) + geometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2)) + geometry.setAttribute('aEdge', new Float32BufferAttribute(edges, 1)) + geometry.setAttribute('aPlane', new Float32BufferAttribute(planes, 2)) + geometry.setIndex(indices) + + const mesh = new Mesh(geometry, material) + mesh.position.set(position[0] + centreX, position[1] + centreY, position[2]) + if (options.rotation) mesh.rotation.set(...options.rotation) + return mesh +} + +/** + * Narrowest web of material between any two rings of the profile - the outer + * outline and each opening. Infinite when the part has no holes at all. + * + * Measured point-to-edge in both directions, never corner-to-corner: two + * concentric rectangles a tenth apart have corners a seventh apart, and trusting + * that larger figure lets a chamfer open a hole wider than the outline it is + * supposed to sit inside. + * + * It runs on the filleted rings rather than the polygons they came from, because + * those rings are what actually gets offset - rounding two facing corners pulls + * them closer than the straight edges ever were, and measuring the input would + * miss it. + */ +function ringClearance(rings: RingPoint[][]): number { + if (rings.length < 2) return Infinity + let smallest = Infinity + for (let a = 0; a < rings.length; a += 1) { + for (let b = 0; b < rings.length; b += 1) { + if (a === b) continue + for (const { x: px, y: py } of rings[a]) { + const ring = rings[b] + for (let i = 0; i < ring.length; i += 1) { + const { x: ax, y: ay } = ring[i] + const { x: bx, y: by } = ring[(i + 1) % ring.length] + const dx = bx - ax + const dy = by - ay + const lengthSquared = dx * dx + dy * dy + const t = lengthSquared > 0 + ? Math.min(1, Math.max(0, ((px - ax) * dx + (py - ay) * dy) / lengthSquared)) + : 0 + smallest = Math.min(smallest, Math.hypot(px - (ax + dx * t), py - (ay + dy * t))) + } + } + } + } + return smallest +} + +/** Smallest width of a ring's bounding box - its room for a constant wear band. */ +function ringSpan(ring: RingPoint[]): number { + let minX = Infinity + let maxX = -Infinity + let minY = Infinity + let maxY = -Infinity + for (const point of ring) { + minX = Math.min(minX, point.x) + maxX = Math.max(maxX, point.x) + minY = Math.min(minY, point.y) + maxY = Math.max(maxY, point.y) + } + return Math.min(maxX - minX, maxY - minY) +} + +function isConvexRing(ring: RingPoint[]): boolean { + const count = ring.length + let sign = 0 + for (let i = 0; i < count; i += 1) { + const a = ring[i] + const b = ring[(i + 1) % count] + const c = ring[(i + 2) % count] + const cross = (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x) + if (Math.abs(cross) < 1e-9) continue + const current = Math.sign(cross) + if (sign === 0) sign = current + else if (current !== sign) return false + } + return true +} + +/** + * A single quad. Engraved marks, dashes, and slot cuts on a flat armor face are + * two triangles apiece, the way they would be modelled or floated by hand - + * they never justify a beveled solid. + */ +export function flatPlate( + material: MeshPhysicalMaterial, + size: Vec2, + position: Vec3, + rotation: Vec3 = [0, 0, 0], + engraved = true, +): Mesh { + const hx = size[0] * 0.5 + const hy = size[1] * 0.5 + const geometry = new BufferGeometry() + geometry.setAttribute( + 'position', + new Float32BufferAttribute([-hx, -hy, 0, hx, -hy, 0, hx, hy, 0, -hx, hy, 0], 3), + ) + geometry.setAttribute('normal', new Float32BufferAttribute([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], 3)) + geometry.setAttribute('uv', new Float32BufferAttribute([0, 0, 1, 0, 1, 1, 0, 1], 2)) + // Engraved marks sit in a cut, so they read as worn along their whole length. + geometry.setAttribute('aEdge', new Float32BufferAttribute([0.7, 0.7, 0.7, 0.7], 1)) + geometry.setAttribute( + 'aPlane', + new Float32BufferAttribute([-hx, -hy, hx, -hy, hx, hy, -hx, hy], 2), + ) + geometry.setIndex([0, 1, 2, 0, 2, 3]) + const mesh = new Mesh(geometry, material) + mesh.position.set(...position) + mesh.rotation.set(...rotation) + // A cut runs along the mark's long axis, so its profile is read across the + // short one. Painted markers are not cuts and opt out. + if (engraved) mesh.userData.grooveCross = size[0] >= size[1] ? 'y' : 'x' + return mesh +} + +/** + * A real cut: a narrow channel with two side walls and a floor, extruded along + * its length. + * + * A dark quad floated on a face shares that face's normal, so it lights + * identically to the surface around it and reads as paint no matter how black it + * is. What makes a panel line read as engraved is that its two walls face + * opposite directions - one catches the key and one falls into shadow - which + * only exists if the walls are geometry. Six triangles buys that. + * + * The channel is cut into the plane z = 0 with the face normal along +z; rotate + * the mesh to place it on any other face. + */ +export function groove( + material: MeshPhysicalMaterial, + length: number, + width: number, + depth: number, + position: Vec3, + rotation: Vec3 = [0, 0, 0], +): Mesh { + const hw = width * 0.5 + const hl = length * 0.5 + // Wall draft. A dead-vertical wall gives the two sides the same shading under + // a frontal key, so the cut needs a real opening angle to separate them. + const wall = Math.min(hw * 0.55, depth * 0.9) + + // Cross-section across the width, from one rim down to the floor and back. + const section: Vec2[] = [ + [-hw, 0], + [-hw + wall, -depth], + [hw - wall, -depth], + [hw, 0], + ] + + const positions: number[] = [] + const normals: number[] = [] + const uvs: number[] = [] + const edges: number[] = [] + const planes: number[] = [] + const indices: number[] = [] + + for (let i = 0; i < section.length - 1; i += 1) { + const [ax, az] = section[i] + const [bx, bz] = section[i + 1] + // Outward normal of this facet: perpendicular to the section edge, pointing + // up out of the cut. + const dx = bx - ax + const dz = bz - az + const nl = Math.hypot(dx, dz) || 1 + const nx = -dz / nl + const nz = dx / nl + const base = positions.length / 3 + for (const [x, z] of [[ax, az], [bx, bz]] as const) { + for (const y of [-hl, hl]) { + positions.push(x, y, z) + normals.push(nx, 0, nz) + uvs.push((x + hw) / width, (y + hl) / length) + // A cut is worn along its whole length; nothing in here is pristine. + edges.push(0.85) + planes.push(y, x) + } + } + indices.push(base, base + 2, base + 3, base, base + 3, base + 1) + } + + const geometry = new BufferGeometry() + geometry.setAttribute('position', new Float32BufferAttribute(positions, 3)) + geometry.setAttribute('normal', new Float32BufferAttribute(normals, 3)) + geometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2)) + geometry.setAttribute('aEdge', new Float32BufferAttribute(edges, 1)) + geometry.setAttribute('aPlane', new Float32BufferAttribute(planes, 2)) + geometry.setIndex(indices) + + const mesh = new Mesh(geometry, material) + mesh.position.set(...position) + mesh.rotation.set(...rotation) + mesh.userData.grooveCross = 'x' + return mesh +} + +export function cylinder( + material: MeshPhysicalMaterial, + radius: number, + depth: number, + position: Vec3, + rotation: Vec3 = [0, 0, 0], + segments = 8, +): Mesh { + const geometry = new CylinderGeometry(radius, radius, depth, segments) + // Bolt heads and pivot bosses are small proud hardware: worn across the cap. + const count = geometry.getAttribute('position').count + geometry.setAttribute('aEdge', new Float32BufferAttribute(new Float32Array(count).fill(0.75), 1)) + const mesh = new Mesh(geometry, material) + mesh.position.set(...position) + mesh.rotation.set(...rotation) + return mesh +} + +/** Flat down-pointing triangle, so the latch arrow is deterministic. */ +export function downTriangle(material: MeshPhysicalMaterial, width: number, height: number, position: Vec3): Mesh { + const hx = width * 0.5 + const hy = height * 0.5 + const hz = 0.01 + const face: Vec2[] = [ + [-hx, hy], + [hx, hy], + [0, -hy], + ] + const positions: number[] = [] + const normals: number[] = [] + const uvs: number[] = [] + for (const z of [-hz, hz]) { + for (const [x, y] of face) { + positions.push(x, y, z) + normals.push(0, 0, Math.sign(z)) + uvs.push(0.5, 0.5) + } + } + const indices = [0, 2, 1, 3, 4, 5, 0, 1, 4, 0, 4, 3, 1, 2, 5, 1, 5, 4, 2, 0, 3, 2, 3, 5] + const geometry = new BufferGeometry() + geometry.setAttribute('position', new Float32BufferAttribute(positions, 3)) + geometry.setAttribute('normal', new Float32BufferAttribute(normals, 3)) + geometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2)) + geometry.setAttribute('aEdge', new Float32BufferAttribute(new Float32Array(6).fill(0.6), 1)) + geometry.setIndex(indices) + const mesh = new Mesh(geometry, material) + mesh.position.set(...position) + return mesh +} + diff --git a/src/lib/vibe3d/scifi-kit/generator/profile.ts b/src/lib/vibe3d/scifi-kit/generator/profile.ts new file mode 100644 index 0000000..a455cd0 --- /dev/null +++ b/src/lib/vibe3d/scifi-kit/generator/profile.ts @@ -0,0 +1,158 @@ +import { orientRing, signedArea, type Vec2 } from './primitives.ts' + +/** + * Shape algebra for extrusion profiles. + * + * `extrudeProfile` has always accepted any polygon, so a notched frame or an + * interlocking pair was never beyond the geometry - it was beyond the *notation*. + * Absolute coordinate lists can only be typed out, and two parts that must fit + * each other can only be typed out twice and kept in sync by hand, which never + * survives the first edit. + * + * These are the operations hard-surface forms are actually conceived in: take an + * outline, step one of its edges, offset the whole ring to get the part that + * mates with it. A profile built this way stays correct when its source moves, + * which is the only reason a fit ever holds. + */ + +const EPSILON = 1e-6 + +function unit(x: number, y: number): Vec2 { + const length = Math.hypot(x, y) || 1 + return [x / length, y / length] +} + +/** Axis-aligned rectangle, counter-clockwise from the top-right. */ +export function rect(halfWidth: number, halfHeight: number): Vec2[] { + return [ + [halfWidth, halfHeight], + [-halfWidth, halfHeight], + [-halfWidth, -halfHeight], + [halfWidth, -halfHeight], + ] +} + +/** Rectangle with all four corners clipped at 45 degrees - the kit's octagon. */ +export function octagon(halfWidth: number, halfHeight: number, clip: number): Vec2[] { + return [ + [halfWidth, halfHeight - clip], [halfWidth - clip, halfHeight], + [-halfWidth + clip, halfHeight], [-halfWidth, halfHeight - clip], + [-halfWidth, -halfHeight + clip], [-halfWidth + clip, -halfHeight], + [halfWidth - clip, -halfHeight], [halfWidth, -halfHeight + clip], + ] +} + +/** Mirrors a right-hand outline into a closed symmetric ring. */ +export function mirrorProfile(right: Vec2[]): Vec2[] { + return [...right, ...[...right].reverse().map(([x, y]): Vec2 => [-x, y])] +} + +export type Side = 'top' | 'bottom' | 'left' | 'right' + +/** + * Steps a centred span of one side in or out, joined by 45-degree runs. + * + * This is the notch that shows up on nearly every hard-surface frame and stand, + * and the reason it is worth a named operation is that writing it by hand means + * inventing six coordinates that have to stay symmetric about the centre and + * stay put when the outline around them changes. + * + * A positive `rise` pushes the span outward; a negative one sinks it, which + * makes two reflex corners - filleted and extruded exactly like convex ones. + */ +export function stepEdge( + profile: Vec2[], + side: Side, + halfSpan: number, + rise: number, + run = Math.abs(rise), +): Vec2[] { + const ring = orientRing(profile, true) + const horizontal = side === 'top' || side === 'bottom' + const outward = side === 'top' || side === 'right' ? 1 : -1 + + // Along-axis coordinate of the side, and the ring's extreme in that direction. + const axis = (point: Vec2): number => (horizontal ? point[1] : point[0]) + const across = (point: Vec2): number => (horizontal ? point[0] : point[1]) + let extreme = -Infinity + for (const point of ring) extreme = Math.max(extreme, axis(point) * outward) + extreme *= outward + + const make = (alongCentre: number, acrossValue: number): Vec2 => + horizontal ? [acrossValue, alongCentre] : [alongCentre, acrossValue] + + const stepped = extreme + rise * outward + const result: Vec2[] = [] + let inserted = false + + for (let i = 0; i < ring.length; i += 1) { + const current = ring[i] + const next = ring[(i + 1) % ring.length] + result.push(current) + if (inserted) continue + // The edge lying on the side being stepped, long enough to hold the span. + if (Math.abs(axis(current) - extreme) > EPSILON) continue + if (Math.abs(axis(next) - extreme) > EPSILON) continue + const from = across(current) + const to = across(next) + if (Math.min(from, to) > -halfSpan - run || Math.max(from, to) < halfSpan + run) continue + + // Insert in traversal order so the ring stays wound the way it arrived. + const descending = to < from + const outer = halfSpan + run + const spans: Array<[number, number]> = descending + ? [[outer, extreme], [halfSpan, stepped], [-halfSpan, stepped], [-outer, extreme]] + : [[-outer, extreme], [-halfSpan, stepped], [halfSpan, stepped], [outer, extreme]] + for (const [acrossValue, alongValue] of spans) result.push(make(alongValue, acrossValue)) + inserted = true + } + + if (!inserted) { + throw new Error(`stepEdge: no ${side} edge wide enough for a ${halfSpan * 2} span`) + } + return result +} + +/** + * Offsets every edge of a ring by a constant distance, mitring the corners. + * + * Positive grows the shape, negative shrinks it. This is what makes two parts + * fit by construction: author the inner part once, and derive whatever wraps it + * as `offsetProfile(inner, gap)`. Edit the inner outline afterwards - add a + * notch to it, move a corner - and the mating part follows, because it was never + * a second copy of the numbers in the first place. + */ +export function offsetProfile(profile: Vec2[], distance: number, miterLimit = 4): Vec2[] { + const ring = orientRing(profile, true) + const count = ring.length + const winding = signedArea(ring) > 0 ? 1 : -1 + const result: Vec2[] = [] + + for (let i = 0; i < count; i += 1) { + const previous = ring[(i - 1 + count) % count] + const vertex = ring[i] + const next = ring[(i + 1) % count] + + const incoming = unit(vertex[0] - previous[0], vertex[1] - previous[1]) + const outgoing = unit(next[0] - vertex[0], next[1] - vertex[1]) + // Outward edge normal of a counter-clockwise ring is the direction turned + // right; `winding` keeps that true if a caller hands in a reversed loop. + const firstNormal: Vec2 = [incoming[1] * winding, -incoming[0] * winding] + const secondNormal: Vec2 = [outgoing[1] * winding, -outgoing[0] * winding] + + const bisector = unit(firstNormal[0] + secondNormal[0], firstNormal[1] + secondNormal[1]) + const cosine = bisector[0] * firstNormal[0] + bisector[1] * firstNormal[1] + if (!Number.isFinite(cosine) || cosine < EPSILON) { + result.push([vertex[0] + firstNormal[0] * distance, vertex[1] + firstNormal[1] * distance]) + continue + } + // A sharp corner's mitre runs away to infinity, so it is capped rather than + // allowed to throw a spike out of the silhouette. + const reach = Math.min(1 / cosine, miterLimit) + result.push([ + vertex[0] + bisector[0] * distance * reach, + vertex[1] + bisector[1] * distance * reach, + ]) + } + return result +} diff --git a/src/lib/vibe3d/scifi-kit/generator/wear.ts b/src/lib/vibe3d/scifi-kit/generator/wear.ts new file mode 100644 index 0000000..d23d45b --- /dev/null +++ b/src/lib/vibe3d/scifi-kit/generator/wear.ts @@ -0,0 +1,524 @@ +import { + Box3, + Float32BufferAttribute, + Mesh, + MeshPhysicalMaterial, + Vector3, + type BufferGeometry, + type Group, +} from 'three/webgpu' +import { + abs, + attribute, + clamp, + cos, + float, + floor, + fract, + hash, + mix, + normalWorld, + oneMinus, + positionLocal, + positionWorld, + pow, + sin, + normalize, + max, + sqrt, + cross, + smoothstep, + step, + transformNormalToView, + uv, + vec3, + vec4, +} from 'three/tsl' + +/** + * Wear is placed by the form, never sprayed over it. + * + * Two attributes baked into the mesh at build time do all the placing: `aEdge` + * marks the convex bevels and corner arcs the prism generator already knows + * about, and `aOcc` is a short-ray occlusion bake against the other parts, so + * grime lands in the seams and under the overhangs that actually exist. Noise + * only breaks those masks up - a perfectly even rub outline is the tell that + * nobody authored it by hand. + */ + +const OCCLUSION_REACH = 0.34 +const OCCLUSION_RAYS: Array<[number, number, number]> = [ + [0, 0, 1], + [0.62, 0, 0.78], + [-0.62, 0, 0.78], + [0, 0.62, 0.78], + [0, -0.62, 0.78], +] + +/** Slab test: distance along `direction` at which the ray first enters `box`, or Infinity. */ +function rayBoxEntry(origin: Vector3, direction: Vector3, box: Box3, limit: number): number { + let near = 0 + let far = limit + for (const axis of ['x', 'y', 'z'] as const) { + const d = direction[axis] + if (Math.abs(d) < 1e-6) { + if (origin[axis] < box.min[axis] || origin[axis] > box.max[axis]) return Infinity + continue + } + let t0 = (box.min[axis] - origin[axis]) / d + let t1 = (box.max[axis] - origin[axis]) / d + if (t0 > t1) [t0, t1] = [t1, t0] + if (t0 > near) near = t0 + if (t1 < far) far = t1 + if (near > far) return Infinity + } + return near +} + +/** An orthonormal basis around `normal`, so the ray cone spreads across the surface. */ +function basisFor(normal: Vector3, tangent: Vector3, bitangent: Vector3): void { + const helper = Math.abs(normal.y) > 0.9 ? new Vector3(1, 0, 0) : new Vector3(0, 1, 0) + tangent.crossVectors(helper, normal).normalize() + bitangent.crossVectors(normal, tangent).normalize() +} + +/** + * Bakes `aOcc` per vertex by marching a small cone of rays against every other + * part's world bounds. A vertex on an exposed panel face sees nothing and stays + * clean; one down a channel or under the lid overhang is hit from several + * directions and collects grime. + */ +export interface OcclusionBakeOptions { + /** Maximum world-space distance at which another part can occlude a vertex. */ + readonly reach?: number +} + +export function bakeOcclusion(root: Group, options: OcclusionBakeOptions = {}): void { + const reach = options.reach ?? OCCLUSION_REACH + root.updateMatrixWorld(true) + + const meshes: Mesh[] = [] + root.traverse((object) => { + if (object instanceof Mesh) meshes.push(object) + }) + + const bounds = meshes.map((mesh) => { + const box = new Box3().setFromObject(mesh) + return { + box, + centre: box.getCenter(new Vector3()), + radius: box.getSize(new Vector3()).length() * 0.5, + } + }) + + const position = new Vector3() + const normal = new Vector3() + const tangent = new Vector3() + const bitangent = new Vector3() + const origin = new Vector3() + const direction = new Vector3() + + for (const [index, mesh] of meshes.entries()) { + const geometry = mesh.geometry as BufferGeometry + const positions = geometry.getAttribute('position') + const normals = geometry.getAttribute('normal') + if (!positions || !normals) continue + const occlusion = new Float32Array(positions.count) + + for (let v = 0; v < positions.count; v += 1) { + position.fromBufferAttribute(positions, v).applyMatrix4(mesh.matrixWorld) + normal.fromBufferAttribute(normals, v).transformDirection(mesh.matrixWorld).normalize() + basisFor(normal, tangent, bitangent) + // Lift off the surface so a part never occludes itself at its own skin. + origin.copy(position).addScaledVector(normal, 0.014) + + let hits = 0 + for (const [tx, ty, tz] of OCCLUSION_RAYS) { + direction + .copy(normal) + .multiplyScalar(tz) + .addScaledVector(tangent, tx) + .addScaledVector(bitangent, ty) + .normalize() + + let nearest = Infinity + for (const [other, bound] of bounds.entries()) { + if (other === index) continue + if (origin.distanceTo(bound.centre) - bound.radius > reach) continue + const entry = rayBoxEntry(origin, direction, bound.box, reach) + if (entry < nearest) nearest = entry + } + if (nearest < reach) hits += 1 - nearest / reach + } + occlusion[v] = Math.min(1, hits / (OCCLUSION_RAYS.length * 0.7)) + } + + geometry.setAttribute('aOcc', new Float32BufferAttribute(occlusion, 1)) + } +} + +export interface WearProfile { + /** How readily this surface rubs through to bare metal on its edges. */ + readonly rub: number + /** How much grime this surface collects in its occluded areas. */ + readonly grime: number + /** Scratch visibility. Rubber and lenses take almost none. */ + readonly scratch: number +} + +/** + * Bakes each part's surface identity into vertex attributes: base colour, + * roughness/metalness, and its wear character. + * + * This exists because the whole case is deliberately one material. Giving each + * part its own node material instead would make several materials compile to + * structurally identical graphs, and they then share a program and bindings - + * every surface ends up wearing the colour of whichever material compiled last. + * Baking to attributes also collapses the prop to a handful of draw calls, + * which is what a real hand-authored asset would ship as anyway. + */ +export function bakeSurfaceAttributes( + root: Group, + profiles: ReadonlyMap, +): void { + root.traverse((object) => { + if (!(object instanceof Mesh) || Array.isArray(object.material)) return + const material = object.material as MeshPhysicalMaterial + const profile = profiles.get(material) + if (!profile) return + const geometry = object.geometry as BufferGeometry + const positions = geometry.getAttribute('position') + const normals = geometry.getAttribute('normal') + const count = positions.count + + // An engraved mark needs its cut direction in world space so the shader can + // tilt the two walls apart. The local cross axis is known at authoring time; + // the world matrix is still available here, before the merge flattens it. + const cross = object.userData.grooveCross as 'x' | 'y' | undefined + const direction = new Vector3(cross === 'x' ? 1 : 0, cross === 'y' ? 1 : 0, 0) + if (cross) direction.transformDirection(object.matrixWorld).normalize() + + const edge = geometry.getAttribute('aEdge') + const occlusion = geometry.getAttribute('aOcc') + + // WebGPU allows eight vertex buffers and position/normal/uv take three, so + // everything the wear shader needs is packed into four. + const mask = new Float32Array(count * 4) + const plane = new Float32Array(count * 2) + const vertex = new Vector3() + const faceNormal = new Vector3() + const source = geometry.getAttribute('aPlane') + // Flake frequency relative to the part. One world frequency makes a bolt + // and a lid wear at the same absolute grain, so small parts read as camo. + geometry.computeBoundingBox() + const extent = geometry.boundingBox!.getSize(new Vector3()) + const span = Math.max(0.06, (extent.x + extent.y + extent.z) / 3) + const flakeScale = Math.min(2.6, Math.max(0.55, 0.9 / span)) + const origin = new Vector3().setFromMatrixPosition(object.matrixWorld) + const offsetU = origin.x * 3.17 + origin.y * 1.41 + origin.z * 0.83 + const offsetV = origin.z * 2.71 + origin.y * 0.97 - origin.x * 1.13 + const colour = new Float32Array(count * 3) + const surface = new Float32Array(count * 4) + const wearDir = new Float32Array(count * 4) + for (let v = 0; v < count; v += 1) { + mask[v * 4] = edge ? edge.getX(v) : 0 + mask[v * 4 + 1] = occlusion ? occlusion.getX(v) : 0 + // Groove state packed into one slot: 0 none, 1 cut across X, 2 across Y. + mask[v * 4 + 2] = cross ? (cross === 'y' ? 2 : 1) : 0 + + // Prisms and flat marks bake a real surface parameter in the generator. + // Offset it per part, or two identical parts wear identically - and that + // repeat is far more obvious than any noise pattern. + vertex.fromBufferAttribute(positions, v).applyMatrix4(object.matrixWorld) + if (source) { + plane[v * 2] = source.getX(v) + offsetU + plane[v * 2 + 1] = source.getY(v) + offsetV + } else { + // Lathe primitives have no unwrap; project them, they are small enough + // that the stretch never reads. + faceNormal.fromBufferAttribute(normals, v).transformDirection(object.matrixWorld) + const ax = Math.abs(faceNormal.x) + const ay = Math.abs(faceNormal.y) + const az = Math.abs(faceNormal.z) + const dominant = ax >= ay && ax >= az ? 0 : ay >= az ? 1 : 2 + plane[v * 2] = dominant === 0 ? vertex.z : vertex.x + plane[v * 2 + 1] = dominant === 1 ? vertex.z : vertex.y + } + mask[v * 4 + 3] = flakeScale + + colour[v * 3] = material.color.r + colour[v * 3 + 1] = material.color.g + colour[v * 3 + 2] = material.color.b + surface[v * 4] = material.roughness + surface[v * 4 + 1] = material.metalness + surface[v * 4 + 2] = profile.rub + surface[v * 4 + 3] = profile.grime + wearDir[v * 4] = profile.scratch + wearDir[v * 4 + 1] = direction.x + wearDir[v * 4 + 2] = direction.y + wearDir[v * 4 + 3] = direction.z + } + geometry.setAttribute('aMask', new Float32BufferAttribute(mask, 4)) + geometry.setAttribute('aPlane', new Float32BufferAttribute(plane, 2)) + geometry.setAttribute('aSurface', new Float32BufferAttribute(surface, 4)) + geometry.setAttribute('aWearDir', new Float32BufferAttribute(wearDir, 4)) + geometry.deleteAttribute('aEdge') + geometry.deleteAttribute('aOcc') + geometry.setAttribute('aColor', new Float32BufferAttribute(colour, 3)) + }) +} + +export const WEAR_ATTRIBUTES = ['aMask', 'aColor', 'aSurface', 'aWearDir', 'aPlane'] as const + +/** + * The single wear material. + * + * Deliberately no fractal noise in any placement term. Fractal noise is + * isotropic, so it produces soft clouds, and clouds read as fog rather than as + * damage. Real wear is structured and hard-edged: paint chips off in discrete + * flakes with crisp boundaries, scratches are thin straight cuts, and grime is + * placed by cavities and gravity with noise only varying its density. + */ +export interface WearMaterialOptions { + readonly name?: string + readonly clearcoat?: number + readonly clearcoatRoughness?: number +} + +export function createWearMaterial(options: WearMaterialOptions = {}): MeshPhysicalMaterial { + const material = new MeshPhysicalMaterial({ name: options.name ?? 'asset-forge / worn surface' }) + material.clearcoat = options.clearcoat ?? 0.3 + material.clearcoatRoughness = options.clearcoatRoughness ?? 0.3 + // One graph, shared across all four outputs. Calling wearOutputs() per output + // builds the whole noise stack once per channel and costs four times as much. + const outputs = wearOutputs() + material.colorNode = outputs.colour + material.roughnessNode = outputs.roughness + material.metalnessNode = outputs.metalness + material.normalNode = outputs.normal + return material +} + +export interface WearOutputs { + colour: typeof positionWorld + roughness: typeof positionWorld.x + metalness: typeof positionWorld.x + normal: typeof positionWorld + worldNormal: typeof positionWorld +} + +/** + * The whole wear stack as node expressions. + * + * Everything is evaluated in the surface's own plane rather than in 3D. Slicing + * a 3D noise field with a surface is both the reason the cracks read as flat + * polygonal cells and the reason this was costing three 27-cell worley lookups + * per pixel per output. Cracks and chips are surface phenomena, so 2D is both + * cheaper and correct. All noise here is a four-tap value noise. + */ +export function wearOutputs(): WearOutputs { + /** A plain float-valued node; the concrete TSL node classes vary by helper. */ + type Scalar = typeof positionLocal.x + + const mask = attribute('aMask', 'vec4') as unknown as ReturnType + const packed = attribute('aSurface', 'vec4') as unknown as ReturnType + const wearDir = attribute('aWearDir', 'vec4') as unknown as ReturnType + const baseColour = attribute('aColor', 'vec3') as unknown as ReturnType + + const edge = mask.x + const occ = mask.y + const grooveOn = step(float(0.5), mask.z) + const grooveCross = step(float(1.5), mask.z) + const surface = packed + const character = vec3(packed.z, packed.w, wearDir.x) + const grooveDir = vec3(wearDir.y, wearDir.z, wearDir.w) + + const metalColour = vec3(0.56, 0.575, 0.59) + const grimeColour = vec3(0.16, 0.15, 0.13) + const dustColour = vec3(0.47, 0.46, 0.42) + + // Object-local coordinates keep the procedural surface attached to an + // animated assembly. The geometry is merged into root/lid local space before + // rendering, so this costs the same as positionWorld while following the + // lid's hinge transform instead of swimming through it in world space. + const p = positionLocal + + // Surface-plane coordinates and the axis they came from, both baked per vertex + // so they are stable no matter how the shading normal wobbles. + const planeCoord = attribute('aPlane', 'vec2') as unknown as ReturnType + const planeU = planeCoord.x.toVar() + const planeV = planeCoord.y.toVar() + // A surface basis from the normal, so nothing here depends on world axes. + const helper = mix(vec3(0, 1, 0), vec3(1, 0, 0), step(float(0.9), abs(normalWorld.y))) + const tangentU = normalize(cross(helper, normalWorld)) + const tangentV = cross(normalWorld, tangentU) + + const lattice = (x: Scalar, y: Scalar) => hash(x.mul(127.1).add(y.mul(311.7))) + /** Four-tap 2D value noise, for the surface-space grain only. */ + const noise = (x: Scalar, y: Scalar) => { + const ix = floor(x) + const iy = floor(y) + const fx = fract(x) + const fy = fract(y) + const ux = fx.mul(fx).mul(fx.mul(-2).add(3)) + const uy = fy.mul(fy).mul(fy.mul(-2).add(3)) + return mix( + mix(lattice(ix, iy), lattice(ix.add(1), iy), ux), + mix(lattice(ix, iy.add(1)), lattice(ix.add(1), iy.add(1)), ux), + uy, + ) + } + + /** + * Eight-tap 3D value noise. + * + * Everything that should read as belonging to the object rather than to one + * panel is evaluated in object-local space with this. A 2D surface parameter cannot + * be continuous across a part boundary, or across the seam between a face and + * its own bevel, so patterns built on one always die at those edges - which is + * exactly the "bound to a single face" break. 3D has no seams and no + * projection stretch. It costs eight hashes; the worley field this replaces + * cost twenty-seven. + */ + const noise3 = (q: typeof positionWorld) => { + const i = floor(q) + const f = fract(q) + const u = f.mul(f).mul(f.mul(-2).add(3)) + const corner = (dx: number, dy: number, dz: number) => + hash(i.x.add(dx).mul(127.1).add(i.y.add(dy).mul(311.7)).add(i.z.add(dz).mul(74.7))) + return mix( + mix( + mix(corner(0, 0, 0), corner(1, 0, 0), u.x), + mix(corner(0, 1, 0), corner(1, 1, 0), u.x), + u.y, + ), + mix( + mix(corner(0, 0, 1), corner(1, 0, 1), u.x), + mix(corner(0, 1, 1), corner(1, 1, 1), u.x), + u.y, + ), + u.z, + ) + } + + // Paint chips. Frequency is scaled per part, so a bolt gets flakes sized to a + // bolt rather than the one world frequency that made small parts read as + // camouflage. Chipping is an edge phenomenon, so the mask is tied hard to the + // edge attribute and blended in rather than stepped, which stops it shouting. + const flakeScale = mask.w + const flakeField = noise3(p.mul(flakeScale.mul(22))) + const cluster = smoothstep(float(0.36), float(0.56), noise3(p.mul(flakeScale.mul(3.4)))) + const flake = smoothstep(float(0.52), float(0.36), flakeField) + const rub = pow(edge, float(3)) + .mul(flake) + .mul(cluster) + .mul(oneMinus(occ.mul(0.85))) + .mul(character.x) + .toVar() + + // Scratches as 3D slabs. A drag event picks a direction in object-local space + // and lays parallel planes along it; wherever a surface cuts those planes it + // gets straight parallel cuts that carry on across bevels and onto the next part. + const region = floor(p.mul(0.4)) + const seed = region.x.mul(37.3).add(region.y.mul(91.7)).add(region.z.mul(53.1)) + const azimuth = hash(seed).mul(6.2831853) + const height = hash(seed.add(3.7)).mul(2).sub(1) + const ring = sqrt(clamp(oneMinus(height.mul(height)), 0, 1)) + const slab = vec3(cos(azimuth).mul(ring), height, sin(azimuth).mul(ring)) + const pitch = hash(seed.add(5.1)).mul(24).add(26) + const band = p.dot(slab).mul(pitch).add(hash(seed.add(11.3)).mul(20)) + const cell = floor(band) + const offset = fract(band).sub(0.5) + const across = abs(offset).mul(2) + const halfWidth = hash(cell.mul(7.7).add(seed)).mul(0.13).add(0.05) + const line = step(across, halfWidth) + const picked = step(float(0.78), hash(cell.mul(13.1).add(seed.mul(3.3)))) + const alongDir = normalize(cross(slab, vec3(0.31, 0.79, 0.53))) + const run = step(float(0.36), hash(floor(p.dot(alongDir).mul(1.7)).mul(19.7).add(cell.mul(3.1)))) + // A slab lying nearly parallel to the surface would smear into a wide wash, + // so fade the cut out as the two approach alignment. + const bite = oneMinus(abs(slab.dot(normalWorld))) + const exposure = oneMinus(occ).mul(smoothstep(float(-0.2), float(0.5), normalWorld.y.add(0.25))) + const cut = line.mul(picked).mul(run).mul(exposure).mul(smoothstep(float(0.15), float(0.5), bite)).toVar() + const scratch = cut.mul(character.z) + const trough = oneMinus(clamp(across.div(halfWidth), 0, 1)).mul(scratch).toVar() + const lip = clamp(across.div(halfWidth), 0, 1).mul(scratch).toVar() + + // Brushed finish. Deliberately carried by roughness rather than by the normal: + // the grain's fast axis is the baked surface parameter, but the direction it + // can be tilted along comes from a cross-product basis that has no relation to + // it, so where the two disagree a normal-driven grain visibly stretches and + // thins from face to face. Roughness has no direction to get wrong, and a + // brushed surface reads through the specular anyway. + const grain = noise(planeU.mul(3.1), planeV.mul(68)).sub(0.5).toVar() + const grainFine = noise(planeU.mul(9), planeV.mul(165)).sub(0.5) + const finish = grain.mul(0.68).add(grainFine.mul(0.32)).mul(surface.y.add(0.4)).toVar() + + // Engraved marks are flat geometry, so their depth comes from a V profile + // read across the mark's own UVs. + const grooveCoord = mix(uv().x, uv().y, grooveCross) + const grooveFloor = oneMinus(abs(grooveCoord.sub(0.5)).mul(2)).mul(grooveOn).toVar() + const grooveWall = clamp(grooveCoord.sub(0.5).mul(2), -1, 1).mul(grooveOn) + + // Grime. Occlusion and gravity place all of it; noise only varies density. + const down = clamp(normalWorld.y.negate(), 0, 1) + const up = clamp(normalWorld.y, 0, 1) + const splash = smoothstep(float(1.05), float(0.12), p.y) + const streak = noise3(p.mul(vec3(9, 0.9, 9))) + const grime = clamp(occ.mul(1.15).add(down.mul(0.24)).add(splash.mul(0.3)), 0, 1) + .mul(streak.mul(0.4).add(0.7)) + .mul(character.y) + .toVar() + const dust = up.mul(0.26).mul(streak.mul(0.5).add(0.5)).mul(oneMinus(rub)).mul(character.y) + + let colour = mix(baseColour, grimeColour, grime.mul(0.6)) + colour = mix(colour, dustColour, dust.mul(0.28)) + colour = mix(colour, metalColour, rub.mul(0.55)) + colour = mix(colour, grimeColour, trough.mul(0.85)) + colour = mix(colour, metalColour, lip.mul(0.6)) + colour = colour.mul(oneMinus(grooveFloor.mul(0.35))) + + const roughness = clamp( + surface.x + .add(grime.mul(0.3)) + .add(trough.mul(0.38)) + .add(grooveFloor.mul(0.2)) + .sub(rub.mul(0.2)) + .sub(lip.mul(0.18)) + .add(finish.mul(0.1)), + 0.04, + 1, + ) + const metalness = clamp( + surface.y.add(rub.mul(0.35)).add(lip.mul(0.25)).sub(grime.mul(0.22)), + 0, + 1, + ) + + // Normals. The scratch walls tilt across the cut, the crack walls tilt along + // the gradient of the ridge field - which is what gives a crack actual depth + // rather than leaving it a grey line - and engraved marks use their baked axis. + // A cut leans its walls toward its own centre: on the +across side the normal + // tilts to -across. Adding +across instead builds a raised welt, which is why + // every scratch read as sticking out of the surface rather than into it. + // A cut leans its walls toward its own centre: on the +across side the normal + // tilts to -across. Adding +across instead builds a raised welt, which is why + // every scratch read as sticking out of the surface rather than into it. + const wall = clamp(offset.div(halfWidth), -1, 1).mul(cut).mul(character.z).mul(1.9) + const inPlane = slab.sub(normalWorld.mul(slab.dot(normalWorld))) + const acrossCut = inPlane.div(max(inPlane.length(), float(1e-4))) + + const perturbed = normalWorld + .sub(acrossCut.mul(wall)) + .sub(grooveDir.mul(grooveWall.mul(0.85))) + .add(tangentV.mul(finish.mul(0.055))) + .normalize() + + return { + colour, + roughness, + metalness, + normal: transformNormalToView(perturbed), + worldNormal: perturbed, + } +} diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 0000000..8bb97eb --- /dev/null +++ b/src/main.ts @@ -0,0 +1,168 @@ +import { WebGPURenderer } from 'three/webgpu' +import { Color, DirectionalLight, HemisphereLight, PerspectiveCamera, Scene, Vector3 } from 'three' +import { OrbitControls } from 'three/addons/controls/OrbitControls.js' + +// İki farklı registry'den iki model. Aynı CLI, aynı proje, aynı render döngüsü. +import { createPreview as createGaugePreview } from '@/models/scifi-kit/pressure-gauge/model.ts' +import { createModel as createBarrel } from '@/models/medieval-kit/wooden-barrel/model.ts' + +const canvas = document.querySelector('#viewport')! +const status = document.querySelector('#status')! +const stageButtons = document.querySelectorAll('[data-stage]') +const actionButton = document.querySelector('#action')! + +if (!navigator.gpu) { + status.classList.add('error') + status.textContent = + 'Bu tarayıcıda WebGPU yok. scifi-kit modelleri TSL düğüm materyalleri kullanıyor ve ' + + 'WebGPURenderer gerektiriyor. Chrome/Edge 113+ deneyin.' + throw new Error('WebGPU unavailable') +} + +const renderer = new WebGPURenderer({ canvas, antialias: true }) +await renderer.init() +renderer.setPixelRatio(Math.min(globalThis.devicePixelRatio, 2)) + +interface Stage { + readonly scene: Scene + readonly camera: PerspectiveCamera + readonly target: Vector3 + readonly actionLabel: string + readonly note: string + action(): void + update(deltaSeconds: number): void + dispose(): void +} + +/** + * Sci-fi ölçer: sahneyi, ışıkları ve referans kamerasını modelin kendi + * `createPreview` fonksiyonu kuruyor. Model yazarının niyet ettiği kadraj bu. + */ +function gaugeStage(aspect: number): Stage { + const preview = createGaugePreview({ aspect }) + return { + scene: preview.scene, + camera: preview.camera, + target: new Vector3(0.25, 2.55, 0), + actionLabel: 'Basınç testi', + note: '@scifi-kit/pressure-gauge · WebGPU + TSL aşınma materyali · sahne modelin createPreview\'ından geliyor', + action: () => preview.triggerPressureTest(), + update: (delta) => preview.update(delta), + dispose: () => preview.dispose(), + } +} + +/** + * Medieval fıçı: registry sadece modeli dağıtıyor, önizleme yok. Sahneyi, + * ışıkları ve kamerayı uygulama kuruyor — vibe3d'nin asıl sözleşmesi bu. + */ +function barrelStage(aspect: number): Stage { + const barrel = createBarrel() + + const scene = new Scene() + scene.background = new Color(0x0b0d10) + scene.add(barrel.root) + scene.add(new HemisphereLight(0xb9c7d4, 0x141008, 0.7)) + const key = new DirectionalLight(0xffe9c4, 2.4) + key.position.set(-3, 5, 4) + scene.add(key) + const rim = new DirectionalLight(0x8fb4d6, 0.9) + rim.position.set(4, 3, -4) + scene.add(rim) + + const camera = new PerspectiveCamera(35, aspect, 0.05, 50) + camera.position.set(1.5, 1.25, 2.1) + camera.lookAt(0, 0.1, 0) + scene.add(camera) + + // configure() topolojiyi yeniden kurar ama kök ve anchor'lar aynı kalır. + const staveOptions = [12, 7, 20] + let staveIndex = 0 + + return { + scene, + camera, + target: new Vector3(0, 0.1, 0), + actionLabel: 'Tahta sayısını değiştir', + note: '@medieval-kit/wooden-barrel · sizin registry\'niz · düz WebGL materyali, TSL yok', + action: () => { + staveIndex = (staveIndex + 1) % staveOptions.length + const result = barrel.configure({ staveCount: staveOptions[staveIndex] }) + status.textContent = `staveCount = ${staveOptions[staveIndex]} · rebuilt = ${result.rebuilt} · kök nesne aynı kaldı` + }, + update: () => undefined, + dispose: () => { + scene.remove(barrel.root) + barrel.dispose() + }, + } +} + +const stages = { gauge: gaugeStage, barrel: barrelStage } as const +type StageName = keyof typeof stages + +let stage: Stage +let controls: OrbitControls + +function aspect(): number { + const width = canvas.clientWidth || 1 + const height = canvas.clientHeight || 1 + return width / height +} + +function selectStage(name: StageName): void { + stage?.dispose() + controls?.dispose() + stage = stages[name](aspect()) + controls = new OrbitControls(stage.camera, canvas) + controls.enableDamping = true + controls.target.copy(stage.target) + actionButton.textContent = stage.actionLabel + status.textContent = stage.note + for (const button of stageButtons) { + button.classList.toggle('active', button.dataset.stage === name) + } + resize() +} + +// ResizeObserver, `resize` olayından daha güvenilir: sekme gizliyken açılan ya da +// düzeni sonradan oturan sayfalarda canvas 0x0 kalmıyor. +function resize(): void { + const width = canvas.clientWidth + const height = canvas.clientHeight + if (width === 0 || height === 0) return + renderer.setSize(width, height, false) + stage.camera.aspect = width / height + stage.camera.updateProjectionMatrix() +} + +selectStage('gauge') +new ResizeObserver(resize).observe(canvas) + +for (const button of stageButtons) { + button.addEventListener('click', () => selectStage(button.dataset.stage as StageName)) +} +actionButton.addEventListener('click', () => stage.action()) + +// Geliştirme kolaylığı: konsoldan `__vibe3d.stage.scene` ile sahneyi gezebilir, +// `__vibe3d.renderOnce()` ile sekme arka plandayken bile tek kare aldırabilirsiniz. +if (import.meta.env.DEV) { + Object.defineProperty(globalThis, '__vibe3d', { + value: { + renderer, + get stage() { return stage }, + renderOnce: () => renderer.render(stage.scene, stage.camera), + }, + configurable: true, + }) +} + +let previous = performance.now() +renderer.setAnimationLoop(() => { + const now = performance.now() + const delta = (now - previous) / 1000 + previous = now + stage.update(delta) + controls.update() + void renderer.render(stage.scene, stage.camera) +}) diff --git a/src/models/medieval-kit/core/geometry.ts b/src/models/medieval-kit/core/geometry.ts new file mode 100644 index 0000000..043e4f7 --- /dev/null +++ b/src/models/medieval-kit/core/geometry.ts @@ -0,0 +1,292 @@ +import { BufferAttribute, BufferGeometry, Color } from 'three' +import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js' + +/** + * Kitin geometri dili. + * + * Hepsi INDEKSSİZ üretiliyor. Sebep: indekssiz geometride + * computeVertexNormals() her üçgene kendi normalini verir, yani düz gölgeleme + * (flat shading) geometrinin doğal sonucu olur — materyal bayrağına gerek + * kalmaz. Lowpoly'de istediğimiz tam olarak bu. + * + * Konum çerçevesi: point(a, r, y) = (sin a · r, y, cos a · r) + * Yani a = 0 → +Z yönü; a büyüdükçe +X'e doğru. + * + * Sarımlar elle çözüldü ve `scripts/verify-model.ts` içindeki denetim onları + * mutasyonla sınıyor: dış kabuktaki radyal yüzler eksenden dışa bakmalı. + */ + +export type Vec3 = readonly [number, number, number] + +export interface Level { + /** Dikey konum (metre). */ + readonly y: number + /** O yükseklikteki DIŞ yarıçap (metre). */ + readonly radius: number +} + +function point(angle: number, radius: number, y: number): Vec3 { + return [Math.sin(angle) * radius, y, Math.cos(angle) * radius] +} + +interface Sink { + readonly position: number[] + readonly color: number[] +} + +function tri(sink: Sink, a: Vec3, b: Vec3, c: Vec3, colour: Color): void { + sink.position.push(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2]) + for (let i = 0; i < 3; i += 1) sink.color.push(colour.r, colour.g, colour.b) +} + +/** Üç köşesi ayrı renkli üçgen — dikey renk geçişleri için. */ +function triShaded(sink: Sink, a: Vec3, b: Vec3, c: Vec3, ca: Color, cb: Color, cc: Color): void { + sink.position.push(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2]) + sink.color.push(ca.r, ca.g, ca.b, cb.r, cb.g, cb.b, cc.r, cc.g, cc.b) +} + +/** Dörtgeni (a,b,c,d) sırasıyla iki üçgene böler. Normal a→b→c sarımından çıkar. */ +function quad(sink: Sink, a: Vec3, b: Vec3, c: Vec3, d: Vec3, colour: Color): void { + tri(sink, a, b, c, colour) + tri(sink, a, c, d, colour) +} + +function finish(sink: Sink): BufferGeometry { + const geometry = new BufferGeometry() + geometry.setAttribute('position', new BufferAttribute(new Float32Array(sink.position), 3)) + geometry.setAttribute('color', new BufferAttribute(new Float32Array(sink.color), 3)) + return geometry +} + +/** + * Eksen hizalı kutu. Kitin en çok kullanılan parçası: tahta, kiriş, demir + * kayış, ayak — hepsi bu. + */ +export function boxGeometry( + size: Vec3, + centre: Vec3, + colour: Color, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const [hx, hy, hz] = [size[0] / 2, size[1] / 2, size[2] / 2] + const [cx, cy, cz] = centre + const v = (sx: number, sy: number, sz: number): Vec3 => [cx + sx * hx, cy + sy * hy, cz + sz * hz] + + quad(sink, v(-1, -1, 1), v(1, -1, 1), v(1, 1, 1), v(-1, 1, 1), colour) // +Z + quad(sink, v(1, -1, -1), v(-1, -1, -1), v(-1, 1, -1), v(1, 1, -1), colour) // -Z + quad(sink, v(1, -1, 1), v(1, -1, -1), v(1, 1, -1), v(1, 1, 1), colour) // +X + quad(sink, v(-1, -1, -1), v(-1, -1, 1), v(-1, 1, 1), v(-1, 1, -1), colour) // -X + quad(sink, v(-1, 1, 1), v(1, 1, 1), v(1, 1, -1), v(-1, 1, -1), colour) // +Y + quad(sink, v(-1, -1, -1), v(1, -1, -1), v(1, -1, 1), v(-1, -1, 1), colour) // -Y + + return finish(sink) +} + +/** + * Kesik koni / prizma: ayak, sap, kâse, alev dili. + * + * `colourTop` verilirse renk yüksekliğe göre geçiş yapar — alev için gerekli, + * çünkü alevin dibi ile ucu aynı renk değildir. + */ +export function prismGeometry( + radiusBottom: number, + radiusTop: number, + height: number, + segments: number, + centre: Vec3, + colour: Color, + options: { readonly capTop?: boolean; readonly capBottom?: boolean; readonly colourTop?: Color } = {}, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const { capTop = true, capBottom = true } = options + const top = options.colourTop ?? colour + const [cx, cy, cz] = centre + const low = cy - height / 2 + const high = cy + height / 2 + const stepAngle = (Math.PI * 2) / segments + const shift = (p: Vec3): Vec3 => [p[0] + cx, p[1], p[2] + cz] + + for (let i = 0; i < segments; i += 1) { + const a0 = i * stepAngle + const a1 = (i + 1) * stepAngle + const l0 = shift(point(a0, radiusBottom, low)) + const l1 = shift(point(a1, radiusBottom, low)) + const h0 = shift(point(a0, radiusTop, high)) + const h1 = shift(point(a1, radiusTop, high)) + + // Yan yüz: dışa bakar. + triShaded(sink, l0, l1, h1, colour, colour, top) + triShaded(sink, l0, h1, h0, colour, top, top) + + if (capTop && radiusTop > 0) tri(sink, [cx, high, cz], h0, h1, top) + if (capBottom && radiusBottom > 0) tri(sink, [cx, low, cz], l1, l0, colour) + } + + return finish(sink) +} + +/** + * Bir fıçı tahtası (stave): halkanın bir dilimi, kalınlığı olan kapalı bir katı. + * + * Her seviyede dört köşe var: + * A = dış/başlangıç açısı B = dış/bitiş açısı + * C = iç/bitiş açısı D = iç/başlangıç açısı + */ +export function staveGeometry( + levels: readonly Level[], + angleStart: number, + angleEnd: number, + thickness: number, + colour: Color, +): BufferGeometry { + if (levels.length < 2) throw new Error('staveGeometry en az iki seviye ister') + + const sink: Sink = { position: [], color: [] } + + const corners = levels.map((level) => { + // Kalınlık, en ince yarıçapın yarısını geçemez; yoksa iç yüzey dışa taşar. + const inner = Math.max(level.radius * 0.5, level.radius - thickness) + return { + a: point(angleStart, level.radius, level.y), + b: point(angleEnd, level.radius, level.y), + c: point(angleEnd, inner, level.y), + d: point(angleStart, inner, level.y), + } + }) + + for (let i = 0; i < corners.length - 1; i += 1) { + const low = corners[i]! + const high = corners[i + 1]! + quad(sink, low.a, low.b, high.b, high.a, colour) // dış yüz → dışa bakar + quad(sink, low.c, low.d, high.d, high.c, colour) // iç yüz → eksene bakar + quad(sink, low.d, low.a, high.a, high.d, colour) // başlangıç kenarı + quad(sink, low.b, low.c, high.c, high.b, colour) // bitiş kenarı + } + + const top = corners.at(-1)! + const bottom = corners[0]! + quad(sink, top.a, top.b, top.c, top.d, colour) // üst kapak → +Y + quad(sink, bottom.d, bottom.c, bottom.b, bottom.a, colour) // alt kapak → -Y + + return finish(sink) +} + +/** + * Demir çember: dikdörtgen kesitli bir halka. + * + * İç yüzey kasten üretilmiyor — yaslandığı gövde onu her kameradan gizler. + * Üçgen bütçesinin dörtte biri buradan kazanılıyor. + */ +export function bandGeometry( + radius: number, + y: number, + height: number, + thickness: number, + segments: number, + colour: Color, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const half = height / 2 + const inner = radius - thickness + const stepAngle = (Math.PI * 2) / segments + + for (let i = 0; i < segments; i += 1) { + const a0 = i * stepAngle + const a1 = (i + 1) * stepAngle + + const outerLow0 = point(a0, radius, y - half) + const outerLow1 = point(a1, radius, y - half) + const outerHigh0 = point(a0, radius, y + half) + const outerHigh1 = point(a1, radius, y + half) + const innerHigh0 = point(a0, inner, y + half) + const innerHigh1 = point(a1, inner, y + half) + const innerLow0 = point(a0, inner, y - half) + const innerLow1 = point(a1, inner, y - half) + + quad(sink, outerLow0, outerLow1, outerHigh1, outerHigh0, colour) // dış → dışa + quad(sink, outerHigh0, outerHigh1, innerHigh1, innerHigh0, colour) // üst → +Y + quad(sink, innerLow0, innerLow1, outerLow1, outerLow0, colour) // alt → -Y + } + + return finish(sink) +} + +/** + * Yelpaze disk: fıçı kapağı, kâse dibi. + * + * Tek parça ahşap değil, birkaç tahtadan kurulmuş gibi okunması için her + * üçgen, merkezinin X konumuna göre bir "tahta bandına" düşer ve o bandın tonu + * vertex color'a yazılır. Geometri maliyeti sıfır. + */ +export function headGeometry( + radius: number, + y: number, + segments: number, + facing: 'up' | 'down', + colour: Color, + plankCount: number, + plankShade: number, +): BufferGeometry { + const sink: Sink = { position: [], color: [] } + const centre: Vec3 = [0, y, 0] + const stepAngle = (Math.PI * 2) / segments + const plankWidth = (radius * 2) / Math.max(1, plankCount) + const tint = new Color() + + for (let i = 0; i < segments; i += 1) { + const p0 = point(i * stepAngle, radius, y) + const p1 = point((i + 1) * stepAngle, radius, y) + + // Tahtalar X ekseni boyunca dilimlenmiş şeritler; üçgenin ağırlık + // merkezinin X'i hangi şeride düşüyorsa onun tonunu alır. + const centroidX = (p0[0] + p1[0]) / 3 + const band = Math.floor((centroidX + radius) / plankWidth) + tint.copy(colour).multiplyScalar(1 + (band % 2 === 0 ? plankShade : -plankShade)) + + if (facing === 'up') tri(sink, centre, p0, p1, tint) + else tri(sink, centre, p1, p0, tint) + } + + return finish(sink) +} + +/** + * Her üçgenin sarımını ters çevirir, yani tüm normalleri döndürür. + * + * İçi görünen kaplar için gerekli: bir kâsenin dış yüzeyi dışa, iç yüzeyi içe + * bakmalı. İkisini ayrı ayrı yazmak yerine aynı koniyi üretip birini + * çeviriyoruz. + */ +export function flipGeometry(geometry: BufferGeometry): BufferGeometry { + for (const name of ['position', 'color'] as const) { + const attribute = geometry.getAttribute(name) + if (!attribute) continue + const array = attribute.array as Float32Array + const stride = attribute.itemSize + // Üçgenin 2. ve 3. köşesini takas etmek sarımı ters çevirir. + for (let i = 0; i < attribute.count; i += 3) { + for (let k = 0; k < stride; k += 1) { + const b = (i + 1) * stride + k + const c = (i + 2) * stride + k + const swap = array[b]! + array[b] = array[c]! + array[c] = swap + } + } + attribute.needsUpdate = true + } + return geometry +} + +/** + * Aynı materyali paylaşan parçaları tek geometriye indirger — materyal başına + * tek çizim çağrısı. Normaller birleştirmeden SONRA hesaplanır: indekssiz + * geometride bu her üçgene kendi normalini verir, yani düz gölgeleme. + */ +export function mergeColoured(geometries: readonly BufferGeometry[]): BufferGeometry { + const merged = mergeGeometries(geometries as BufferGeometry[], false) + if (!merged) throw new Error('Geometriler birleştirilemedi: attribute setleri uyuşmuyor') + for (const geometry of geometries) geometry.dispose() + merged.computeVertexNormals() + return merged +} diff --git a/src/models/medieval-kit/core/index.ts b/src/models/medieval-kit/core/index.ts new file mode 100644 index 0000000..7b20fd9 --- /dev/null +++ b/src/models/medieval-kit/core/index.ts @@ -0,0 +1,15 @@ +export { createRandom, jitter } from './random.ts' +export { + bandGeometry, + boxGeometry, + flipGeometry, + headGeometry, + mergeColoured, + prismGeometry, + staveGeometry, +} from './geometry.ts' +export type { Level, Vec3 } from './geometry.ts' +export { createPart } from './parts.ts' +export type { PartSlot } from './parts.ts' +export { MEDIEVAL_PALETTE, createMedievalMaterials } from './materials.ts' +export type { MedievalPalette, MedievalSlot } from './materials.ts' diff --git a/src/models/medieval-kit/core/materials.ts b/src/models/medieval-kit/core/materials.ts new file mode 100644 index 0000000..8f4d4a0 --- /dev/null +++ b/src/models/medieval-kit/core/materials.ts @@ -0,0 +1,121 @@ +import { Color, MeshBasicMaterial, MeshStandardMaterial } from 'three' + +import type { ResourceScope } from '@/lib/vibe3d/ownership.ts' + +/** + * Kitin paylaşılan materyal seti. + * + * Kritik tercih: her materyal `vertexColors: true`. Renk varyasyonu materyalde + * değil GEOMETRİDE taşınıyor. Böylece 13 tahtanın 13 ayrı tonu olabiliyor ama + * hepsi tek materyali, dolayısıyla tek çizim çağrısını paylaşıyor. + * + * Bu, scifi-kit'in aşınma boru hattındaki fikrin küçük hâli: yüzey kimliğini + * vertex attribute'una yaz, sonra birleştir. + */ +export type MedievalSlot = 'oak' | 'iron' | 'ember' | 'char' + +/** + * Her yuvanın materyal TİPİ farklı olabilir. `ember` aydınlatılmayan bir + * MeshBasicMaterial; diğerleri PBR. Bu eşleme sayesinde model kodu hangi tipi + * aldığını derleme zamanında biliyor. + */ +export interface SlotMaterial { + readonly oak: MeshStandardMaterial + readonly iron: MeshStandardMaterial + readonly ember: MeshBasicMaterial + readonly char: MeshStandardMaterial +} + +export interface MedievalPalette { + /** Meşe gövde tonu. */ + readonly oak: Color + /** Kapak tahtası — gövdeden biraz daha soğuk ve açık (damar ucu). */ + readonly oakEnd: Color + /** Dövme demir. */ + readonly iron: Color + /** Alev dibi — sıcak ve parlak. */ + readonly ember: Color + /** Alev ucu — daha doygun, daha kırmızı. */ + readonly emberTip: Color + /** Sönmüş kömür. */ + readonly char: Color + /** Kor hâlindeki kömür. */ + readonly charHot: Color +} + +/** + * Renkler sRGB olarak yazılır; three, ColorManagement açıkken bunları içeride + * lineer uzayda saklar. Vertex color attribute'u lineer beklediği için + * `color.r/g/b` doğrudan yazılabilir — ekstra dönüşüm gerekmez. + */ +export const MEDIEVAL_PALETTE: MedievalPalette = { + oak: new Color(0x8a5a34), + oakEnd: new Color(0x9a7350), + iron: new Color(0x40464d), + ember: new Color(0xffd27a), + emberTip: new Color(0xd8571b), + char: new Color(0x241f1c), + charHot: new Color(0xc4441a), +} + +/** + * İstenen yuvalar için materyal üretir. + * + * Slot listesi bilerek zorunlu: mangalın meşeye, fıçının emissive materyale + * ihtiyacı yok. Kullanılmayan materyal üretmek hem boşuna GPU kaynağı hem de + * modelin `materialSlots` bildirimiyle çelişen bir yalan olur. + * + * Dönüş tipi istenen yuvalara daraltılır, yani `materials.ember` sadece onu + * isteyen modelde derlenir. + */ +export function createMedievalMaterials( + scope: ResourceScope, + slots: readonly S[], +): Pick { + const build: { [K in MedievalSlot]: () => SlotMaterial[K] } = { + oak: () => new MeshStandardMaterial({ + name: 'medieval-kit / oak', + // Beyaz taban: tüm renk bilgisi vertex color'dan geliyor, materyal onu + // çarpmasın diye. + color: 0xffffff, + vertexColors: true, + roughness: 0.82, + metalness: 0, + }), + iron: () => new MeshStandardMaterial({ + name: 'medieval-kit / wrought iron', + color: 0xffffff, + vertexColors: true, + roughness: 0.52, + metalness: 0.8, + }), + // Alev ışık ALMAZ, yayar. MeshStandardMaterial burada yanlış araç olurdu: + // `emissive` tek bir Color'dır, vertex renklerinden beslenmez — yani + // alevin dibinden ucuna renk geçişi yapılamaz. MeshBasicMaterial + // aydınlatmayı tamamen atlar ve vertex rengini olduğu gibi gösterir; + // toneMapped kapalı ki sahne pozlaması alevi söndürmesin. + ember: () => new MeshBasicMaterial({ + name: 'medieval-kit / ember', + color: 0xffffff, + vertexColors: true, + toneMapped: false, + }), + char: () => new MeshStandardMaterial({ + name: 'medieval-kit / charcoal', + color: 0xffffff, + vertexColors: true, + roughness: 0.95, + metalness: 0, + }), + } + + const materials = {} as { [K in S]: SlotMaterial[K] } + for (const slot of slots) { + // TypeScript ilişkili birleşimleri (correlated unions) takip edemiyor: + // `build[slot]` bir fonksiyon birleşimine genişliyor, dolayısıyla dönüşün + // tam olarak SlotMaterial[slot] olduğunu bilemiyor. Eşleme yukarıda elle + // kurulduğu için dönüşüm güvenli. + materials[slot] = scope.ownMaterial(build[slot]()) as SlotMaterial[S] + } + return materials +} diff --git a/src/models/medieval-kit/core/parts.ts b/src/models/medieval-kit/core/parts.ts new file mode 100644 index 0000000..8559bca --- /dev/null +++ b/src/models/medieval-kit/core/parts.ts @@ -0,0 +1,46 @@ +import { Group } from 'three' + +import type { PartHandle } from '@/lib/vibe3d/model.ts' + +/** + * Semantik parça yuvası: sabit anchor + değiştirilebilir içerik. + * + * vibe3d'nin en kolay yanlış anlaşılan sözleşmesi bu. `PartHandle` iki ayrı + * nesne bildirir ve ikisi AYNI OLAMAZ: + * + * anchor modelin ömrü boyunca aynı nesne. Tüketici ışığını, etiketini, + * çarpışma gövdesini, gameplay nesnesini buraya takar. + * content configure() her çağrıldığında atılıp yeniden kurulan geometri. + * + * İkisini aynı Group yapıp rebuild'de `clear()` çağırmak, tüketicinin taktığı + * her şeyi de sessizce siler — model çalışmaya devam eder, ama protokolün asıl + * vaadi bozulmuştur. `scripts/verify-model.ts` bunu ayrıca test ediyor. + */ +export interface PartSlot extends PartHandle { + readonly anchor: Group + readonly content: Group + /** İçeriği taze bir Group ile değiştirir ve onu döndürür. Anchor'a dokunmaz. */ + reset(): Group +} + +export function createPart(name: string): PartSlot { + const anchor = new Group() + anchor.name = name + let content = new Group() + content.name = `${name}/content` + anchor.add(content) + + return { + anchor, + get content(): Group { + return content + }, + reset(): Group { + anchor.remove(content) + content = new Group() + content.name = `${name}/content` + anchor.add(content) + return content + }, + } +} diff --git a/src/models/medieval-kit/core/random.ts b/src/models/medieval-kit/core/random.ts new file mode 100644 index 0000000..f7750e1 --- /dev/null +++ b/src/models/medieval-kit/core/random.ts @@ -0,0 +1,26 @@ +/** + * Deterministik rastgelelik. + * + * Prosedürel bir kitte varyasyon şart — mükemmel simetri "üretilmiş" gibi + * okunur. Ama varyasyon tekrarlanabilir olmalı: aynı seed her zaman aynı + * modeli vermeli, yoksa ne önizleme, ne test, ne de sanat yönetimi tutar. + * Math.random() bu yüzden kullanılmıyor. + * + * mulberry32: 32-bit durum, hızlı, kriptografik değil ama görsel varyasyon + * için fazlasıyla yeterli. + */ +export function createRandom(seed: number): () => number { + let state = seed >>> 0 + return () => { + state = (state + 0x6d2b79f5) >>> 0 + let t = state + t = Math.imul(t ^ (t >>> 15), t | 1) + t ^= t + Math.imul(t ^ (t >>> 7), t | 61) + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +/** -amount .. +amount aralığında simetrik sapma. */ +export function jitter(random: () => number, amount: number): number { + return (random() * 2 - 1) * amount +} diff --git a/src/models/medieval-kit/iron-brazier/model.ts b/src/models/medieval-kit/iron-brazier/model.ts new file mode 100644 index 0000000..479b029 --- /dev/null +++ b/src/models/medieval-kit/iron-brazier/model.ts @@ -0,0 +1,396 @@ +/** + * @medieval-kit/iron-brazier + * + * Kitin ilk HAREKETLİ modeli. Fıçı ve sandık statik: kurulurlar ve öyle + * kalırlar. Mangal, vibe3d protokolünün onların hiç dokunmadığı iki parçasını + * çalıştırıyor: + * + * - tipli `actions` → yak / söndür + * - `update(dt)` → alev titremesi ve ışık dalgalanması + * + * Ayrım önemli: `configure()` topolojiyi yeniden kurar ve pahalıdır, kullanıcı + * ayarı içindir. Kare başına değişen her şey `update()` içinde olmalı. + * + * Model ayrıca bir PointLight taşıyor. Işık `flame` anchor'ına takılı, yani + * configure() geometriyi yeniden kursa bile ışık hayatta kalıyor. + */ +import { + Color, + Group, + Mesh, + PointLight, + type BufferGeometry, + type Material, +} from 'three' + +import type { ConfigureResult, MaterialBindings, ModelInstance, PartHandle } from '@/lib/vibe3d/model.ts' +import { ResourceScope } from '@/lib/vibe3d/ownership.ts' + +import { + MEDIEVAL_PALETTE, + bandGeometry, + boxGeometry, + createMedievalMaterials, + createPart, + createRandom, + flipGeometry, + jitter, + mergeColoured, + prismGeometry, +} from '../core/index.ts' + +export interface IronBrazierConfig { + /** Ayak dâhil toplam yükseklik (metre). */ + readonly height: number + /** Kâsenin üst ağız yarıçapı (metre). */ + readonly bowlRadius: number + /** Kâse çevresindeki köşe sayısı. Düşük tut — lowpoly silueti bu belirler. */ + readonly bowlSegments: number + /** Ayak sayısı. */ + readonly legCount: number + /** Alev dili sayısı. 0 = alev yok, sadece kömür. */ + readonly flameCount: number + /** Varyasyon tohumu. */ + readonly seed: number +} + +export const ironBrazierDefaults: IronBrazierConfig = { + height: 0.86, + bowlRadius: 0.26, + bowlSegments: 12, + legCount: 3, + flameCount: 5, + seed: 11, +} + +export interface IronBrazierParts { + /** Kâse ve ağız çemberi. */ + readonly bowl: PartHandle + /** Ayaklar ve pabuçlar. */ + readonly legs: PartHandle + /** Sönmüş kömürler. */ + readonly coals: PartHandle + /** Alev dilleri, kor kömürler ve ışık. Söndürülünce gizlenir. */ + readonly flame: PartHandle +} + +export interface IronBrazierActions { + /** Ateşi yakar ya da söndürür. */ + setLit(lit: boolean): void + /** Şu anda yanıyor mu. */ + isLit(): boolean +} + +const SLOTS = ['iron', 'char', 'ember'] as const +type Slot = (typeof SLOTS)[number] + +interface Blade { + readonly mesh: Group + readonly phase: number + readonly speed: number + readonly reach: number +} + +export function createModel( + overrides: Partial = {}, +): ModelInstance { + let config: IronBrazierConfig = { ...ironBrazierDefaults, ...overrides } + + const scope = new ResourceScope() + const defaults = createMedievalMaterials(scope, SLOTS) + const overridesBySlot = new Map() + const resolve = (slot: Slot): Material => overridesBySlot.get(slot) ?? defaults[slot] + + const root = new Group() + root.name = 'iron-brazier' + const bowl = createPart('iron-brazier/bowl') + const legs = createPart('iron-brazier/legs') + const coals = createPart('iron-brazier/coals') + const flame = createPart('iron-brazier/flame') + root.add(bowl.anchor, legs.anchor, coals.anchor, flame.anchor) + + // Işık ANCHOR'a takılı, üretilen içeriğe değil. Anchor rebuild'de + // değişmediği için configure() ateşi söndürmüyor — tüketicinin kendi + // eklediği nesneler de aynı sebeple hayatta kalıyor. + const light = new PointLight(0xffa04d, 0, 6, 2) + light.name = 'iron-brazier/firelight' + flame.anchor.add(light) + + let owned: BufferGeometry[] = [] + let blades: Blade[] = [] + let lit = true + let elapsed = 0 + + /** Kâsenin üst ağzının dünya yüksekliği. */ + const bowlTop = (): number => config.height * 0.5 + const bowlDepth = (): number => config.bowlRadius * 0.78 + + function buildBowl(random: () => number): BufferGeometry { + const tint = new Color() + const shade = (): Color => { + tint.copy(MEDIEVAL_PALETTE.iron) + tint.offsetHSL(0, jitter(random, 0.02), jitter(random, 0.055)) + return tint + } + + const depth = bowlDepth() + const centreY = bowlTop() - depth / 2 + const outerBottom = config.bowlRadius * 0.56 + const wall = config.bowlRadius * 0.055 + + // Dış kabuk ve iç kabuk aynı koni; içteki ters çevrilmiş, çünkü kâsenin + // içine bakıldığında yüzeyler bize dönük olmalı. + const outer = prismGeometry( + outerBottom, config.bowlRadius, depth, config.bowlSegments, + [0, centreY, 0], shade(), { capTop: false, capBottom: true }, + ) + const inner = flipGeometry(prismGeometry( + outerBottom - wall, config.bowlRadius - wall, depth, config.bowlSegments, + [0, centreY + wall, 0], shade(), { capTop: false, capBottom: true }, + )) + // Ağız çemberi dış ve iç kabuğun arasındaki boşluğu kapatır ve dövme bir + // dudak izlenimi verir. + const rim = bandGeometry( + config.bowlRadius + wall * 0.4, bowlTop(), wall * 2.6, wall * 1.6, + config.bowlSegments, shade(), + ) + + return mergeColoured([outer, inner, rim]) + } + + function buildLegs(random: () => number): BufferGeometry { + const tint = new Color() + const pieces: BufferGeometry[] = [] + const attachY = bowlTop() - bowlDepth() + const legLength = attachY * 1.16 + const thickness = config.bowlRadius * 0.1 + const tilt = 0.24 + + for (let i = 0; i < Math.max(1, config.legCount); i += 1) { + const angle = (i / Math.max(1, config.legCount)) * Math.PI * 2 + tint.copy(MEDIEVAL_PALETTE.iron) + tint.offsetHSL(0, jitter(random, 0.02), jitter(random, 0.05)) + + // Önce origin'in ALTINA sarkan bir çubuk kur, sonra dışa yatır, sonra + // yerine döndür. Sıra önemli: rotate her zaman origin etrafında döner. + const leg = boxGeometry([thickness, legLength, thickness], [0, -legLength / 2, 0], tint) + leg.rotateZ(tilt) + leg.rotateY(angle) + leg.translate(0, attachY, 0) + pieces.push(leg) + + // Pabuç: ayağın yere bastığı yassı taban. + const spread = Math.sin(tilt) * legLength + const foot = boxGeometry( + [thickness * 2.1, thickness * 0.7, thickness * 2.1], + [0, 0, 0], + tint, + ) + foot.rotateY(angle) + foot.translate( + Math.sin(angle) * spread, + attachY - Math.cos(tilt) * legLength + thickness * 0.35, + Math.cos(angle) * spread, + ) + pieces.push(foot) + } + + return mergeColoured(pieces) + } + + /** Kâsenin içine dağılmış kömür parçaları. `hot` olanlar ışıldar. */ + function coalPieces(random: () => number, hot: boolean): BufferGeometry[] { + const tint = new Color() + const pieces: BufferGeometry[] = [] + const floor = bowlTop() - bowlDepth() + config.bowlRadius * 0.06 + const count = hot ? 4 : 7 + + for (let i = 0; i < count; i += 1) { + const angle = random() * Math.PI * 2 + const radius = Math.sqrt(random()) * config.bowlRadius * 0.62 + const size = config.bowlRadius * (0.13 + random() * 0.1) + tint.copy(hot ? MEDIEVAL_PALETTE.charHot : MEDIEVAL_PALETTE.char) + tint.offsetHSL(jitter(random, 0.02), jitter(random, 0.08), jitter(random, hot ? 0.09 : 0.05)) + + const coal = boxGeometry( + [size, size * 0.62, size * 0.86], + [0, 0, 0], + tint, + ) + coal.rotateY(random() * Math.PI) + coal.rotateX(jitter(random, 0.25)) + coal.translate( + Math.sin(angle) * radius, + floor + size * 0.31 + (hot ? size * 0.12 : 0), + Math.cos(angle) * radius, + ) + pieces.push(coal) + } + + return pieces + } + + /** + * Alev dilleri. Her biri ayrı bir Group içinde, çünkü update() onları tek + * tek ölçekleyip döndürecek — birleştirilmiş tek geometri kıpırdayamazdı. + */ + function buildFlame(random: () => number, target: Group): { geometries: BufferGeometry[]; blades: Blade[] } { + const geometries: BufferGeometry[] = [] + const madeBlades: Blade[] = [] + const base = bowlTop() - bowlDepth() * 0.35 + const material = resolve('ember') + const hot = new Color() + const tip = new Color() + + for (let i = 0; i < config.flameCount; i += 1) { + const angle = (i / Math.max(1, config.flameCount)) * Math.PI * 2 + jitter(random, 0.4) + const radius = config.bowlRadius * (0.1 + random() * 0.42) + const reach = config.bowlRadius * (0.85 + random() * 1.15) + const width = config.bowlRadius * (0.16 + random() * 0.13) + + hot.copy(MEDIEVAL_PALETTE.ember).offsetHSL(0, jitter(random, 0.04), jitter(random, 0.05)) + tip.copy(MEDIEVAL_PALETTE.emberTip).offsetHSL(jitter(random, 0.02), 0, jitter(random, 0.05)) + + // Uç yarıçapı sıfır: koni. Renk dipten uca geçiş yapıyor, alevin dibi ile + // ucu aynı renk değildir. + const blade = prismGeometry( + width, 0, reach, 5, + [0, reach / 2, 0], hot, + { capBottom: true, capTop: false, colourTop: tip }, + ) + geometries.push(blade) + + const holder = new Group() + holder.name = `iron-brazier/flame-${i}` + holder.position.set(Math.sin(angle) * radius, base, Math.cos(angle) * radius) + const mesh = new Mesh(blade, material) + mesh.name = `iron-brazier/flame-${i}/blade` + mesh.userData.vibe3d = { model: '@medieval-kit/iron-brazier', part: 'flame', materialSlot: 'ember' } + holder.add(mesh) + target.add(holder) + + madeBlades.push({ + mesh: holder, + phase: random() * Math.PI * 2, + speed: 2.6 + random() * 2.9, + reach, + }) + } + + return { geometries, blades: madeBlades } + } + + function attach(target: Group, geometry: BufferGeometry, part: string, slot: Slot): void { + owned.push(geometry) + const mesh = new Mesh(geometry, resolve(slot)) + mesh.name = `iron-brazier/${part}` + mesh.userData.vibe3d = { model: '@medieval-kit/iron-brazier', part, materialSlot: slot } + target.add(mesh) + } + + function build(): void { + for (const geometry of owned) geometry.dispose() + owned = [] + blades = [] + // reset() sadece üretilmiş içeriği değiştirir; anchor'lar ve onlara + // takılanlar (ışık dâhil) yerinde kalır. + const random = createRandom(config.seed) + attach(bowl.reset(), buildBowl(random), 'bowl', 'iron') + attach(legs.reset(), buildLegs(random), 'legs', 'iron') + attach(coals.reset(), mergeColoured(coalPieces(random, false)), 'coals', 'char') + + const flameTarget = flame.reset() + const glowing = coalPieces(random, true) + const built = buildFlame(random, flameTarget) + owned.push(...built.geometries) + blades = built.blades + + const hotCoals = mergeColoured(glowing) + owned.push(hotCoals) + const hotMesh = new Mesh(hotCoals, resolve('ember')) + hotMesh.name = 'iron-brazier/hot-coals' + hotMesh.userData.vibe3d = { model: '@medieval-kit/iron-brazier', part: 'flame', materialSlot: 'ember' } + flameTarget.add(hotMesh) + + applyLit() + } + + function applyLit(): void { + // Üretilen alev içeriği content'te; ışık anchor'da. İkisi de sönmeli. + flame.content.visible = lit + light.visible = lit + light.position.y = bowlTop() + if (!lit) light.intensity = 0 + } + + build() + + const materials: MaterialBindings = { + get: (slot) => (SLOTS.includes(slot as Slot) ? resolve(slot as Slot) : undefined), + override: (slot, material) => { + if (!SLOTS.includes(slot as Slot)) return + overridesBySlot.set(slot as Slot, material) + build() + }, + reset: (slot) => { + if (!overridesBySlot.delete(slot as Slot)) return + build() + }, + } + + return { + root, + parts: { bowl, legs, coals, flame }, + actions: { + setLit: (next: boolean) => { + if (next === lit) return + lit = next + applyLit() + }, + isLit: () => lit, + }, + materials, + getConfig: () => config, + configure: (patch): ConfigureResult => { + const next = { ...config, ...patch } + const changed = (Object.keys(next) as Array) + .some((keyName) => next[keyName] !== config[keyName]) + if (!changed) return { rebuilt: false } + config = next + build() + return { rebuilt: true } + }, + update: (deltaSeconds: number) => { + if (!lit) return + // Kare atlamalarında alevin fırlamaması için adımı sınırla. + elapsed += Math.min(Math.max(deltaSeconds, 0), 0.05) + + let brightness = 0 + for (const blade of blades) { + // İki farklı frekansın toplamı: tek sinüs fazla düzenli, "nefes alan" + // bir ritim veriyor; ateş öyle yanmaz. + const wave = + Math.sin(elapsed * blade.speed + blade.phase) * 0.6 + + Math.sin(elapsed * blade.speed * 2.7 + blade.phase * 1.9) * 0.4 + blade.mesh.scale.y = 1 + wave * 0.22 + blade.mesh.scale.x = 1 - wave * 0.07 + blade.mesh.scale.z = blade.mesh.scale.x + blade.mesh.rotation.z = wave * 0.09 + brightness += wave + } + + const average = blades.length > 0 ? brightness / blades.length : 0 + light.intensity = 2.4 + average * 0.9 + }, + dispose: () => { + for (const geometry of owned) geometry.dispose() + owned = [] + blades = [] + bowl.reset() + legs.reset() + coals.reset() + flame.reset() + scope.dispose() + }, + } +} diff --git a/src/models/medieval-kit/wooden-barrel/model.ts b/src/models/medieval-kit/wooden-barrel/model.ts new file mode 100644 index 0000000..e636b92 --- /dev/null +++ b/src/models/medieval-kit/wooden-barrel/model.ts @@ -0,0 +1,275 @@ +/** + * @medieval-kit/wooden-barrel + * + * Gerçek bir fıçı tek parça değildir: uçlara doğru daralan ayrı tahtalardan + * (stave) kurulur, demir çemberlerle sıkıştırılır, kapağı gövdenin içine + * gömülür ve tahtalar kapağın üstünde bir bilezik (chime) bırakır. Bu model + * onu böyle kuruyor — şişirilmiş bir silindir olarak değil. + * + * Bağımlılıklar: düz `three` ve `@medieval-kit/core`. scifi-kit'in + * primitive/aşınma boru hattına hiç dokunmuyor; WebGL yeterli. + */ +import { Color, Group, Mesh, type BufferGeometry, type Material } from 'three' + +import type { ConfigureResult, MaterialBindings, ModelInstance, PartHandle } from '@/lib/vibe3d/model.ts' +import { ResourceScope } from '@/lib/vibe3d/ownership.ts' + +import { + MEDIEVAL_PALETTE, + bandGeometry, + createMedievalMaterials, + createPart, + createRandom, + headGeometry, + jitter, + mergeColoured, + staveGeometry, + type Level, +} from '../core/index.ts' + +export interface WoodenBarrelConfig { + /** Toplam yükseklik (metre). */ + readonly height: number + /** Göbekteki (bilge) dış yarıçap (metre). */ + readonly radius: number + /** Uçların göbeğe göre ne kadar daraldığı. 0.16 = uçlar %84 genişlikte. */ + readonly taper: number + /** Tahta sayısı. Tek sayı, mükemmel simetriyi kırdığı için varsayılan. */ + readonly staveCount: number + /** Demir çember sayısı. */ + readonly hoopCount: number + /** Varyasyon tohumu. Aynı tohum her zaman aynı fıçıyı verir. */ + readonly seed: number +} + +export const woodenBarrelDefaults: WoodenBarrelConfig = { + height: 1.04, + radius: 0.41, + taper: 0.17, + staveCount: 13, + hoopCount: 4, + seed: 7, +} + +export interface WoodenBarrelParts { + /** Duvar tahtaları. */ + readonly staves: PartHandle + /** Üst ve alt kapaklar. */ + readonly heads: PartHandle + /** Demir çemberler. */ + readonly hoops: PartHandle +} + +const SLOTS = ['oak', 'iron'] as const +type Slot = (typeof SLOTS)[number] + +/** Fıçı profili: t ∈ [-1,1], uçlarda dar, göbekte geniş. */ +function profileAt(t: number, taper: number): number { + return 1 - taper * t * t +} + +/** + * Çemberler uçtan içe doğru simetrik yerleşir: en dıştakiler "chime" (uç) + * çemberi, içtekiler "bilge" (göbek) çemberi. + */ +function hoopPositions(count: number): number[] { + if (count <= 0) return [] + if (count === 1) return [0] + const outer = 0.87 + const inner = count <= 2 ? 0.87 : 0.33 + const pairs = Math.floor(count / 2) + const positions: number[] = [] + for (let i = 0; i < pairs; i += 1) { + const t = pairs === 1 ? outer : outer - (outer - inner) * (i / (pairs - 1)) + positions.push(t, -t) + } + if (count % 2 === 1) positions.push(0) + return positions +} + +export function createModel( + overrides: Partial = {}, +): ModelInstance { + let config: WoodenBarrelConfig = { ...woodenBarrelDefaults, ...overrides } + + // Modelin sahip olduğu kaynaklar. Tüketicinin verdiği materyaller buraya + // girmez, dolayısıyla dispose() onlara dokunmaz. + const scope = new ResourceScope() + const defaults = createMedievalMaterials(scope, SLOTS) + const overridesBySlot = new Map() + const resolve = (slot: Slot): Material => overridesBySlot.get(slot) ?? defaults[slot] + + // Kök ve anchor'lar modelin ömrü boyunca aynı NESNE kalır. configure() sadece + // içlerini yeniden kurar, böylece tüketicinin anchor'a taktığı ışık, etiket + // veya gameplay nesnesi rebuild'i atlatır. + const root = new Group() + root.name = 'wooden-barrel' + const staves = createPart('wooden-barrel/staves') + const heads = createPart('wooden-barrel/heads') + const hoops = createPart('wooden-barrel/hoops') + root.add(staves.anchor, heads.anchor, hoops.anchor) + + let owned: BufferGeometry[] = [] + + function buildStaves(random: () => number, half: number, levels: number[]): BufferGeometry { + const wallThickness = config.radius * 0.13 + const step = (Math.PI * 2) / config.staveCount + // Tahtalar arasında ince bir boşluk — "tek parça" değil "monte edilmiş" + // okunmasını sağlayan tek detay bu. + const gap = step * 0.055 + const tint = new Color() + const pieces: BufferGeometry[] = [] + + for (let index = 0; index < config.staveCount; index += 1) { + // Her tahta kendi ufak sapmalarını taşır: yarıçap, uç yüksekliği, ton. + // Mükemmel tekrar "üretilmiş" gibi okunur; kural: aynaları kır. + const radiusBias = 1 + jitter(random, 0.014) + const topBias = jitter(random, 0.006) + const bottomBias = jitter(random, 0.006) + + const shaped: Level[] = levels.map((t, level) => { + const edge = level === 0 ? bottomBias : level === levels.length - 1 ? topBias : 0 + return { + y: t * half + edge, + radius: config.radius * profileAt(t, config.taper) * radiusBias, + } + }) + + tint.copy(MEDIEVAL_PALETTE.oak) + tint.offsetHSL(jitter(random, 0.014), jitter(random, 0.05), jitter(random, 0.055)) + + pieces.push(staveGeometry( + shaped, + index * step + gap / 2, + (index + 1) * step - gap / 2, + wallThickness, + tint, + )) + } + + return mergeColoured(pieces) + } + + function buildHeads(random: () => number, half: number): BufferGeometry { + const wallThickness = config.radius * 0.13 + const endRadius = config.radius * profileAt(1, config.taper) + // Kapak gövdenin İÇİNE oturur ve uçtan biraz geride kalır; tahtaların + // üstte bıraktığı bilezik (chime) fıçıyı fıçı yapan siluet detayı. + const seatRadius = endRadius - wallThickness * 0.9 + const inset = config.height * 0.055 + const tint = new Color(MEDIEVAL_PALETTE.oakEnd) + tint.offsetHSL(0, jitter(random, 0.03), jitter(random, 0.03)) + + return mergeColoured([ + headGeometry(seatRadius, half - inset, config.staveCount, 'up', tint, 3, 0.06), + headGeometry(seatRadius, -half + inset, config.staveCount, 'down', tint, 3, 0.06), + ]) + } + + function buildHoops(random: () => number, half: number): BufferGeometry | undefined { + const positions = hoopPositions(config.hoopCount) + if (positions.length === 0) return undefined + + const tint = new Color() + const pieces: BufferGeometry[] = [] + + for (const t of positions) { + const seat = config.radius * profileAt(t, config.taper) + // Uç çemberleri daha geniştir: en çok zorlanan yer orası. + const bandHeight = config.height * (0.045 + 0.03 * Math.abs(t)) + tint.copy(MEDIEVAL_PALETTE.iron) + tint.offsetHSL(0, jitter(random, 0.02), jitter(random, 0.05)) + + pieces.push(bandGeometry( + seat + config.radius * 0.022, + t * half, + bandHeight, + config.radius * 0.05, + config.staveCount, + tint, + )) + } + + return mergeColoured(pieces) + } + + function build(): void { + for (const geometry of owned) geometry.dispose() + owned = [] + // reset() sadece üretilmiş içeriği değiştirir; anchor ve ona takılanlar kalır. + const staveTarget = staves.reset() + const headTarget = heads.reset() + const hoopTarget = hoops.reset() + + const random = createRandom(config.seed) + const half = config.height / 2 + // Beş seviye: uçlar, çeyrekler ve göbek. Lowpoly bir fıçı eğrisi için + // yeterli; altıncı seviye siluete ölçülebilir bir şey katmıyor. + const levels = [-1, -0.58, 0, 0.58, 1] + + const staveGeometryData = buildStaves(random, half, levels) + owned.push(staveGeometryData) + const staveMesh = new Mesh(staveGeometryData, resolve('oak')) + staveMesh.name = 'wooden-barrel/staves' + staveMesh.userData.vibe3d = { model: '@medieval-kit/wooden-barrel', part: 'staves', materialSlot: 'oak' } + staveTarget.add(staveMesh) + + const headGeometryData = buildHeads(random, half) + owned.push(headGeometryData) + const headMesh = new Mesh(headGeometryData, resolve('oak')) + headMesh.name = 'wooden-barrel/heads' + headMesh.userData.vibe3d = { model: '@medieval-kit/wooden-barrel', part: 'heads', materialSlot: 'oak' } + headTarget.add(headMesh) + + const hoopGeometryData = buildHoops(random, half) + if (hoopGeometryData) { + owned.push(hoopGeometryData) + const hoopMesh = new Mesh(hoopGeometryData, resolve('iron')) + hoopMesh.name = 'wooden-barrel/hoops' + hoopMesh.userData.vibe3d = { model: '@medieval-kit/wooden-barrel', part: 'hoops', materialSlot: 'iron' } + hoopTarget.add(hoopMesh) + } + } + + build() + + const materials: MaterialBindings = { + get: (slot) => (SLOTS.includes(slot as Slot) ? resolve(slot as Slot) : undefined), + override: (slot, material) => { + if (!SLOTS.includes(slot as Slot)) return + overridesBySlot.set(slot as Slot, material) + build() + }, + reset: (slot) => { + if (!overridesBySlot.delete(slot as Slot)) return + build() + }, + } + + return { + root, + parts: { staves, heads, hoops }, + actions: {}, + materials, + getConfig: () => config, + configure: (patch): ConfigureResult => { + const next = { ...config, ...patch } + const changed = (Object.keys(next) as Array) + .some((keyName) => next[keyName] !== config[keyName]) + if (!changed) return { rebuilt: false } + config = next + build() + return { rebuilt: true } + }, + update: () => undefined, + dispose: () => { + for (const geometry of owned) geometry.dispose() + owned = [] + staves.reset() + heads.reset() + hoops.reset() + // Sadece modelin kendi materyallerini siler; override edilenlere dokunmaz. + scope.dispose() + }, + } +} diff --git a/src/models/medieval-kit/wooden-crate/model.ts b/src/models/medieval-kit/wooden-crate/model.ts new file mode 100644 index 0000000..3486732 --- /dev/null +++ b/src/models/medieval-kit/wooden-crate/model.ts @@ -0,0 +1,273 @@ +/** + * @medieval-kit/wooden-crate + * + * Sandık, kutu değildir: dört köşe dikmesine çakılmış yatay tahta sıralarıdır. + * Aradaki ince boşluklar ve dikmelerin dışa taşması, siluete "monte edilmiş" + * okunuşunu veren şey. Bu model onu böyle kuruyor. + * + * Fıçıyla aynı core'u paylaşıyor: aynı meşe tonu, aynı deterministik + * rastgelelik, aynı vertex-renk tekniği. Yan yana koyduğunuzda aynı + * katalogdan gelmiş gibi durmalarının sebebi bu. + */ +import { Color, Group, Mesh, type BufferGeometry, type Material } from 'three' + +import type { ConfigureResult, MaterialBindings, ModelInstance, PartHandle } from '@/lib/vibe3d/model.ts' +import { ResourceScope } from '@/lib/vibe3d/ownership.ts' + +import { + MEDIEVAL_PALETTE, + boxGeometry, + createMedievalMaterials, + createPart, + createRandom, + jitter, + mergeColoured, + type Vec3, +} from '../core/index.ts' + +export interface WoodenCrateConfig { + /** Genişlik (X ekseni, metre). */ + readonly width: number + /** Yükseklik (metre). */ + readonly height: number + /** Derinlik (Z ekseni, metre). */ + readonly depth: number + /** Her yüzdeki yatay tahta sırası sayısı. */ + readonly plankRows: number + /** Demir kayış sayısı. 0 = sade ahşap sandık. */ + readonly strapCount: number + /** Varyasyon tohumu. */ + readonly seed: number +} + +export const woodenCrateDefaults: WoodenCrateConfig = { + width: 0.66, + height: 0.52, + depth: 0.52, + plankRows: 3, + strapCount: 2, + seed: 3, +} + +export interface WoodenCrateParts { + /** Köşe dikmeleri. */ + readonly posts: PartHandle + /** Yan, üst ve alt tahtalar. */ + readonly planks: PartHandle + /** Demir kayışlar. */ + readonly straps: PartHandle +} + +const SLOTS = ['oak', 'iron'] as const +type Slot = (typeof SLOTS)[number] + +export function createModel( + overrides: Partial = {}, +): ModelInstance { + let config: WoodenCrateConfig = { ...woodenCrateDefaults, ...overrides } + + const scope = new ResourceScope() + const defaults = createMedievalMaterials(scope, SLOTS) + const overridesBySlot = new Map() + const resolve = (slot: Slot): Material => overridesBySlot.get(slot) ?? defaults[slot] + + const root = new Group() + root.name = 'wooden-crate' + const posts = createPart('wooden-crate/posts') + const planks = createPart('wooden-crate/planks') + const straps = createPart('wooden-crate/straps') + root.add(posts.anchor, planks.anchor, straps.anchor) + + let owned: BufferGeometry[] = [] + + /** + * Ölçü sözleşmesi. + * + * Z-FIGHTING KURALI: hiçbir iki yüzey aynı düzlemde, aynı yöne bakarak + * örtüşmemeli. Gerçek marangozlukta parçalar birbirine geçer; burada da öyle + * yapıyoruz. Dikmeler tahtalardan dışarı taşıyor, kapak ve taban çerçeveden + * biraz sarkıyor, tahtalar birbirine küt ekleniyor. Böylece her yüzey kendi + * düzleminde tek başına. + */ + const dims = () => { + const post = Math.min(config.width, config.depth) * 0.11 + const board = post * 0.5 + return { + post, + board, + /** Dikmelerin tahta yüzeyinden ne kadar dışarı taştığı. */ + postProud: board * 0.45, + /** Kapak ve tabanın çerçeveden sarkması. */ + overhang: board * 0.6, + half: config.height / 2, + } + } + + function buildPosts(random: () => number): BufferGeometry { + const { post, board, half } = dims() + const tint = new Color() + const pieces: BufferGeometry[] = [] + const x = config.width / 2 - post / 2 + const z = config.depth / 2 - post / 2 + // Dikmeler kapak ve tabanın İÇİNE giriyor; uçları o katı parçaların + // içinde kaldığı için görünmez ve hiçbir yüzeyle hizalanmaz. + const reach = half - board * 0.3 + + for (const [sx, sz] of [[-1, -1], [1, -1], [1, 1], [-1, 1]] as const) { + tint.copy(MEDIEVAL_PALETTE.oak) + // Dikmeler gövdeden biraz daha koyu: farklı kesim, daha çok yıpranma. + tint.offsetHSL(jitter(random, 0.01), jitter(random, 0.04), -0.045 + jitter(random, 0.02)) + pieces.push(boxGeometry([post, reach * 2, post], [sx * x, 0, sz * z], tint)) + } + + return mergeColoured(pieces) + } + + function buildPlanks(random: () => number): BufferGeometry { + const { board, postProud, overhang, half } = dims() + const tint = new Color() + const pieces: BufferGeometry[] = [] + + // Yan tahtalar dikmelerin ARKASINA çekili: dış yüzleri ±width/2 değil, + // ±(width/2 - postProud). Dikmelerle aynı düzleme oturmamalarının sebebi bu. + const faceX = config.width / 2 - postProud - board / 2 + const faceZ = config.depth / 2 - postProud - board / 2 + // Küt ek (butt joint): ön/arka tahtalar yan tahtaların iç yüzüne dayanır. + // Değiyorlar ama örtüşmüyorlar — kenar teması z-fighting üretmez. + const spanX = (config.width / 2 - postProud - board) * 2 + const spanZ = (config.depth / 2 - postProud - board) * 2 + + // Sıralar kapak ve tabanın içine girecek kadar uzanıyor, ama dikmelerin + // uçlarından FARKLI bir yükseklikte bitiyor. + const wallTop = half - board * 0.65 + const rows = Math.max(1, config.plankRows) + const gap = config.height * 0.012 + const rowHeight = (wallTop * 2 - gap * (rows - 1)) / rows + + for (let row = 0; row < rows; row += 1) { + const y = -wallTop + rowHeight / 2 + row * (rowHeight + gap) + for (const side of [-1, 1] as const) { + tint.copy(MEDIEVAL_PALETTE.oak) + tint.offsetHSL(jitter(random, 0.012), jitter(random, 0.05), jitter(random, 0.06)) + pieces.push(boxGeometry([spanX, rowHeight, board], [0, y, side * faceZ], tint)) + + tint.copy(MEDIEVAL_PALETTE.oak) + tint.offsetHSL(jitter(random, 0.012), jitter(random, 0.05), jitter(random, 0.06)) + pieces.push(boxGeometry([board, rowHeight, spanZ], [side * faceX, y, 0], tint)) + } + } + + // Kapak ve taban: çerçevenin üstüne/altına oturan, biraz sarkan tahta + // levhalar. Sarkma sayesinde yan yüzleri dikmelerin yüzleriyle hizalanmıyor. + const slabWidth = config.width + overhang * 2 + const slabDepth = config.depth + overhang * 2 + const slabBoards = 3 + const slabGap = slabDepth * 0.014 + const boardDepth = (slabDepth - slabGap * (slabBoards - 1)) / slabBoards + + for (const [y, shade] of [[half - board / 2, 0.03], [-half + board / 2, -0.05]] as const) { + for (let i = 0; i < slabBoards; i += 1) { + tint.copy(MEDIEVAL_PALETTE.oakEnd) + tint.offsetHSL(jitter(random, 0.01), jitter(random, 0.04), shade + jitter(random, 0.05)) + pieces.push(boxGeometry( + [slabWidth, board, boardDepth], + [0, y, -slabDepth / 2 + boardDepth / 2 + i * (boardDepth + slabGap)], + tint, + )) + } + } + + return mergeColoured(pieces) + } + + function buildStraps(random: () => number): BufferGeometry | undefined { + if (config.strapCount <= 0) return undefined + + const { post } = dims() + const tint = new Color() + const pieces: BufferGeometry[] = [] + const bandHeight = config.height * 0.07 + const proud = post * 0.3 + + for (let i = 0; i < config.strapCount; i += 1) { + // Kayışlar üstten ve alttan içe doğru simetrik yerleşir. + const t = config.strapCount === 1 + ? 0 + : 0.6 - (1.2 * i) / (config.strapCount - 1) + const y = (t * config.height) / 2 + tint.copy(MEDIEVAL_PALETTE.iron) + tint.offsetHSL(0, jitter(random, 0.02), jitter(random, 0.06)) + + // Ön/arka kayışlar köşelerde dışa taşıyor; yan kayışlar onlara VARMADAN + // bitiyor. Böylece dört parçanın üst yüzleri köşede üst üste binmiyor. + pieces.push( + boxGeometry([config.width + proud * 2, bandHeight, proud], [0, y, config.depth / 2], tint), + boxGeometry([config.width + proud * 2, bandHeight, proud], [0, y, -config.depth / 2], tint), + boxGeometry([proud, bandHeight, config.depth - proud], [config.width / 2, y, 0], tint), + boxGeometry([proud, bandHeight, config.depth - proud], [-config.width / 2, y, 0], tint), + ) + } + + return mergeColoured(pieces) + } + + function attach(target: Group, geometry: BufferGeometry | undefined, part: string, slot: Slot): void { + if (!geometry) return + owned.push(geometry) + const mesh = new Mesh(geometry, resolve(slot)) + mesh.name = `wooden-crate/${part}` + mesh.userData.vibe3d = { model: '@medieval-kit/wooden-crate', part, materialSlot: slot } + target.add(mesh) + } + + function build(): void { + for (const geometry of owned) geometry.dispose() + owned = [] + // reset() sadece üretilmiş içeriği değiştirir; anchor ve ona takılanlar kalır. + const random = createRandom(config.seed) + attach(posts.reset(), buildPosts(random), 'posts', 'oak') + attach(planks.reset(), buildPlanks(random), 'planks', 'oak') + attach(straps.reset(), buildStraps(random), 'straps', 'iron') + } + + build() + + const materials: MaterialBindings = { + get: (slot) => (SLOTS.includes(slot as Slot) ? resolve(slot as Slot) : undefined), + override: (slot, material) => { + if (!SLOTS.includes(slot as Slot)) return + overridesBySlot.set(slot as Slot, material) + build() + }, + reset: (slot) => { + if (!overridesBySlot.delete(slot as Slot)) return + build() + }, + } + + return { + root, + parts: { posts, planks, straps }, + actions: {}, + materials, + getConfig: () => config, + configure: (patch): ConfigureResult => { + const next = { ...config, ...patch } + const changed = (Object.keys(next) as Array) + .some((keyName) => next[keyName] !== config[keyName]) + if (!changed) return { rebuilt: false } + config = next + build() + return { rebuilt: true } + }, + update: () => undefined, + dispose: () => { + for (const geometry of owned) geometry.dispose() + owned = [] + posts.reset() + planks.reset() + straps.reset() + scope.dispose() + }, + } +} diff --git a/src/models/scifi-kit/pressure-gauge/model.ts b/src/models/scifi-kit/pressure-gauge/model.ts new file mode 100644 index 0000000..e35d1c6 --- /dev/null +++ b/src/models/scifi-kit/pressure-gauge/model.ts @@ -0,0 +1,539 @@ +import { + Color, + DirectionalLight, + ExtrudeGeometry, + Float32BufferAttribute, + Group, + HemisphereLight, + Mesh, + MeshPhysicalMaterial, + PerspectiveCamera, + Scene, + Shape, + SphereGeometry, + TorusGeometry, +} from 'three/webgpu' +import { mergeVertices } from 'three/addons/utils/BufferGeometryUtils.js' + +import { + MaterialLibrary, + WEAR_ATTRIBUTES, + bakeOcclusion, + bakeSurfaceAttributes, + createWearMaterial, + cylinder, + flatPlate, + mergeStaticByMaterial, + prism, + tuneMaterial, + type MaterialHandle, + type Vec3, + type WearProfile, +} from '@/lib/vibe3d/scifi-kit/generator/index.ts' + +const FACE_Y = 3.12 +const OUTER_RADIUS = 2.46 +const BEZEL_RADIUS = 2 +const DIAL_RADIUS = 1.48 +const FRONT_Z = 0.82 + +interface GaugeMaterials { + shell: MeshPhysicalMaterial + shellShade: MeshPhysicalMaterial + graphite: MeshPhysicalMaterial + graphiteEdge: MeshPhysicalMaterial + ink: MeshPhysicalMaterial + dial: MeshPhysicalMaterial + brass: MeshPhysicalMaterial + amber: MeshPhysicalMaterial + amberDim: MeshPhysicalMaterial + cyan: MeshPhysicalMaterial +} + +function disk( + material: MeshPhysicalMaterial, + radius: number, + depth: number, + position: Vec3, + segments = 48, +): Mesh { + return cylinder(material, radius, depth, position, [Math.PI / 2, 0, 0], segments) +} + +function torus( + material: MeshPhysicalMaterial, + radius: number, + tube: number, + position: Vec3, + radialSegments = 6, + tubularSegments = 24, +): Mesh { + const mesh = new Mesh(new TorusGeometry(radius, tube, radialSegments, tubularSegments), material) + mesh.position.set(...position) + return mesh +} + +function arcPanel( + material: MeshPhysicalMaterial, + innerRadius: number, + outerRadius: number, + start: number, + sweep: number, + z: number, + depth = 0.16, +): Mesh { + const end = start + sweep + const shape = new Shape() + shape.moveTo(Math.cos(start) * outerRadius, Math.sin(start) * outerRadius) + shape.absarc(0, 0, outerRadius, start, end, false) + shape.lineTo(Math.cos(end) * innerRadius, Math.sin(end) * innerRadius) + shape.absarc(0, 0, innerRadius, end, start, true) + shape.closePath() + const bevel = Math.min(0.035, depth * 0.25, (outerRadius - innerRadius) * 0.12) + const geometry = new ExtrudeGeometry(shape, { + depth, + bevelEnabled: true, + bevelSegments: 1, + bevelSize: bevel, + bevelThickness: bevel, + curveSegments: 1, + }) + const normals = geometry.getAttribute('normal') + const edge = new Float32Array(normals.count) + for (let index = 0; index < normals.count; index += 1) { + const facing = Math.abs(normals.getZ(index)) + edge[index] = facing > 0.92 ? 0.16 : facing < 0.2 ? 0.92 : 0.58 + } + geometry.setAttribute('aEdge', new Float32BufferAttribute(edge, 1)) + const mesh = new Mesh(geometry, material) + mesh.position.set(0, FACE_Y, z - depth * 0.5) + return mesh +} + +function addMount(parent: Group, m: GaugeMaterials): void { + // The offset wall plate and its two stand-off braces are visible beyond the + // gauge's right flank. They make the object read as mounted instrumentation, + // not a freestanding clock. + parent.add( + prism(m.graphite, [1.56, 3.45, 0.34], [2.38, FACE_Y, -0.98], { + chamfer: [0.2, 0.18, 0.18, 0.2], + fillet: 0.06, + bevel: 0.06, + }), + ) + parent.add( + prism(m.graphiteEdge, [1.62, 1.62, 0.5], [1.86, FACE_Y, -0.69], { + chamfer: 0.18, + fillet: 0.06, + bevel: 0.05, + rotation: [0, 0, Math.PI * 0.25], + }), + ) + parent.add( + prism(m.graphiteEdge, [1.45, 0.34, 0.9], [2.05, FACE_Y + 0.62, -0.58], { + chamfer: 0.11, + fillet: 0.04, + bevel: 0.04, + rotation: [0, -0.16, -0.72], + }), + ) + parent.add( + prism(m.graphiteEdge, [1.45, 0.34, 0.9], [2.05, FACE_Y - 0.62, -0.58], { + chamfer: 0.11, + fillet: 0.04, + bevel: 0.04, + rotation: [0, 0.16, 0.72], + }), + ) + + for (const y of [FACE_Y - 1.14, FACE_Y + 1.14]) { + // Dark inset plus a smaller inner wall makes each mounting hole read as a + // real bored opening from the beauty camera. + parent.add(disk(m.ink, 0.21, 0.035, [2.86, y, -0.79], 24)) + parent.add(disk(m.graphiteEdge, 0.11, 0.04, [2.86, y, -0.765], 24)) + parent.add(disk(m.ink, 0.07, 0.044, [2.86, y, -0.74], 24)) + } +} + +function addHousing(parent: Group, m: GaugeMaterials): void { + // Deep white instrument shell with a dark rear gasket and stepped front lip. + parent.add(disk(m.ink, OUTER_RADIUS + 0.08, 0.36, [0, FACE_Y, -0.52])) + parent.add(disk(m.shellShade, OUTER_RADIUS + 0.05, 1.34, [0, FACE_Y, -0.02], 16)) + parent.add(disk(m.shell, OUTER_RADIUS, 0.76, [0, FACE_Y, 0.29], 16)) + parent.add(torus(m.graphite, 2.29, 0.235, [0, FACE_Y, 0.61], 8, 64)) + + // Broad annular armor segments replace a generic continuous ring. Unequal + // gaps and slightly different radial depths reproduce the reference's shell + // assembly while the sixteen-sided body carries the faceted silhouette. + for (const [start, sweep, inner, outer, material] of [ + [0.07, 0.63, 2.07, 2.52, m.shell], + [0.76, 0.69, 2.1, 2.49, m.shell], + [1.52, 0.83, 2.08, 2.5, m.shell], + [2.43, 0.71, 2.11, 2.48, m.shellShade], + [3.21, 0.79, 2.06, 2.5, m.shell], + [4.07, 0.83, 2.04, 2.53, m.shell], + [4.98, 0.69, 2.09, 2.48, m.shellShade], + [5.74, 0.47, 2.07, 2.51, m.shell], + ] as const) { + parent.add(arcPanel(material, inner, outer, start, sweep, 0.75)) + } + + // Raised caps bridge selected segment breaks instead of decorating every + // radial division. These are large enough to shape the protective shell. + for (const [angle, width] of [[0.73, 0.58], [2.38, 0.68], [3.98, 0.56], [5.69, 0.72]] as const) { + const radius = 2.34 + parent.add( + prism(m.shellShade, [width, 0.32, 0.34], [ + Math.cos(angle) * radius, + FACE_Y + Math.sin(angle) * radius, + 0.78, + ], { + chamfer: 0.08, + fillet: 0.035, + bevel: 0.035, + rotation: [0, 0, angle - Math.PI * 0.5], + }), + ) + } + + // The reference carries extra armor weight on the lower-right quadrant. + // This stepped plate also provides a believable base for the vial pod. + parent.add(prism(m.shell, [1.28, 0.56, 0.44], [1.48, 1.32, 0.58], { + chamfer: [0.1, 0.24, 0.2, 0.08], + fillet: 0.055, + bevel: 0.05, + rotation: [0, 0, 0.48], + })) + parent.add(arcPanel(m.cyan, 2.36, 2.42, 1.22, 0.42, 0.91, 0.035)) +} + +function addFace(parent: Group, m: GaugeMaterials): Group { + // The reference flange is a stack of flat machined rings, not a soft tire. + // Overlapping faceted disks leave visible annuli while preserving a deep, + // physically layered front assembly. + parent.add(disk(m.graphite, BEZEL_RADIUS + 0.16, 0.44, [0, FACE_Y, FRONT_Z + 0.04], 24)) + parent.add(disk(m.graphiteEdge, 1.98, 0.18, [0, FACE_Y, 1.15], 24)) + parent.add(disk(m.graphite, 1.74, 0.14, [0, FACE_Y, 1.26], 32)) + parent.add(torus(m.ink, 1.55, 0.07, [0, FACE_Y, 1.34], 8, 64)) + parent.add(disk(m.dial, DIAL_RADIUS, 0.085, [0, FACE_Y, 1.3], 40)) + + // Four heavy retention clamps at the cardinal axes are the reference's + // characteristic flange landmarks. + for (let index = 0; index < 4; index += 1) { + const angle = (index / 4) * Math.PI * 2 + const x = Math.sin(angle) * 2 + const y = FACE_Y + Math.cos(angle) * 2 + parent.add( + prism(m.graphiteEdge, [index === 0 ? 0.66 : 0.56, 0.34, 0.28], [x, y, 1.39], { + chamfer: 0.08, + fillet: 0.035, + bevel: 0.03, + rotation: [0, 0, -angle], + }), + ) + } + + // Four recessed fasteners at the diagonal quadrants. + for (const angle of [Math.PI * 0.25, Math.PI * 0.75, Math.PI * 1.25, Math.PI * 1.75]) { + const x = Math.sin(angle) * 1.83 + const y = FACE_Y + Math.cos(angle) * 1.83 + parent.add(disk(m.ink, 0.21, 0.055, [x, y, 1.255], 16)) + parent.add(disk(m.shellShade, 0.135, 0.065, [x, y, 1.29], 6)) + parent.add(disk(m.ink, 0.06, 0.07, [x, y, 1.33], 8)) + } + + // Readable analogue scale: long major marks every fifth division and short + // minor marks between. The open lower sector mirrors the reference dial. + const start = -2.15 + const end = 2.15 + const divisions = 30 + for (let index = 0; index <= divisions; index += 1) { + const angle = start + ((end - start) * index) / divisions + const major = index % 5 === 0 + const length = major ? 0.34 : 0.2 + const radius = DIAL_RADIUS - 0.16 - length * 0.5 + const x = Math.sin(angle) * radius + const y = FACE_Y + Math.cos(angle) * radius + parent.add( + flatPlate(m.graphite, [major ? 0.075 : 0.04, length], [x, y, 1.355], [0, 0, -angle], false), + ) + } + + // Needle, counterweight, and stacked pivot hub. + const needleAngle = 0.72 + const needleLength = 1.25 + const needlePivot = new Group() + needlePivot.name = 'pressure-gauge / animated needle' + needlePivot.position.set(0, FACE_Y, 1.43) + parent.add(needlePivot) + needlePivot.add( + prism(m.graphite, [0.105, needleLength, 0.055], [ + Math.sin(needleAngle) * needleLength * 0.44, + Math.cos(needleAngle) * needleLength * 0.44, + 0, + ], { + chamfer: [0.045, 0.045, 0.025, 0.025], + fillet: 0.02, + bevel: 0.018, + rotation: [0, 0, -needleAngle], + }), + ) + const tailLength = 0.55 + needlePivot.add( + prism(m.graphite, [0.13, tailLength, 0.06], [ + -Math.sin(needleAngle) * tailLength * 0.46, + -Math.cos(needleAngle) * tailLength * 0.46, + 0, + ], { + chamfer: 0.04, + fillet: 0.02, + bevel: 0.018, + rotation: [0, 0, -needleAngle], + }), + ) + parent.add(disk(m.graphite, 0.27, 0.09, [0, FACE_Y, 1.45], 32)) + parent.add(disk(m.graphiteEdge, 0.1, 0.095, [0, FACE_Y, 1.51], 24)) + + // Small amber status lamp in the quiet lower quadrant. + parent.add(disk(m.graphite, 0.19, 0.055, [0, FACE_Y - 1.08, 1.38], 24)) + parent.add(disk(m.amber, 0.105, 0.06, [0, FACE_Y - 1.08, 1.42], 24)) + return needlePivot +} + +function addSideIndicator(parent: Group, m: GaugeMaterials): void { + // A raised white service pod shelters the amber level tube. Its negative + // space separates it from the circular bezel and makes it a landmark. + parent.add( + prism(m.shell, [0.84, 2.46, 0.48], [2.13, FACE_Y - 0.04, 0.85], { + chamfer: [0.2, 0.2, 0.15, 0.15], + fillet: 0.055, + bevel: 0.055, + }), + ) + parent.add( + prism(m.graphite, [0.54, 1.72, 0.19], [2.13, FACE_Y - 0.04, 1.14], { + chamfer: 0.18, + fillet: 0.08, + bevel: 0.025, + }), + ) + parent.add(prism(m.ink, [0.34, 1.42, 0.08], [2.13, FACE_Y - 0.04, 1.265], { + chamfer: 0.15, + fillet: 0.07, + bevel: 0.018, + })) + parent.add(cylinder(m.amberDim, 0.105, 1.12, [2.13, FACE_Y - 0.04, 1.34], [0, 0, 0], 12)) + const sphereGeometry = new SphereGeometry(0.105, 12, 8) + for (const y of [FACE_Y - 0.54, FACE_Y + 0.54]) { + const cap = new Mesh(sphereGeometry.clone(), m.amber) + cap.position.set(2.13, y - 0.04, 1.34) + parent.add(cap) + } + for (const x of [1.92, 2.34]) { + for (const y of [FACE_Y - 0.83, FACE_Y + 0.75]) { + parent.add(disk(m.ink, 0.085, 0.04, [x, y, 1.32], 12)) + parent.add(disk(m.graphiteEdge, 0.04, 0.045, [x, y, 1.345], 8)) + } + } +} + +function addConnector(parent: Group, m: GaugeMaterials): void { + const axisX = 0.24 + const bodyBottom = FACE_Y - OUTER_RADIUS + parent.add(prism(m.graphite, [0.96, 0.56, 0.82], [axisX, bodyBottom - 0.11, -0.04], { + chamfer: 0.13, + fillet: 0.045, + bevel: 0.045, + })) + parent.add(cylinder(m.graphiteEdge, 0.5, 0.34, [axisX, bodyBottom - 0.52, -0.02], [0, 0, 0], 8)) + parent.add(cylinder(m.brass, 0.35, 0.34, [axisX, bodyBottom - 0.84, -0.02], [0, 0, 0], 12)) + parent.add(cylinder(m.graphite, 0.47, 0.5, [axisX, bodyBottom - 1.25, -0.02], [0, 0, 0], 12)) + + // Grip flutes around the coupling are geometry rather than a procedural + // normal pattern, so the silhouette survives thumbnail scale. + for (let index = 0; index < 12; index += 1) { + const angle = (index / 12) * Math.PI * 2 + const x = axisX + Math.sin(angle) * 0.47 + const z = -0.02 + Math.cos(angle) * 0.47 + parent.add(prism(m.graphiteEdge, [0.065, 0.4, 0.085], [x, bodyBottom - 1.25, z], { + chamfer: 0.02, + fillet: 0.012, + bevel: 0.012, + rotation: [0, angle, 0], + })) + } + const cyanRing = new Mesh(new TorusGeometry(0.43, 0.04, 8, 32), m.cyan) + cyanRing.position.set(axisX, bodyBottom - 1.55, -0.02) + cyanRing.rotation.x = Math.PI / 2 + parent.add(cyanRing) + parent.add(cylinder(m.graphite, 0.28, 0.62, [axisX, bodyBottom - 1.85, -0.02], [0, 0, 0], 12)) + parent.add(cylinder(m.ink, 0.18, 0.24, [axisX, bodyBottom - 2.28, -0.02], [0, 0, 0], 12)) +} + +function acquireMaterials(): { + materials: GaugeMaterials + handles: MaterialHandle[] + profiles: Map +} { + const library = new MaterialLibrary() + const shell = library.acquire({ recipeId: 'MAT-04', palette: 'SHELL-200', condition: 'maintained', seed: 3301 }) + const shellShade = library.acquire({ recipeId: 'MAT-04', palette: 'SHELL-300', condition: 'maintained', seed: 3302 }) + const graphite = library.acquire({ recipeId: 'MAT-03', palette: 'GRAPHITE-800', condition: 'maintained', seed: 3303 }) + const graphiteEdge = library.acquire({ recipeId: 'MAT-03', palette: 'GRAPHITE-700', condition: 'maintained', seed: 3304 }) + const ink = library.acquire({ recipeId: 'MAT-03', palette: 'INK-950', condition: 'maintained', seed: 3305 }) + const dial = library.acquire({ recipeId: 'MAT-07', palette: 'AMBER-050', condition: 'maintained', seed: 3306 }) + const brass = library.acquire({ recipeId: 'MAT-07', palette: 'BRASS', condition: 'maintained', seed: 3307 }) + const amber = library.acquire({ recipeId: 'MAT-09', palette: 'AMBER-400', condition: 'active', seed: 3308 }) + const amberDim = library.acquire({ recipeId: 'MAT-09', palette: 'AMBER-400', condition: 'active', seed: 3309 }) + const cyan = library.acquire({ recipeId: 'MAT-09', palette: 'CYAN-400', condition: 'active', seed: 3310 }) + + const materials: GaugeMaterials = { + shell: tuneMaterial(shell, 0xb6bab8, 0.52, 0.16, { clearcoat: 0.2 }), + shellShade: tuneMaterial(shellShade, 0x81898b, 0.58, 0.2, { clearcoat: 0.12 }), + graphite: tuneMaterial(graphite, 0x242a30, 0.43, 0.52, { clearcoat: 0.22 }), + graphiteEdge: tuneMaterial(graphiteEdge, 0x444b50, 0.39, 0.58, { clearcoat: 0.25 }), + ink: tuneMaterial(ink, 0x090d11, 0.68, 0.3), + dial: tuneMaterial(dial, 0xc79643, 0.5, 0.16, { emissive: 0.34 }), + brass: tuneMaterial(brass, 0x8c6427, 0.34, 0.72, { clearcoat: 0.18 }), + amber: tuneMaterial(amber, 0xffa21a, 0.22, 0, { emissive: 3.2 }), + amberDim: tuneMaterial(amberDim, 0xe77b08, 0.25, 0, { emissive: 1.7 }), + cyan: tuneMaterial(cyan, 0x43e7e9, 0.25, 0, { emissive: 1.8 }), + } + const profiles = new Map([ + [materials.shell, { rub: 0.78, grime: 0.66, scratch: 0.92 }], + [materials.shellShade, { rub: 0.62, grime: 0.78, scratch: 0.74 }], + [materials.brass, { rub: 0.24, grime: 0.4, scratch: 0.25 }], + ]) + + return { + handles: [shell, shellShade, graphite, graphiteEdge, ink, dial, brass, amber, amberDim, cyan], + materials, + profiles, + } +} + +export function createModel(): { + root: Group + update: (deltaSeconds: number) => void + triggerPressureTest: () => void + dispose: () => void +} { + const { materials, handles, profiles } = acquireMaterials() + const root = new Group() + root.name = 'pressure-gauge' + + addMount(root, materials) + addHousing(root, materials) + const needlePivot = addFace(root, materials) + addSideIndicator(root, materials) + addConnector(root, materials) + + // Bake form-aware grime and edge wear while every authored part still has + // its own source material and spatial relationship. Signals and the warm + // dial intentionally retain their clean emissive materials. + bakeOcclusion(root) + bakeSurfaceAttributes(root, profiles) + const wearMaterial = createWearMaterial({ name: 'pressure-gauge / worn chassis' }) + root.traverse((object) => { + if (!(object instanceof Mesh) || Array.isArray(object.material)) return + if (profiles.has(object.material as MeshPhysicalMaterial)) object.material = wearMaterial + }) + + // Collapse the static prop to one draw per resolved material. The needle is + // the only moving assembly, so it stays outside the batches and is restored + // under its pivot after the static geometry has been flattened. + root.remove(needlePivot) + const mergedGeometries = mergeStaticByMaterial(root, { + retainedAttributes: (material) => material === wearMaterial ? WEAR_ATTRIBUTES : [], + meshName: (material) => `pressure-gauge / ${material.name}`, + }) + const staticMeshes = root.children.filter((object): object is Mesh => object instanceof Mesh) + const batchedGeometries = staticMeshes.map((mesh, index) => { + const source = mergedGeometries[index] + const indexed = mergeVertices(source, 1e-5) + mesh.geometry = indexed + source.dispose() + return indexed + }) + root.add(needlePivot) + + let testElapsed = -1 + const testDuration = 2.3 + const smooth = (value: number): number => value * value * (3 - 2 * value) + + return { + root, + update: (deltaSeconds: number) => { + if (testElapsed < 0) return + testElapsed = Math.min(testDuration, testElapsed + Math.min(Math.max(deltaSeconds, 0), 0.05)) + const response = testElapsed < 0.82 + ? smooth(testElapsed / 0.82) + : 1 - smooth((testElapsed - 0.82) / (testDuration - 0.82)) + needlePivot.rotation.z = -response * 1.3 + materials.amber.emissiveIntensity = 3.2 + response * 2.2 + materials.amberDim.emissiveIntensity = 1.7 + response * 3.1 + if (testElapsed >= testDuration) { + testElapsed = -1 + needlePivot.rotation.z = 0 + materials.amber.emissiveIntensity = 3.2 + materials.amberDim.emissiveIntensity = 1.7 + } + }, + triggerPressureTest: () => { + testElapsed = 0 + }, + dispose: () => { + needlePivot.traverse((object) => { + if (object instanceof Mesh) object.geometry.dispose() + }) + for (const geometry of batchedGeometries) geometry.dispose() + wearMaterial.dispose() + for (const handle of handles) handle.release() + }, + } +} + +export function createPreview(options: { aspect: number }): { + scene: Scene + root: Group + camera: PerspectiveCamera + update: (deltaSeconds: number) => void + triggerPressureTest: () => void + dispose: () => void +} { + const controller = createModel() + const scene = new Scene() + scene.name = 'pressure-gauge / reference-matched preview' + scene.background = new Color(0x000000) + scene.add(controller.root) + + scene.add(new HemisphereLight(0x94a9b5, 0x080a0d, 0.65)) + const key = new DirectionalLight(0xfff0dc, 2.05) + key.position.set(-7, 10, 11) + scene.add(key) + const fill = new DirectionalLight(0x9ec4db, 0.75) + fill.position.set(9, 4, 8) + scene.add(fill) + const rim = new DirectionalLight(0x8ba9c0, 0.85) + rim.position.set(6, 8, -9) + scene.add(rim) + + const aspect = Number.isFinite(options.aspect) && options.aspect > 0 ? options.aspect : 1 + const camera = new PerspectiveCamera(31, aspect, 0.15, 80) + camera.name = 'pressure-gauge / reference camera' + camera.position.set(5.3, 6.15, 13.5) + camera.lookAt(0.25, 2.55, 0) + scene.add(camera) + + return { + scene, + root: controller.root, + camera, + update: controller.update, + triggerPressureTest: controller.triggerPressureTest, + dispose: () => { + scene.remove(controller.root) + controller.dispose() + }, + } +} diff --git a/src/viewer.css b/src/viewer.css new file mode 100644 index 0000000..13911f6 --- /dev/null +++ b/src/viewer.css @@ -0,0 +1,395 @@ +/* Palet, scifi-kit'in kendi materyal yuvalarından türetildi: + surface.graphite / recess.ink / signal.amber / signal.cyan */ +:root { + --ink: #0b0e12; + --graphite: #151a21; + --graphite-lift: #1e252e; + --rule: #2a333e; + --rule-soft: #202730; + --text: #c7d1db; + --text-dim: #7a8899; + --text-faint: #56636f; + --amber: #f0a93c; + --amber-dim: #8a6221; + --cyan: #5fc8e8; + + --rail: 304px; + --step: 14px; +} + +* { box-sizing: border-box; } + +html, body { + height: 100%; + margin: 0; + background: var(--ink); + color: var(--text); + font-family: Archivo, ui-sans-serif, system-ui, sans-serif; + font-size: 14px; + overflow: hidden; +} + +#app { + display: grid; + grid-template-columns: var(--rail) 1fr; + height: 100vh; + background: var(--ink); +} + +/* ---------- sol ray ---------- */ + +.rail { + display: flex; + flex-direction: column; + gap: 0; + background: var(--graphite); + border-right: 1px solid var(--rule); + overflow-y: auto; + overscroll-behavior: contain; +} + +.rail::-webkit-scrollbar { width: 10px; } +.rail::-webkit-scrollbar-track { background: var(--graphite); } +.rail::-webkit-scrollbar-thumb { background: var(--rule); border: 3px solid var(--graphite); border-radius: 5px; } + +.brand { + display: flex; + flex-direction: column; + gap: 3px; + padding: 18px var(--step) 16px; + border-bottom: 1px solid var(--rule); +} + +.brand-mark { + font-size: 15px; + font-weight: 700; + letter-spacing: -0.01em; + color: var(--text); +} + +.brand-sub { + font-family: 'IBM Plex Mono', ui-monospace, monospace; + font-size: 10.5px; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--text-faint); +} + +.block { + padding: 14px var(--step) 16px; + border-bottom: 1px solid var(--rule-soft); +} + +.block-label { + font-family: 'IBM Plex Mono', ui-monospace, monospace; + font-size: 10px; + font-weight: 500; + letter-spacing: 0.11em; + text-transform: uppercase; + color: var(--text-faint); + margin: 0 0 10px; +} + +/* ---------- registry grupları ---------- */ + +.ns-head { + display: flex; + flex-direction: column; + gap: 2px; + margin-bottom: 8px; +} + +.ns-name { + font-family: 'IBM Plex Mono', ui-monospace, monospace; + font-size: 12.5px; + font-weight: 600; + color: var(--text); +} + +.ns-source { + font-family: 'IBM Plex Mono', ui-monospace, monospace; + font-size: 10.5px; + color: var(--text-faint); + word-break: break-all; +} + +.ns-source .scheme { color: var(--cyan); } + +.models { + list-style: none; + margin: 0 0 4px; + padding: 0; + display: flex; + flex-direction: column; + gap: 3px; +} + +.model { + width: 100%; + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + padding: 8px 10px; + border: 1px solid transparent; + border-radius: 3px; + background: transparent; + color: var(--text-dim); + font-family: 'IBM Plex Mono', ui-monospace, monospace; + font-size: 12px; + text-align: left; + cursor: pointer; + transition: background 120ms ease, color 120ms ease, border-color 120ms ease; +} + +.model:hover { background: var(--graphite-lift); color: var(--text); } + +.model:focus-visible { + outline: 2px solid var(--cyan); + outline-offset: 1px; +} + +.model[aria-pressed='true'] { + background: var(--graphite-lift); + border-color: var(--amber-dim); + color: var(--text); +} + +.model[aria-pressed='true'] .model-name::before { + background: var(--amber); +} + +.model-name { display: flex; align-items: center; gap: 8px; } + +.model-name::before { + content: ''; + width: 5px; + height: 5px; + border-radius: 50%; + background: var(--rule); + flex: none; + transition: background 120ms ease; +} + +.model-tris { + font-size: 10.5px; + color: var(--text-faint); + font-variant-numeric: tabular-nums; +} + +/* ---------- okumalar ---------- */ + +.readout { + display: grid; + grid-template-columns: auto 1fr; + gap: 6px 12px; + margin: 0; + font-family: 'IBM Plex Mono', ui-monospace, monospace; + font-size: 11.5px; +} + +.readout dt { color: var(--text-faint); } + +.readout dd { + margin: 0; + text-align: right; + color: var(--text); + font-variant-numeric: tabular-nums; +} + +.readout dd.accent { color: var(--amber); } + +/* ---------- parametreler ---------- */ + +.params { + display: flex; + flex-direction: column; + gap: 13px; +} + +.param { display: flex; flex-direction: column; gap: 6px; } + +.param-top { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + font-family: 'IBM Plex Mono', ui-monospace, monospace; + font-size: 11.5px; +} + +.param-name { color: var(--text-dim); } + +.param-value { + color: var(--amber); + font-variant-numeric: tabular-nums; +} + +input[type='range'] { + -webkit-appearance: none; + appearance: none; + width: 100%; + height: 3px; + margin: 4px 0; + border-radius: 2px; + background: var(--rule); + cursor: pointer; +} + +input[type='range']:focus-visible { + outline: 2px solid var(--cyan); + outline-offset: 4px; +} + +input[type='range']::-webkit-slider-thumb { + -webkit-appearance: none; + appearance: none; + width: 13px; + height: 13px; + border-radius: 50%; + background: var(--amber); + border: 2px solid var(--graphite); +} + +input[type='range']::-moz-range-thumb { + width: 13px; + height: 13px; + border: 2px solid var(--graphite); + border-radius: 50%; + background: var(--amber); +} + +/* Sayfadaki tek düzyazı parçaları Archivo'da; tanımlayıcılar ve sayılar mono + kalıyor. Ayrım bilgi türünü kodluyor, süs değil. */ +.empty-note { + font-family: Archivo, ui-sans-serif, system-ui, sans-serif; + font-size: 11.5px; + line-height: 1.6; + color: var(--text-faint); + margin: 0; + max-width: 34ch; +} + +/* ---------- eylemler ---------- */ + +.actions { display: flex; flex-direction: column; gap: 6px; } + +.action { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + width: 100%; + padding: 9px 11px; + border: 1px solid var(--rule); + border-radius: 3px; + background: var(--graphite-lift); + color: var(--text-dim); + font-family: 'IBM Plex Mono', ui-monospace, monospace; + font-size: 11.5px; + cursor: pointer; + transition: border-color 120ms ease, color 120ms ease; +} + +.action:hover { color: var(--text); border-color: var(--text-faint); } + +.action:focus-visible { outline: 2px solid var(--cyan); outline-offset: 1px; } + +.action[aria-pressed='true'] { color: var(--amber); border-color: var(--amber-dim); } + +.action .state { color: var(--text-faint); } +.action[aria-pressed='true'] .state { color: var(--amber); } + +.action-primary { + justify-content: center; + background: var(--amber); + border-color: var(--amber); + color: #16120a; + font-weight: 600; +} + +.action-primary:hover { background: #ffbe55; border-color: #ffbe55; color: #16120a; } + +/* ---------- viewport ---------- */ + +.viewport { + position: relative; + min-width: 0; + background: var(--ink); +} + +canvas { display: block; width: 100%; height: 100%; } + +.overlay { + position: absolute; + pointer-events: none; + font-family: 'IBM Plex Mono', ui-monospace, monospace; +} + +.provenance { + top: 16px; + right: 18px; + max-width: 340px; + text-align: right; + display: flex; + flex-direction: column; + gap: 4px; +} + +.provenance .address { + font-size: 13px; + color: var(--text); +} + +.provenance .who { + font-family: Archivo, ui-sans-serif, system-ui, sans-serif; + font-size: 11.5px; + line-height: 1.55; + color: var(--text-faint); + text-wrap: balance; +} + +.provenance .who b { color: var(--cyan); font-weight: 500; } + +.hint { + left: 18px; + bottom: 16px; + font-size: 10.5px; + letter-spacing: 0.05em; + text-transform: uppercase; + color: var(--text-faint); +} + +.scale-note { + right: 18px; + bottom: 16px; + font-size: 10.5px; + color: var(--text-faint); + font-variant-numeric: tabular-nums; +} + +.fatal { + position: absolute; + inset: 0; + display: grid; + place-content: center; + gap: 10px; + padding: 40px; + text-align: center; + color: var(--text-dim); + font-family: 'IBM Plex Mono', ui-monospace, monospace; + font-size: 12.5px; + line-height: 1.6; +} + +.fatal b { color: var(--amber); font-weight: 600; } + +@media (prefers-reduced-motion: reduce) { + * { transition-duration: 0.01ms !important; } +} + +@media (max-width: 820px) { + #app { grid-template-columns: 1fr; grid-template-rows: 46vh 1fr; } + .rail { border-right: 0; border-bottom: 1px solid var(--rule); } + .provenance { max-width: 55vw; } +} diff --git a/src/viewer.ts b/src/viewer.ts new file mode 100644 index 0000000..a4439f5 --- /dev/null +++ b/src/viewer.ts @@ -0,0 +1,588 @@ +import { + Box3, + Color, + DirectionalLight, + GridHelper, + Group, + HemisphereLight, + LineBasicMaterial, + LineSegments, + Mesh, + PerspectiveCamera, + Scene, + Sphere, + Vector3, + WireframeGeometry, + type Material, + type Object3D, +} from 'three/webgpu' +import { WebGPURenderer } from 'three/webgpu' +import { OrbitControls } from 'three/addons/controls/OrbitControls.js' + +import './viewer.css' + +import { createModel as createGauge } from '@/models/scifi-kit/pressure-gauge/model.ts' +import { createModel as createBarrel } from '@/models/medieval-kit/wooden-barrel/model.ts' +import { createModel as createCrate } from '@/models/medieval-kit/wooden-crate/model.ts' +import { createModel as createBrazier } from '@/models/medieval-kit/iron-brazier/model.ts' + +/* ------------------------------------------------------------------ katalog */ + +interface ParamSpec { + readonly key: string + readonly label: string + readonly min: number + readonly max: number + readonly step: number + readonly unit?: string +} + +interface ParamGroup { + readonly specs: readonly ParamSpec[] + current(): Record + apply(patch: Record): void +} + +/** + * Kaydırıcıları modele bağlar. + * + * Viewer her modelin yapılandırma tipini bilmek zorunda değil — sadece sayısal + * alanlar görüyor. Ama `keyof C` sayesinde ÇAĞRI YERİNDE anahtarlar hâlâ + * denetleniyor: modelde olmayan bir alan yazmak derleme hatası verir. (Bu + * denetim daha önce yeniden adlandırılmış bir alanı yakalamıştı.) + */ +function numericParams( + model: { getConfig(): Readonly; configure(patch: Partial): unknown }, + specs: ReadonlyArray, +): ParamGroup { + return { + specs, + current: () => model.getConfig() as Record, + apply: (patch) => { model.configure(patch as Partial) }, + } +} + +interface Entry { + readonly id: string + readonly namespace: string + readonly address: string + readonly who: string + /** Modeli kurar; kök + istege bagli update/action döndürür. */ + build(): { + root: Group + update?: (deltaSeconds: number) => void + action?: { label(): string; run(): void } + params?: ParamGroup + dispose(): void + } +} + +const REGISTRIES = [ + { + namespace: '@scifi-kit', + scheme: 'npm:', + rest: '@scifi-kit/registry', + entries: ['pressure-gauge'], + }, + { + namespace: '@medieval-kit', + scheme: 'file:', + rest: 'my-registry/dist/registry.json', + entries: ['wooden-barrel', 'wooden-crate', 'iron-brazier'], + }, +] as const + +const CATALOG: Record = { + 'pressure-gauge': { + id: 'pressure-gauge', + namespace: '@scifi-kit', + address: '@scifi-kit/pressure-gauge', + who: 'vibe3d ekibi yazdı · npm\'den kuruldu · 539 satır TypeScript', + build: () => { + const gauge = createGauge() + return { + root: gauge.root, + update: gauge.update, + action: { label: () => 'Basınç testi', run: () => gauge.triggerPressureTest() }, + dispose: () => gauge.dispose(), + } + }, + }, + 'wooden-barrel': { + id: 'wooden-barrel', + namespace: '@medieval-kit', + address: '@medieval-kit/wooden-barrel', + who: 'bu oturumda yazıldı · sizin registry\'niz · 13 ayrı tahta, vertex renkli meşe', + build: () => { + const barrel = createBarrel() + return { + root: barrel.root, + params: numericParams(barrel, [ + { key: 'height', label: 'height', min: 0.4, max: 2, step: 0.02, unit: 'm' }, + { key: 'radius', label: 'radius', min: 0.15, max: 0.9, step: 0.01, unit: 'm' }, + { key: 'taper', label: 'taper', min: 0, max: 0.34, step: 0.01 }, + { key: 'staveCount', label: 'staveCount', min: 6, max: 28, step: 1 }, + { key: 'hoopCount', label: 'hoopCount', min: 0, max: 6, step: 1 }, + { key: 'seed', label: 'seed', min: 1, max: 64, step: 1 }, + ]), + dispose: () => barrel.dispose(), + } + }, + }, + 'wooden-crate': { + id: 'wooden-crate', + namespace: '@medieval-kit', + address: '@medieval-kit/wooden-crate', + who: "köşe dikmelerine çakılı tahta sıraları · core'un kutu primitive'i", + build: () => { + const crate = createCrate() + return { + root: crate.root, + params: numericParams(crate, [ + { key: 'width', label: 'width', min: 0.3, max: 1.4, step: 0.02, unit: 'm' }, + { key: 'height', label: 'height', min: 0.25, max: 1.2, step: 0.02, unit: 'm' }, + { key: 'depth', label: 'depth', min: 0.3, max: 1.4, step: 0.02, unit: 'm' }, + { key: 'plankRows', label: 'plankRows', min: 1, max: 6, step: 1 }, + { key: 'strapCount', label: 'strapCount', min: 0, max: 4, step: 1 }, + { key: 'seed', label: 'seed', min: 1, max: 64, step: 1 }, + ]), + dispose: () => crate.dispose(), + } + }, + }, + 'iron-brazier': { + id: 'iron-brazier', + namespace: '@medieval-kit', + address: '@medieval-kit/iron-brazier', + who: 'kitin ilk hareketli modeli · tipli actions + update() · kendi ateş ışığını taşıyor', + build: () => { + const brazier = createBrazier() + return { + root: brazier.root, + update: brazier.update, + action: { + label: () => (brazier.actions.isLit() ? 'Ateşi söndür' : 'Ateşi yak'), + run: () => brazier.actions.setLit(!brazier.actions.isLit()), + }, + params: numericParams(brazier, [ + { key: 'height', label: 'height', min: 0.4, max: 1.6, step: 0.02, unit: 'm' }, + { key: 'bowlRadius', label: 'bowlRadius', min: 0.12, max: 0.5, step: 0.01, unit: 'm' }, + { key: 'bowlSegments', label: 'bowlSegments', min: 5, max: 20, step: 1 }, + { key: 'legCount', label: 'legCount', min: 3, max: 6, step: 1 }, + { key: 'flameCount', label: 'flameCount', min: 0, max: 9, step: 1 }, + { key: 'seed', label: 'seed', min: 1, max: 64, step: 1 }, + ]), + dispose: () => brazier.dispose(), + } + }, + }, +} + +/* -------------------------------------------------------------------- iskele */ + +const app = document.querySelector('#app')! + +app.innerHTML = ` + +
+ +
+ + +
+ sürükle · tekerlek ile yakınlaş + +
+` + +const canvas = app.querySelector('canvas')! +const viewport = app.querySelector('.viewport')! +const paramsHost = app.querySelector('[data-params]')! +const paramsBlock = app.querySelector('[data-params-block]')! +const actionButton = app.querySelector('[data-action]')! +const readout = (name: string) => app.querySelector(`[data-readout="${name}"]`)! +const provenanceAddress = app.querySelector('[data-provenance-address]')! +const provenanceWho = app.querySelector('[data-provenance-who]')! +const scaleNote = app.querySelector('[data-scale]')! + +function fatal(html: string): void { + const box = document.createElement('div') + box.className = 'fatal' + box.innerHTML = html + viewport.append(box) +} + +/* ------------------------------------------------------------------ renderer */ + +// WebGPURenderer, navigator.gpu yoksa kendi WebGL2 backend'ine düşer. scifi-kit +// modelinin TSL düğüm materyali her iki yolda da derlenir. +const renderer = new WebGPURenderer({ canvas, antialias: true }) +try { + await renderer.init() +} catch (error) { + fatal(`Renderer başlatılamadı.${String(error)}`) + throw error +} +renderer.setPixelRatio(Math.min(globalThis.devicePixelRatio, 2)) + +const backend = navigator.gpu ? 'WebGPU' : 'WebGL2 (yedek)' +readout('backend').textContent = backend + +const scene = new Scene() +scene.background = new Color(0x0b0e12) +scene.add(new HemisphereLight(0x94a9b5, 0x0a0c10, 0.7)) + +const key = new DirectionalLight(0xfff0dc, 2.1) +key.position.set(-7, 10, 11) +const fill = new DirectionalLight(0x9ec4db, 0.8) +fill.position.set(9, 4, 8) +const rim = new DirectionalLight(0x8ba9c0, 0.95) +rim.position.set(6, 8, -9) +scene.add(key, fill, rim) + +const camera = new PerspectiveCamera(34, 1, 0.02, 400) +const controls = new OrbitControls(camera, canvas) +controls.enableDamping = true +controls.autoRotateSpeed = 0.9 + +let grid: GridHelper | undefined + +/* ------------------------------------------------------------------- durumlar */ + +let current: ReturnType | undefined +let currentEntry: Entry | undefined +let wireframe = false +let showGrid = true + +const triangleCounts = new Map() + +interface Survey { + meshes: number + triangles: number + materials: number + size: Vector3 + centre: Vector3 + radius: number +} + +function survey(root: Object3D): Survey { + let meshes = 0 + let triangles = 0 + const materials = new Set() + + root.traverse((object) => { + if (!(object instanceof Mesh)) return + meshes += 1 + const index = object.geometry.getIndex() + const position = object.geometry.getAttribute('position') + triangles += Math.round((index ? index.count : position.count) / 3) + for (const material of Array.isArray(object.material) ? object.material : [object.material]) { + materials.add(material) + } + }) + + const box = new Box3().setFromObject(root) + const sphere = box.getBoundingSphere(new Sphere()) + return { + meshes, + triangles, + materials: materials.size, + size: box.getSize(new Vector3()), + centre: sphere.center.clone(), + radius: sphere.radius, + } +} + +// Tel kafes, `material.wireframe` ile DEĞİL, ayrı bir çizgi katmanıyla çiziliyor. +// three'nin WebGPU backend'i bu modellerin indeksli geometrilerinde +// material.wireframe için geçerli bir index buffer üretemiyor ve +// `setIndexBuffer` hata veriyor. WireframeGeometry her iki backend'de de +// çalışıyor ve gölgeli yüzeyin üstünde okunur bir topoloji katmanı veriyor. +const wireMaterial = new LineBasicMaterial({ + color: 0x5fc8e8, + transparent: true, + opacity: 0.6, + depthWrite: false, +}) + +let wireOverlays: LineSegments[] = [] + +function applyWireframe(root: Object3D): void { + for (const overlay of wireOverlays) { + overlay.removeFromParent() + overlay.geometry.dispose() + } + wireOverlays = [] + if (!wireframe) return + + const meshes: Mesh[] = [] + root.traverse((object) => { if (object instanceof Mesh) meshes.push(object) }) + for (const mesh of meshes) { + const overlay = new LineSegments(new WireframeGeometry(mesh.geometry), wireMaterial) + overlay.renderOrder = 1 + mesh.add(overlay) + wireOverlays.push(overlay) + } +} + +/** Modeli, ölçeği ne olursa olsun kadraja oturtur. */ +function frame(info: Survey): void { + const distance = (info.radius * 1.15) / Math.sin((camera.fov * Math.PI) / 360) + const direction = new Vector3(0.62, 0.42, 1).normalize() + camera.position.copy(info.centre).addScaledVector(direction, distance) + camera.near = Math.max(0.01, distance - info.radius * 3) + camera.far = distance + info.radius * 8 + camera.updateProjectionMatrix() + controls.target.copy(info.centre) + controls.update() +} + +function rebuildGrid(info: Survey): void { + if (grid) { + scene.remove(grid) + grid.geometry.dispose() + } + // Izgara adımı modelin ölçeğine göre: 1 m, 0.5 m ya da 0.1 m. + const span = Math.max(info.size.x, info.size.z) + const stepSize = span > 4 ? 1 : span > 1.2 ? 0.5 : 0.1 + const divisions = Math.max(8, Math.ceil((span * 2.4) / stepSize)) + grid = new GridHelper(divisions * stepSize, divisions, 0x2a333e, 0x1a2029) + grid.position.y = new Box3().setFromObject(current!.root).min.y + grid.visible = showGrid + scene.add(grid) + scaleNote.textContent = `ızgara adımı ${stepSize} m` +} + +function renderParams(): void { + paramsHost.replaceChildren() + const params = current?.params + + if (!params) { + paramsBlock.hidden = false + const note = document.createElement('p') + note.className = 'empty-note' + note.textContent = + 'Bu model yapılandırılabilir alan bildirmiyor — registry meta\'sında controls boş.' + paramsHost.append(note) + return + } + + paramsBlock.hidden = false + for (const spec of params.specs) { + const row = document.createElement('div') + row.className = 'param' + + const top = document.createElement('div') + top.className = 'param-top' + const name = document.createElement('span') + name.className = 'param-name' + name.textContent = spec.label + const value = document.createElement('span') + value.className = 'param-value' + top.append(name, value) + + const slider = document.createElement('input') + slider.type = 'range' + slider.min = String(spec.min) + slider.max = String(spec.max) + slider.step = String(spec.step) + slider.value = String(params.current()[spec.key]) + slider.setAttribute('aria-label', spec.label) + + const show = (raw: number): void => { + const digits = spec.step < 1 ? (spec.step < 0.05 ? 2 : 2) : 0 + value.textContent = `${raw.toFixed(digits)}${spec.unit ? ` ${spec.unit}` : ''}` + } + show(Number(slider.value)) + + slider.addEventListener('input', () => { + const raw = Number(slider.value) + show(raw) + params.apply({ [spec.key]: raw }) + applyWireframe(current!.root) + const info = survey(current!.root) + writeReadout(info) + triangleCounts.set(currentEntry!.id, info.triangles) + paintTriangleBadges() + }) + + row.append(top, slider) + paramsHost.append(row) + } +} + +function writeReadout(info: Survey): void { + readout('meshes').textContent = String(info.meshes) + readout('triangles').textContent = info.triangles.toLocaleString('tr-TR') + readout('materials').textContent = String(info.materials) + readout('size').textContent = + `${info.size.x.toFixed(2)} × ${info.size.y.toFixed(2)} × ${info.size.z.toFixed(2)} m` +} + +function paintTriangleBadges(): void { + for (const [id, count] of triangleCounts) { + const badge = app.querySelector(`[data-tris-for="${id}"]`) + if (badge) badge.textContent = `${count.toLocaleString('tr-TR')} △` + } +} + +function select(id: string): void { + const entry = CATALOG[id] + if (!entry) return + + if (current) { + scene.remove(current.root) + current.dispose() + } + + currentEntry = entry + current = entry.build() + scene.add(current.root) + applyWireframe(current.root) + + const info = survey(current.root) + triangleCounts.set(id, info.triangles) + writeReadout(info) + paintTriangleBadges() + frame(info) + rebuildGrid(info) + renderParams() + + provenanceAddress.textContent = entry.address + provenanceWho.innerHTML = entry.who + + if (current.action) { + actionButton.hidden = false + actionButton.textContent = current.action.label() + } else { + actionButton.hidden = true + } + + for (const button of app.querySelectorAll('[data-model]')) { + button.setAttribute('aria-pressed', String(button.dataset.model === id)) + } +} + +/* ------------------------------------------------------------------- olaylar */ + +for (const button of app.querySelectorAll('[data-model]')) { + button.addEventListener('click', () => select(button.dataset.model!)) +} + +actionButton.addEventListener('click', () => { + current?.action?.run() + // Etiket duruma bağlı olabilir (yak / söndür), o yüzden her tıklamada tazele. + if (current?.action) actionButton.textContent = current.action.label() +}) + +function bindToggle(name: string, onChange: (on: boolean) => void, labels: [string, string]): void { + const button = app.querySelector(`[data-toggle="${name}"]`)! + const state = button.querySelector('.state')! + button.addEventListener('click', () => { + const next = button.getAttribute('aria-pressed') !== 'true' + button.setAttribute('aria-pressed', String(next)) + state.textContent = next ? labels[0] : labels[1] + onChange(next) + }) +} + +bindToggle('wireframe', (on) => { + wireframe = on + if (current) applyWireframe(current.root) +}, ['açık', 'kapalı']) + +bindToggle('spin', (on) => { controls.autoRotate = on }, ['açık', 'kapalı']) + +bindToggle('grid', (on) => { + showGrid = on + if (grid) grid.visible = on +}, ['açık', 'kapalı']) + +// ResizeObserver, `resize` olayından güvenilir: sekme gizliyken açılan ya da +// düzeni sonradan oturan sayfalarda canvas 0x0 kalmıyor. +function resize(): void { + const width = canvas.clientWidth + const height = canvas.clientHeight + if (width === 0 || height === 0) return + renderer.setSize(width, height, false) + camera.aspect = width / height + camera.updateProjectionMatrix() +} +new ResizeObserver(resize).observe(canvas) + +/* --------------------------------------------------------------------- döngü */ + +controls.autoRotate = true +select('iron-brazier') +// Seçili olmayan modellerin üçgen rozetleri için birer kez kurup ölç, sonra +// bırak. Böylece listedeki her satır ne kadar ağır olduğunu baştan söylüyor. +for (const id of Object.keys(CATALOG)) { + if (triangleCounts.has(id)) continue + const probe = CATALOG[id]!.build() + triangleCounts.set(id, survey(probe.root).triangles) + probe.dispose() +} +paintTriangleBadges() +resize() + +let previous = performance.now() +renderer.setAnimationLoop(() => { + const now = performance.now() + const delta = Math.min((now - previous) / 1000, 0.05) + previous = now + current?.update?.(delta) + controls.update() + void renderer.render(scene, camera) +}) diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..814f74a --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "types": ["vite/client", "node", "@webgpu/types"], + "baseUrl": ".", + "paths": { + "@/*": ["./src/*"] + } + }, + "include": ["src", "scripts", "vite.config.ts"] +} diff --git a/viewer.html b/viewer.html new file mode 100644 index 0000000..66cdbfb --- /dev/null +++ b/viewer.html @@ -0,0 +1,18 @@ + + + + + + Prosedürel Model İnceleyici + + + + + +
+ + + diff --git a/vite.config.ts b/vite.config.ts new file mode 100644 index 0000000..6028beb --- /dev/null +++ b/vite.config.ts @@ -0,0 +1,23 @@ +import { fileURLToPath, URL } from 'node:url' +import { defineConfig } from 'vite' + +export default defineConfig({ + resolve: { + alias: [ + // vibe3d, kurulan kaynağı "@/lib/vibe3d/..." ve "@/models/..." takma + // adlarıyla yazar. Bu adlar models.json içindeki `aliases` alanından gelir, + // o yüzden bundler tarafında da aynı şekilde tanımlanmaları gerekir. + { find: '@', replacement: fileURLToPath(new URL('./src', import.meta.url)) }, + + // `three` ve `three/webgpu` AYRI bundle'lar; ikisi de çekirdek sınıfların + // kendi kopyasını içerir. scifi-kit modeli three/webgpu'dan, taşınabilir + // medieval modeli düz three'den import ettiği için tarayıcı "Multiple + // instances of Three.js" uyarısı veriyor ve instanceof kontrolleri iki + // kopya arasında bozuluyor. WebGPU ile çalışan uygulamada standart çözüm: + // `three`yi tek kopyaya, three/webgpu'ya yönlendirmek. + // Regex şart — düz string önek eşleşmesi yapar ve "three/addons/..." yolunu + // da bozardı. + { find: /^three$/, replacement: 'three/webgpu' }, + ], + }, +}) diff --git a/vite.viewer.config.ts b/vite.viewer.config.ts new file mode 100644 index 0000000..88e525b --- /dev/null +++ b/vite.viewer.config.ts @@ -0,0 +1,28 @@ +import { fileURLToPath, URL } from 'node:url' +import { defineConfig } from 'vite' + +/** + * Viewer'ı tek dosyalık bir Artifact'e gömmek için ayrı build. + * `scripts/build-artifact.ts` çıktıyı tek HTML'e indirger. + */ +export default defineConfig({ + resolve: { + alias: [ + { find: '@', replacement: fileURLToPath(new URL('./src', import.meta.url)) }, + // `three` ve `three/webgpu` ayrı bundle'lar; ikisini de yüklemek çekirdeği + // iki kez paketler ve instanceof kontrollerini bozar. Regex şart — + // düz string önek eşleşmesi `three/addons/...` yolunu da bozardı. + { find: /^three$/, replacement: 'three/webgpu' }, + ], + }, + build: { + outDir: 'dist-viewer', + emptyOutDir: true, + target: 'esnext', + cssCodeSplit: false, + rollupOptions: { + input: fileURLToPath(new URL('./viewer.html', import.meta.url)), + output: { inlineDynamicImports: true, entryFileNames: 'viewer.js', assetFileNames: 'viewer[extname]' }, + }, + }, +})