Rebuild the object in a reference image as a code-only, procedural, quality-gated, animation-ready Three.js model. Token-efficient image-to-3D.
Python 3dai-agentsclaude-codecomputer-graphicsgenerativeimage-to-3dprocedural-generationthreejstypescriptwebgl
Feat/add cs2 item reconstruction (#27)
TamL.ffe0ace9cfcb
diff --git a/.gitignore b/.gitignoreindex 54d82d3..75e1b33 100644--- a/.gitignore+++ b/.gitignore@@ -17,3 +17,18 @@ docs/PLAN_*.md# OMC planning/team state — local orchestration artifacts, never part of a release.omc/+.omo/+.opencode/++# Extracted Valve CS2 textures -- IP belongs to Valve, never committed.+cs2_textures/++# Runtime dependencies and generated browser bundles+runtime/**/node_modules/+runtime/**/dist/+runtime/**/.vite/++.cache/spec-search/+assets/+openspec/+runtime/diff --git a/README.md b/README.mdindex 56c87da..82e203f 100644--- a/README.md+++ b/README.md@@ -56,6 +56,7 @@ It runs under Claude Code, Codex, or OpenCode. It is agent-agnostic: wherever th- **Objects and characters.** Each subject is classified `object`, `character`, or `hybrid`. Objects follow the hard-surface pipeline; characters route through an anatomy-aware track (head-unit proportions, facial landmarks, pose) documented in `grimoire/character/reconstruction.md`.- **Detail-first analysis.** Before code generation the pipeline enumerates a `detailInventory` of identity-defining small details (gloss, bevel/rounding, screws/rivets, engraved or painted linework, contours, stains and wear). Every detail must map to a real component or material entry, and a strict-quality gate blocks generation until the inventory is complete. Taxonomy: `grimoire/intake/detail_inventory.md`.- **Maximum likeness for a specific person or character.** An opt-in projection-first path fits a parametric template to image landmarks, de-lights the photo, camera-matches the render, and projects the reference onto the mesh. A single image cannot guarantee 100 percent likeness, so the pipeline reports per-region confidence and asks for more views when it matters. Details: `grimoire/character/likeness_maximization.md`.+- **CS2 knife review gates.** The manifest-driven knife path records exactness tier, family identity, painted-region and projection coverage, per-region confidence, approximation notes, and versioned review-scene metadata. See [`docs/cs2/review-gates.md`](docs/cs2/review-gates.md).---@@ -189,6 +190,7 @@ The net effect: you still get a faithful 3D model from an image, but the expensi| `stage3_build/generate_threejs_factory.py` | Emit the Three.js `Group` factory for the current unlocked pass. || `stage4_review/make_comparison_sheet.py` | Package one reference-vs-render sheet for review. || `stage4_review/append_review.py` | Record a per-pass review: scores, decision, evidence. |+| `stage4_review/cs2_review.py` | Evaluate the blocking CS2 knife review contract and versioned scene thresholds. || `_shared/feature_acceptance_policy.py` | Internal helper enforcing per-feature score thresholds. || `stage1_intake/build_detail_inventory.py` | Slice the reference into zones and scaffold a detail inventory. || `stage1_intake/extract_landmarks.py` | Overlay a landmark grid and scaffold an anatomy block for characters. |diff --git a/SKILL.md b/SKILL.mdindex 6c03d28..c4a6e94 100644--- a/SKILL.md+++ b/SKILL.md@@ -2,7 +2,7 @@name: img2threejsdescription: Turn an object or character reference image into a quality-gated, animation-ready procedural Three.js model built in code. Use for image-to-3D reconstruction, detail-accurate object rebuilds, stylized/likeness-maximized human characters, sculpt specs, and staged code generation.license: Apache-2.0-version: 1.3.0+version: 1.4.0---# img2threejs — Image to procedural Three.js@@ -24,8 +24,9 @@ action-ready props, game objects, botanical/mechanical parts, and stylized recon## Core PromiseSculpt from a photo, in order — never one-shot a mesh:-1. **Validate** the image is a suitable 3D target (`grimoire/intake/validation_rubric.md`).-2. **Assess** object class + complexity, then write a `qualityContract` before any code.+1. **Run `python3 forge/next.py <spec>` first.** It reports the current unlocked pass, exact next command, and unmet acceptance criteria.+2. **Validate** the image is a suitable 3D target (`grimoire/intake/validation_rubric.md`).+3. **Assess** object class + complexity, then write a `qualityContract` before any code.3. **Spec** it: component hierarchy, materials, lighting, pivots, sockets, action anchors.4. **Build pass-by-pass** from blockout → structure → form → material → lighting → interaction → optimization.5. **Verify** each pass with a screenshot compared against the reference; fail a pass if an identity-defining feature is wrong even when the global score looks fine.@@ -33,36 +34,101 @@ Sculpt from a photo, in order — never one-shot a mesh:State explicitly when output is approximate/stylized/low-poly. A single image cannot revealhidden sides or guarantee exact geometry — say so instead of faking confidence.+## Transparency and Process Debugging (Critical — from Bowie Knife reconstruction)++**The problem:** When the user cannot tell what was done or where something went wrong, they cannot debug the process. Over-claiming (reporting success when features still don't match) destroys trust and makes iterative improvement impossible.++**Rule:** Be transparent + don't over-claim. State exactly what changed each pass, with evidence, and name what still doesn't match:+- After each pass, explicitly list what changed: "Updated guard shape to extend left edge from -0.56 to -0.48 for handle overlap"+- Provide evidence: reference the specific values, coordinates, or parameters that changed+- Name what still doesn't match: "Handle silhouette traced but still flat plane (no Z palm-swell), procedural crosshatch not reference's exact dot-grid knurl"+- Explain why a change was made: "Extended guard left edge because handle ends at X=-0.42 and guard ended at X=-0.20, causing visual gap"+- Never claim a feature is "done" when it's only "improved" — use precise language+- When a gate passes but visual inspection shows issues, explain the limitation: "2D gate passed (fidelity 0.83) but three-quarter render shows blade reads as toy (no grind wedge) — 2D gates are blind to 3D realism"++**The user needs to be able to debug the process, not just the output.** If something is wrong, they should be able to trace which decision led to the error and correct it. Opaque processes force restarts; transparent processes enable refinement.+## Required Inputs- one image path / screenshot / URL / attached image (if missing or unreadable, ask)- intended use: prop, game object, hero render, playable/destructible object, animation rig(default: real-time browser prop with interactive performance)+- for a CS2 request, an authoritative classification record (family/subtype and evidence refs) or+ an explicit request for the user/vision provider to supply one; heuristic detection alone is not+ enough to select a geometry adapter## The Loop (scripts do enforcement; agent vision does judgment)Run scripts from the skill root (`forge/...`). Pure Python 3.10+ stdlib, no pip installs.Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that is the agent's job.-1. Probe local images: `forge/stage1_intake/probe_image.py <image>` (metadata only, not a visual check).+1. **Analyze the image first** (agent vision, before any script): work the layered observation+ protocol in `grimoire/intake/image_analysis.md` — identify/classify, decompose macro→meso→micro,+ map part relationships, name materials in PBR terms, list identity-defining features, and flag+ what the single view hides. Observation before inference; controlled 3D vocabulary; 3D+ object-space not 2D image-space. This is generic for any subject and feeds every field below.+ Then probe local images: `forge/stage1_intake/probe_image.py <image>` (metadata only, not a visual check).+1a. **Local Spec Search** — after image analysis and before writing or refining a spec, local+ evidence is a pipeline stage, not an optional memory lookup, whenever the request needs+ domain-specific anatomy, PBR, wear, geometry, runtime, or physics specifications. The pre-spec+ command automatically runs BM25, chooses `cs2` for CS2 targets and `core_3d` otherwise, and+ writes a `localSpecSearch` evidence bundle into the assessment:+ `python3 forge/stage2_spec/new_pre_spec_assessment.py "Name" --image <img> --out assessment.json`.+ Add observed terms with repeatable `--spec-query "<term>"`; use `--collection <collection>` only+ when the automatic collection choice is insufficient. `new_sculpt_spec.py --assessment` carries+ that bundle into the final spec, including snippets, `source_refs`, and `evidence_refs`.+ For extra focused retrieval, the direct CLI remains available:+ `python3 forge/stage1_intake/search_specs.py "<query>" --collection <collection> --limit 3 --snippet-chars 250 --json`.+ For CS2, include English/Vietnamese variants, for example `--spec-query "safety ring vòng ngón"`+ or `search_specs.py "roughness độ nhám" --collection cs2`. Expand queries with object names,+ component names, material/finish terms, behavior terms, and bilingual aliases; retry focused+ alternatives when the first result is incomplete. Build the spec from returned evidence and do+ not invent domain specs when local evidence exists. Search caches are local/generated only;+ preserve JSONL records and source provenance rather than replacing them with cache output.+1b. **CS2 intake manifest** — for a CS2 request, create and validate `cs2-intake.json` before+ pre-spec authoring. Run admission and probing for every source view, record the heuristic signal+ as non-authoritative evidence, attach the classification record, resolve the supported family,+ and choose `route` independently from `exactnessTier`. Missing classification, insufficient+ coverage, or a contradictory high-confidence class is `request-input`; unsupported families do+ not continue into spec generation.2. **Pre-Spec Assessment Gate** — classify + score complexity + write the quality contract:`forge/stage2_spec/new_pre_spec_assessment.py "Name" --image <img> --complexity <simple|moderate|complex|ultra-complex> --out assessment.json`. Rules: `grimoire/intake/quality_contract.md`.Set `objectClass.primaryDomain` (`object` | `character` | `hybrid`) and fill the seeded- `detailInventory` (its `targetMinDetails` scales with complexity).+ `detailInventory` (its `targetMinDetails` scales with complexity). **Supported CS2 knife+ skins**: always pass `--cs2`, which defaults the complexity tier to `ultra-complex`+ (`targetMinDetails` 16) — the finish/wear/hardware is the item, so CS2 is held to the top+ fidelity bar; `targetMinDetails` never drops below the 9 floor even if downgraded by hand.+ **Author procedural GEOMETRY (blade/guard/grip profiles) but make the FINISH a de-lit+ reference-crop PROJECTION, not a procedural finish material** — projecting the photo's own+ pixels is what reaches reference fidelity for patterned skins (Doppler/Gamma/Marble/Fade), and+ is what the v1.3 baseline demos do; a procedural finish for a patterned skin reads visibly wrong+ against the reference. Take the projection path in step 2c (it generalizes from characters to+ any reference-matched surface). Procedural finish is the fallback ONLY when live view-dependent+ response matters more than matching this one reference. Finish routes + rulebook:+ `grimoire/build/cs2_finishes.md`; optional exact-texture acquisition:+ `grimoire/intake/cs2_texture_acquisition.md`.2b. **Detail inventory** (do not skip for detailed subjects) — scan zones and enumerate everyidentity-defining small detail (gloss, bevel, fasteners, linework, contours, stains):`forge/stage1_intake/build_detail_inventory.py <image> --mode grid-3x3 --out-dir <dir> --out di.json`.Each detail MUST map to a `component.localFeatures` or `material.localOverrides` entry — neverprose only. Taxonomy + 3D-term recipes: `grimoire/intake/detail_inventory.md`.-2c. **Character/hybrid subjects** — capture head-unit proportions + facial/body landmarks:- `forge/stage1_intake/extract_landmarks.py <image> --out anatomy.json --overlay overlay.png`, then- fill `preSpecAssessment.anatomy`. Route: `grimoire/character/reconstruction.md`. For maximum- likeness use the projection-first path (`grimoire/character/likeness_maximization.md`): solve the camera- (`stage1_intake/solve_camera_pose.py`), de-light the photo (`stage1_intake/delight_albedo.py`), and project it onto- the fitted mesh (`stage3_build/bake_projected_texture.py`). A single image cannot guarantee 100% likeness —- report per-region confidence and request more views for a real person.+2c. **Projection-first fidelity (characters AND reference-matched surfaces — supported CS2 knife skins, decals,+ painted patterns)** — when the goal is matching a specific reference's surface, put the photo's+ own pixels on the mesh instead of approximating them procedurally. This is the single biggest+ fidelity lever; a procedural material for a patterned surface is the #1 reconstruction failure.+ Recipe (`grimoire/character/likeness_maximization.md` — its two levers, align-mesh+camera and+ project-the-photo, generalize past characters): solve the camera+ (`stage1_intake/solve_camera_pose.py` → `referenceCamera`), **de-light** the reference so it is+ free of baked lighting (`stage1_intake/delight_albedo.py`, hard requirement — this is what makes+ projection safe, not the flat-lit icon), then project the de-lit crop onto the mesh and bake it+ into UVs (`stage3_build/bake_projected_texture.py --mesh-id <id>`). For a CS2 skin the mesh is the+ procedural blade/guard/grip you author in the spec, and the projected de-lit crop IS the finish+ (front + back from the two views) — no procedural Doppler material. For characters, first capture+ landmarks (`stage1_intake/extract_landmarks.py --out anatomy.json`), fill `preSpecAssessment.anatomy`,+ route `grimoire/character/reconstruction.md`. A single view cannot show hidden sides — report+ per-region confidence and request more views when it matters.3. Author the spec from the assessment:- `forge/stage2_spec/new_sculpt_spec.py "Name" --image <img> --assessment assessment.json --out object-sculpt-spec.json`.+ `forge/stage2_spec/new_sculpt_spec.py "Name" --image <img> --assessment assessment.json --manifest cs2-intake.json --out object-sculpt-spec.json`.Replace generic starter `featureReviewTargets` with the object's real identity-definingsystems (≤5 critical, ≤3 important per pass); for characters add `anatomy-proportion`,`face-landmark-placement`, `pose-silhouette`, `outfit-and-palette`. Use 3D-graphics terms only@@ -94,10 +160,82 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that i8. Package one side-by-side sheet, then inspect it with agent vision:`forge/stage4_review/make_comparison_sheet.py --reference <img> --render <shot> --out cmp.png --json`.9. Record the review (overall + per-layer + per-feature scores + decision):- `forge/stage4_review/append_review.py object-sculpt-spec.json --pass-id <pass> --fidelity <0-1> --action <continue|refine-spec|refine-code|request-input|stop> --summary "..." --render-screenshot <shot> --comparison-image cmp.png --ai-vision-score <0-1> --layer-scores-json '{...}' --feature-reviews-json <f.json> --in-place`.+ `forge/stage4_review/append_review.py object-sculpt-spec.json --pass-id <pass> --fidelity <0-1> --action <continue|refine-spec|refine-code|request-input|stop> --summary "..." --render-screenshot <shot> --comparison-image cmp.png --ai-vision-score <0-1> --layer-scores-json '{...}' --feature-reviews-json <f.json> --in-place`.+ For the CS2 knife path, also attach the versioned report with+ `--cs2-review-json cs2-review.json --review-scene-json forge/tests/fixtures/knife_review_scene.json`.+ A failed family, painted-region, projection-coverage, critical-detail, or orbit gate blocks+ `continue` even when the global score passes. See `docs/cs2/review-gates.md`.10. Sync pipeline state after manual review edits:`forge/stage3_build/orchestrate_passes.py sync object-sculpt-spec.json --in-place`.+## CS2 image-matched rule++For a CS2 item, the target is observable agreement between the supplied image and the rendered+item: silhouette, proportions, edge profile, hardware layout, coating colour, pattern placement,+wear, roughness response, and camera framing. Every decision must be traceable to evidence or be+labelled as an approximation.++The initial CS2 family boundary is **knife only**. Pistol, rifle, SMG, sniper, heavy, glove, and+unknown knife subtypes must stop with `unsupported-family` or `unsupported-subtype`; they must not+receive the knife component tree as a generic fallback.++### Layer contract++Pass these records between layers. Do not copy an informal vision description into the next stage:++| Layer | Owns | Must emit | Must not decide alone |+| --- | --- | --- | --- |+| Intake | view validity and technical evidence | role, path/hash, resolution, coverage, duplicate status, admission verdict | item identity from aspect ratio or filename |+| Classification | semantic identity | family, subtype, confidence, evidence refs, provider/version, timeout state | geometry or finish parameters |+| Identity | skin/name/paint metadata | precedence, resolved values, ambiguity candidates, provenance | guessed paint index, float, or seed |+| Surface evidence | pixels and texture sources | de-lit reference, PBR channels, map provenance, colour space, UV orientation, confidence | albedo reused as roughness/normal/AO |+| Geometry adapter | family-specific form | component tree, topology, dimensions, edge/spine, hardware relationships, painted regions | hidden geometry without confidence notes |+| Spec/route | evidence-backed implementation choice | route, exactness tier, assumptions, feature targets, camera contract | exact-texture claim without exact evidence |+| Build/review | rendered observables | fixed view, two non-degenerate orbit views, per-region results, failed gates, next action | overriding a failed critical feature with a global score |++The canonical hand-off is `cs2-intake.json` (`schemaVersion: 1`). Its state is one of+`proceed`, `request-input`, `fallback`, `rejected`, `unsupported-family`, or+`unsupported-subtype`. Write it atomically and preserve unknown provider fields under+`extensions`; a fallback must never erase prior evidence.++### CS2 intake order++1. Admit and technically probe every view. Reject undecodable, empty, tiny, fragmented, or+ duplicate references before classification.+2. Record the heuristic CS2 signal only as a routing hint. `detect_cs2.py` is never authoritative+ identity evidence.+3. Require a classification record before selecting a family adapter. If classification is absent,+ timed out, or contradicts a high-confidence objectness result, return `request-input`.+4. Resolve identity in this order: explicit user metadata, uniquely resolved metadata, then the+ authoritative classification record. Preserve ambiguity rather than guessing.+5. Select route and exactness independently:+ - `reference-projection`: default for matching a specific patterned image;+ - `authored-texture`: only when independent texture maps are supplied or legally acquired;+ - `procedural-finish`: fallback when projection evidence is unavailable or live response is the+ stated priority.+ Exactness is `image-only`, `metadata-assisted`, or `exact-texture`; changing route must not+ silently upgrade or downgrade the evidence tier.+6. Select the knife adapter only after family/subtype validation. Record painted regions, unpainted+ substrate, visible hardware, hidden-region confidence, and every approximation in the spec.+7. For projection, solve the camera and de-light the source first. Projected pixels provide colour+ evidence, not automatic geometry truth; geometry still comes from the adapter and silhouette+ review.++### Surface and review rule++For a specific CS2 reference, preserve the reference's own colour/pattern pixels whenever legal and+technically possible. Procedural Doppler/Fade/Gamma/Marble patterns are not equivalent to the input+image and may only be used with an explicit `procedural-finish` route and approximation warning.+Keep albedo, roughness, metalness, normal/height, AO, mask, and wear as independent channels. Record+channel source, colour space, UV orientation, dimensions, packed-channel decoding, and missing-channel+derivation. A low-confidence PBR inference is a refine-input signal, not proof of exact material.++Single-view reconstruction may proceed only when visible identity features are sufficiently covered;+hidden blade sides, underside, and back hardware must carry inference confidence and may trigger+`request-input`. Review the fixed camera plus two meaningful orbit views. Report what changed, which+evidence caused it, what still differs, and choose exactly one next action:+`continue`, `refine-spec`, `refine-code`, `request-input`, or `stop`.+## Gates (do not skip)- **Suitability + reference integrity**: pass / conditional / reject before any planning@@ -116,6 +254,12 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that i`forge/stage4_review/diagnose_render_multi_angle.py` flags `degenerate-view` when an orbitedsilhouette collapses (a flat plane faking a volume). Orbit angles use reference-freeself-consistency — never scored against a reference angle the photo doesn't cover.+- **CS2 knife review contract**: `forge/stage4_review/cs2_review.py` consumes the manifest and+ versioned scene fixture, then blocks wrong family identity, missing projection coverage,+ painted-region mismatch, critical identity-detail failure, finish/material response failure,+ and degenerate orbit form. It records exactness tier, hidden-region confidence, per-region+ confidence, approximation notes, camera, environment hash, exposure, tone mapping, resolution,+ background, and renderer version.- **Bounded correction loop (token-burn safety)**: `forge/stage4_review/correction_loop.py`guarantees termination (success/repeated-defect/oscillation/plateau/hard-ceiling), escalating to`request-input` — never a silent infinite burn.diff --git a/docs/cs2-anatomy/gloves.md b/docs/cs2-anatomy/gloves.mdnew file mode 100644index 0000000..b7196f1--- /dev/null+++ b/docs/cs2-anatomy/gloves.md@@ -0,0 +1,132 @@+# CS2 Item Anatomy Vocabulary — Gloves (Găng tay)++> Bộ từ vựng song ngữ để **gọi đúng tên từng bộ phận của găng tay** khi mô tả lỗi fidelity trong pipeline img2threejs.+> Quy tắc dùng: **geometry/hình khối sai** → dùng tên bộ phận vật lý (mục 1–3). **Texture/màu/pattern sai** → dùng thuật ngữ skin CS2 (mục 4).+> Lưu ý bối cảnh CS2: găng tay **chỉ tồn tại dạng skin** (không có "súng" gốc như dao/súng) — chúng phủ lên bàn tay/cẳng tay người chơi ở góc nhìn thứ nhất. Vùng nhìn thấy nhiều nhất là **mu bàn tay, khớp ngón, ngón tay và cổ găng**; lòng bàn tay gần như không thấy.+>+> Nguồn: research NotebookLM (fast mode, 9 nguồn ready) — cs2floatchecker.com (CS2 Gloves Guide: types + float caps), steamanalyst.com (danh mục glove), csboard.com (Moto Gloves), steamcommunity.com (Cobalt Skulls), 2× reddit r/GlobalOffensive (real-life glove refs); alpinestars/adbmag.com.au, bigbiketours.com, walkervn.com (giải phẫu găng mô tô/bảo hộ). Chỗ thiếu đánh dấu [kiến thức chung].+> Notebook: `CS2 Item Anatomy Vocabulary — Gloves (VN+EN)` (`d353b31a`).+> _Lưu ý: 1 nguồn (studocu.vn) fail khi index; phần anatomy được nguồn găng mô tô + CS2 guide cover đủ._++---++## 1. Giải phẫu găng tay tổng quát — General glove anatomy++Áp dụng cho các kiểu găng "có ngón" (Sport, Driver, Moto, Specialist, Bloodhound, Hydra, Broken Fang). Hand Wraps (băng quấn hở ngón) — xem mục 2.++### A. CỔ GĂNG & CỔ TAY (Cuff & Wrist)++| English | VN | Định nghĩa |+|---|---|---|+| **Cuff** / wristband, gauntlet edge | Cổ găng tay | Phần mở của găng từ cổ tay trùm xuống cổ tay/cẳng tay dưới. |+| **Wrist strap** / closure, wrist fastener | Đai khóa cổ tay | Dây siết quanh cổ tay để găng ôm khít, không tuột. |+| **Hook-and-loop strap** / Velcro strap, touch fastener | Khóa dán Velcro | Khóa dán vi-móc + vòng, chỉnh độ ôm chính xác — điểm nhận diện rõ ở cổ găng. |+| **Gauntlet** / long cuff, forearm shroud | Găng cổ dài | Kiểu găng kéo dài quá cổ tay, che cả cẳng tay dưới. |++### B. MU BÀN TAY & KHỚP NGÓN (Back of hand & Knuckles)++| English | VN | Định nghĩa |+|---|---|---|+| **Back of hand** / dorsal side, top hand | Mu bàn tay | Mặt trên đối diện lòng bàn tay — **vùng nhìn thấy chính** trong CS2, thường mang họa tiết/logo skin. |+| **Knuckles** / knuckle ridge, finger joints | Khớp ngón tay | Các khớp nối ngón vào bàn tay, gờ nhô chịu va đập nhiều nhất. |+| **Knuckle padding** / foam backing, impact cushion | Đệm lót khớp | Lớp đệm mềm (foam) sau lớp cứng để hấp thụ & phân tán lực. |+| **Knuckle guard** / hard-shell armor, knuckle plate | Gù bảo vệ khớp | Tấm cứng (TPU/carbon/da cứng) chụp lên khớp — dấu hiệu chính của Moto/Bloodhound. |++### C. NGÓN TAY & LÒNG BÀN TAY (Fingers & Palm)++| English | VN | Định nghĩa |+|---|---|---|+| **Fingers** / digits, finger stalls | Ngón tay | Các ống găng bọc từng ngón. |+| **Fingertips** / finger ends, tactile tips | Đầu ngón tay | Chóp ngón găng, hay được gia cố hoặc cắt hở. |+| **Finger gussets** / fourchettes, sidewalls | Vách giữa ngón tay | Dải vải/lưới nối hai bên ngón, tăng cử động & thoáng khí. |+| **Thumb** / first digit, pollex | Ngón cái | Ngón cái, thường gia cố vì tì vào súng liên tục. |+| **Palm** / thenar surface, grip | Lòng bàn tay | Mặt trong để cầm nắm (da dê/kangaroo) — gần như không thấy ở góc FPS. |+| **Palm patch** / palm reinforcement, palm slider | Miếng gia cố lòng bàn tay | Lớp/tấm phụ ở gót lòng bàn tay, chống trượt & mài mòn. |++### D. KẾT CẤU (Construction)++| English | VN | Định nghĩa |+|---|---|---|+| **Seams** / joins, stitch lines | Đường nối / đường may ráp | Đường ghép giữa các mảng vật liệu (ngoài để êm, trong để đẹp). |+| **Stitching** / topstitching, thread lines | Đường chỉ may | Các mũi chỉ giữ mảng vật liệu & phần gia cố. |+| **Perforations** / ventilation holes, air holes | Lỗ thông khí / lỗ đục | Lỗ đục nhỏ cho thoát nhiệt & lưu thông khí — đặc trưng bề mặt da Sport. |+| **Pull tab** / pull loop, donning loop | Tab kéo / vòng kéo | Tab/vòng nhỏ ở cổ găng giúp kéo găng vào tay. [kiến thức chung] |+| **Lining** / inner liner, interior fabric | Lớp lót trong | Vật liệu mềm mặt trong, êm da & hút ẩm. |++---++## 2. Băng quấn tay — Hand Wraps (kiểu đặc biệt)++Không phải "găng có ngón": là **dải vải quấn** quanh bàn tay & cổ tay, **hở ngón**.++| English | VN | Định nghĩa |+|---|---|---|+| **Wrapped cloth strips** / bandage wrap, handwraps | Băng vải quấn tay | Dải vải dài quấn quanh bàn tay & cổ tay để đỡ & ổn định. |+| **Exposed fingers** / fingerless, open fingertips | Ngón tay hở | Thiết kế cắt ngắn để lộ đầu ngón thật của người chơi. |+| **Crossing wrap over knuckles** / X-pattern wrap | Quấn vải chéo khớp tay | Kỹ thuật quấn chéo hình chữ X đè lên gờ khớp để tập trung lực đỡ. |+| **Thumb loop** / starter loop | Vòng móc ngón cái | Vòng ở đầu dải băng móc vào ngón cái để cố định điểm bắt đầu quấn. |++_(Cổ tay, mu bàn tay, khớp ngón — dùng tên ở mục 1.)_++---++## 3. Nhận diện 8 loại găng tay CS2++Mỗi dòng: **tên** — [VN] — hình khối/vật liệu nhận biết ở góc nhìn thứ nhất (mu bàn tay, ngón, cổ găng).++- **Bloodhound Gloves** — Găng Bloodhound — da tactical với **gù/tấm cứng bọc khớp ngón** (hardened knuckle) + đinh tán tròn dọc gờ khớp + logo chiến dịch trên mu bàn tay.+- **Sport Gloves** — Găng thể thao — **da đục lỗ (perforated) kiểu găng lái xe thể thao**, mảng trơn tương phản trên mu bàn tay, dáng gọn ôm — profile rất dễ thấy ở FPS.+- **Driver Gloves** — Găng lái xe — **da trơn nguyên bản (smooth leather)**, silhouette tối giản mượt, thường có **lỗ tròn khoét ở khớp**, vân da rắn/dệt.+- **Hand Wraps** — Băng quấn tay — **dải vải/bạt quấn quanh tay & cổ tay, hở hoàn toàn các ngón** (kiểu võ sĩ).+- **Moto Gloves** — Găng mô tô — **gù cứng bảo vệ khớp (hardshell knuckle guard)** nổi bật + cổ găng cuộn + họa tiết tam giác trên tấm bảo vệ.+- **Specialist Gloves** — Găng tactical cổ dài — lai **lòng bàn tay da + mu bàn tay vải (textile)** + gân cao su gia cố khớp + **cổ găng kéo dài (cuffed)**.+- **Hydra Gloves** — Găng Hydra — kiểu hở ngón, nhận ra qua **4 đinh tán kim loại nhỏ ở khớp** + huy hiệu/medallion tròn giữa mu bàn tay.+- **Broken Fang Gloves** — Găng Broken Fang — da tactical hở ngón, **đinh tán kim loại ở khớp** + emblem "broken fang" trên mu bàn tay.++---++## 4. Thuật ngữ SKIN / FINISH CS2 → map lên bộ phận găng tay++Dùng khi **texture/màu/pattern** sai (không phải hình khối).++### Phần được phủ skin & Pattern+| English | VN | Nghĩa & vị trí |+|---|---|---|+| **Painted area** / skinned surface, texture zone | Vùng phủ skin | Các mảng nhận họa tiết/màu — **mu bàn tay, ngón, cổ găng**. |+| **Bare area** / unskinned, default material | Vùng vật liệu gốc | Phần giữ vật liệu nền (da đen/vải xám) không phủ pattern — lớp lót trong, một số mảng lòng bàn tay. |+| **Pattern seed** / pattern index, paint seed | Chỉ số hoa văn | Số 0–999 dịch vị trí & căn chỉnh texture trên model — quyết định chỗ đặt họa tiết trên **mu bàn tay & khớp**. |+| **Centered pattern** / god-tier centering | Hoa văn căn giữa | Trường hợp hiếm: chi tiết chính căn hoàn hảo ở phần dễ thấy nhất — **mu bàn tay (dorsal)**. |++### Kiểu finish / vật liệu+| English | VN | Đặc trưng & vị trí |+|---|---|---|+| **Leather** / hide, goatskin, kangaroo | Da | Finish da bền, trơn hoặc có vân — lòng bàn tay, ngón cái, ống ngón. |+| **Fabric** / textile, mesh | Vải / lưới | Vật liệu thoáng, hay dùng cho Specialist/Moto — rõ nhất trên **mu bàn tay & vách giữa ngón**. |+| **Cloth wrap** / tarp, bandage | Băng vải quấn | Finish vải nhiều lớp riêng của Hand Wraps — phủ cả tay & cổ tay trừ ngón hở. |+| **Printed pattern** / geometric, pinstripe | Hoa văn in | Lớp phủ trang trí (tam giác, sọc mảnh) trên nền — trên **tấm khớp & mu bàn tay**. |+| **Camo** / digital camo, polycam | Hoa văn rằn ri | Camo kiểu quân sự — rõ trên nền vải & vùng gia cố của Specialist. |++### Wear / Float+| English | VN | Nghĩa & vị trí mòn |+|---|---|---|+| **Float value** / wear rating, condition index | Chỉ số Float | Mức mòn thị giác của găng, dải ~0.06–0.80. |+| **Glove float cap** / wear limit | Giới hạn Float găng | Chặn cứng riêng cho găng (min ~0.06, max ~0.80) — găng **không bao giờ đạt 0.00** hoàn hảo. |+| **Factory New (FN)** | Mới xuất xưởng | ~0.06–0.07, màu no & không hư hại — sắc nét ở điểm cao & cạnh. |+| **Minimal Wear (MW)** | Ít trầy xước | ~0.07–0.15, xước nhỏ bắt đầu ở **cạnh cổ găng & gù khớp**. |+| **Field-Tested (FT)** | Đã qua sử dụng | ~0.15–0.38, mòn/phai rõ ở **cạnh lòng bàn tay, khớp & đầu ngón**. |+| **Well-Worn (WW)** | Mòn nhiều | ~0.38–0.45, pattern phai mạnh — mảng mất màu lớn trên **mu bàn tay & lòng bàn tay**. |+| **Battle-Scarred (BS)** | Trầy xước nặng | ~0.45–0.80, texture "bùn", pattern gần như mất — nặng nhất ở **đường may & phần gù/armor nhô**. |+| **Abrasion** / scuffs, scratches | Vết trầy xước | Hư hại texture do float cao — rõ nhất ở **gù khớp, palm slider, đầu ngón**. |+| **Browning** / fraying to base fabric | Hiện tượng lộ vải nền | Lớp màu trên sờn đi lộ vải nền nâu/tối — thường ở **khớp của Hand Wraps**. |+| **Fading** / washing out | Bạc màu / phai màu | Mất độ đậm màu khi float tăng — phủ toàn bộ, làm pattern trông "bụi"/xỉn. |+| **Wear high points** | Điểm dễ mòn | Chịu mòn trước: **gù/khớp ngón, đầu ngón, cạnh lòng bàn tay, cạnh cổ găng, đường may**. |++---++## Ghi chú dùng cho debug fidelity++- **Sai hình khối** → mục 1–3: vd "Moto/Bloodhound thiếu gù cứng ở khớp", "Hand Wraps đang bọc kín ngón thay vì hở ngón", "Specialist thiếu cổ găng kéo dài", "Sport thiếu lỗ đục (perforation) trên da".+- **Sai texture/màu** → mục 4: vd "pattern seed lệch làm họa tiết trên mu bàn tay sai vị trí (không centered)", "wear đặt ở lòng bàn tay thay vì gù khớp / đầu ngón / high points", "float dưới 0.06 là sai vì găng có float cap".+- **Vùng nhìn thấy ở CS2**: mu bàn tay + khớp + ngón + cổ găng là nơi lỗi dễ lộ nhất; lòng bàn tay hầu như khuất — ưu tiên fidelity mặt lưng (dorsal).++_Đã xong: [dao](knives.md), [pistol](pistols.md), gloves. Các loại còn lại (SMG / rifle / sniper) — mỗi loại một file trong `docs/cs2-anatomy/`._diff --git a/docs/cs2-anatomy/heavy.md b/docs/cs2-anatomy/heavy.mdnew file mode 100644index 0000000..0a9845c--- /dev/null+++ b/docs/cs2-anatomy/heavy.md@@ -0,0 +1,172 @@+# CS2 Item Anatomy Vocabulary — Heavy: Shotguns & MGs (Súng hạng nặng)++> Bộ từ vựng song ngữ để **gọi đúng tên từng bộ phận của shotgun & súng máy** khi mô tả lỗi fidelity trong pipeline img2threejs.+> Quy tắc dùng: **geometry/hình khối sai** → dùng tên bộ phận vật lý (mục 1–3). **Texture/màu/pattern sai** → dùng thuật ngữ skin CS2 (mục 4).+>+> Nguồn: research NotebookLM (fast mode, 8/10 nguồn ready) — englishan.com (Parts of a Shotgun + diagram), portal.ct.gov (Parts & Features of Firearms), dokumen.pub *Streetsweepers* (combat shotgun), steamcommunity (CS:GO guns in real life), breakingdefense.com (IWI/Negev), vi.wikipedia (Săn — thuật ngữ VN), white.market (pattern seed), skinvault.gg (wear levels) + kiến thức chuẩn về súng cho phần bị thiếu.+> Notebook: `CS2 Item Anatomy Vocabulary — Heavy: Shotguns & MGs (VN+EN)` (`8430ab72`).+> _Lưu ý: 2 nguồn (cs.money finish catalog, scribd M249 assembly guide) fail khi index; phần anatomy được englishan + CT.gov + Streetsweepers + steamcommunity cover đủ, chỗ thiếu đánh dấu [kiến thức chung]._++---++## 1. Giải phẫu shotgun — Combat shotgun anatomy++Áp dụng cho shotgun bơm (pump-action: Nova, Sawed-Off, MAG-7) và bán tự động (semi-auto: XM1014).++### A. THÂN & NÒNG (Receiver & Barrel)++| English | VN | Định nghĩa |+|---|---|---|+| **Receiver** / body | Hộp khóa nòng | Khung vỏ kim loại trung tâm kết nối các bộ phận chính và chứa cụm phát hỏa. |+| **Barrel** / tube | Nòng súng | Ống kim loại dài dẫn viên đạn/chùm đạn khi khai hỏa. |+| **Muzzle** / front end | Miệng nòng | Đầu hở phía trước nòng, nơi chùm đạn thoát ra. |+| **Choke** / choke tube | Ống bóp nòng | Bộ phận ở đầu nòng kiểm soát độ chụm & hình dạng tán xạ của chùm đạn. |+| **Ventilated rib** / rib | Gờ thông gió | Dải kim loại nhô cao chạy dọc lưng nòng, thoát nhiệt & làm mặt phẳng ngắm. |+| **Bolt** / breech bolt | Khóa nòng | Bộ phận di động nạp đạn vào buồng, khóa kín và hất vỏ đạn sau khi bắn. |+| **Bolt carrier** / carrier assembly | Bệ khóa nòng | Bộ phận giữ & dẫn hướng khóa nòng di chuyển để thực hiện chu trình nạp đạn. |+| **Ejection port** / ejector port | Cửa hất vỏ đạn | Khe hở trên hộp khóa nòng, nơi vỏ đạn đã bắn văng ra. |++### B. TIẾP ĐẠN & NẠP ĐẠN (Magazine & Loading)++| English | VN | Định nghĩa |+|---|---|---|+| **Tubular magazine** / under-barrel tube, tube magazine | Ống chứa đạn (dưới nòng) | Ống dự trữ đạn nằm dưới nòng, chứa các viên xếp nối tiếp nhau. |+| **Box magazine** / detachable magazine | Hộp tiếp đạn | Hộp đạn tháo rời (MAG-7 dùng loại này thay ống dưới nòng). |+| **Loading port** / loading gate, loading tray | Cửa nạp đạn | Khe dưới gầm súng nơi người bắn đẩy viên đạn mới vào ống chứa. |+| **Forend** / fore-end, pump, slide handle, forearm | Ốp lót tay trượt / tay bơm | Tay cầm trước trượt tới-lui để nạp đạn trên shotgun bơm. |+| **Action bars** / operating rods | Thanh truyền động | Thanh kim loại nối ốp lót tay với khóa nòng, biến lực kéo thành chu trình nạp. |+| **Follower** / magazine follower | Con đẩy đạn | Bệ có lò xo trong ống/hộp đạn, đẩy đạn về phía buồng nòng. |++### C. BÁNG & TAY CẦM (Stock & Grip)++| English | VN | Định nghĩa |+|---|---|---|+| **Buttstock** / shoulder stock, stock | Báng súng | Phần đuôi tì vào vai để ổn định & giảm giật. |+| **Pistol grip** / handgrip | Tay nắm chính | Tay cầm kiểu súng ngắn nằm ngay sau cò. |+| **Trigger** / firing lever | Cò súng | Lẫy bóp để kích hoạt cơ chế điểm hỏa. |+| **Trigger guard** / safety loop | Vành bảo vệ cò | Vòng bao quanh cò, chống cướp cò ngoài ý muốn. |+| **Safety** / manual safety | Khóa an toàn | Cơ cấu cơ khí ngăn súng khai hỏa ngoài ý muốn. |+| **Recoil pad** / butt pad | Đế báng giảm giật | Đệm cao su cuối báng, hấp thụ lực giật lên vai. |++### D. NGẮM (Sights)++| English | VN | Định nghĩa |+|---|---|---|+| **Front bead** / bead sight, front bead sight | Đầu ngắm hạt | Điểm ngắm nhỏ hình hạt ở đầu nòng, lấy mục tiêu nhanh. |+| **Rear sight** / aperture, notch, ghost ring | Thước ngắm | Bộ ngắm sau; XM1014 dùng vòng "ghost ring". |+| **Ventilated rib as sighting plane** | Mặt phẳng ngắm | Bề mặt phẳng trên gờ thông gió dẫn hướng mắt (Nova). |++---++## 2. Giải phẫu súng máy hạng nhẹ — Light Machine Gun (LMG / SAW)++Áp dụng cho súng máy bắn băng đạn mắt xích (belt-fed): M249, Negev.++### A. THÂN & NÒNG (Receiver & Barrel)++| English | VN | Định nghĩa |+|---|---|---|+| **Receiver** | Hộp khóa nòng | Khung vỏ kim loại trung tâm nối nòng, báng và chứa cụm phát hỏa. |+| **Barrel** | Nòng súng | Ống kim loại dài dẫn đầu đạn; tháo nhanh (quick-change) để thay khi quá nhiệt. |+| **Barrel shroud** / barrel jacket, handguard | Ốp bao nòng / ốp lót tay | Bộ phận bao quanh nòng, bảo vệ tay khỏi nhiệt khi bắn liên tục. |+| **Flash hider** / muzzle device | Loa che lửa | Thiết bị đầu nòng giảm ánh chớp, tránh lộ vị trí xạ thủ. [kiến thức chung] |+| **Gas system** / gas tube, gas piston | Hệ thống trích khí | Tận dụng khí thuốc đẩy bệ khóa nòng lùi để thực hiện chu kỳ nạp đạn. [kiến thức chung] |+| **Charging handle** / cocking handle | Tay kéo khóa nòng | Bộ phận kéo khóa nòng về sau để lên đạn hoặc xử lý kẹt đạn. |++### B. TIẾP ĐẠN (Feeding)++| English | VN | Định nghĩa |+|---|---|---|+| **Belt** / linked ammunition | Dây băng đạn | Dải đạn nối bằng mắt xích kim loại, nạp liên tục vào súng. |+| **Feed tray** | Khay nạp đạn | Bề mặt kim loại đặt dây băng đạn để cơ cấu tiếp đạn bắt lấy. |+| **Feed cover** / top cover | Nắp trên hộp khóa nòng | Nắp đậy trên khay nạp, giữ dây băng đạn cố định & bảo vệ cơ cấu. |+| **Belt box** / ammo box, ammunition pouch, assault pack | Hộp băng đạn / túi đạn | Thùng/túi gắn vào súng chứa dây băng đạn gọn gàng khi di chuyển. |+| **Drum** | Hộp tiếp đạn hình trống | Hộp tròn sức chứa lớn, một số súng máy dùng. [kiến thức chung] |+| **Feed mechanism** | Cơ cấu nạp đạn | Hệ bộ phận chuyển động kéo dây băng đạn vào buồng nòng theo chu kỳ bắn. |++### C. HỖ TRỢ & BÁNG (Support & Stock)++| English | VN | Định nghĩa |+|---|---|---|+| **Bipod** | Giá hai chân | Bộ chân đỡ gập gọn gắn phía trước, tăng ổn định khi bắn nằm. |+| **Carrying handle** | Tay xách | Quai cầm để vận chuyển súng / cầm nắm khi thay nòng nóng. |+| **Buttstock** | Báng súng | Phần đuôi tì vào vai tạo điểm tựa & giảm giật. |+| **Pistol grip** | Tay nắm chính | Tay cầm kiểu súng ngắn để điều khiển súng. |+| **Trigger** | Cò súng | Lẫy bóp kích hoạt cơ chế điểm hỏa. |+| **Trigger guard** | Vành bảo vệ cò | Vòng kim loại bao quanh cò, chống cướp cò ngoài ý muốn. |++### D. NGẮM & RAY (Sights & Rails)++| English | VN | Định nghĩa |+|---|---|---|+| **Front sight** | Đầu ngắm | Điểm ngắm ở đầu nòng để căn đường ngắm vào mục tiêu. |+| **Rear sight** | Thước ngắm | Bộ ngắm sau hộp khóa nòng, thường chỉnh được tầm & hướng gió. |+| **Picatinny rail** / rail | Ray Picatinny | Rãnh răng cưa tiêu chuẩn để gắn kính ngắm, đèn, phụ kiện. |++---++## 3. Nhận diện 6 khẩu heavy CS2++Mỗi dòng: **tên** — [VN] — súng thật + đặc điểm nhận biết.++### Shotguns+- **Nova** — [Shotgun bơm] — dựa trên **Benelli Nova**; thân (receiver) & báng đúc liền khối polymer gia cố thép, **nòng dài**, nạp đạn qua **ống chứa dưới nòng**, đầu ngắm hạt trên gờ thông gió.+- **XM1014** — [Shotgun bán tự động] — dựa trên **Benelli M4 Super 90**; nòng dài, **hệ thống trích khí (ARGO)** bắn liên tục, báng thu gọn được, **ngắm vòng "ghost ring"**.+- **Sawed-Off** — [Shotgun cưa nòng] — dựa trên **Remington Model 870** (biến thể nòng ngắn); **nòng & báng cắt cụt tối đa**, hình bóng cực ngắn, thô sơ, dáng "double-barrel".+- **MAG-7** — [Shotgun bullpup] — dựa trên **Techno Arms MAG-7M1**; thiết kế **bullpup**, **hộp tiếp đạn hộp (box magazine) nằm trong tay cầm chính** (trước cò), tổng thể cực ngắn.++### Machine guns+- **M249** — [Súng máy chi viện / SAW] — dựa trên **FN Herstal M249 SAW**; **nòng thay nhanh**, **giá hai chân (bipod) gập trước**, dùng **dây băng đạn mắt xích** (hoặc hộp STANAG), hộp/túi đạn gắn dưới thân.+- **Negev** — [Súng máy hạng nhẹ] — dựa trên **IMI/IWI Negev LMG**; ngoại hình gần M249 nhưng **gọn hơn**, **tay xách lớn**, dùng **hộp băng đạn vải/nhựa gắn dưới thân**.++---++## 4. Thuật ngữ SKIN / FINISH CS2 → map lên bộ phận heavy++Dùng khi **texture/màu/pattern** sai (không phải hình khối).++### Phân biệt phần được sơn+| English | VN | Nghĩa & vị trí |+|---|---|---|+| **Vanilla / stock** | Mặc định / nguyên bản | Súng không skin — đen mờ hoặc xám thép/polymer — toàn bộ súng. |+| **Painted parts** | Bộ phận được sơn | Bề mặt lớn nhận họa tiết — **thân (receiver), báng, ốp lót tay/ốp bao nòng**. |+| **Bare metal parts** | Kim loại trần | Chi tiết chức năng giữ màu gốc — **khóa nòng, mắt xích băng đạn, nòng, cần điều khiển, cò**. |++### Pattern+| English | VN | Nghĩa & vị trí |+|---|---|---|+| **Pattern seed** / pattern index | Chỉ số hoa văn / seed | Số (~1–999) định vị bản đồ vân — mỗi seed cho một diện mạo cố định — thân & ốp lót tay. |++### Kiểu finish+| English | VN | Đặc trưng & vị trí |+|---|---|---|+| **Solid Color** / custom paint job | Sơn màu đơn sắc | Lớp màu đồng nhất phủ kín — thường trên **receiver**. |+| **Hydrographic** / water transfer | In chuyển nước / thủy ấn | Phim họa tiết nhúng nước quấn quanh bề mặt cong; **lộ wear rất nhanh** khi float tăng — thân & ốp lót tay. |+| **Anodized** / chemical finish | Sơn mạ anode | Lớp phủ kim loại (dùng cho phần nhôm, vd XM1014), chống ăn mòn & giảm bóng. |+| **Patina** / chemical reaction | Lên màu hóa học | Đổi màu kim loại qua phản ứng hóa học, **không lộ rõ vết xước vật lý** — bề mặt thép. |+| **Gunsmith** / mixed finish | Chế tác thủ công | Lai sơn tùy chỉnh + patina; độ mòn rất khó nhận ra bằng mắt — thân kim loại + phần polymer. |+| **Spray-Paint** / stenciled | Sơn xịt | Hiệu ứng khuôn tô thô, thường camo (vd Safari Mesh) — thân & ốp lót tay. |+| **Fade** / gradient | Chuyển màu / fade | Dải màu (vàng/hồng/xanh) chuyển dần — phủ trên **nòng hoặc receiver**. |++### Wear / Float+| English | VN | Nghĩa & vị trí mòn |+|---|---|---|+| **Float Value** | Chỉ số mài mòn | 0.00–1.00, mức hư hại thị giác trên toàn súng. |+| **Factory New (FN)** | Mới xuất xưởng | 0.00–0.07, sạch nhất, gần như không xước. |+| **Minimal Wear (MW)** | Ít trầy xước | 0.07–0.15, vết mòn rất nhỏ, khó nhận ra. |+| **Field-Tested (FT)** | Đã qua sử dụng | 0.15–0.38, tình trạng phổ biến nhất, xước & xỉn rõ. |+| **Well-Worn (WW)** | Mòn nhiều | 0.38–0.45, xước & bong sơn hiện rõ, vẻ cũ kỹ. |+| **Battle-Scarred (BS)** | Trầy xước nặng | 0.45–1.00, độ mòn tối đa, sơn bong gần hết. |+| **Shotgun wear high points** | Điểm dễ mòn (shotgun) | **miệng nòng, cạnh hộp khóa nòng, ốp lót tay trượt, ống chứa đạn dưới nòng, báng**. |+| **LMG wear high points** | Điểm dễ mòn (súng máy) | **nắp hộp khóa nòng (feed cover), tay xách, chân chống (bipod), gờ receiver, nòng & ốp bao nòng**. |++---++## Ghi chú dùng cho debug fidelity++- **Sai hình khối** → mục 1–3: vd "Nova thiếu ống chứa đạn dưới nòng", "MAG-7 chưa ra dáng bullpup / hộp đạn sai vị trí (phải nằm trước cò)", "Sawed-Off nòng chưa đủ cụt", "M249 thiếu bipod / feed cover", "Negev thiếu tay xách lớn", "XM1014 thiếu ghost ring".+- **Sai texture/màu** → mục 4: vd "pattern seed lệch làm vân trên receiver sai vị trí", "wear đặt ở giữa thân thay vì cạnh receiver / feed cover / miệng nòng / high points", "Fade chạy sai chiều trên nòng".+- **Bare metal accents**: khóa nòng, mắt xích băng đạn, nòng, cần điều khiển, cò thường KHÔNG sơn — nếu model sơn cả lên đó là sai.+- **Phân biệt tiếp đạn** (dấu hiệu nhận diện mạnh nhất): Nova/XM1014 = **ống dưới nòng**; MAG-7 = **hộp đạn trong tay cầm**; M249/Negev = **dây băng đạn + hộp/túi đạn treo dưới thân**.++_Đã xong: [dao](knives.md), [pistol](pistols.md), heavy (shotgun + súng máy). Loại tiếp theo: SMG / rifle / sniper / gloves — mỗi loại một file trong `docs/cs2-anatomy/`._diff --git a/docs/cs2-anatomy/knives.md b/docs/cs2-anatomy/knives.mdnew file mode 100644index 0000000..3c3bb53--- /dev/null+++ b/docs/cs2-anatomy/knives.md@@ -0,0 +1,216 @@+# CS2 Item Anatomy Vocabulary — Knives (Dao)++> Bộ từ vựng song ngữ để **gọi đúng tên từng bộ phận của dao** khi mô tả lỗi fidelity trong pipeline img2threejs.+> Quy tắc dùng: **geometry/hình khối sai** → dùng tên bộ phận vật lý (mục 1–3). **Texture/màu/pattern sai** → dùng thuật ngữ skin CS2 (mục 5).+>+> Nguồn: research NotebookLM (fast mode, 9 nguồn) — jayfisher.com, nobliecustomknives.com, sulang.org (anatomy); Balisong Wikipedia; shengtools.com (Bowie); shadowpay / steamanalyst / csboard / hellcase (CS2 skin & finish).+> Notebook: `CS2 Item Anatomy Vocabulary — Knives (VN+EN)` (`3302413b`).++---++## 1. Giải phẫu dao tổng quát — General knife anatomy++### A. Bộ phận LƯỠI (Blade)++| English | VN | Định nghĩa |+|---|---|---|+| **Point** / tip | Mũi dao | Điểm cực trước, nơi sống và lưỡi gặp nhau. |+| **Edge** / cutting edge, primary edge | Lưỡi cắt / cạnh sắc | Đường sắc dùng để cắt, chạy từ gót đến mũi. |+| **Belly** | Bụng dao | Phần cong lồi của lưỡi cắt, dùng để cắt lát / lột. |+| **Spine** / back | Sống dao | Lưng lưỡi không mài, đối diện lưỡi cắt; tạo độ cứng. |+| **False edge** / swage, swedge | Lưỡi giả | Mặt vát trên sống gần mũi, tăng khả năng đâm xuyên. |+| **Fuller** / cannelure, "blood groove" | Rãnh máu / rãnh trợ lực | Rãnh xẻ dọc thân lưỡi để giảm trọng lượng, chống cong ngang. |+| **Ricasso** | Đốc lưỡi / ricasso | Đoạn phẳng không mài giữa lưỡi cắt và cán/chắn tay. |+| **Choil** | Hốc dao / khuyết ngón tay | Khấc nhỏ gần gót — điểm bắt đầu mài hoặc đặt ngón tay. |+| **Heel** | Gót lưỡi | Phần cuối của lưỡi cắt, gần cán nhất. |+| **Grind** | Kiểu mài | Hình cắt ngang của lưỡi (cách vát mỏng thép). |+| **Bevel** | Mặt vát | Bề mặt nghiêng dẫn xuống lưỡi cắt (primary = tạo hình, secondary = tạo cạnh sắc). |+| **Flat grind** / primary grind | Mài phẳng | Lưỡi vát thẳng từ sống xuống cạnh. |+| **Serrations** / rip teeth | Răng cưa | Các khấc kiểu cưa trên lưỡi, thường gần cán, để cắt vật liệu dai. |+| **Serration teeth / scallops** | Răng cưa đơn / rãnh răng cưa | Từng chiếc răng nhọn và rãnh lõm tạo nên đoạn răng cưa. |+| **Jimping** | Răng cưa bám tay | Khấc nhỏ trên sống/cán để tăng độ bám cho ngón cái. |+| **Plunge line** / grind termination | Đường plunge | Đường chuyển tiếp nơi kiểu mài bắt đầu/kết thúc gần ricasso. |+| **Tang junction** | Điểm nối chuôi | Nơi thép lưỡi gặp phần cán. |++### B. Bộ phận CÁN (Handle)++| English | VN | Định nghĩa |+|---|---|---|+| **Handle** / grip, haft, hilt | Cán dao | Toàn bộ phần cầm để điều khiển lưỡi. |+| **Scales** / slabs | Ốp cán | Hai tấm vật liệu ốp hai bên chuôi tạo phần nắm. |+| **Bolster** | Đệm cán / khâu dao | Miếng (thường kim loại) gia cố chỗ nối cán–lưỡi hoặc đuôi cán. |+| **Guard** / crossguard, quillon | Miếng chắn / vệ tay | Phần nhô giữa lưỡi và cán, chặn tay trượt lên lưỡi. |+| **Full tang** | Chuôi xuyên / full tang | Thép lưỡi chạy hết chiều dài & rộng của cán, nhìn thấy ở rìa. |+| **Hidden tang** / rat-tail tang | Chuôi ẩn / chuôi chuột | Chuôi hẹp luồn trong cán, bị vật liệu cán bọc kín. |+| **Butt** | Đuôi cán | Đầu cuối của cán, xa lưỡi nhất. |+| **Pommel** | Núm chuôi | Nắp/núm kim loại ở đuôi cán, khóa cụm chuôi ẩn. |+| **Lanyard hole** / thong hole | Lỗ xỏ dây | Lỗ ở đuôi để luồn dây đeo/giữ. |+| **Finger grooves** | Rãnh ngón tay | Chỗ lõm trên cán để cầm chắc & tiện tay. |+| **Backspacer** / standoffs | Thanh đệm lưng | Bộ phận ngăn cách & đỡ ốp/liner dọc sống dao gập. |+| **Liner** | Tấm lót cán | Tấm kim loại bên trong dao gập, đỡ ốp, trục và khóa. |++### Bộ phận DAO GẬP (Folding-knife)++| English | VN | Định nghĩa |+|---|---|---|+| **Pivot** | Trục xoay | Trục/bu-lông để lưỡi dao gập xoay quanh khi mở/đóng. |+| **Thumb stud** / thumb bob | Chốt ngón cái | Chốt nhỏ trên sống lưỡi để mở một tay. |+| **Flipper tab** | Lẫy bật / flipper | Phần nhô ở chuôi lưỡi để búng mở bằng một ngón. |+| **Lock** / lockbar, liner lock | Khóa lưỡi | Cơ cấu giữ lưỡi ở vị trí mở để dùng an toàn. |+| **Backspring** | Lò xo lưng | Lò xo dọc lưng dao slipjoint giữ lưỡi đúng vị trí. |+| **Detent** / detent ball | Chốt bi / bi định vị | Bi + lỗ giữ lưỡi đóng cho tới khi cố ý mở. |+| **Stop pin** | Chốt dừng | Chốt cứng giới hạn hành trình lưỡi khi mở/đóng hết. |++---++## 2. Dao bướm / Balisong — Butterfly Knife++Dao gập kiểu Filipino, **hai cán** xoay 180° quanh chuôi để giấu/lộ lưỡi.++| English | VN | Định nghĩa |+|---|---|---|+| **Safe handle** | Cán an toàn | Cán đóng về phía **sống** — cầm khi múa thì không bị cắt. |+| **Bite handle** | Cán nguy hiểm | Cán đóng về phía **lưỡi sắc** — cầm nhầm khi đóng sẽ bị cắt. |+| **Blade** | Lưỡi dao | Phần lưỡi trung tâm, nằm gọn trong hai cán khi đóng. |+| **Tang** | Chuôi lưỡi | Gốc lưỡi nơi hai cán gắn qua trục xoay. |+| **Tang pin** | Chốt chuôi | Chốt trên chuôi giữ hai cán không đập vào nhau/vào lưỡi. |+| **Kicker** / kicker pin | Điểm dừng lưỡi | Phần chuôi lưỡi chạm mặt trong cán để lưỡi không chạm đáy cán. |+| **Latch** / locking pin | Chốt khóa | Chốt ở đầu cán giữ hai cán khép lại (mở hoặc đóng). |+| **Batangas latch** | Khóa Batangas | Latch gắn ở **cán nguy hiểm** (kiểu Filipino truyền thống). |+| **Manila latch** | Khóa Manila | Latch gắn ở **cán an toàn**. |+| **Latch gate** | Chốt chặn khóa | Khối trong cán chặn latch thụt vào làm hư lưỡi. |+| **Latch bite** | Rãnh chốt | Khấc trên cán đối diện, nơi latch cài để khóa hai cán. |+| **Pivot pins** / axle pins | Trục xoay | Hai chốt làm trục cho hai cán quay quanh lưỡi. |+| **Zen pins** | Chốt Zen | Chốt bên trong cán chặn hành trình lưỡi (thay cho tang pin). |+| **Choil** | Hốc dao | Vùng không mài giữa lưỡi cắt và chuôi. |+| **Handle channel** | Cán rãnh đơn | Cán phay từ một khối duy nhất (không phải hai ốp rời). |+| **Skeletonized handle** | Cán đục lỗ | Cán có lỗ/khoét để giảm nặng & bám tay. |+| **Flipping** | Múa dao | Kỹ thuật mở/đóng bằng cổ tay. |++---++## 3. Dao găm Karambit — Karambit++Nhận ra ngay nhờ **đường cong ngược (reverse curve)** + **vòng ngón (finger ring)**.++| English | VN | Định nghĩa |+|---|---|---|+| **Hawkbill blade** / curved talon | Lưỡi mỏ diều hâu | Lưỡi cong sâu như móng hổ / móng vuốt chim. |+| **Safety ring** / finger ring, retention ring | Vòng giữ ngón | Lỗ ở núm chuôi để xỏ ngón, giữ & kiểm soát dao. |+| **Inner edge** / concave edge | Lưỡi trong | Cạnh sắc chính, nằm ở mặt lõm bên trong đường cong. |+| **Outer spine** / convex spine | Sống ngoài | Lưng lưỡi chạy theo cung lồi bên ngoài. |+| **Belly** | Bụng dao | Đỉnh nhô nhất của cung, tạo lực chém mạnh. |+| **Point** / tip | Mũi dao | Đầu lưỡi, dùng đâm & thao tác chính xác. |+| **Spine** | Sống dao | Lưng lưỡi không mài, đỡ kết cấu đường cong. |+| **Second edge** / top edge | Lưỡi phụ | Cạnh sắc trên cung ngoài (một số bản tactical) để cắt đa hướng. |+| **Reverse grip** | Cầm ngược | Kiểu cầm chuẩn: lưỡi chĩa xuống, ngón trỏ xỏ qua vòng. |++---++## 4. Nhận diện 20 loại dao CS2 — CS2 knife shapes++Mỗi dòng: **tên** — [VN] — hình lưỡi + đặc điểm cán + dấu hiệu nhận biết.++- **Bayonet** — Dao lê — lưỡi clip-point thẳng, một cạnh sắc + cán rãnh có vòng nòng súng + dáng quân đội dài cổ điển.+- **M9 Bayonet** — Dao lê M9 — lưỡi lớn một cạnh, **sống răng cưa (sawback)** + chắn tay đầy đủ + to & hầm hố hơn Bayonet thường.+- **Bowie Knife** — Dao Bowie — lưỡi clip-point cực lớn, **bụng sâu**, full tang + chắn tay chắc (thường đồng thau) + dáng "miền viễn tây" khổng lồ.+- **Butterfly Knife** — Dao bướm / Balisong — lưỡi mảnh một cạnh + hai cán đục lỗ xoay 180° + nhận ra qua động tác múa mở.+- **Falchion Knife** — Dao Falchion — lưỡi cong một cạnh (kiểu kiếm châu Âu) + cán gập ôm theo cung lưỡi + cán lớn, animation "xoay giữ thăng bằng".+- **Flip Knife** — Dao gập / Flip — lưỡi cong dài một cạnh, **mũi nhọn như kim** + cán gập gọn + lưỡi to bất thường so với cán.+- **Gut Knife** — Dao mổ / Gut — lưỡi bản rộng có **móc mổ bụng (gut hook)** trên sống + cán nhám + nhận ra qua cái móc để xẻ thịt.+- **Huntsman Knife** — Dao săn / Huntsman — lưỡi dày góc cạnh, sống kiểu cưa, **mũi tanto** + cán tactical nặng + dáng gồ ghề, răng cưa.+- **Karambit** — Dao găm Karambit — lưỡi hawkbill/talon cong sâu + cán có **vòng ngón** ở núm chuôi (cầm ngược) + dáng "móng hổ" ĐNÁ, động tác xoay.+- **Navaja Knife** — Dao Navaja — lưỡi gập nhỏ cong mượt một cạnh + khung cán thon gọn + kiểu Tây Ban Nha truyền thống, tối giản.+- **Nomad Knife** — Dao du mục / Nomad — lưỡi dày cong một cạnh + cán cân bằng chắc chắn + animation rút dao "nhăn mặt như bị cắt".+- **Paracord Knife** — Dao Paracord — lưỡi cố định mảnh, drop-point + **cán full tang bọc dây paracord** + dáng sinh tồn nhẹ, quấn dây.+- **Shadow Daggers** — Dao đôi / Shadow Daggers — **hai** lưỡi ngắn bản rộng, hai cạnh sắc + cán push-dagger chữ T kẹp giữa ngón + cầm đôi, đâm kiểu đấm.+- **Skeleton Knife** — Dao khung xương / Skeleton — lưỡi dài hai cạnh sắc, **lỗ lớn gần chuôi** + cán đục lỗ quấn băng + nhận ra qua lỗ ngón to ở chỗ nối lưỡi–cán.+- **Stiletto Knife** — Dao bấm Stiletto — lưỡi cực mảnh, **mũi kim** + cán mỏng kiểu bấm lò xo (switchblade) + dáng Ý hẹp, bung nhanh.+- **Survival Knife** — Dao sinh tồn / Survival — lưỡi cố định thô, có gut hook + răng cưa trên sống + cán bắt **bu-lông lục giác lộ ra** + dáng ngoài trời nặng.+- **Talon Knife** — Dao Talon — lưỡi cong kiểu Karambit + **ba lỗ gần chuôi** & răng cưa trên sống + cán ngà có vòng ngón + phân biệt với Karambit nhờ răng sống + lỗ.+- **Ursus Knife** — Dao Ursus — lưỡi tanto cắt mặt (faceted), sống thẳng, mũi nhọn + cán vuông đơn giản full tang + dáng công nghiệp gọn.+- **Classic Knife** — Dao cổ điển — lưỡi mảnh một cạnh hơi cong, **có fuller dọc sống** + cán ôm tay truyền thống + gợi nhớ CS bản gốc.+- **Kukri Knife** — Dao Kukri — lưỡi recurve to nặng, cạnh cong vào trong + cán có đuôi loe + dáng chặt "Gurkha" dốc xuống đặc trưng.++---++## 5. Thuật ngữ SKIN / FINISH CS2 → map lên bộ phận++Dùng khi **texture/màu/pattern** sai (không phải hình khối).++### Phân biệt phần được sơn+| English | VN | Nghĩa & vị trí |+|---|---|---|+| **Vanilla** / bare metal | Nguyên bản | Thép mặc định, không pattern — toàn bộ dao. |+| **Painted surface** / skinned | Bề mặt sơn | Vùng engine áp texture finish — mặt lưỡi, sống, đôi khi cán. |+| **Bare metal accents** | Kim loại trần | Bộ phận để trần dù đã skin — **cạnh sắc, trục, bu-lông**. |++### Kiểu finish / loại skin+| English | VN | Đặc trưng & vị trí |+|---|---|---|+| **Solid Color** | Màu đơn sắc | Một lớp màu đều — mặt lưỡi & sống. |+| **Hydrographic** | In chuyển nước | Pattern in đè lên lớp nền (Crimson Web, Forest DDPAT) — mặt lưỡi. |+| **Anodized Multicolored** / airbrushed | Anode đa sắc | Sơn trong mờ trên nền kim loại → gradient (Fade) hoặc vằn (Slaughter) — mặt lưỡi & sống. |+| **Patina** | Lớp gỉ / patina | Xử lý hóa học đổi màu thép, đậm dần theo mòn (Blue Steel, Case Hardened) — mặt lưỡi. |+| **Gunsmith** | Gunsmith | Lai texture chi tiết cao + hiệu ứng patina — mặt lưỡi & cán. |+| **Spray-Paint** | Sơn xịt | Vẻ khuôn tô thô, thường camo (Safari Mesh, Night) — mặt lưỡi & sống. |+| **Doppler** | Doppler | Pattern sóng trong mờ, các phase P1–P4, Ruby, Sapphire, Black Pearl — mặt lưỡi. |+| **Gamma Doppler** | Gamma Doppler | Biến thể Doppler tông xanh lục/ngọc lục — mặt lưỡi. |+| **Fade** | Chuyển sắc / Fade | Gradient màu trong mờ trên nền chrome — mặt lưỡi & mũi. |+| **Marble Fade** | Fade cẩm thạch | Vân cẩm thạch nhiều màu, có biến thể "Fire and Ice" — mặt lưỡi & mũi. |+| **Tiger Tooth** | Răng hổ | Lưỡi vàng-cam với vằn ngang lởm chởm — mặt lưỡi. |+| **Ultraviolet** | Ultraviolet | Lưỡi đen mờ + điểm nhấn tím đặc trên cán — mặt lưỡi & cán. |+| **Case Hardened** | Nhiệt luyện / Case Hardened | Pha vàng-tím-"Blue Gem" do nung than — mặt lưỡi. |+| **Crimson Web** | Mạng nhện | Mạng nhện in hydrographic trên nền đỏ — mặt lưỡi. |+| **Slaughter** | Tàn sát | Vằn ngựa vằn bằng sơn nhôm & chrome — mặt lưỡi. |+| **Damascus Steel** | Thép Damascus | Vân sóng phân tầng của thép ghép — mặt lưỡi. |+| **Freehand** | Vẽ tay | Nét vẽ kiểu phấn trên nền tím/đen — mặt lưỡi. |+| **Lore** | Lore | Lưỡi vàng + hoa văn thắt nút Celtic xanh, cán bọc da — lưỡi, sống & cán. |+| **Autotronic** | Autotronic | Mảng đỏ + thép súng + lưới trắng — mặt lưỡi & fuller. |+| **Bright Water** | Nước trong | Camo hàng hải tông xanh — mặt lưỡi. |+| **Black Laminate** | Gỗ ép đen | Vân gỗ tối, mờ — mặt lưỡi & ốp cán. |+| **Rust Coat** | Lớp gỉ sét | Gỉ nặng, càng mòn càng cam & sần — mặt lưỡi. |+| **Scorched** | Cháy sém | Xám than với đốm đen như vết cháy — mặt lưỡi & sống. |+| **Stained** | Vết ố | Loang xám mờ kiểu rửa acid — mặt lưỡi. |+| **Boreal Forest / Forest DDPAT** | Ngụy trang rừng | Camo số/truyền thống tông xanh lá — mặt lưỡi. |+| **Blue Steel** | Thép xanh | Xanh nguội, nhạt khi mới, đậm tím theo mòn — mặt lưỡi. |+| **Night** | Đêm | Xanh đêm đặc, tối — mặt lưỡi & sống. |+| **Safari Mesh / Urban Masked** | Safari Mesh / Urban Masked | Lưới khuôn tô / camo đô thị xám bê tông — mặt lưỡi & sống. |++### Fade+| English | VN | Nghĩa & vị trí |+|---|---|---|+| **Fade Percentage** | Tỷ lệ Fade | Giá trị (~80–100%) = mức phủ gradient trên lưỡi — mặt lưỡi. |+| **Full Fade (100%)** | Fade hoàn toàn | Hiếm nhất: đủ 3 màu ở cường độ tối đa — mặt lưỡi. |+| **Fade Color Order** | Thứ tự màu Fade | Vàng → Cam → Hồng → Tím, chạy từ mũi đến gót — dọc lưỡi. |+| **Acid Fade** | Acid Fade | Biến thể gradient tông xám & vàng/xanh — mặt lưỡi. |+| **Fade Measurement** | Đo Fade | Đo bằng mức tím "lấn" ở gót lưỡi hoặc độ đậm màu ở mũi — mặt lưỡi. |++### Pattern+| English | VN | Nghĩa & vị trí |+|---|---|---|+| **Pattern Seed** / pattern index, template | Pattern Seed | Số (0–1000) dịch ngẫu nhiên bản đồ texture trên model — mặt lưỡi. |+| **Fire and Ice** | Băng và Lửa | Marble Fade chỉ đỏ & xanh, không vàng ở mũi — mặt lưỡi & mũi. |+| **Doppler Phase** | Giai đoạn Doppler | Khoảng pattern index cho cân bằng màu khác nhau (P1–P4, Ruby…) — mặt lưỡi. |+| **Blue Gem** | Blue Gem | Case Hardened phủ xanh tối đa — mặt lưỡi. |++### Wear / Float+| English | VN | Nghĩa & vị trí mòn |+|---|---|---|+| **Float Value** | Chỉ số mòn / Float | Số 0.00–1.00 định độ mòn — cạnh, sống, mũi, điểm cao. |+| **Factory New (FN)** | Mới xuất xưởng | 0.00–0.07, sáng nhất, gần như không xước — mặt lưỡi & sống. |+| **Minimal Wear (MW)** | Mòn tối thiểu | 0.07–0.15, chi tiết hơi mềm đi — cạnh & mũi. |+| **Field-Tested (FT)** | Đã qua sử dụng | 0.15–0.38, xước & xỉn rõ — cạnh, mũi, điểm cao. |+| **Well-Worn (WW)** | Mòn nhiều | 0.38–0.45, mất finish & xỉn nặng — mặt lưỡi & sống. |+| **Battle-Scarred (BS)** | Tàn phá | 0.45–1.00, mất finish/oxy hóa tối đa — mọi bề mặt sơn. |+| **Wear locations** | Vị trí mòn | Xước xuất hiện trước ở **cạnh sắc, sống, mũi, điểm cao (high points)** và chỗ nối lưỡi–cán. |++---++## Ghi chú dùng cho debug fidelity++- **Sai hình khối** → mục 1–4: vd "belly (bụng dao) của Bowie chưa đủ sâu", "safety ring (vòng ngón) của Karambit đặt sai vị trí", "sống dao M9 thiếu sawback".+- **Sai texture/màu** → mục 5: vd "fade color order ngược (tím ở mũi thay vì gót)", "pattern seed lệch làm Blue Gem không phủ đủ", "wear đặt ở mặt lưỡi thay vì high points".+- **Bare metal accents**: cạnh sắc, trục, bu-lông thường KHÔNG sơn — nếu model sơn cả lên đó là sai.++_Các loại item tiếp theo (súng ngắn, súng trường, súng ngắm, găng tay…) sẽ được research riêng, mỗi loại một file trong `docs/cs2-anatomy/`._diff --git a/docs/cs2-anatomy/pistols.md b/docs/cs2-anatomy/pistols.mdnew file mode 100644index 0000000..acc6ed0--- /dev/null+++ b/docs/cs2-anatomy/pistols.md@@ -0,0 +1,164 @@+# CS2 Item Anatomy Vocabulary — Pistols (Súng ngắn)++> Bộ từ vựng song ngữ để **gọi đúng tên từng bộ phận của súng ngắn** khi mô tả lỗi fidelity trong pipeline img2threejs.+> Quy tắc dùng: **geometry/hình khối sai** → dùng tên bộ phận vật lý (mục 1–3). **Texture/màu/pattern sai** → dùng thuật ngữ skin CS2 (mục 4).+>+> Nguồn: research NotebookLM (fast mode) — targetbarn.com (Parts of a Pistol + diagram), Magnum Research (manual Desert Eagle), bo3.gg (R8 Revolver), Liquipedia (P250), cs.money (weapon names), + kiến thức chuẩn về súng cho phần bị thiếu.+> Notebook: `CS2 Item Anatomy Vocabulary — Pistols (VN+EN)` (`7b0376c6`).+> _Lưu ý: 3 nguồn (cs.money, az.gov, usconcealedcarry) fail khi index; phần anatomy được targetbarn + Magnum Research cover đủ, chỗ thiếu đánh dấu [kiến thức chung]._++---++## 1. Giải phẫu súng lục bán tự động — Semi-auto pistol anatomy++Áp dụng cho hầu hết pistol CS2 (trừ R8 Revolver — xem mục 2).++### A. KHÓA NÒNG & NÒNG (Slide & Barrel)++| English | VN | Định nghĩa |+|---|---|---|+| **Slide** | Khóa nòng | Phần trên trượt lùi theo giật để nạp đạn kế tiếp (bán tự động). |+| **Rear cocking serrations** | Rãnh kéo khóa nòng (sau) | Rãnh khía phía sau slide để bám tay khi lên đạn. |+| **Front cocking serrations** | Rãnh kéo khóa nòng (trước) | Rãnh khía phía trước slide, dùng press-check. |+| **Ejection port** | Cửa hất vỏ đạn | Khe trên slide để văng vỏ đạn đã bắn ra ngoài. |+| **Breech face** | Mặt khóa nòng | Bề mặt trong của slide tì vào đáy vỏ đạn khi lên nòng. |+| **Barrel** | Nòng súng | Ống thép dẫn viên đạn sau khi kích nổ. |+| **Muzzle** | Miệng nòng | Đầu trước nòng, nơi đạn thoát ra. |+| **Crown** | Loa nòng | Đầu miệng nòng được vát/thụt để bảo vệ khương tuyến. |+| **Chamber** | Buồng đạn | Khoang cuối nòng nơi viên đạn nằm trước khi bắn. |+| **Feed ramp** | Đường dẫn đạn | Mặt dốc dẫn viên đạn từ hộp tiếp đạn vào buồng đạn. |+| **Recoil spring guide rod** | Thanh dẫn lò xo hồi lực | Thanh đỡ lò xo hồi, chống kẹt khi slide di chuyển. |+| **Extractor** | Móng văng / móc đạn | Móc kéo vỏ đạn đã bắn ra khỏi buồng đạn. |++### B. KHUNG & TAY CẦM (Frame & Grip)++| English | VN | Định nghĩa |+|---|---|---|+| **Frame** / receiver | Khung súng / thân súng | Thân chính chứa nòng, slide và cụm cò. |+| **Dust cover** | Ốp che bụi | Phần khung phía trước, nằm dưới nòng. |+| **Accessory rail** / Picatinny, under-barrel rail | Rãnh phụ kiện / ray Picatinny | Ray chuẩn dưới nòng để gắn đèn/laser. |+| **Takedown lever** / disassembly latch | Chốt tháo súng | Chốt trên khung để mở slide khi tháo súng. |+| **Grip** | Tay cầm | Phần khung cầm bằng tay, chứa hộp tiếp đạn. |+| **Grip panels** / grip scales | Ốp tay cầm | Tấm ốp hai bên tay cầm tăng bám & êm tay. |+| **Backstrap** | Phần sau tay cầm | Mặt đứng sau tay cầm, tì vào lòng bàn tay. |+| **Front strap** | Phần trước tay cầm | Mặt đứng trước tay cầm, nơi các ngón quấn quanh. |+| **Beavertail** / grip tang | Đuôi nheo | Phần nhô trên đỉnh backstrap, chống "hammer bite" & slide cứa tay. |+| **Checkering / stippling** | Vân nhám / họa tiết bám | Vân/nhám trên bề mặt tay cầm chống trượt. |++### C. ĐIỀU KHIỂN & CƠ CẤU (Controls & Mechanism)++| English | VN | Định nghĩa |+|---|---|---|+| **Trigger** | Cò súng | Bộ phận bóp để khởi động chuỗi bắn. |+| **Trigger guard** | Vành bảo vệ cò | Vòng bao quanh cò, chống cướp cò ngoài ý muốn. |+| **Hammer** (spurred vs bobbed) | Búa đập | Đập vào kim hỏa; spurred có mấu ngón cái, bobbed bo tròn. |+| **Striker** | Kim hỏa | Kim hỏa lò xo bên trong, thay cho búa ở súng striker-fired. |+| **Slide stop** / slide release | Cần giữ khóa nòng | Cần khóa slide mở khi hết đạn / thả slide về. |+| **Thumb safety** / manual safety | Khóa an toàn | Cần gạt tay vô hiệu hóa cơ cấu bắn. |+| **Decocker** | Cần hạ búa an toàn | Cần hạ búa đã lên mà không kích nổ đạn trong buồng. |+| **Grip safety** | Khóa an toàn tay cầm | Thanh an toàn ở backstrap, phải nắm đúng mới bắn được. |+| **Magazine release button** | Nút tháo hộp tiếp đạn | Nút trên khung để nhả hộp tiếp đạn khỏi tay cầm. |++### D. NGẮM (Sights)++| English | VN | Định nghĩa |+|---|---|---|+| **Front sight** (post/blade) | Đầu ngắm | Điểm ngắm gần miệng nòng, đầu slide. |+| **Rear sight** (notch) | Thước ngắm | Bộ ngắm sau slide, thường có khe chữ U/V. |+| **Sight dovetail** | Rãnh đuôi én gắn ngắm | Rãnh hình nêm cắt trên slide để cố định bộ ngắm. |+| **Three-dot sight** | Điểm ngắm ba chấm | Hệ ngắm 1 chấm trước + 2 chấm sau để căn nhanh. |++### E. HỘP TIẾP ĐẠN (Magazine)++| English | VN | Định nghĩa |+|---|---|---|+| **Magazine** | Hộp tiếp đạn / băng đạn | Hộp rời chứa đạn, đẩy đạn vào cơ cấu. |+| **Magazine well** | Hốc chứa hộp tiếp đạn | Khe dưới tay cầm để lắp hộp tiếp đạn. |+| **Magazine baseplate** / floorplate | Đế hộp tiếp đạn | Miếng đáy bịt kín hộp tiếp đạn. |+| **Follower** | Miếng đẩy đạn | Bệ lò xo trong hộp đẩy đạn lên. |+| **Threaded barrel / suppressor mount** | Nòng ren / giá gắn giảm thanh | Nòng có ren ở miệng để gắn ống giảm thanh (USP-S). |++---++## 2. Súng ổ xoay R8 — R8 Revolver++| English | VN | Định nghĩa |+|---|---|---|+| **Cylinder** / drum | Ổ xoay | Trụ chứa 8 khoang đạn, xoay quanh trục để đưa đạn vào vị trí bắn. |+| **Cylinder release / latch** | Chốt mở ổ xoay | Nút gạt trên khung để lật ổ xoay ra nạp đạn. |+| **Crane / yoke** | Trục bản lề ổ xoay | Cánh đòn gắn ổ xoay vào khung, cho ổ vung ra ngoài. |+| **Ejector rod** | Thanh đẩy vỏ đạn | Thanh ở tâm ổ xoay để đẩy vỏ đạn đã bắn ra. |+| **Extractor star** | Sao trích vỏ đạn | Bộ phận hình sao mặt sau ổ xoay, bám vành đạn để đẩy ra. |+| **Forcing cone** | Côn nòng | Đầu nòng hình phễu tiếp giáp ổ xoay, dẫn hướng viên đạn. |+| **Top strap** | Khung trên | Phần khung chạy dọc phía trên ổ xoay, nối thân với nòng. |+| **Frame** | Khung súng | Thân chính chứa cơ cấu kích hỏa (in logo "Precision & Accuracy"). |+| **Hammer** | Búa đập | Búa ngoài, quạt bằng tay hoặc bằng cò để đập kim hỏa. |+| **Barrel underlug / shroud** | Phần dưới nòng | Vỏ thép dưới nòng, bảo vệ thanh đẩy vỏ đạn. |+| **Barrel + rail** | Nòng + ray | Nòng R8 tích hợp ray Picatinny trên và dưới. |++_(Cò, vành cò, đầu/thước ngắm, backstrap, ốp tay cầm, miệng nòng — giống mục 1.)_++---++## 3. Nhận diện 10 khẩu pistol CS2++- **USP-S** — Súng lục có nòng giảm thanh — khung polymer, striker-fired, **ống giảm thanh dài tháo rời** là dấu hiệu chính.+- **P2000** — Súng lục compact tiêu chuẩn — khung polymer, striker-fired, ngắn gọn, **không có giảm thanh**.+- **Glock-18** — Súng lục polymer bắn loạt — khung polymer, striker-fired, **thân hình khối vuông**, có nấc chọn chế độ bắn loạt.+- **P250** — Súng lục mô-đun — khung polymer lõi thép, **có búa đập ngoài**, cỡ vừa.+- **Five-SeveN** — Súng lục FN cơ số đạn lớn — thân bọc polymer, búa kín, **tay cầm dài** chứa hộp 20 viên.+- **Tec-9** — Súng lục khung thép dập — phần trên thép hình ống, khung dưới polymer, **nòng có vỏ tản nhiệt, hộp đạn dài**.+- **CZ75-Auto** — Súng lục full-auto toàn thép — **búa đập ngoài**, hộp đạn phụ gắn trước làm điểm nhận diện.+- **Dual Berettas** (Elites) — Cặp súng lục — **hai khẩu đối xứng** (một khẩu văng vỏ trái), nòng hở trên slide, búa ngoài, vành cò lớn.+- **Desert Eagle** — Súng lục hạng nặng — **khung thép khổng lồ, nòng hình tam giác lớn**, slide chiếm phần lớn chiều dài súng.+- **R8 Revolver** — Súng ổ xoay 8 viên — **ổ xoay lớn**, búa ngoài lộ rõ, có ray Picatinny trên nòng.++---++## 4. Thuật ngữ SKIN / FINISH CS2 → map lên bộ phận pistol++Dùng khi **texture/màu/pattern** sai (không phải hình khối).++### Phân biệt phần được sơn+| English | VN | Nghĩa & vị trí |+|---|---|---|+| **Vanilla / stock** | Mặc định / nguyên bản | Súng không skin — slide & nòng màu đen/bạc trơn — toàn bộ súng. |+| **Painted parts** | Bộ phận được sơn | Bề mặt lớn nhận họa tiết skin — **slide, khung (frame), ốp tay cầm**. |+| **Bare metal parts** | Kim loại trần | Chi tiết chức năng giữ màu gốc — **thước/đầu ngắm, cần điều khiển, cò**. |++### Pattern+| English | VN | Nghĩa & vị trí |+|---|---|---|+| **Pattern seed** / pattern index | Chỉ số hoa văn | Số định vị ngẫu nhiên bản đồ vân — **slide & khung**. |++### Kiểu finish+| English | VN | Đặc trưng & vị trí |+|---|---|---|+| **Solid Color** / custom paint job | Sơn màu đơn | Lớp sơn đồng nhất phủ kín — slide & khung. |+| **Hydrographic** / dipping | Sơn nhúng / thủy ấn | Phim họa tiết quấn quanh bề mặt cong — rõ nhất trên **ống giảm thanh & slide**. |+| **Anodized** | Sơn mạ / anode | Lớp phủ màu bóng kim loại — slide hoặc nòng, giữ ánh thép. |+| **Patina** | Lên màu thời gian | Đổi màu kim loại theo mòn (không bong tróc) — slide. |+| **Gunsmith** | Chế tác thủ công | Patina trên **slide kim loại** + sơn tùy chỉnh trên **khung/tay cầm polymer**. |+| **Spray-Paint** | Sơn xịt | Chi tiết thấp, bong sớm ở **cạnh slide & miệng nòng**. |+| **Fade** | Chuyển màu / fade | Gradient chạy dọc chiều dài **slide & ống giảm thanh**. |++### Wear / Float+| English | VN | Nghĩa & vị trí mòn |+|---|---|---|+| **Float Value** | Chỉ số mài mòn | 0.00–1.00, mức hư hại thị giác trên toàn súng. |+| **Factory New (FN)** | Mới xuất xưởng | Sắc nét tối đa trên slide & suppressor, không xước. |+| **Minimal Wear (MW)** | Ít trầy xước | Xước cực nhỏ ở **góc cạnh sắc của slide**. |+| **Field-Tested (FT)** | Đã qua sử dụng | Mờ/bong rõ ở **miệng nòng, cạnh slide, nút điều khiển**. |+| **Well-Worn (WW)** | Mòn nhiều | Lộ kim loại trần ở **front strap & điểm gờ cao trên slide**. |+| **Battle-Scarred (BS)** | Trầy xước nặng | Bong/xỉn nặng ở **cạnh slide, controls, vùng ma sát cao trên tay cầm**. |+| **Wear high points** | Điểm dễ mòn | Chịu tác động trước: **cạnh slide, miệng nòng, cần an toàn, rãnh serrations**. |++---++## Ghi chú dùng cho debug fidelity++- **Sai hình khối** → mục 1–3: vd "nòng Desert Eagle chưa đủ dáng tam giác", "USP-S thiếu ống giảm thanh", "ổ xoay R8 sai số khoang", "Glock thiếu dáng khối vuông".+- **Sai texture/màu** → mục 4: vd "pattern seed lệch làm vân trên slide sai vị trí", "wear đặt ở giữa slide thay vì cạnh/miệng nòng/high points".+- **Bare metal accents**: đầu/thước ngắm, cần điều khiển, cò thường KHÔNG sơn — nếu model sơn cả lên đó là sai.++_Đã xong: [dao](knives.md), pistol. Loại tiếp theo: SMG (súng ngắn liên thanh) / rifle / sniper / gloves — mỗi loại một file trong `docs/cs2-anatomy/`._diff --git a/docs/cs2-anatomy/rifles.md b/docs/cs2-anatomy/rifles.mdnew file mode 100644index 0000000..cba1f3a--- /dev/null+++ b/docs/cs2-anatomy/rifles.md@@ -0,0 +1,148 @@+# CS2 Item Anatomy Vocabulary — Rifles (Súng trường)++> Bộ từ vựng song ngữ để **gọi đúng tên từng bộ phận của súng trường tấn công** khi mô tả lỗi fidelity trong pipeline img2threejs.+> Quy tắc dùng: **geometry/hình khối sai** → dùng tên bộ phận vật lý (mục 1–3). **Texture/màu/pattern sai** → dùng thuật ngữ skin CS2 (mục 4).+>+> Nguồn: research NotebookLM (fast mode, 10 nguồn) — M16 Wikipedia (tiếng Việt) + ARMY TM 9-1005-319 (M16 manual); TM 8370-50007 (AK-47 maintenance manual); Glosbe (từ điển EN↔VI); Steyr AUG Wikipedia + cheaperthandirt.com (bullpup vs conventional); pewpewtactical.com (flash hider / muzzle brake / compensator); profilerr.net (M4A4 vs M4A1-S); cs2floatchecker.com (float/wear); white.market (pattern seed). Chỗ thiếu đánh dấu [kiến thức chung].+> Notebook: `CS2 Item Anatomy Vocabulary — Rifles (VN+EN)` (`ed67e020`).++---++## 1. Giải phẫu súng trường tấn công — Assault-rifle anatomy++Áp dụng cho cả 7 rifle CS2. Layout **bullpup** (FAMAS/AUG) xem mục 2.++### A. THÂN SÚNG & NÒNG (Receiver & Barrel)++| English | VN | Định nghĩa |+|---|---|---|+| **Upper receiver** / top receiver | Thân trên | Phần trên thân súng, chứa cụm bệ khóa nòng và là nơi lắp nòng. |+| **Lower receiver** | Thân dưới | Phần dưới thân, chứa cụm cò, bộ chọn chế độ bắn và khe cắm hộp tiếp đạn. |+| **Receiver cover** / dust cover, top cover | Nắp thân súng / nắp chắn bụi | Nắp bảo vệ bộ phận chuyển động bên trong (AK có top cover hình vòm rõ). |+| **Ejection port** | Cửa hắt vỏ đạn | Khe hở trên thân nơi vỏ đạn đã bắn văng ra ngoài. |+| **Forward assist** | Nút đẩy khóa nòng | Nút nhấn để đẩy khóa nòng về vị trí đóng hoàn toàn (đặc trưng dòng M4/M16). |+| **Brass deflector** | Gờ hắt vỏ đạn | Gờ nhô sau cửa hắt vỏ, hướng vỏ đạn văng ra xa mặt người bắn. |+| **Barrel** | Nòng súng | Ống thép có rãnh xoắn định hướng & tạo xoáy cho đầu đạn. |+| **Muzzle** | Miệng nòng | Đầu mút nòng nơi đầu đạn thoát ra. |+| **Flash hider** / flash suppressor | Loa che lửa | Đầu nòng phân tán khí thuốc để giảm ánh lửa đầu nòng khi bắn. |+| **Muzzle brake** | Bộ phận bù giật | Đầu nòng chuyển khí thuốc sang hai bên để giảm lực giật về sau. |+| **Compensator** | Bộ phận giảm nảy | Đầu nòng hướng khí thuốc lên trên để chống nòng nảy lên khi bắn loạt. |+| **Threaded barrel / suppressor mount** | Đầu nòng có ren | Miệng nòng tiện ren để lắp ống giảm thanh (M4A1-S). |+| **Gas block** | Khối trích khí | Bộ phận trên nòng, trích một phần khí thuốc vào hệ vận hành. |+| **Gas tube** | Ống dẫn khí | Ống dẫn khí thuốc từ khối trích khí về bệ khóa nòng (AK: nằm rõ trên nòng). |+| **Gas piston** / short-stroke piston | Pít-tông khí | Nhận áp lực khí thuốc đẩy bệ khóa nòng về sau (hệ piston, khác direct-impingement). |+| **Front sight base** | Bệ đầu ruồi | Đế gắn trên nòng để giữ đầu ruồi. |++### B. PHỤ KIỆN THÂN (Furniture: báng + tay cầm + ốp lót tay)++| English | VN | Định nghĩa |+|---|---|---|+| **Buttstock** / stock | Báng súng | Phần sau súng tựa vào vai khi ngắm bắn. |+| **Fixed stock** | Báng cố định | Báng liền, không gập/kéo rút. |+| **Collapsible stock** / telescoping | Báng kéo rút | Báng trượt điều chỉnh chiều dài (dòng M4). |+| **Folding stock** | Báng gập | Báng gập sang bên để rút gọn súng (SG 553 gập ngang). |+| **Skeletonized stock** | Báng khung xương | Báng khoét rỗng để giảm nặng (Galil AR gập về phải). |+| **Cheek riser** / cheek rest | Ốp má | Phần đệm nhô lên báng cho vị trí tì má tối ưu khi dùng kính ngắm. |+| **Recoil pad** / buttplate | Đế báng súng | Đệm cuối báng giảm chấn & chống trượt khi tì vai. |+| **Pistol grip** | Tay cầm khai hỏa | Tay cầm sau cụm cò để giữ & điều khiển súng. |+| **Handguard** / foregrip | Ốp lót tay / tay cầm trước | Ốp bao quanh nòng, bảo vệ tay khỏi nhiệt & cho điểm cầm nắm. |+| **Vertical foregrip** | Tay cầm dọc trước | Tay cầm đứng dưới ốp lót tay (AUG có loại gập được). |+| **Rail system** (Picatinny / M-LOK / KeyMod) | Hệ thống ray | Rãnh chuẩn trên thân/ốp tay để gắn đèn, laser, kính ngắm. |++### C. NẠP ĐẠN & VẬN HÀNH (Feeding & Action)++| English | VN | Định nghĩa |+|---|---|---|+| **Magazine** (straight / curved / banana) | Hộp tiếp đạn (thẳng / cong / quả chuối) | Hộp chứa đạn, lò xo đẩy đạn lên; AK là "quả chuối" cong dài. |+| **Magazine well** | Khe cắm hộp tiếp đạn | Khoang trên thân dưới nơi lắp hộp tiếp đạn. |+| **Magazine release** / magazine catch | Chốt giữ hộp tiếp đạn | Nút/lẫy để nhả hộp tiếp đạn ra khỏi súng. |+| **Bolt** | Khóa nòng | Đẩy đạn vào buồng, đóng kín buồng đạn & khai hỏa. |+| **Bolt carrier group** (BCG) | Cụm bệ khóa nòng | Bệ + khóa nòng + kim hỏa, vận hành chu kỳ nạp/bắn. |+| **Charging handle** / cocking handle | Cần kéo nạp đạn | Kéo bệ khóa nòng về sau để lên đạn đầu / xử lý kẹt (AK ở bên phải, Galil hướng lên). |+| **Safety / fire selector** | Khóa an toàn kiêm cần chọn chế độ bắn | Lẫy khóa súng hoặc chọn phát một / loạt / tự động. |+| **Trigger** | Cò súng | Bóp để giải phóng búa đập, thực hiện phát bắn. |+| **Trigger guard** | Vành bảo vệ cò | Vòng bao quanh cò, chống cướp cò ngoài ý muốn. |++### D. NGẮM & RAY (Sights & Rails)++| English | VN | Định nghĩa |+|---|---|---|+| **Front sight post** | Đầu ruồi | Điểm ngắm trước, cột thép nhỏ trên bệ đầu ruồi. |+| **Rear sight** (aperture / peep sight) | Thước ngắm / khe ngắm | Bộ ngắm sau, căn với đầu ruồi để xác định mục tiêu. |+| **Carry handle** | Tay xách | Bộ phận trên lưng súng để xách, thường tích hợp thước ngắm (M16/M4A1-S, FAMAS lớn). |+| **Integrated optic** | Kính ngắm tích hợp | Hệ ngắm quang học gắn cố định theo thiết kế súng (AUG). |+| **Optic rail** / top rail | Ray gắn kính ngắm | Ray trên thân để lắp kính ngắm quang học. |+| **Iron sights** | Thước ngắm cơ khí | Hệ ngắm kim loại truyền thống (đầu ruồi + thước ngắm). |+| **Flip-up sights** / backup sights | Thước ngắm gập | Thước ngắm gập xuống khi không dùng / khi lắp kính. |++---++## 2. Layout Bullpup — FAMAS & AUG++Kiểu **bullpup**: **hộp tiếp đạn và bệ máy (action) nằm PHÍA SAU cò súng**, ngay trong phần báng. Ưu điểm: **giảm mạnh chiều dài tổng thể** mà vẫn giữ nguyên chiều dài nòng (gọn trong không gian hẹp, không mất tầm bắn). Dấu hiệu nhận diện: **không có báng riêng phía sau tay cầm** — thân súng chạy thẳng ra vai, hộp tiếp đạn cắm sau cò.++- **FAMAS** — bullpup Pháp, **tay xách (carry handle) rất lớn kéo dài gần hết lưng súng** che thước ngắm.+- **AUG** — bullpup Áo, thân polymer "hữu cơ", **kính ngắm quang học tích hợp** + tay cầm dọc trước gập được.++---++## 3. Nhận diện 7 khẩu rifle CS2++- **Galil AR** — Súng trường truyền thống — thân (receiver) góc cạnh, **báng khung xương gập về phải**, cần kéo nạp đạn hướng thẳng lên, ốp lót tay & furniture kiểu AK-family.+- **FAMAS** — **Bullpup** Pháp — bệ máy sau cò, **tay xách rất lớn** phủ gần hết lưng súng, dáng hộp gọn.+- **AK-47** — Súng trường truyền thống — **hộp tiếp đạn "quả chuối" cong dài**, nắp thân (top cover) hình vòm, **ống dẫn khí nằm rõ trên nòng**, cần kéo nạp bên phải.+- **M4A4** — Carbine hiện đại — nòng ngắn, **báng kéo rút (collapsible)**, hệ ray Picatinny bao quanh ốp lót tay, có forward assist & brass deflector.+- **M4A1-S** — M4A1-Silencer — nòng dài mảnh, **ống giảm thanh trụ tháo rời** là dấu hiệu chính, tay xách/thân trên kiểu M4.+- **SG 553** — SIG SG 553 — truyền thống — ốp lót tay hẹp, **báng gập ngang**, hộp tiếp đạn nhựa trong có thể kẹp đôi.+- **AUG** — Steyr AUG — **Bullpup** Áo — thân polymer "hữu cơ" tương lai, **kính ngắm quang học tích hợp**, tay cầm dọc trước gập được.++---++## 4. Thuật ngữ SKIN / FINISH CS2 → map lên bộ phận rifle++Dùng khi **texture/màu/pattern** sai (không phải hình khối).++### Phân biệt phần được sơn+| English | VN | Nghĩa & vị trí |+|---|---|---|+| **Vanilla / stock** | Mặc định / nguyên bản | Súng không skin — màu gốc trên toàn bộ từ nòng đến báng. |+| **Painted parts** | Bộ phận được sơn | Bề mặt lớn nhận họa tiết — **thân (receiver), ốp lót tay (handguard), báng súng (stock)**. |+| **Bare-metal parts** | Kim loại trần | Chi tiết chức năng giữ màu gốc — **thước/đầu ngắm, cần chọn chế độ bắn, cò, khóa nòng, cần kéo nạp đạn**. |++### Pattern+| English | VN | Nghĩa & vị trí |+|---|---|---|+| **Pattern seed** / pattern index | Chỉ số hoa văn / seed | Số 0–1000 định vị + góc xoay + cách xếp họa tiết trên model — rõ nhất với Fade & Case Hardened, trên **thân & ốp tay**. |++### Kiểu finish+| English | VN | Đặc trưng & vị trí |+|---|---|---|+| **Solid Color** / Custom Paint Job | Sơn màu đơn / họa tiết riêng | Mảng màu đồng nhất hoặc hình vẽ nghệ thuật — thân, ốp tay, báng. |+| **Hydrographic** / dipping | In chuyển nước / sơn nhúng | Họa tiết lặp phủ quanh bề mặt cong — rõ trên phụ kiện nhựa/gỗ & thân. |+| **Anodized** | Mạ anode | Lớp phủ màu bóng ánh kim — bộ phận nhôm như thân/nòng. |+| **Patina** | Lên màu thời gian | Oxy hóa/đổi màu kim loại theo mòn — thân & nòng. |+| **Gunsmith** | Chế tác thủ công | Lai: hình vẽ tùy chỉnh + hiệu ứng patina — khác nhau trên **thân kim loại** vs **báng gỗ/polymer**. |+| **Spray-Paint** | Sơn xịt | Giả khuôn tô + sơn xịt, vẻ thô, phủ toàn bề mặt; bong sớm ở **cạnh thân & miệng nòng**. |+| **Fade** | Chuyển màu / fade | Gradient nhiều sắc chạy dọc phần kim loại — thân & nòng. |++### Wear / Float+| English | VN | Nghĩa & vị trí mòn |+|---|---|---|+| **Float Value** / wear value | Chỉ số mài mòn / float | 0.00–1.00, mức hư hại thị giác trên toàn súng. |+| **Factory New (FN)** | Mới xuất xưởng | 0.00–0.07, sắc nét tối đa; thân, nòng & hộp tiếp đạn gần như không xước. |+| **Minimal Wear (MW)** | Ít trầy xước | 0.07–0.15, xước nhỏ bắt đầu ở **góc cạnh: cửa hắt vỏ, miệng nòng**. |+| **Field-Tested (FT)** | Đã qua sử dụng | 0.15–0.38, bong sơn rõ trên **ốp lót tay & hộp tiếp đạn**. |+| **Well-Worn (WW)** | Mòn nhiều | 0.38–0.45, xước nặng lộ kim loại trần dưới **thân & nòng**. |+| **Battle-Scarred (BS)** | Trầy xước nặng | 0.45–1.00, mất phần lớn sơn / xỉn tối trên **mọi bề mặt**. |+| **Wear high points** | Điểm dễ mòn | Chịu mòn trước: **miệng nòng, nòng, cạnh thân (receiver), hộp tiếp đạn, cạnh báng, đỉnh thước ngắm / ray**. |++---++## Ghi chú dùng cho debug fidelity++- **Sai hình khối** → mục 1–3: vd "AK thiếu hộp tiếp đạn cong quả chuối", "AK thiếu ống dẫn khí trên nòng", "M4A1-S thiếu ống giảm thanh tháo rời", "FAMAS/AUG chưa ra dáng bullpup (báng liền thân, mag sau cò)", "Galil thiếu báng khung xương gập phải", "SG 553 thiếu báng gập ngang".+- **Sai texture/màu** → mục 4: vd "pattern seed lệch làm vân trên thân/ốp tay sai vị trí", "wear đặt ở giữa thân thay vì cạnh/miệng nòng/high points", "Fade gradient chạy sai chiều".+- **Bare metal accents**: thước/đầu ngắm, cần chọn chế độ bắn, cò, khóa nòng, cần kéo nạp đạn thường KHÔNG sơn — nếu model sơn cả lên đó là sai.+- **Bullpup lưu ý**: FAMAS & AUG KHÔNG có báng riêng sau tay cầm — hộp tiếp đạn cắm phía sau cò; nếu model dựng chúng như súng conventional (mag trước cò + báng riêng) là sai layout.++_Đã xong: [dao](knives.md), [pistol](pistols.md), rifle. Loại tiếp theo: SMG (súng ngắn liên thanh) / sniper (súng ngắm) / gloves (găng tay) — mỗi loại một file trong `docs/cs2-anatomy/`._diff --git a/docs/cs2-anatomy/smgs.md b/docs/cs2-anatomy/smgs.mdnew file mode 100644index 0000000..757ce52--- /dev/null+++ b/docs/cs2-anatomy/smgs.md@@ -0,0 +1,147 @@+# CS2 Item Anatomy Vocabulary — SMGs (Súng ngắn liên thanh)++> Bộ từ vựng song ngữ để **gọi đúng tên từng bộ phận của súng ngắn liên thanh (SMG)** khi mô tả lỗi fidelity trong pipeline img2threejs.+> Quy tắc dùng: **geometry/hình khối sai** → dùng tên bộ phận vật lý (mục 1–2). **Texture/màu/pattern sai** → dùng thuật ngữ skin CS2 (mục 3).+>+> Nguồn: research NotebookLM (fast mode, 10 nguồn) — tecom.marines.mil (Field Medical handbook), scribd/studocu.vn (GDQP súng tiểu liên — thuật ngữ VN), heckler-koch.com (MP5), lums.edu.pk (FN P90 loading), sadefensejournal.com (PP-Bizon), pickem (MP7 vs MP9 CS2) cho anatomy & nhận diện; counter-strike.net (Workshop Finishes), cs.trade (float & pattern), steamcommunity "Redline for Nerds" cho skin/finish.+> Notebook: `CS2 Item Anatomy Vocabulary — SMGs (VN+EN)` (`f783b110`).+> _Lưu ý: một số bộ phận chuẩn không có trong nguồn được bổ sung & đánh dấu [kiến thức chung]._++---++## 1. Giải phẫu súng ngắn liên thanh tổng quát — General SMG anatomy++Áp dụng cho cả 7 khẩu SMG CS2 (MAC-10, MP9, MP7, MP5-SD, UMP-45, P90, PP-Bizon). Đa số SMG dùng cơ chế **blowback** (phản lực trực tiếp) và bắn từ bolt kín/hở.++### A. THÂN SÚNG & NÒNG (Receiver & Barrel)++| English | VN | Định nghĩa |+|---|---|---|+| **Receiver** / housing | Hộp khóa nòng / thân súng | Thân chính chứa bolt, cụm cò và giá nòng; khung tham chiếu của cả súng. |+| **Upper receiver** | Thân trên | Phần thân trên chứa bolt và đỡ nòng. |+| **Lower receiver** / grip frame | Thân dưới | Phần thân dưới chứa cụm cò và hốc cắm hộp tiếp đạn. |+| **Barrel** | Nòng súng | Ống thép dẫn viên đạn sau khi kích nổ. |+| **Muzzle** | Miệng nòng | Đầu trước nòng, nơi đạn thoát ra. |+| **Muzzle device** / flash hider, compensator | Thiết bị đầu nòng | Phụ kiện đầu nòng giảm chớp lửa hoặc ghì giật. |+| **Barrel shroud / jacket** (cooling holes/vents) | Áo nòng / ốp nòng (lỗ tản nhiệt) | Vỏ bọc quanh nòng, thường khoét lỗ để tản nhiệt & chống bỏng tay (rõ trên MAC-10, UMP-45). |+| **Suppressor** / integral silencer | Ống giảm thanh | Ống trụ bọc/nối miệng nòng để giảm tiếng — MP5-SD có **giảm thanh tích hợp** bao trọn nòng. |+| **Bolt / bolt carrier** | Khối khóa nòng / bệ khóa nòng | Cụm cơ khí lên đạn & chứa kim hỏa, trượt tới lui khi bắn. |+| **Blowback action** | Cơ chế phản lực (blowback) | Kiểu vận hành dùng áp suất khí đẩy bolt lùi để lên đạn kế tiếp. |+| **Charging handle** / cocking handle | Tay kéo khóa nòng / tay lên đạn | Tay cầm kéo bolt về sau để lên viên đầu hoặc thông kẹt. |+| **Ejection port** | Cửa hất vỏ đạn | Khe trên thân để văng vỏ đạn đã bắn (P90 hất **xuống dưới**). |+| **Extractor** | Móng văng / móc đạn | Móc trên mặt bolt kéo vỏ đạn ra khỏi buồng đạn. |++### B. BÁNG & TAY CẦM (Stock & Grip)++| English | VN | Định nghĩa |+|---|---|---|+| **Fixed stock** | Báng cố định | Báng không chỉnh, tối đa độ ổn định khi bắn. |+| **Folding stock** (side-folding, under-folding) | Báng gấp | Báng gấp sang bên/xuống dưới để gọn khi mang (MP9, UMP-45, PP-Bizon). |+| **Collapsible stock** / telescoping, retractable | Báng rút / báng kéo dài | Báng chỉnh chiều dài, trượt vào-ra (MP7, MAC-10). |+| **Wire stock** | Báng khung dây thép | Báng tối giản làm bằng thanh/dây kim loại (MAC-10). |+| **Buttplate** / buttpad | Đế báng | Mặt sau báng tì vào vai. |+| **Cheek rest** / cheek weld | Điểm tựa má | Phần trên báng để áp má căn ngắm. |+| **Pistol grip** | Tay cầm khai hỏa | Tay cầm chính của tay bóp cò. |+| **Grip stippling / texture** | Nhám tay cầm | Vân/nhám trên tay cầm chống trượt. |+| **Handguard** | Ốp lót tay | Vỏ che quanh nòng để cầm phần trước súng không bỏng tay. |+| **Foregrip** / vertical grip, forward grip | Tay cầm phụ / tay cầm trước | Tay cầm thêm phía trước tăng ổn định (MP9 tích hợp sẵn). |+| **Forend** / forearm | Phần đầu thân súng | Phần trước thân/khung nằm dưới nòng. |+| **Thumbhole** | Lỗ luồn ngón cái | Lỗ khoét trên thân bullpup để luồn ngón cái (P90). |++### C. TIẾP ĐẠN (Feeding)++| English | VN | Định nghĩa |+|---|---|---|+| **Box / stick magazine** | Băng đạn hộp / băng thẳng | Hộp rời chứa đạn, đẩy đạn bằng lò xo; thẳng hoặc hơi cong. |+| **Curved magazine** | Băng đạn cong | Băng cong theo độ côn của đạn (MP5-SD). |+| **Magazine well** | Hốc / khe cắm băng đạn | Khe trên thân/tay cầm để lắp băng đạn. |+| **P90 top-mounted horizontal magazine** | Băng đạn nằm ngang phía trên (P90) | Băng nhựa **nằm ngang, phẳng dọc nóc súng**, song song nòng; đạn xoay 90° trước khi vào buồng. |+| **PP-Bizon helical magazine** / drum | Băng đạn xoắn ốc (PP-Bizon) | Băng trụ dài **lắp dưới nòng**, cấp đạn kiểu xoắn ốc; kiêm điểm tì tay. |+| **Magazine release** / mag catch | Nút / lẫy tháo băng đạn | Cần/nút nhả băng đạn khỏi súng. |+| **Magazine baseplate** / floorplate | Đế băng đạn | Miếng đáy bịt & giữ lò xo trong băng. |+| **Follower** | Bản nâng đạn | Bệ trong băng đẩy đạn lên vị trí tiếp. |++### D. ĐIỀU KHIỂN & NGẮM (Controls & Sights)++| English | VN | Định nghĩa |+|---|---|---|+| **Trigger** | Cò súng | Lẫy bóp để khởi động chuỗi bắn. |+| **Trigger guard** | Vành bảo vệ cò | Vòng bao quanh cò, chống cướp cò ngoài ý muốn. |+| **Fire selector** / selector switch | Cần chọn chế độ bắn | Cần gạt chọn safe / bán tự động / liên thanh. |+| **Safety** | Khóa an toàn | Cơ cấu chặn súng bắn ngoài ý muốn. |+| **Front sight** (post/blade) | Đầu ngắm | Điểm ngắm gần miệng nòng. |+| **Rear sight** (notch/aperture) | Thước ngắm | Bộ ngắm phía sau thân, khe chữ U/V hoặc lỗ tròn. |+| **Iron sights** | Hệ ngắm cơ khí | Bộ ngắm không quang học gồm đầu + thước ngắm. |+| **Optic rail** / Picatinny, accessory rail | Ray gắn phụ kiện | Ray chuẩn để gắn ống ngắm/đèn/laser (P90 & MP7 có ray dọc nóc). |+| **Sling mount** / swivel, sling loop | Điểm gắn dây đeo | Móc/khuyên gắn dây đeo súng. |++---++## 2. Nhận diện 7 khẩu SMG CS2 — CS2 SMG identification++Mỗi dòng: **tên** — silhouette + vị trí băng đạn + kiểu báng + dấu hiệu nhận biết.++- **MAC-10** — Súng tiểu liên thép dập — **khối thân hình hộp vuông vức**, băng đạn hộp thẳng **cắm thẳng vào tay cầm chính**, báng khung dây thép rút gọn, thường có dây đai vải phía trước — dáng thô, ngắn, vuông.+- **MP9** — SMG polymer nhỏ gọn (kiểu B&T/Steyr) — **băng đạn nghiêng ra trước, nằm trước tay cầm chính**, báng gấp sang bên, tay cầm phụ tích hợp sẵn phía trước — dáng hiện đại, gọn.+- **MP7** — PDW siêu nhỏ gọn — **băng đạn cắm trong tay cầm chính** (như súng lục), báng thanh trượt rút gọn, **ray Picatinny kéo dài dọc nóc súng** — nhỏ nhất, dáng "súng lục to".+- **MP5-SD** — SMG có giảm thanh tích hợp — **ống giảm thanh trụ lớn bao trùm toàn bộ nòng**, băng đạn cong đặc trưng gắn trước vòng cò, báng rút — nhận ra ngay qua ống giảm thanh mập.+- **UMP-45** — SMG polymer .45 to bản — **băng đạn thẳng/thanh dài** to (cỡ .45), báng polymer đặc gấp sang bên, khe tản nhiệt lớn trên ốp lót tay — dáng gồ ghề, nặng nề.+- **P90** — SMG bullpup FN — **thiết kế bullpup** (cụm khai hỏa sau tay cầm), **băng đạn nhựa trong suốt nằm ngang dọc nóc súng**, thân liền khối có lỗ luồn ngón cái (thumbhole), cửa hất vỏ hướng xuống — silhouette độc nhất, không lẫn với súng nào.+- **PP-Bizon** — SMG nền AK — nắp hộp khóa nòng kiểu AK, **băng đạn hình trụ xoắn ốc (helical) lớn lắp dưới nòng** (kiêm điểm tì tay), báng khung tam giác gấp sang bên — nhận ra qua ống băng đạn trụ dài dưới nòng.++**Lưu ý hình khối then chốt (dễ sai nhất):**+- P90 = băng đạn **nằm ngang trên nóc** (KHÔNG phải băng cắm dưới như súng thường).+- PP-Bizon = ống **trụ xoắn dưới nòng** (KHÔNG phải băng hộp cong).+- MP7 & MAC-10 = băng đạn **trong tay cầm**; MP9 = băng **trước tay cầm**.+- MP5-SD = **giảm thanh liền** bao trọn nòng (không tháo rời như USP-S).++---++## 3. Thuật ngữ SKIN / FINISH CS2 → map lên bộ phận SMG++Dùng khi **texture/màu/pattern** sai (không phải hình khối).++### Phân biệt phần được sơn+| English | VN | Nghĩa & vị trí |+|---|---|---|+| **Vanilla / stock** | Mặc định / nguyên bản | Súng chưa áp skin — vật liệu nhà máy gốc — toàn bộ súng. |+| **Paintable parts** / refinishable areas | Vùng có thể sơn | Bề mặt lớn nhận texture skin — **thân súng (receiver), báng (stock), ốp lót tay (handguard)**, và băng đạn. |+| **Bare metal parts** / substrate, unfinishable areas | Kim loại trần / bề mặt phôi | Chi tiết chức năng giữ màu gốc — **đầu/thước ngắm, cần chọn chế độ, cò, ốc vít, trong nòng**. |++### Pattern+| English | VN | Nghĩa & vị trí |+|---|---|---|+| **Paint seed** / pattern seed, pattern index | Mã hạt / số seed | Giá trị ngẫu nhiên (1–1000) quyết định vị trí, độ xoay & độ lệch của họa tiết trên model — **thân súng & băng đạn**. |++### Kiểu finish+| English | VN | Đặc trưng & vị trí |+|---|---|---|+| **Solid Color** | Màu đơn sắc | Từng bộ phận sơn tối đa 4 màu riêng trước khi lắp ráp — thân, báng, ốp lót tay. |+| **Spray-Paint** | Sơn xịt | Sơn nhiều lớp qua khuôn chắn (stencil), hiệu ứng chồng lớp; bong sớm ở **cạnh thân & miệng nòng**. |+| **Hydrographic** / dipping | Sơn nhúng / thủy ấn | Nhúng bộ phận qua màng phim họa tiết nổi trên nước — rõ trên bề mặt cong (**ống giảm thanh MP5-SD, thân súng**). |+| **Anodized** / airbrushed, multicolored | Sơn mạ / anode | Lớp màu mỏng (candy coat) trên nền chrome bóng — giữ ánh kim loại trên thân/nòng. |+| **Patina** | Lên màu thời gian / rỉ kim loại | Đổi màu kim loại kiểu phản ứng hóa học (xanh hóa, tôi thép) — thân kim loại. |+| **Custom Paint Job** | Sơn tùy chỉnh | Tranh vẽ cố định áp thẳng lên UV map, **không đổi theo seed** — toàn thân. |+| **Gunsmith** | Chế tác thủ công | Lai Patina + Custom Paint Job trên cùng khẩu — thân kim loại + báng/ốp polymer. |+| **Fade** | Chuyển màu / fade | Biến thể Anodized, các màu hòa & chuyển dần dọc **thân súng & báng**. |++### Wear / Float+| English | VN | Nghĩa & vị trí mòn |+|---|---|---|+| **Float Value** / wear value | Chỉ số Float / độ mòn | Số 0.00–1.00 định mức trầy xước & xuống cấp lớp sơn — toàn súng. |+| **Factory New (FN)** | Mới xuất xưởng | 0.00–0.07, hoàn hảo nhất, gần như không xước — thân & băng đạn. |+| **Minimal Wear (MW)** | Ít trầy xước | 0.07–0.15, vài xước nhỏ ở cạnh, màu hơi tối — **cạnh thân & góc sắc**. |+| **Field-Tested (FT)** | Đã qua sử dụng | 0.15–0.37, phổ biến nhất, xước & bụi bẩn rõ — cạnh thân, miệng nòng, controls. |+| **Well-Worn (WW)** | Mòn nhiều | 0.37–0.44, bong tróc đáng kể, lộ kim loại trần — high points & cạnh băng đạn. |+| **Battle-Scarred (BS)** | Tàn phá / vết sẹo chiến tranh | 0.44–1.00, mất phần lớn lớp sơn, xỉn & bẩn — mọi bề mặt sơn. |+| **Wear high points** | Điểm dễ mòn | Chịu tác động trước: **cạnh & góc sắc của thân, miệng nòng, các điểm nhô cao, cần điều khiển, cạnh băng đạn**. |++---++## Ghi chú dùng cho debug fidelity++- **Sai hình khối** → mục 1–2: vd "P90 để băng đạn cắm dưới thay vì nằm ngang trên nóc", "PP-Bizon thiếu ống băng đạn xoắn dưới nòng", "MP5-SD thiếu giảm thanh tích hợp bao nòng", "MAC-10 chưa đủ dáng khối hộp vuông", "MP7 để băng ngoài tay cầm".+- **Sai texture/màu** → mục 3: vd "pattern seed lệch làm họa tiết trên thân sai vị trí", "wear đặt ở giữa thân thay vì cạnh/miệng nòng/high points", "Fade chuyển màu sai hướng dọc thân".+- **Bare metal accents**: đầu/thước ngắm, cần chọn chế độ, cò, ốc vít thường KHÔNG sơn — nếu model sơn cả lên đó là sai.++_Đã xong: [dao](knives.md), [pistol](pistols.md), SMG. Loại tiếp theo: rifle / sniper / gloves — mỗi loại một file trong `docs/cs2-anatomy/`._diff --git a/docs/cs2-anatomy/snipers.md b/docs/cs2-anatomy/snipers.mdnew file mode 100644index 0000000..45b2f32--- /dev/null+++ b/docs/cs2-anatomy/snipers.md@@ -0,0 +1,152 @@+# CS2 Item Anatomy Vocabulary — Snipers (Súng ngắm / Súng bắn tỉa)++> Bộ từ vựng song ngữ để **gọi đúng tên từng bộ phận của súng ngắm** khi mô tả lỗi fidelity trong pipeline img2threejs.+> Quy tắc dùng: **geometry/hình khối sai** → dùng tên bộ phận vật lý (mục 1–3). **Texture/màu/pattern sai** → dùng thuật ngữ skin CS2 (mục 4).+> Đặc điểm định danh của dòng này là **ống ngắm (scope/optic)** — nên nó có mục riêng (mục 2).+>+> Nguồn: research NotebookLM (fast mode, 10 nguồn) — Liquipedia (SSG 08), strafe.com (AWP deep dive), Leupold Tactical Riflescope Manual + Rugged Suppressors (anatomy nòng/ngắm); Shephard Infantry Equipment Handbook, H&K G3 Wikipedia, vi.wikipedia (cơ cấu lên đạn thủ công), GunSkins (bolt-action vs semi-auto); counter-strike.net Workshop Finishes + ProSettings (skin & finish CS2), + kiến thức chuẩn về súng cho phần bị thiếu.+> Notebook: `CS2 Item Anatomy Vocabulary — Snipers (VN+EN)` (`e20b3968`).+> _Lưu ý: cả 10 nguồn import thành công; chỗ không có nguồn phủ được đánh dấu [kiến thức chung]._++---++## 1. Giải phẫu súng ngắm tổng quát — Sniper / precision-rifle anatomy++### A. CƠ CẤU & NÒNG (Action & Barrel)++| English | VN | Định nghĩa |+|---|---|---|+| **Receiver** (frame) | Hộp khóa nòng | Thân trung tâm chứa các bộ phận vận hành bên trong của súng. |+| **Action** (operating system) | Cơ cấu lên đạn | Hệ cơ khí lo việc nạp, bắn và tống vỏ đạn. |+| **Bolt** (breechblock) | Khối khóa nòng | Bộ phận trượt trong hộp khóa nòng để lên đạn và bịt kín buồng đạn. |+| **Bolt handle** (cocking handle) | Cần kéo khóa nòng | Cần kim loại gắn vào khối khóa nòng để lên đạn thủ công. |+| **Bolt knob** (handle tip) | Núm kéo khóa nòng | Núm ở đầu cần kéo khóa nòng để tay bám khi giật. |+| **Charging handle** (cocking lever) | Cần lên đạn | Cần kéo lùi khối khóa nòng / bệ khóa nòng trên súng bán tự động. |+| **Bolt-action** (manual action) | Cơ cấu lên đạn thủ công | Hệ phải kéo khóa nòng thủ công cho từng phát bắn (SSG 08, AWP). |+| **Semi-automatic** (self-loading) | Súng bán tự động | Hệ dùng năng lượng giật/khí thuốc tự lên đạn sau mỗi phát (SCAR-20, G3SG1). |+| **Barrel** (tube) | Nòng súng | Ống thép dẫn viên đạn khi bắn. |+| **Fluted barrel** (grooved barrel) | Nòng xẻ rãnh | Nòng có rãnh xẻ dọc để giảm nặng và tăng diện tích tản nhiệt. |+| **Free-floating barrel** | Nòng treo tự do | Nòng không chạm ốp/báng, tránh nhiễu để tăng độ chính xác. |+| **Heavy barrel** (bull barrel) | Nòng hạng nặng | Nòng dày, cứng, giảm rung và chịu nhiệt khi bắn liên tục. |+| **Muzzle** (bore exit) | Đầu nòng / miệng nòng | Đầu trước nòng, nơi đạn thoát ra. |+| **Muzzle brake** (compensator) | Bộ hãm giật đầu nòng | Chuyển hướng khí thuốc để giảm giật cảm nhận. |+| **Flash hider** (flash suppressor) | Bộ che lửa đầu nòng | Gắn ở miệng nòng, giảm tia lửa nhìn thấy khi bắn. |+| **Threaded muzzle** (threaded tip) | Đầu nòng có ren | Miệng nòng có ren để gắn giảm thanh / phụ kiện đầu nòng. |++### B. BÁNG & TAY CẦM (Stock & Grip)++| English | VN | Định nghĩa |+|---|---|---|+| **Buttstock** (shoulder stock) | Báng súng | Phần sau súng tì vào vai để đỡ. |+| **Adjustable stock** (modular stock) | Báng điều chỉnh được | Báng có phần chỉnh kích thước theo cơ thể người bắn. |+| **Folding stock** (collapsible stock) | Báng gấp | Báng gấp/thu lại để súng gọn khi mang (SSG 08). |+| **Skeletonized stock** (hollow stock) | Báng dạng khung xương | Báng khoét bớt vật liệu cho nhẹ mà vẫn cứng (SSG 08). |+| **Cheek riser** (cheek piece) | Ốp má | Phần nâng trên báng đỡ đầu người bắn để căn mắt vào ngắm. |+| **Adjustable comb** (riser plate) | Ốp má chỉnh được | Ốp má chỉnh cao/thấp để căn mắt với ống ngắm gắn cao. |+| **Recoil pad** (buttpad) | Đệm báng súng | Đệm mềm ở đuôi báng để hấp thụ lực giật. |+| **Pistol grip** (main grip) | Tay nắm chính | Tay cầm dọc cho tay thuận đỡ súng và bóp cò (SCAR-20, G3SG1). |+| **Trigger** (firing lever) | Cò súng | Cần bóp để nhả cơ cấu kích hỏa. |+| **Trigger guard** (safety loop) | Vành bảo vệ cò | Vòng bao quanh cò, chống cướp cò ngoài ý muốn. |+| **Two-stage trigger** (precision trigger) | Cò hai giai đoạn | Cò có đoạn "take-up" đầu rồi mới tới điểm nhả dứt khoát. |++### C. TIẾP ĐẠN & RAY (Feeding & Rails)++| English | VN | Định nghĩa |+|---|---|---|+| **Magazine** (clip) | Hộp tiếp đạn / băng đạn | Hộp chứa đạn, đẩy đạn vào cơ cấu. |+| **Magazine well** (magwell) | Hốc cắm hộp tiếp đạn | Khe trên hộp khóa nòng để lắp và khóa hộp tiếp đạn. |+| **Box magazine** (detachable magazine) | Hộp tiếp đạn dạng khối | Hộp đạn hình chữ nhật, tháo rời (SCAR-20, G3SG1). |+| **Handguard** (forend) | Ốp lót tay | Phần bọc trước súng, bảo vệ tay khỏi nòng nóng. |+| **Picatinny rail** (tactical rail) | Ray Picatinny | Ray chuẩn để gắn ống ngắm, đèn/laser, phụ kiện. |+| **Bipod** (support stand) | Chân chống hai chân | Chân hai càng để tì súng lên mặt phẳng cho ổn định (G3SG1). |+| **Sling swivel** (sling mount) | Vòng khoen dây đeo | Điểm gắn dây đeo để mang súng. |+| **Ejection port** (shell window) | Cửa hất vỏ đạn | Khe trên hộp khóa nòng để văng vỏ đạn đã bắn (súng bán tự động). |+| **Dust cover** (action cover) | Nắp che bụi | Nắp/vạt che chống bụi lọt vào cơ cấu bên trong. |++---++## 2. Ống ngắm — Riflescope / Optic (đặc điểm định danh của dòng sniper)++Đây là bộ phận nổi bật nhất; sai hình khối ống ngắm thường là lỗi fidelity dễ thấy nhất.++| English | VN | Định nghĩa |+|---|---|---|+| **Objective lens** (front lens) | Vật kính | Thấu kính đầu ống, gom sáng và tạo ảnh ban đầu của mục tiêu. |+| **Objective bell** (front housing) | Đầu loe vật kính | Phần loe trước của thân ống, chứa vật kính. |+| **Ocular lens / eyepiece** (eyepiece lens) | Thị kính | Cụm thấu kính sau ống, gần mắt, phóng đại ảnh. |+| **Scope tube / main tube** (body tube) | Thân ống chính | Ống trụ giữa, chứa cụm thấu kính đảo ảnh và cơ cấu bên trong. |+| **Elevation turret** (elevation adjustment) | Núm chỉnh cao độ | Núm trên đỉnh, chỉnh dọc tâm ngắm để bù độ rơi đạn. |+| **Windage turret** (windage adjustment) | Núm chỉnh hướng gió | Núm bên hông, chỉnh ngang tâm ngắm để bù gió tạt. |+| **Parallax adjustment / side focus** (side parallax dial) | Núm chỉnh thị sai | Chỉnh cho ảnh mục tiêu và tâm ngắm về cùng mặt phẳng tiêu cự. |+| **Magnification ring / power ring / zoom ring** (power selector) | Vòng chỉnh độ phóng đại | Vòng xoay đổi mức phóng đại (ống ngắm biến đổi). |+| **Reticle / crosshair** (aiming point) | Tâm ngắm / vạch chữ thập | Hoa văn/đường giao bên trong để căn súng với mục tiêu. |+| **Scope mount** (base) | Gá ống ngắm / chân đế | Bộ gá cố định ống ngắm lên hộp khóa nòng hoặc ray. |+| **Scope rings** (mounting rings) | Vòng khuyên giữ ống ngắm | Kẹp tròn ôm thân ống, siết ống vào gá/ray. |+| **One-piece mount** (uni-mount) | Chân đế nguyên khối | Một khối gá liền tích hợp cả hai vòng, tăng độ đồng trục & vững. |+| **Sunshade / lens hood** (glare shield) | Ống che nắng | Ống nối dài trước vật kính, giảm lóa và bảo vệ thấu kính. |+| **Eye relief** (eye distance) | Khoảng đặt mắt | Khoảng cách từ thị kính tới mắt để thấy trọn ảnh ngắm rõ. |+| **Diopter / eyepiece focus ring** (diopter lock ring) | Vòng lấy nét thị kính | Chỉnh trên thị kính để lấy nét tâm ngắm theo mắt người bắn. |+| **Illumination control / brightness knob** (illumination dial) | Núm chỉnh đèn tâm ngắm | Núm/nút bật và chỉnh độ sáng của tâm ngắm phát sáng. |++---++## 3. Nhận diện 4 khẩu sniper CS2++- **SSG 08** (Scout) — Súng ngắm bolt-action hạng nhẹ — **cơ cấu lên đạn thủ công**, dáng mảnh, **báng khung xương/gấp**, ống ngắm gọn gắn ray Picatinny. Nhẹ nhất trong nhóm.+- **AWP** — Arctic Warfare bolt-action hạng nặng — **cơ cấu lên đạn thủ công**, nặng và cồng kềnh, **thân xanh olive** đặc trưng, **ống ngắm to độ phóng đại cao**, cần kéo khóa nòng bên phải, nòng dày.+- **SCAR-20** — Súng ngắm bán tự động (nền FN SCAR-H) — **không có cần kéo khóa nòng**, nặng, **hộp khóa nòng dáng khối**, tay nắm chính (pistol grip), hộp tiếp đạn khối, ray gắn ống ngắm, báng cố định.+- **G3SG1** — Súng ngắm bán tự động (nền H&K G3) — **không có cần kéo khóa nòng**, dài & nặng, **ốp lót tay dài có chân chống (bipod) tích hợp**, hộp tiếp đạn khối, ống ngắm chuyên dụng (Hensoldt/Zeiss).++_Phân biệt cốt lõi: **có cần kéo khóa nòng (bolt handle) = bolt-action** (SSG 08, AWP); **không có, có cửa hất vỏ = bán tự động** (SCAR-20, G3SG1)._++---++## 4. Thuật ngữ SKIN / FINISH CS2 → map lên bộ phận sniper++Dùng khi **texture/màu/pattern** sai (không phải hình khối).++### Phân biệt phần được sơn+| English | VN | Nghĩa & vị trí |+|---|---|---|+| **Vanilla / stock** (default) | Mặc định / nguyên bản | Súng không skin, giữ diện mạo gốc — toàn bộ súng. |+| **Painted parts** (paintable areas) | Bộ phận được sơn | Vùng nhận màu/họa tiết skin — **hộp khóa nòng, nòng, báng, ốp lót tay**. |+| **Bare-metal parts** (unpainted regions) | Kim loại trần | Chi tiết giữ màu gốc — **khối khóa nòng, cò**; và **ống ngắm thường KHÔNG được skin sơn**. |++### Pattern+| English | VN | Nghĩa & vị trí |+|---|---|---|+| **Pattern seed** (pattern index) | Chỉ số hoa văn | Số ngẫu nhiên định vị/xoay/căn bản đồ vân trên súng — receiver, nòng, báng. |++### Kiểu finish+| English | VN | Đặc trưng & vị trí |+|---|---|---|+| **Solid Color** (paint by number) | Màu đơn | Tối đa 4 màu áp lên các vùng định sẵn của súng. |+| **Hydrographic** (hydro-dipping) | Sơn nhúng nước | Phim họa tiết quấn quanh bề mặt cong — rõ nhất trên nòng & báng. |+| **Anodized** (candy coat) | Mạ anode | Lớp "candy coat" màu phủ trên nền chrome, giữ ánh kim. |+| **Spray-Paint** (stencil) | Sơn xịt | Áp qua khuôn tô, triplanar mapping — chi tiết thô. |+| **Patina** (forced aging) | Lên màu/oxy hóa | Đổi màu kim loại theo phản ứng hóa học (case-harden, bluing) — receiver & nòng. |+| **Gunsmith** (mixed media) | Chế tác thủ công | Patina trên **phần kim loại** + sơn tùy chỉnh trên **báng/ốp** furniture. |+| **Fade** (gradient) | Chuyển màu / fade | Gradient trên nền anode/chrome chạy dọc nòng & receiver. |+| **Custom Paint Job** (graphic art) | Sơn tùy chỉnh | Đồ họa chi tiết cao áp thẳng lên bản đồ UV của súng. |++### Wear / Float+| English | VN | Nghĩa & vị trí mòn |+|---|---|---|+| **Float value** (wear index) | Chỉ số mài mòn | 0.00–1.00, mức hư hại thị giác trên toàn súng. |+| **Factory New (FN)** | Mới xuất xưởng | 0.00–0.07, gần như không xước, sắc nét nhất. |+| **Minimal Wear (MW)** | Ít trầy xước | 0.07–0.15, vài xước cực nhỏ, gần như mới. |+| **Field-Tested (FT)** | Đã qua sử dụng | 0.15–0.38, xước & bong sơn vừa phải. |+| **Well-Worn (WW)** | Mòn nhiều | 0.38–0.45, mất sơn & xỉn nặng khắp súng. |+| **Battle-Scarred (BS)** | Trầy xước nặng | 0.45–1.00, mất finish gốc gần hết, oxy hóa tối đa. |+| **Wear high points** | Điểm dễ mòn | Chịu tác động trước: **đầu nòng, cạnh nòng, cạnh báng, hộp tiếp đạn, gờ cao receiver, cần kéo khóa nòng**. |++---++## Ghi chú dùng cho debug fidelity++- **Sai hình khối** → mục 1–3: vd "ống ngắm AWP chưa đủ to / thiếu đầu loe vật kính", "SSG 08 thiếu báng khung xương", "SCAR-20 vẽ nhầm cần kéo khóa nòng (phải bỏ vì là bán tự động)", "G3SG1 thiếu bipod tích hợp dưới ốp lót tay", "nòng AWP chưa đủ dày".+- **Sai ống ngắm** → mục 2: vd "sai tỉ lệ vật kính/thị kính", "thiếu núm chỉnh cao độ/hướng gió (turret)", "vòng chỉnh độ phóng đại đặt sai chỗ", "gá/vòng khuyên giữ ống ngắm sai".+- **Sai texture/màu** → mục 4: vd "pattern seed lệch làm vân trên receiver/báng sai vị trí", "wear đặt giữa nòng thay vì đầu nòng/cạnh/high points".+- **Bare metal & ống ngắm**: khối khóa nòng, cò — và **ống ngắm** — thường KHÔNG được skin sơn; nếu model sơn cả họa tiết skin lên ống ngắm là sai.++_Đã xong: [dao](knives.md), [pistol](pistols.md), sniper. Loại tiếp theo: SMG / rifle / gloves — mỗi loại một file trong `docs/cs2-anatomy/`._diff --git a/docs/cs2/3D_Technical_Mapping.json b/docs/cs2/3D_Technical_Mapping.jsonnew file mode 100644index 0000000..1fcc57b--- /dev/null+++ b/docs/cs2/3D_Technical_Mapping.json@@ -0,0 +1,207 @@+{+ "metadata": {+ "title": "3D Technical Mapping - CS2 to Three.js",+ "version": "1.0.0",+ "created": "2026-07-24",+ "notebook_id": "30ec3dba-5a20-4980-8886-ce89b506b634",+ "sources": [+ "Three.js Docs",+ "Valve Developer Community",+ "CSFloat Blog",+ "Steam Community",+ "Three.js Forum"+ ]+ },+ "pbr_properties": {+ "core": {+ "color": {"type": "Color", "default": "0xffffff", "range": null, "effect": "Base surface color", "perf": "low"},+ "metalness": {"type": "Float", "default": 0.0, "range": [0.0, 1.0], "effect": "0=dielectric, 1=metal", "perf": "low"},+ "roughness": {"type": "Float", "default": 1.0, "range": [0.0, 1.0], "effect": "0=mirror, 1=matte", "perf": "low"},+ "envMapIntensity": {"type": "Float", "default": 1.0, "range": [0.0, null], "effect": "Reflection strength", "perf": "low"},+ "flatShading": {"type": "Boolean", "default": false, "effect": "Faceted vs smooth", "perf": "low"},+ "side": {"type": "Enum", "default": "FRONT", "effect": "Rendered face(s)", "perf": "low"}+ },+ "advanced": {+ "clearcoat": {"type": "Float", "default": 0.0, "range": [0.0, 1.0], "effect": "Extra glossy layer", "perf": "medium"},+ "clearcoatRoughness": {"type": "Float", "default": 0.0, "range": [0.0, 1.0], "effect": "Clearcoat roughness", "perf": "medium"},+ "transmission": {"type": "Float", "default": 0.0, "range": [0.0, 1.0], "effect": "Light transmission", "perf": "very_high"},+ "thickness": {"type": "Float", "default": 0.0, "range": [0.0, null], "effect": "Absorption thickness", "perf": "high"},+ "ior": {"type": "Float", "default": 1.5, "range": [1.0, 2.33], "effect": "Refraction index", "perf": "medium"},+ "sheen": {"type": "Float", "default": 0.0, "range": [0.0, 1.0], "effect": "Velvet/fabric effect", "perf": "medium"},+ "sheenRoughness": {"type": "Float", "default": 0.0, "range": [0.0, 1.0], "effect": "Sheen roughness", "perf": "medium"},+ "sheenColor": {"type": "Color", "default": "0x000000", "effect": "Sheen color tint", "perf": "medium"},+ "iridescence": {"type": "Float", "default": 0.0, "range": [0.0, 1.0], "effect": "Thin-film interference", "perf": "high"},+ "iridescenceIOR": {"type": "Float", "default": 1.3, "range": [1.0, 3.0], "effect": "Iridescent layer IOR", "perf": "high"},+ "iridescenceThicknessRange": {"type": "[min,max]", "default": [100, 400], "effect": "Iridescence thickness", "perf": "high"},+ "anisotropy": {"type": "Float", "default": 0.0, "range": [0.0, 1.0], "effect": "Stretched highlights", "perf": "high"},+ "anisotropyRotation": {"type": "Float", "default": 0.0, "range": [0, 6.28], "effect": "Anisotropic direction", "perf": "high"},+ "attenuationColor": {"type": "Color", "default": "0xffffff", "effect": "Transmission absorption color", "perf": "high"},+ "attenuationDistance": {"type": "Float", "default": 0.5, "range": [0.0, null], "effect": "Absorption distance", "perf": "high"}+ }+ },+ "material_presets": {+ "polished_metal": {"color": "0xaaaaaa", "metalness": 1.0, "roughness": 0.05, "envMapIntensity": 1.5},+ "brushed_steel": {"color": "0x888888", "metalness": 1.0, "roughness": 0.3, "anisotropy": 0.8},+ "matte_plastic": {"color": "0x1a1a1a", "metalness": 0.0, "roughness": 0.75, "ior": 1.45},+ "gunmetal": {"color": "0x3a3a3a", "metalness": 1.0, "roughness": 0.45, "envMapIntensity": 1.2},+ "glass": {"color": "0xffffff", "metalness": 0.0, "roughness": 0.0, "transmission": 1.0, "thickness": 0.5, "ior": 1.5},+ "wood": {"color": "0x6f4e37", "metalness": 0.0, "roughness": 0.6, "clearcoat": 0.2},+ "fabric": {"color": "0x2d2d2d", "metalness": 0.0, "roughness": 0.9, "sheen": 1.0, "sheenColor": "0xffffff"},+ "rubber": {"color": "0x111111", "metalness": 0.0, "roughness": 0.85, "clearcoat": 0.1}+ },+ "cs2_finish_styles": {+ "anodized": {+ "metalness": [1.0, 1.0],+ "roughness": [0.05, 0.15],+ "clearcoat": [0.3, 0.5],+ "iridescence": [0.0, 0.2],+ "wear_behavior": "Color peels from edges, reveals base metal",+ "examples": ["Fade", "Blue Steel"]+ },+ "anodized_multicolored": {+ "metalness": [1.0, 1.0],+ "roughness": [0.05, 0.10],+ "iridescence": [0.3, 0.5],+ "iridescenceIOR": [1.5, 2.0],+ "wear_behavior": "Gloss fades, color gradient shifts",+ "examples": ["Fade 100%", "Doppler"]+ },+ "custom_paint_job": {+ "metalness": [0.0, 0.0],+ "roughness": [0.3, 0.5],+ "clearcoat": [0.2, 0.4],+ "wear_behavior": "Paint scratches from edges, reveals metal",+ "examples": ["Slaughter", "Crimson Web", "Asiimov"]+ },+ "gunsmith": {+ "metalness": [0.7, 0.9],+ "roughness": [0.2, 0.4],+ "clearcoat": [0.0, 0.1],+ "wear_behavior": "Combined paint fading + metal exposure",+ "examples": ["Night", "Corticera"]+ },+ "hydrographic": {+ "metalness": [0.0, 0.0],+ "roughness": [0.5, 0.7],+ "clearcoat": [0.1, 0.2],+ "wear_behavior": "Large patches peel, exposes base",+ "examples": ["Boreal Forest", "Safari Mesh"]+ },+ "patina": {+ "metalness": [0.9, 1.0],+ "roughness": [0.2, 0.4],+ "iridescence": [0.3, 0.6],+ "wear_behavior": "Color shifts/darkens, oxidation",+ "examples": ["Case Hardened", "Blue Steel"]+ },+ "solid_color": {+ "metalness": [0.0, 0.0],+ "roughness": [0.3, 0.5],+ "clearcoat": [0.2, 0.3],+ "wear_behavior": "Scratches reveal metal at edges",+ "examples": ["Urban Masked", "Jungle Spray"]+ },+ "sprayed": {+ "metalness": [0.0, 0.0],+ "roughness": [0.6, 0.8],+ "clearcoat": [0.0, 0.0],+ "wear_behavior": "Heavy scratching, base metal visible",+ "examples": ["Scorched", "Sand Dune"]+ }+ },+ "wear_tiers": {+ "factory_new": {"min": 0.00, "max": 0.07, "abbr": "FN"},+ "minimal_wear": {"min": 0.07, "max": 0.15, "abbr": "MW"},+ "field_tested": {"min": 0.15, "max": 0.38, "abbr": "FT"},+ "well_worn": {"min": 0.38, "max": 0.45, "abbr": "WW"},+ "battle_scarred": {"min": 0.45, "max": 1.00, "abbr": "BS"}+ },+ "knife_components": {+ "blade_types": {+ "clip_point": {"geometry": "ExtrudeGeometry", "ratio": "1:3.5", "metalness": 1.0, "roughness": 0.15},+ "drop_point": {"geometry": "ExtrudeGeometry", "ratio": "1:3", "metalness": 0.9, "roughness": 0.2},+ "tanto": {"geometry": "ExtrudeGeometry", "ratio": "1:3", "metalness": 1.0, "roughness": 0.1},+ "karambit": {"geometry": "ExtrudeGeometry", "ratio": "1:2", "metalness": 1.0, "roughness": 0.05},+ "falchion": {"geometry": "LatheGeometry", "ratio": "1:4", "metalness": 1.0, "roughness": 0.15},+ "gut_hook": {"geometry": "ExtrudeGeometry+CSG", "ratio": "1:2.5", "metalness": 1.0, "roughness": 0.3}+ },+ "handle": {+ "tang": {"geometry": "BoxGeometry", "metalness": 1.0, "roughness": 0.4},+ "scales": {"geometry": "ExtrudeGeometry", "metalness": 0.0, "roughness": 0.75},+ "screws": {"geometry": "CylinderGeometry", "metalness": 1.0, "roughness": 0.35},+ "guard": {"geometry": "BoxGeometry", "metalness": 1.0, "roughness": 0.3},+ "pommel": {"geometry": "CylinderGeometry", "metalness": 1.0, "roughness": 0.35},+ "lanyard": {"geometry": "TorusGeometry", "metalness": 0.0, "roughness": 0.9}+ }+ },+ "pistol_components": {+ "slide": {"geometry": "BoxGeometry", "boolean": ["ejection_port", "rail"]},+ "frame": {"geometry": "ExtrudeGeometry+Box", "boolean": ["mag_well"]},+ "barrel": {"geometry": "CylinderGeometry", "boolean": ["bore"]},+ "trigger_guard": {"geometry": "ExtrudeGeometry", "boolean": []},+ "magazine": {"geometry": "BoxGeometry", "boolean": ["feed_lips"]},+ "sights": {"geometry": "BoxGeometry", "boolean": []},+ "grip": {"geometry": "ExtrudeGeometry", "boolean": [], "note": "Use normalMap for texture"}+ },+ "rifle_components": {+ "receiver_upper": {"geometry": "BoxGeometry"},+ "receiver_lower": {"geometry": "BoxGeometry"},+ "barrel": {"geometry": "CylinderGeometry"},+ "handguard": {"geometry": "BoxGeometry/CylinderGeometry"},+ "stock": {"geometry": "BoxGeometry"},+ "magazine": {"geometry": "BoxGeometry"},+ "pistol_grip": {"geometry": "ExtrudeGeometry"},+ "scope": {"geometry": "TubeGeometry+SphereGeometry"},+ "muzzle": {"geometry": "CylinderGeometry"}+ },+ "spatial_wear_glossary": {+ "core_industry_terms": {+ "surface_imperfections": {"en": "Surface Imperfections", "vi": "Khuyết điểm bề mặt", "def": "Microscopic variations (fingerprints, micro-scratches) that break uniform reflections."},+ "weathering_aging": {"en": "Weathering / Aging", "vi": "Phong hóa / Lão hóa", "def": "Surface degradation from environmental exposure over time."},+ "wear_and_tear": {"en": "Wear and Tear", "vi": "Hao mòn sử dụng", "def": "Physical damage from active use or friction."},+ "edge_wear": {"en": "Edge Wear", "vi": "Mòn cạnh viền", "def": "Damage concentrated along sharp corners or high-exposure edges."},+ "procedural_grunge": {"en": "Procedural Grunge", "vi": "Cáu bẩn thuật toán", "def": "Algorithmically generated dirt distributed via AO or curvature masks."}+ },+ "damage_types_pbr_impact": {+ "oxidation_rust_patina": {+ "en": "Oxidation / Rust / Patina",+ "vi": "Oxy hóa / Rỉ sét / Lớp ô-xy hóa",+ "albedo": "Orange-brown or dark-green shift",+ "roughness": {"range": [0.8, 1.0], "impact": "Increases significantly"},+ "metalness": {"range": [0.0, 0.0], "impact": "Drops to 0 (Dielectric oxide)"},+ "normal_height": "Adds high-frequency pitting and scaling"+ },+ "scratches_dents": {+ "en": "Scratches / Dents",+ "vi": "Vết xước / Móp méo",+ "albedo": "Exposes base silver/grey metal",+ "roughness": {"range": [0.1, 0.2], "impact": "Decreases at center (shiny base)"},+ "metalness": {"range": [1.0, 1.0], "impact": "Increases if paint is scraped"},+ "normal_height": "Sharp linear indentations"+ },+ "smudges_fingerprints": {+ "en": "Smudges / Fingerprints",+ "vi": "Vết ố / Dấu vân tay",+ "albedo": "Negligible change",+ "roughness": {"range": [0.4, 0.6], "impact": "Localized increase (oily layer)"},+ "metalness": {"range": [null, null], "impact": "Unchanged"},+ "normal_height": "Unchanged"+ },+ "dust_dirt_mud": {+ "en": "Dust / Dirt / Mud",+ "vi": "Bụi / Đất sét / Bùn",+ "albedo": "Matches environment (tan/brown/grey)",+ "roughness": {"range": [0.9, 1.0], "impact": "Becomes completely rough"},+ "metalness": {"range": [0.0, 0.0], "impact": "Drops to 0 (Non-metallic soil)"},+ "normal_height": "Smooths micro-structures or adds thick volume"+ }+ },+ "spatial_modifiers": {+ "tip_to_spine_gradient": {"en": "Tip-to-spine gradient", "vi": "Gradient từ mũi đến sống dao"},+ "edge_heavy": {"en": "Edge-heavy wear", "vi": "Mòn tập trung ở cạnh"},+ "friction_point": {"en": "Friction-point wear", "vi": "Mòn điểm ma sát"},+ "speckled": {"en": "Speckled", "vi": "Dạng đốm"},+ "exposed_core": {"en": "Exposed core", "vi": "Lộ lõi"}+ }+ }+}diff --git a/docs/cs2/3D_Technical_Reference.md b/docs/cs2/3D_Technical_Reference.mdnew file mode 100644index 0000000..6208164--- /dev/null+++ b/docs/cs2/3D_Technical_Reference.md@@ -0,0 +1,685 @@+# 3D Technical Reference — CS2 to Three.js Mapping+# Từ điển Kỹ thuật 3D — Mapping CS2 sang Three.js++> NotebookLM Research ID: `30ec3dba-5a20-4980-8886-ce89b506b634`+> Last updated: July 2026++---++## Table of Contents++1. [PBR Property Map](#1-pbr-property-map)+2. [Material Preset Recipes](#2-material-preset-recipes)+3. [CS2 Finish Styles → PBR Profiles](#3-cs2-finish-styles--pbr-profiles)+4. [Wear System Bridge](#4-wear-system-bridge)+5. [Component Recipe Database](#5-component-recipe-database)+6. [Vocabulary Glossary](#6-vocabulary-glossary)++---++## 1. PBR Property Map++MeshPhysicalMaterial properties with Three.js bindings, value ranges, and performance cost.++### Core Properties++| Property | Type | Default | Range | Visual Effect | Perf Cost |+|----------|------|---------|-------|---------------|-----------|+| `color` | Color | `0xffffff` | — | Base surface color (Albedo) | Low |+| `metalness` | Float | `0.0` | 0.0–1.0 | 0=dielectric (plastic, wood), 1=metal | Low |+| `roughness` | Float | `1.0` | 0.0–1.0 | 0=mirror-smooth, 1=completely rough/matte | Low |+| `envMapIntensity` | Float | `1.0` | 0.0–∞ | Strength of environment map reflections | Low |+| `flatShading` | Boolean | `false` | — | Faceted vs smooth shading | Low |+| `side` | Enum | `FRONT` | — | FRONT, BACK, DOUBLE sided rendering | Low |++### Advanced Properties++| Property | Type | Default | Range | Visual Effect | Perf Cost |+|----------|------|---------|-------|---------------|-----------|+| `clearcoat` | Float | `0.0` | 0.0–1.0 | Extra glossy layer on top (car paint effect) | Medium |+| `clearcoatRoughness` | Float | `0.0` | 0.0–1.0 | Roughness of the clearcoat layer | Medium |+| `transmission` | Float | `0.0` | 0.0–1.0 | Physical light transmission (NOT opacity) | **Very High** |+| `thickness` | Float | `0.0` | 0.0–∞ | Thickness for transmission absorption | High |+| `ior` | Float | `1.5` | 1.0–2.33 | Index of Refraction — light bending angle | Medium |+| `sheen` | Float | `0.0` | 0.0–1.0 | Soft back-scatter (velvet/fabric effect) | Medium |+| `sheenRoughness` | Float | `0.0` | 0.0–1.0 | Roughness of sheen layer | Medium |+| `sheenColor` | Color | `0x000000` | — | Color tint of sheen effect | Medium |+| `iridescence` | Float | `0.0` | 0.0–1.0 | Thin-film interference (oil slick, soap bubble) | High |+| `iridescenceIOR` | Float | `1.3` | 1.0–3.0 | IOR of the iridescent layer | High |+| `iridescenceThicknessRange` | [min,max] | `[100,400]` | nm | Thickness range for iridescence | High |+| `anisotropy` | Float | `0.0` | 0.0–1.0 | Stretched highlights (brushed metal, CD) | High |+| `anisotropyRotation` | Float | `0.0` | 0–2π | Direction of anisotropic highlights (radians) | High |+| `attenuationColor` | Color | `0xffffff` | — | Color absorption in transmission | High |+| `attenuationDistance` | Float | `0.5` | 0.0–∞ | Distance for color absorption | High |++### Code: Property Reference++```typescript+// Basic PBR+const basic = new THREE.MeshPhysicalMaterial({+ color: 0xaaaaaa,+ metalness: 1.0,+ roughness: 0.05,+});++// Clearcoat (car paint, lacquered wood)+const clearcoat = new THREE.MeshPhysicalMaterial({+ color: 0x222222,+ metalness: 0.9,+ roughness: 0.3,+ clearcoat: 1.0,+ clearcoatRoughness: 0.1,+});++// Transmission (glass, crystal)+const glass = new THREE.MeshPhysicalMaterial({+ color: 0xffffff,+ metalness: 0.0,+ roughness: 0.0,+ transmission: 1.0,+ thickness: 0.5,+ ior: 1.5,+});++// Sheen (fabric, velvet)+const fabric = new THREE.MeshPhysicalMaterial({+ color: 0x334455,+ metalness: 0.0,+ roughness: 0.9,+ sheen: 1.0,+ sheenRoughness: 0.3,+ sheenColor: 0xffffff,+});++// Iridescence (patina, oil slick)+const iridescent = new THREE.MeshPhysicalMaterial({+ color: 0x445566,+ metalness: 1.0,+ roughness: 0.2,+ iridescence: 0.5,+ iridescenceIOR: 1.3,+ iridescenceThicknessRange: [100, 400],+});++// Anisotropy (brushed steel)+const brushed = new THREE.MeshPhysicalMaterial({+ color: 0x888888,+ metalness: 1.0,+ roughness: 0.3,+ anisotropy: 0.8,+ anisotropyRotation: Math.PI / 4,+});+```++---++## 2. Material Preset Recipes++Quick-copy recipes for common materials in CS2 items.++### Polished Metal (Chrome, New Steel)++```typescript+new THREE.MeshPhysicalMaterial({+ color: 0xaaaaaa,+ metalness: 1.0,+ roughness: 0.05,+ envMapIntensity: 1.5,+});+```++### Brushed Steel (Satin Finish)++```typescript+new THREE.MeshPhysicalMaterial({+ color: 0x888888,+ metalness: 1.0,+ roughness: 0.3,+ anisotropy: 0.8,+ anisotropyRotation: Math.PI / 4,+});+```++### Matte Plastic (G10 Handle, Polymer)++```typescript+new THREE.MeshPhysicalMaterial({+ color: 0x1a1a1a,+ metalness: 0.0,+ roughness: 0.75,+ ior: 1.45,+});+```++### Gunmetal (Dark Steel, Blued)++```typescript+new THREE.MeshPhysicalMaterial({+ color: 0x3a3a3a,+ metalness: 1.0,+ roughness: 0.45,+ envMapIntensity: 1.2,+});+```++### Glass (Scope Lens, Sight)++```typescript+new THREE.MeshPhysicalMaterial({+ color: 0xffffff,+ metalness: 0.0,+ roughness: 0.0,+ transmission: 1.0,+ thickness: 0.5,+ ior: 1.5,+});+```++### Wood (Rifle Stock, Handle Scale)++```typescript+new THREE.MeshPhysicalMaterial({+ color: 0x6f4e37,+ metalness: 0.0,+ roughness: 0.6,+ clearcoat: 0.2, // Light varnish+ clearcoatRoughness: 0.3,+});+```++### Fabric (Paracord, Lanyard, Grip Tape)++```typescript+new THREE.MeshPhysicalMaterial({+ color: 0x2d2d2d,+ metalness: 0.0,+ roughness: 0.9,+ sheen: 1.0,+ sheenRoughness: 0.3,+ sheenColor: 0xffffff,+});+```++### Rubber (Grip, Bumper)++```typescript+new THREE.MeshPhysicalMaterial({+ color: 0x111111,+ metalness: 0.0,+ roughness: 0.85,+ clearcoat: 0.1,+});+```++---++## 3. CS2 Finish Styles → PBR Profiles++How each CS2 finish style maps to Three.js material properties.++### Anodized++| Property | Value | Notes |+|----------|-------|-------|+| metalness | 1.0 | Full metallic |+| roughness | 0.05–0.15 | Very smooth, mirror-like |+| clearcoat | 0.3–0.5 | Protective glossy layer |+| iridescence | 0.0–0.2 | Slight color shift at angles |+| color | Tinted (varies) | Blue, gold, red, etc. |++**Wear behavior**: Color coating peels from edges, revealing base metal underneath.+**Examples**: Fade, Blue Steel, Case Hardened (anodized variant)++```typescript+// Anodized Blue+new THREE.MeshPhysicalMaterial({+ color: 0x2244aa,+ metalness: 1.0,+ roughness: 0.08,+ clearcoat: 0.4,+ clearcoatRoughness: 0.05,+});+```++### Anodized Multicolored++| Property | Value | Notes |+|----------|-------|-------|+| metalness | 1.0 | Full metallic |+| roughness | 0.05–0.10 | Ultra smooth |+| iridescence | 0.3–0.5 | Strong multi-color shift |+| iridescenceIOR | 1.5–2.0 | Higher IOR = more color |++**Wear behavior**: Gloss fades before base metal shows. Color gradient shifts with wear.+**Examples**: Fade (100%), Doppler (all phases)++```typescript+// Anodized Multicolored (Fade)+new THREE.MeshPhysicalMaterial({+ color: 0xff6600,+ metalness: 1.0,+ roughness: 0.05,+ iridescence: 0.4,+ iridescenceIOR: 1.8,+ iridescenceThicknessRange: [100, 500],+});+```++### Custom Paint Job++| Property | Value | Notes |+|----------|-------|-------|+| metalness | 0.0 | Non-metallic (painted over) |+| roughness | 0.3–0.5 | Semi-gloss paint |+| clearcoat | 0.2–0.4 | Protective clear coat |+| clearcoatRoughness | 0.1–0.2 | Smooth clear coat |++**Wear behavior**: Paint scratches from edges and high-friction areas, revealing metal.+**Examples**: Slaughter, Crimson Web, Asiimov, Hyper Beast++```typescript+// Custom Paint Job (Asiimov)+new THREE.MeshPhysicalMaterial({+ map: asiimovTexture, // Custom paint texture+ metalness: 0.0,+ roughness: 0.4,+ clearcoat: 0.3,+ clearcoatRoughness: 0.15,+});+```++### Gunsmith++| Property | Value | Notes |+|----------|-------|-------|+| metalness | 0.7–0.9 | Mostly metallic |+| roughness | 0.2–0.4 | Moderate roughness |+| clearcoat | 0.0–0.1 | Minimal clear coat |++**Wear behavior**: Combined paint fading + metal exposure. Chemical treatment look.+**Examples**: Night, Corticera, Guardian++```typescript+// Gunsmith+new THREE.MeshPhysicalMaterial({+ color: 0x333344,+ metalness: 0.8,+ roughness: 0.3,+ envMapIntensity: 1.0,+});+```++### Hydrographic++| Property | Value | Notes |+|----------|-------|-------|+| metalness | 0.0 | Non-metallic (film transfer) |+| roughness | 0.5–0.7 | Matte to semi-gloss |+| clearcoat | 0.1–0.2 | Light protective layer |++**Wear behavior**: Large patches peel off, exposing base material.+**Examples**: Boreal Forest, Safari Mesh, Arctic Wolf++```typescript+// Hydrographic (Boreal Forest)+new THREE.MeshPhysicalMaterial({+ map: borealTexture, // Camo pattern texture+ metalness: 0.0,+ roughness: 0.6,+ clearcoat: 0.15,+});+```++### Patina++| Property | Value | Notes |+|----------|-------|-------|+| metalness | 0.9–1.0 | Full metallic |+| roughness | 0.2–0.4 | Moderate |+| iridescence | 0.3–0.6 | Color-shifting oxidation |+| iridescenceIOR | 1.3–1.5 | Subtle color |++**Wear behavior**: Color changes (darkens/shifts) rather than peeling. Oxidation effect.+**Examples**: Case Hardened, Blue Steel, Damascus Steel++```typescript+// Patina (Case Hardened / Blue Gem)+new THREE.MeshPhysicalMaterial({+ color: 0x667788,+ metalness: 1.0,+ roughness: 0.25,+ iridescence: 0.5,+ iridescenceIOR: 1.4,+ envMapIntensity: 1.3,+});+```++### Solid Color++| Property | Value | Notes |+|----------|-------|-------|+| metalness | 0.0 | Non-metallic |+| roughness | 0.3–0.5 | Semi-gloss |+| clearcoat | 0.2–0.3 | Protective layer |++**Wear behavior**: Scratches reveal underlying metal at edges.+**Examples**: Urban Masked, Jungle Spray++```typescript+// Solid Color+new THREE.MeshPhysicalMaterial({+ color: 0x556633,+ metalness: 0.0,+ roughness: 0.4,+ clearcoat: 0.25,+});+```++### Sprayed++| Property | Value | Notes |+|----------|-------|-------|+| metalness | 0.0 | Non-metallic |+| roughness | 0.6–0.8 | Rough, uneven |+| clearcoat | 0.0 | No clear coat |++**Wear behavior**: Heavy scratching, base metal clearly visible at edges.+**Examples**: Scorched, Sand Dune, Dragon Lore (Spray variant)++```typescript+// Sprayed+new THREE.MeshPhysicalMaterial({+ map: sprayTexture,+ metalness: 0.0,+ roughness: 0.7,+ clearcoat: 0.0,+});+```++---++## 4. Wear System Bridge++How CS2 Float Value translates to Three.js shader parameters.++### Float Value → Visual Effect Mapping++| Wear Tier | Float Range | Visual Characteristics |+|-----------|-------------|----------------------|+| Factory New (FN) | 0.00–0.07 | Pristine. Almost no visible wear. |+| Minimal Wear (MW) | 0.07–0.15 | Minor scratches at edges. Very clean. |+| Field-Tested (FT) | 0.15–0.38 | Noticeable scratches, fading at edges. |+| Well-Worn (WW) | 0.38–0.45 | Significant wear, paint loss. |+| Battle-Scarred (BS) | 0.45–1.00 | Heavy damage, deep scratches, large blemishes. |++### Per-Skin Float Clipping++CS2 restricts float ranges per skin via `wear_remap_min` / `wear_remap_max` in `items_game.txt`:++```json+{+ "wear_remap_min": 0.00,+ "wear_remap_max": 0.80+}+```++This means a skin with `wear_remap_max: 0.80` can NEVER reach Battle-Scarred (0.45+).++### Three.js Wear Implementation++#### Approach 1: Texture Layer Blending (Recommended)++```typescript+// Wear as uniform parameter+const material = new THREE.ShaderMaterial({+ uniforms: {+ baseColorMap: { value: baseTexture },+ wearMap: { value: wearTexture },+ normalMap: { value: normalTexture },+ wearNormalMap: { value: wearNormalTexture },+ float: { value: 0.223 }, // The item's float value+ roughnessClean: { value: 0.3 },+ roughnessWorn: { value: 0.7 },+ },+ vertexShader: `...`,+ fragmentShader: `+ uniform sampler2D baseColorMap;+ uniform sampler2D wearMap;+ uniform float float;+ varying vec2 vUv;++ void main() {+ vec4 clean = texture2D(baseColorMap, vUv);+ vec4 worn = texture2D(wearMap, vUv);++ // Wear alpha: 0 at edges, 1 in center+ // Float value controls blend+ float wearAlpha = smoothstep(0.0, 0.5, float);++ vec4 color = mix(clean, worn, wearAlpha);+ gl_FragColor = color;+ }+ `,+});+```++#### Approach 2: Vertex-Based Wear Zones++```typescript+// Store wear sensitivity per vertex+const wearAttribute = new THREE.BufferAttribute(+ new Float32Array(vertexCount),+ 1+);++// 0.0 = protected (won't wear), 1.0 = high wear (edges, corners)+geometry.setAttribute('wearSensitivity', wearAttribute);++// In shader: multiply wear sensitivity with float value+```++#### Approach 3: Three.js Built-in Blending++```typescript+// For simple wear without custom shaders+const material = new THREE.MeshPhysicalMaterial({+ map: baseColorTexture,+ roughnessMap: wearRoughnessTexture, // Rougher where worn+ metalnessMap: wearMetalnessTexture, // More metallic where paint removed+ normalMap: combinedNormalTexture, // Scratch normals+ metalness: 0.0, // Base: non-metallic (painted)+ roughness: 0.4, // Base: semi-gloss+});+```++### Paint Channels (RGB Masks)++CS2 uses RGB channels to control different wear behaviors:++| Channel | Controls | Three.js Mapping |+|---------|----------|------------------|+| Red | Wear position (edges first) | Alpha mask for base→worn blend |+| Green | Roughness variation | RoughnessMap intensity |+| Blue | Color tint / pattern offset | Color modulation |++### Spatial Wear & Damage Glossary++#### 1. Core Industry Terms (Thuật Ngữ Cốt Lõi)++| EN Term | VI Term | Definition & 3D Application | Practical Example |+| :--- | :--- | :--- | :--- |+| **Surface Imperfections** | **Khuyết điểm bề mặt** | Microscopic surface variations that break up uniform specular reflections. Essential for photorealism. | Fingerprints on glass, dust layers on screens, micro-scratches on polished metal. |+| **Weathering / Aging** | **Phong hóa / Lão hóa** | Surface degradation caused by environmental exposure (rain, temperature, sunlight) over time. | Oxidation on metals (rust/patina), sun-fading on paint, moss growth on damp grips. |+| **Wear and Tear** | **Hao mòn sử dụng** | Physical damage from human handling or operational friction. | Blunted knife tips, hand-worn glossy grips, paint peeling on high-friction weapon parts. |+| **Edge Wear** | **Mòn cạnh viền** | Damage concentrated along the sharp boundaries, corners, or protrusions of a model. | Paint scraping off along the slide edges of a Glock or the guard corners of a Bowie knife. |+| **Procedural Grunge** | **Cáu bẩn thuật toán** | Procedurally generated grime or dirt, often mask-blended using Ambient Occlusion (AO) or curvature. | Dust settling in recessed grooves, gun grease building up in hard-to-clean weapon crevices. |++#### 2. Detailed Classification & PBR Map Impact++| Damage Type | Albedo (Color) Impact | Roughness Map Impact | Metalness Map Impact | Normal/Height Map Impact |+| :--- | :--- | :--- | :--- | :--- |+| **Oxidation / Rust / Patina** | Shifts to orange-brown (rust) or dark-green (patina). | Increases significantly (0.8 - 1.0) due to dry, rough microfacets. | Drops to 0.0 (conductive metal turns into non-conductive oxide). | Adds high-frequency noise, pitting, and scaling surface volume. |+| **Scratches / Dents** | Exposes base metal underneath (usually light grey/silver). | Decreases at scratch center (reveals shiny substrate); increases at scratch lip. | Increases to 1.0 at scratch center if painted coating is scraped off. | Creates sharp, linear indentations or local coordinate normals. |+| **Smudges / Fingerprints** | Negligible change. | Localized increases (0.4 - 0.6) where natural body oils distort reflections. | Unchanged. | Unchanged. |+| **Dust / Dirt / Mud** | Matches environmental soil colors (tan, brown, grey). | Becomes completely rough and diffuse (0.9 - 1.0). | Drops to 0.0 (non-metallic soil coating). | Smooths out micro-structures (dust) or adds thick volumes (caked mud). |++#### 3. Spatial Modifiers++| EN Term | VI Term | Definition |+| :--- | :--- | :--- |+| **Tip-to-spine gradient** | **Gradient từ mũi đến sống dao** | Damage concentration decreases gradually from the tip towards the mid-body. |+| **Edge-heavy wear** | **Mòn tập trung ở cạnh** | Scratches or paint loss occurring exclusively along high-exposure outer edges. |+| **Friction-point wear** | **Mòn điểm ma sát** | Concentrated wear at mechanical contact points (magazine slides, knife locks). |+| **Speckled / Spotted** | **Dạng đốm** | Scattered, point-like occurrences of rust or paint chipping. |+| **Exposed core** | **Lộ lõi** | Complete removal of an outer layer, showing the raw underlying material. |++#### 4. Technical Shader Representation (Three.js TSL)++To describe complex damage distributions (e.g. "Rust covering 50% from tip to spine"), use spatial coordinates and noise mixers in your shader logic:++```javascript+import { Fn, uv, smoothstep, mix, color, float, noise } from 'three/tsl';++const wearLogic = Fn(({ baseColor, rustColor, uvCoord, floatVal }) => {+ // 1. Gradient Mask: Rust 50% from tip (uv.y = 0.0) to spine (uv.y = 0.5)+ const gradientMask = smoothstep(float(0.0), float(0.5), uv().y);++ // 2. Add Stochastic Noise to prevent flat gradients+ const noiseMask = noise(uv().multiply(10.0));+ const finalMask = mix(gradientMask, noiseMask, float(0.2));++ // 3. Blend PBR parameters based on mask+ const finalAlbedo = mix(baseColor, rustColor, finalMask);+ const finalRoughness = mix(float(0.2), float(0.9), finalMask); // Polish to Rust+ const finalMetalness = mix(float(1.0), float(0.0), finalMask); // Metal to Oxide++ return { finalAlbedo, finalRoughness, finalMetalness };+});+```+++### CS2 → Three.js Wear Pipeline++```+Float Value (0.000-1.000)+ │+ ├─→ wear_remap_min/max (per-skin clamp)+ │ │+ │ └─→ Clamped float for this item+ │+ ├─→ RGB Wear Mask+ │ ├─→ Red: Base→Worn alpha blend+ │ ├─→ Green: Roughness modulation+ │ └─→ Blue: Color desaturation+ │+ └─→ Shader Uniforms+ ├─→ float: Wear amount (0-1)+ ├─→ roughnessClean: Starting roughness+ ├─→ roughnessWorn: Ending roughness+ └─→ metalnessWorn: Exposed metal metalness+```++---++## 5. Component Recipe Database++### Knife Components++#### Blade Types++| Type | Three.js Geometry | Proportions (W:L) | PBR (Metal/Rough) | Notes |+|------|-------------------|-------------------|-------------------|-------|+| Clip-point | `ExtrudeGeometry` | 1:3.5 | 1.0 / 0.15 | Notch cutout at tip |+| Drop-point | `ExtrudeGeometry` | 1:3 | 0.9 / 0.2 | Smooth spine curve |+| Tanto | `ExtrudeGeometry` | 1:3 | 1.0 / 0.1 | Angular chisel tip |+| Karambit | `ExtrudeGeometry` | 1:2 (curved) | 1.0 / 0.05 | Extreme curve |+| Falchion | `LatheGeometry` / `Extrude` | 1:4 | 1.0 / 0.15 | Wide, slightly curved |+| Gut Hook | `Extrude` + CSG `Subtract` | 1:2.5 | 1.0 / 0.3 | Hook via boolean |++#### Handle Construction++| Part | Geometry | PBR | Notes |+|------|----------|-----|-------|+| Tang Frame | `BoxGeometry` | Metal 1.0 / 0.4 | Structural core |+| Scales (×2) | `ExtrudeGeometry` | Non-metal 0.0 / 0.75 | G10, Micarta, Wood |+| Screws (×4) | `CylinderGeometry` | Metal 1.0 / 0.35 | Phillips head |+| Guard | `BoxGeometry` | Metal 1.0 / 0.3 | Cross guard or none |+| Pommel | `CylinderGeometry` | Metal 1.0 / 0.35 | End cap |+| Lanyard | `TorusGeometry` | Non-metal 0.0 / 0.9 | Paracord loop |++### Pistol Components++| Part | Geometry | Proportions | Boolean Ops |+|------|----------|-------------|-------------|+| Slide | `BoxGeometry` | 1:0.3:4 | Subtract: ejection port, rail |+| Frame | `ExtrudeGeometry` + `Box` | Complex | Union: grip; Subtract: mag well |+| Barrel | `CylinderGeometry` | r:0.05, L:5 | Subtract: inner bore |+| Trigger Guard | `ExtrudeGeometry` | Thin arc | Union: to frame |+| Magazine | `BoxGeometry` | 0.8:0.2:2.5 | Subtract: feed lips |+| Sights (×2) | `BoxGeometry` | Small | Union: to slide |+| Grip Texture | Normal map | — | NOT geometry |++### Rifle Components (AK-47, M4, AWP)++| Part | Geometry | Notes |+|------|----------|-------|+| Receiver (Upper) | `BoxGeometry` | Main body, rails on top |+| Receiver (Lower) | `BoxGeometry` | Trigger group, mag well |+| Barrel | `CylinderGeometry` | Long cylinder, fluting optional |+| Handguard | `BoxGeometry` / `CylinderGeometry` | Rail system, M-LOK slots |+| Stock | `BoxGeometry` | Fixed, folding, or collapsible |+| Magazine | `BoxGeometry` | Curved (AK) or straight (M4) |+| Pistol Grip | `ExtrudeGeometry` | Ergonomic profile |+| Scope (AWP) | `TubeGeometry` + `SphereGeometry` | Cylinder + lens halves |+| Muzzle Device | `CylinderGeometry` | Flash hider or suppressor |+| Bolt Carrier | `BoxGeometry` | Visible in ejection port |++### Boolean Operations Guide++| Operation | Library | Use Case |+|-----------|---------|----------|+| Subtract | `three-bvh-csg` | Holes, cutouts, slots, ejection ports |+| Union | `three-bvh-csg` | Merging components (frame + grip) |+| Intersect | `three-bvh-csg` | Complex shape intersections |++### Edge Treatment++| Zone | Treatment | How |+|------|-----------|-----|+| Cutting edge | Hard crease | `geometry.computeVertexNormals()` + manual normal adjustment |+| Spine-to-plate | Hard edge | Split vertices at seam |+| Sawback teeth | All hard | No smoothing groups |+| Guard corners | Hard | BoxGeometry naturally hard |+| Handle scales | Smooth | Subdivision or smooth normals |+| Grip checkering | Normal map | NOT geometry |++---++## 6. Vocabulary Glossary++See `3D_Vocabulary_CS2_Dictionary.md` for the full bilingual (EN/VI) glossary covering:++1. **Core 3D Modeling** — Vertex, Edge, Face, Mesh, Topology, Primitives+2. **UV Mapping & Texturing** — UV Coordinates, Texture Maps, Mipmapping+3. **PBR Materials** — PBR Workflow, Metalness, Roughness, Fresnel+4. **CS2 Specific** — Skin System, Wear System, Pattern System, Economy+5. **3D File Formats** — OBJ, FBX, glTF, MDL, VTF, VMT+6. **Animation & Rigging** — Skeleton, Bones, IK/FK, Morph Targets+7. **Rendering & Optimization** — Draw Calls, LOD, Batching+8. **Three.js / Web 3D** — Scene, Camera, Materials, Geometry+9. **CS2 Workshop** — Submission pipeline, QC requirements++---++## Sources++- Three.js MeshPhysicalMaterial documentation+- CS2 Workshop Tools (Valve Developer Community)+- CSFloat Blog: Float Values Technical Deep Dive+- Steam Community Workshop guides+- Three.js community discussions+- CS2 skin finish style documentation++---++*Generated via NotebookLM research — notebook ID: `30ec3dba-5a20-4980-8886-ce89b506b634`*diff --git a/docs/cs2/3D_Vocabulary_CS2.json b/docs/cs2/3D_Vocabulary_CS2.jsonnew file mode 100644index 0000000..a2b2cbd--- /dev/null+++ b/docs/cs2/3D_Vocabulary_CS2.json@@ -0,0 +1,170 @@+{+ "metadata": {+ "title": "3D Technical Vocabulary - CS2 Items Dictionary",+ "version": "1.0.0",+ "created": "2026-07-24",+ "sources": ["Valve Developer Community", "CS2 Workshop Docs", "Three.js Docs", "Blender Manual", "Meshy Docs"]+ },+ "categories": {+ "core_3d_modeling": {+ "name": "Core 3D Modeling",+ "terms": {+ "vertex": {"en": "Vertex", "vi": "Đỉnh", "def": "A point in 3D space with X, Y, Z coordinates"},+ "edge": {"en": "Edge", "vi": "Cạnh", "def": "A line connecting two vertices"},+ "face": {"en": "Face", "vi": "Mặt", "def": "A flat surface enclosed by 3+ edges"},+ "polygon": {"en": "Polygon", "vi": "Đa giác", "def": "Generic term for a face (triangles, quads)"},+ "triangle": {"en": "Triangle (Tris)", "vi": "Tam giác", "def": "A 3-sided polygon"},+ "quad": {"en": "Quad", "vi": "Tứ giác", "def": "A 4-sided polygon, preferred for clean topology"},+ "n_gon": {"en": "N-gon", "vi": "N-cạnh", "def": "Polygon with 5+ sides, generally avoided"},+ "mesh": {"en": "Mesh", "vi": "Lưới", "def": "Complete geometric structure of a 3D object"},+ "topology": {"en": "Topology", "vi": "Cấu trúc", "def": "Arrangement and flow of polygons on mesh surface"},+ "edge_loop": {"en": "Edge Loop", "vi": "Vòng cạnh", "def": "Continuous ring of edges flowing around mesh"},+ "retopology": {"en": "Retopology", "vi": "Tái cấu trúc", "def": "Redrawing mesh with cleaner topology"},+ "high_poly": {"en": "High-Poly", "vi": "Đa giác cao", "def": "Mesh with many polygons for detail"},+ "low_poly": {"en": "Low-Poly", "vi": "Đa giác thấp", "def": "Mesh with few polygons, optimized for real-time"},+ "buffer_geometry": {"en": "BufferGeometry", "vi": "BufferGeometry", "def": "Three.js class for custom geometry"}+ }+ },+ "uv_mapping": {+ "name": "UV Mapping & Texturing",+ "terms": {+ "uv_mapping": {"en": "UV Mapping", "vi": "Ánh xạ UV", "def": "Unwrapping 3D surface onto 2D plane for textures"},+ "uv_coordinates": {"en": "UV Coordinates", "vi": "Tọa độ UV", "def": "2D coordinates mapping texture to surface"},+ "uv_seam": {"en": "UV Seam", "vi": "Đường may UV", "def": "Edges where UV map is cut for flattening"},+ "diffuse_map": {"en": "Diffuse/Albedo Map", "vi": "Bản đồ màu", "def": "Base color texture without lighting"},+ "normal_map": {"en": "Normal Map", "vi": "Bản đồ Normal", "def": "RGB texture simulating surface bumps"},+ "roughness_map": {"en": "Roughness Map", "vi": "Bản đồ thô", "def": "Controls surface smoothness (0=smooth, 1=rough)"},+ "metallic_map": {"en": "Metallic Map", "vi": "Bản đồ kim loại", "def": "Defines metallic vs non-metallic areas"},+ "ao_map": {"en": "Ambient Occlusion", "vi": "Che sáng môi trường", "def": "Shows areas where ambient light is blocked"},+ "displacement_map": {"en": "Displacement Map", "vi": "Bản đồ dịch chuyển", "def": "Actually moves vertices for real detail"},+ "emission_map": {"en": "Emission Map", "vi": "Bản đồ phát sáng", "def": "Defines which parts emit light"},+ "mipmapping": {"en": "Mipmapping", "vi": "Mipmap", "def": "Pre-calculated lower-res texture copies"}+ }+ },+ "pbr_materials": {+ "name": "PBR Materials",+ "terms": {+ "pbr": {"en": "PBR (Physically Based Rendering)", "vi": "Render dựa trên vật lý", "def": "Rendering simulating real-world light interaction"},+ "metallic_roughness": {"en": "Metallic/Roughness Workflow", "vi": "Quy trình Kim loại/Thô", "def": "PBR workflow using Base Color + Metallic + Roughness"},+ "specular_glossiness": {"en": "Specular/Glossiness Workflow", "vi": "Quy trình Phản chiếu/Bóng", "def": "Alternative PBR workflow"},+ "base_color": {"en": "Base Color", "vi": "Màu cơ bản", "def": "Fundamental surface color without lighting"},+ "metalness": {"en": "Metalness", "vi": "Độ kim loại", "def": "0=dielectric, 1=metal"},+ "roughness": {"en": "Roughness", "vi": "Độ thô", "def": "0=mirror-smooth, 1=completely rough"},+ "fresnel": {"en": "Fresnel", "vi": "Fresnel", "def": "Reflectivity increases at grazing angles"},+ "energy_conservation": {"en": "Energy Conservation", "vi": "Bảo toàn năng lượng", "def": "Reflected light cannot exceed incoming light"}+ }+ },+ "cs2_specific": {+ "name": "CS2 Specific Terminology",+ "terms": {+ "skin": {"en": "Skin", "vi": "Da súng", "def": "Cosmetic finish changing weapon appearance"},+ "paint_kit": {"en": "Paint Kit", "vi": "Bộ sơn", "def": "Complete texture set defining skin appearance"},+ "float_value": {"en": "Float Value", "vi": "Giá trị float", "def": "Decimal 0.000-1.000 determining wear"},+ "factory_new": {"en": "Factory New (FN)", "vi": "Mới từ nhà máy", "def": "Float 0.00-0.07, pristine condition"},+ "minimal_wear": {"en": "Minimal Wear (MW)", "vi": "Mòn tối thiểu", "def": "Float 0.07-0.15, minor scratches"},+ "field_tested": {"en": "Field-Tested (FT)", "vi": "Đã thử nghiệm", "def": "Float 0.15-0.38, noticeable wear"},+ "well_worn": {"en": "Well-Worn (WW)", "vi": "Mòn nhiều", "def": "Float 0.38-0.45, significant wear"},+ "battle_scarred": {"en": "Battle-Scarred (BS)", "vi": "Chiến tích", "def": "Float 0.45-1.00, heavy damage"},+ "pattern_index": {"en": "Pattern Index", "vi": "Chỉ mẫu", "def": "Integer 0-1000 controlling texture slice"},+ "blue_gem": {"en": "Blue Gem", "vi": "Đá xanh", "def": "Rare Case Hardened pattern, mostly blue"},+ "fade_percentage": {"en": "Fade Percentage", "vi": "Phần trăm Fade", "def": "Color gradient visibility on Fade skins"},+ "doppler_phase": {"en": "Doppler Phase", "vi": "Giai đoạn Doppler", "def": "Color variations in Doppler skins"},+ "stattrak": {"en": "StatTrak™", "vi": "StatTrak™", "def": "Kill counter variant, ~10% drop rate"},+ "souvenir": {"en": "Souvenir", "vi": "Hàng lưu niệm", "def": "Major tournament exclusive with stickers"},+ "sticker": {"en": "Sticker", "vi": "Tem", "def": "Cosmetic item applied to weapons"},+ "sticker_craft": {"en": "Sticker Craft", "vi": "Bộ tem", "def": "Combination of skin with applied stickers"},+ "wear_remap": {"en": "Float Clipping", "vi": "Cắt float", "def": "Per-skin float range restriction"}+ }+ },+ "file_formats": {+ "name": "3D File Formats",+ "terms": {+ "obj": {"en": "OBJ", "vi": "OBJ", "def": "Simple text format for geometry, no animation"},+ "fbx": {"en": "FBX", "vi": "FBX", "def": "Autodesk format, primary game engine exchange"},+ "gltf_glb": {"en": "glTF/GLB", "vi": "glTF/GLB", "def": "Open web standard, GLB is binary version"},+ "stl": {"en": "STL", "vi": "STL", "def": "Geometry-only, standard for 3D printing"},+ "mdl": {"en": "MDL", "vi": "MDL", "def": "Valve's model format for Source engine"},+ "vtf": {"en": "VTF", "vi": "VTF", "def": "Valve Texture Format"},+ "vmt": {"en": "VMT", "vi": "VMT", "def": "Valve Material Type definition"},+ "items_game": {"en": "items_game.txt", "vi": "items_game.txt", "def": "CS2 config defining all item properties"}+ }+ },+ "animation_rigging": {+ "name": "Animation & Rigging",+ "terms": {+ "skeleton": {"en": "Skeleton", "vi": "Bộ xương", "def": "Hierarchical bone structure for deformation"},+ "bone": {"en": "Bone", "vi": "Xương", "def": "Individual element in skeleton hierarchy"},+ "rigging": {"en": "Rigging", "vi": "Cấp xương", "def": "Creating and binding skeleton to mesh"},+ "weight_painting": {"en": "Weight Painting", "vi": "Vẽ trọng số", "def": "Defining bone influence on vertices"},+ "keyframe": {"en": "Keyframe Animation", "vi": "Hoạt hình khoá khung", "def": "Animation defined by specific poses at times"},+ "ik": {"en": "Inverse Kinematics (IK)", "vi": "Động học nghịch đảo", "def": "Calculate joints from end position"},+ "fk": {"en": "Forward Kinematics (FK)", "vi": "Động học thuận", "def": "Set rotations from root to tip"},+ "morph_targets": {"en": "Morph Targets", "vi": "Mục tiêu biến đổi", "def": "Pre-defined vertex positions for blending"},+ "skinned_mesh": {"en": "SkinnedMesh", "vi": "SkinnedMesh", "def": "Three.js mesh deformable by skeleton"}+ }+ },+ "rendering_optimization": {+ "name": "Rendering & Optimization",+ "terms": {+ "draw_call": {"en": "Draw Call", "vi": "Lệnh vẽ", "def": "Single CPU→GPU command to render"},+ "batching": {"en": "Batching", "vi": "Gộp", "def": "Combining objects into fewer draw calls"},+ "instancing": {"en": "Instancing", "vi": "Thực thể hóa", "def": "Rendering many copies with one draw call"},+ "lod": {"en": "Level of Detail (LOD)", "vi": "Chi tiết cấp độ", "def": "Lower-poly models at distance"},+ "polygon_budget": {"en": "Polygon Budget", "vi": "Ngân sách đa giác", "def": "Max polygons allowed for object/scene"},+ "occlusion_culling": {"en": "Occlusion Culling", "vi": "Loại trừ che khuất", "def": "Not rendering hidden objects"},+ "frustum_culling": {"en": "Frustum Culling", "vi": "Loại trừ ngoài khung hình", "def": "Not rendering objects outside view"}+ }+ },+ "threejs_web3d": {+ "name": "Three.js / Web 3D",+ "terms": {+ "webgl": {"en": "WebGL", "vi": "WebGL", "def": "JavaScript API for hardware-accelerated 3D"},+ "scene": {"en": "Scene", "vi": "Cảnh", "def": "Container for all 3D objects"},+ "camera": {"en": "Camera", "vi": "Máy ảnh", "def": "Defines the viewpoint"},+ "renderer": {"en": "Renderer", "vi": "Bộ kết xuất", "def": "Converts scene to pixels"},+ "mesh_standard": {"en": "MeshStandardMaterial", "vi": "MeshStandardMaterial", "def": "PBR material, most realistic"},+ "mesh_phong": {"en": "MeshPhongMaterial", "vi": "MeshPhongMaterial", "def": "Simpler, faster for mobile"},+ "gltf_loader": {"en": "GLTFLoader", "vi": "GLTFLoader", "def": "Loads glTF/GLB files"},+ "instanced_mesh": {"en": "InstancedMesh", "vi": "InstancedMesh", "def": "Many copies with one draw call"}+ }+ },+ "cs2_workshop": {+ "name": "CS2 Workshop Workflow",+ "terms": {+ "workshop_submission": {"en": "Workshop Submission", "vi": "Gửi lên Workshop", "def": "Submitting custom skins to CS2"},+ "substance_painter": {"en": "Substance Painter", "vi": "Substance Painter", "def": "Industry-standard texture painting tool"},+ "source_2": {"en": "Source 2", "vi": "Source 2", "def": "Valve's game engine for CS2"},+ "tri_count": {"en": "Tri Count", "vi": "Số tam giác", "def": "Total triangle count of weapon model"},+ "paint_pattern": {"en": "Paint Pattern", "vi": "Mẫu sơn", "def": "2D texture projected onto 3D via UV"},+ "wear_overlay": {"en": "Wear Overlay", "vi": "Lớp phủ mòn", "def": "Texture adding damage based on float"},+ "material_proxy": {"en": "Material Proxy", "vi": "Proxy vật liệu", "def": "Dynamic parameter changes based on state"}+ }+ }+ },+ "cs2_wear_ranges": {+ "factory_new": {"min": 0.00, "max": 0.07, "abbreviation": "FN", "vi": "Mới từ nhà máy"},+ "minimal_wear": {"min": 0.07, "max": 0.15, "abbreviation": "MW", "vi": "Mòn tối thiểu"},+ "field_tested": {"min": 0.15, "max": 0.38, "abbreviation": "FT", "vi": "Đã thử nghiệm"},+ "well_worn": {"min": 0.38, "max": 0.45, "abbreviation": "WW", "vi": "Mòn nhiều"},+ "battle_scarred": {"min": 0.45, "max": 1.00, "abbreviation": "BS", "vi": "Chiến tích"}+ },+ "cs2_rarity_grades": [+ {"grade": "Consumer Grade", "vi": "Hàng tiêu dùng", "color": "white"},+ {"grade": "Industrial Grade", "vi": "Hàng công nghiệp", "color": "light blue"},+ {"grade": "Mil-Spec", "vi": "Mil-Spec", "color": "blue"},+ {"grade": "Restricted", "vi": "Hạn chế", "color": "purple"},+ {"grade": "Classified", "vi": "Phân loại", "color": "pink"},+ {"grade": "Covert", "vi": "Bí mật", "color": "red"},+ {"grade": "Contraband", "vi": "Hàng cấm", "color": "gold"}+ ],+ "cs2_finish_styles": [+ "Anodized",+ "Anodized Multicolored",+ "Custom Paint Job",+ "Gunsmith",+ "Hydrographic",+ "Patina",+ "Solid Color",+ "Sprayed"+ ]+}diff --git a/docs/cs2/3D_Vocabulary_CS2_Dictionary.md b/docs/cs2/3D_Vocabulary_CS2_Dictionary.mdnew file mode 100644index 0000000..b5770f5--- /dev/null+++ b/docs/cs2/3D_Vocabulary_CS2_Dictionary.md@@ -0,0 +1,438 @@+# 3D Technical Vocabulary Dictionary - CS2 Items Focus+# Từ điển Thuật ngữ Kỹ thuật 3D - Tập trung vào CS2 Items++---++## Table of Contents / Mục lục+1. [Core 3D Modeling](#1-core-3d-modeling)+2. [UV Mapping & Texturing](#2-uv-mapping--texturing)+3. [PBR Materials](#3-pbr-materials)+4. [CS2 Specific Terminology](#4-cs2-specific-terminology)+5. [3D File Formats](#5-3d-file-formats)+6. [Animation & Rigging](#6-animation--rigging)+7. [Rendering & Optimization](#7-rendering--optimization)+8. [Three.js / Web 3D](#8-threejs--web-3d)+9. [CS2 Workshop Workflow](#9-cs2-workshop-workflow)++---++## 1. Core 3D Modeling++### Geometry & Mesh++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **Vertex (Vertices)** | Đỉnh | A point in 3D space with X, Y, Z coordinates. The fundamental building block of all 3D geometry. |+| **Edge** | Cạnh | A line connecting two vertices. Defines the boundaries of faces. |+| **Face** | Mặt | A flat surface enclosed by 3 or more edges. Can be triangles, quads, or n-gons. |+| **Polygon** | Đa giác | Generic term for a face. Usually refers to triangles (tris) or quads in modeling. |+| **Triangle (Tris)** | Tam giác | A 3-sided polygon. GPU renders everything as triangles ultimately. |+| **Quad** | Tứ giác | A 4-sided polygon. Preferred for clean topology and subdivision. |+| **N-gon** | N-cạnh | A polygon with 5+ sides. Generally avoided in animation meshes. |+| **Mesh** | Lưới | The complete geometric structure of a 3D object, consisting of vertices, edges, and faces. |+| **Geometry** | Hình học | The mathematical representation of shape and form in 3D space. |+| **Wireframe** | Khung dây | Display mode showing only edges and vertices without filled faces. |++### Topology & Structure++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **Topology** | Cấu trúc | The arrangement and flow of polygons on a mesh surface. Clean topology = even quads following surface contours. |+| **Edge Loop** | Vòng cạnh | A continuous ring of edges that flows around a mesh. Critical for deformation and animation. |+| **Edge Flow** | Dòng cạnh | The directional pattern of edges across a surface. Guides how mesh deforms. |+| **Retopology** | Tái cấu trúc | Redrawing a mesh with cleaner, lower-poly topology. Often done on sculpted high-poly models. |+| **Subdivision Surface** | Mặt phụ division | Algorithm that smooths a mesh by recursively subdividing faces. Used to create smooth surfaces from low-poly control cages. |+| **High-Poly** | Đa giác cao | A mesh with many polygons, used for detail sculpting or baking. |+| **Low-Poly** | Đa giác thấp | A mesh with few polygons, optimized for real-time rendering. |+| **Base Mesh** | Mesh cơ bản | Low-resolution starting mesh for sculpting or modeling. |+| **NURBS** | NURBS | Non-Uniform Rational B-Splines. Mathematical surface representation used in CAD/product design for smooth curves. |+| **Watertight Mesh** | Mesh kín | A closed mesh with no holes. Required for 3D printing and some physics simulations. |++### Primitives++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **Primitive** | Khối cơ bản | Basic geometric shapes: Cube, Sphere, Cylinder, Cone, Plane, Torus. Starting points for modeling. |+| **BufferGeometry** | BufferGeometry | Three.js class for defining custom geometry with vertex attributes (positions, normals, UVs). |++---++## 2. UV Mapping & Texturing++### UV Concepts++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **UV Mapping** | Ánh xạ UV | The process of unwrapping a 3D surface onto a 2D plane for texture application. |+| **UV Coordinates** | Tọa độ UV | 2D coordinates (U horizontal, V vertical) that map texture pixels to 3D surface points. |+| **UV Unwrap** | Mở phẳng UV | The act of flattening a 3D mesh surface into 2D space. |+| **UV Seam** | Đường may UV | Edges where the UV map is cut to allow flattening. Visible as texture seams if not placed carefully. |+| **UV Layout** | Bố cục UV | The arrangement of UV islands in texture space. |+| **Texel Density** | Mật độ texel | The amount of texture resolution per unit of 3D surface area. |++### Texture Maps++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **Diffuse/Albedo Map** | Bản đồ màu cơ sở | Base color texture without lighting information. The "paint" of the surface. |+| **Normal Map** | Bản đồ normal | RGB texture that simulates surface bumps by altering surface normals. Adds detail without geometry. |+| **Bump Map** | Bản đồ gồ ghề | Grayscale texture that simulates height variation. Less precise than normal maps. |+| **Displacement Map** | Bản đồ dịch chuyển | Grayscale texture that actually moves vertices to create real geometry detail. |+| **Specular Map** | Bản đồ phản chiếu | Defines intensity and color of specular highlights on a surface. |+| **Roughness Map** | Bản đồ thô | Grayscale map controlling surface smoothness. Black = smooth/glossy, White = rough/matte. |+| **Metallic Map** | Bản đồ kim loại | Defines which parts are metallic (white) vs dielectric/non-metallic (black). |+| **Ambient Occlusion (AO)** | Che sáng môi trường | Grayscale map showing areas where ambient light is blocked by geometry. Adds depth. |+| **Emission Map** | Bản đồ phát sáng | Texture defining which parts of a surface emit light/glow. |+| **Opacity/Alpha Map** | Bản đồ trong suốt | Grayscale map controlling transparency. White = opaque, Black = transparent. |+| **Height Map** | Bản đồ chiều cao | Grayscale map representing surface elevation for displacement. |+| **Cavity Map** | Bản đồ hang | Highlights small surface crevices and edges for added detail. |++### Texture Settings++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **Texture Resolution** | Độ phân giải texture | Pixel dimensions of a texture (e.g., 1024x1024, 2048x2048). Usually power-of-two. |+| **Power-of-Two** | Lũy thừa của 2 | Texture dimensions that are powers of 2 (256, 512, 1024, 2048, 4096). Required for mipmapping. |+| **Mipmapping** | Mipmap | Pre-calculated lower-resolution copies of a texture. Improves quality and performance at distance. |+| **Texture Filtering** | Lọc texture | How textures are sampled: Nearest (pixelated), Bilinear, Trilinear, Anisotropic. |+| **Tiling** | Lặp | Repeating a texture across a surface. |+| **Texture Atlas** | Bảng texture | Combining multiple textures into one image for efficiency. |++---++## 3. PBR Materials++### PBR Workflows++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **PBR (Physically Based Rendering)** | Render dựa trên vật lý | Rendering approach that simulates real-world light interaction for realistic materials. |+| **Metallic/Roughness Workflow** | Quy trình Kim loại/Thô | PBR workflow using Base Color + Metallic + Roughness maps. Most common in games. |+| **Specular/Glossiness Workflow** | Quy trình Phản chiếu/Bóng | PBR workflow using Diffuse + Specular + Glossiness maps. Alternative to Metallic/Roughness. |+| **Base Color** | Màu cơ bản | The fundamental color of a surface without lighting effects. |+| **Metalness** | Độ kim loại | 0-1 value: 0 = dielectric (plastic, wood), 1 = metal (gold, iron). |+| **Roughness** | Độ thô | 0-1 value: 0 = mirror-smooth, 1 = completely rough/matte. |+| **Fresnel** | Fresnel | Effect where reflectivity increases at grazing angles. Essential for realistic materials. |+| **Microfacet** | Vi mặt | Tiny surface irregularities that determine roughness and reflection behavior. |+| **Energy Conservation** | Bảo toàn năng lượng | Principle that reflected light cannot exceed incoming light. Core PBR concept. |++### PBR in Games++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **Material** | Vật liệu | A set of texture maps and parameters defining how a surface looks and responds to light. |+| **Shader** | Trình xử lýshader | Program that runs on GPU to calculate final pixel color based on material properties. |+| **Albedo** | Albedo | Base color without any lighting contribution. The pure "color" of the surface. |+| **Dielectric** | Chất điện môi | Non-metallic material. Has specular reflections but no colored reflections. |++---++## 4. CS2 Specific Terminology++### Skin System++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **Skin** | Da súng / Skin | A cosmetic finish applied to a weapon, changing its appearance without affecting gameplay. |+| **Paint Kit** | Bộ sơn | The complete texture set defining a skin's visual appearance. Contains multiple texture layers. |+| **Finish** | Hoàn thiện / Finish | The final visual style of a skin (e.g., Anodized, Gunsmith, Hydrographic). |+| **Finish Style** | Kiểu finish | Categories of paint application: Anodized, Anodized Multicolored, Custom Paint Job, Gunsmith, Hydrographic, Patina, Solid Color, Sprayed. |++### Wear System++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **Float Value** | Giá trị float | A 32-bit decimal (0.000-1.000) assigned at drop time. Determines wear appearance. Lower = cleaner. |+| **Wear Rating** | Đánh giá mòn | The visible condition category based on float ranges. |+| **Factory New (FN)** | Mới từ nhà máy | Float 0.00-0.07. Pristine condition with almost no visible wear. |+| **Minimal Wear (MW)** | Mòn tối thiểu | Float 0.07-0.15. Minor scratches, very clean appearance. |+| **Field-Tested (FT)** | Đã thử nghiệm | Float 0.15-0.38. Noticeable scratches and blemishes. Mid-range condition. |+| **Well-Worn (WW)** | Mòn nhiều | Float 0.38-0.45. Significant wear, fading, scratches. |+| **Battle-Scarred (BS)** | Chiến tích | Float 0.45-1.00. Heavy damage, deep scratches, large blemishes. |+| **Float Clipping** | Cắt float | Per-skin restriction on which float values are possible. Defined by wear_remap_min/max in items_game.txt. |++### Pattern System++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **Pattern Index (Paint Seed)** | Chỉ mẫu (Màu sơn) | Integer (0-1000) assigned at drop. Controls which slice of texture atlas is visible. |+| **Pattern Seed** | Hạt giống mẫu | Same as Pattern Index. Determines texture placement variation. |+| **Template ID** | ID mẫu | Identifier for specific pattern variations in certain finishes. |+| **Blue Gem** | Đá xanh | Rare Case Hardened pattern with predominantly blue color on playside. Extremely valuable. |+| **Fade Percentage** | Phần trăm Fade | Percentage of color gradient visible on Fade skins. Higher % = more colors = more valuable. |+| **Doppler Phase** | Giai đoạn Doppler | Different color variations in Doppler skins (Phase 1-4, Ruby, Sapphire, Black Pearl, etc.). |+| **Playside** | Mặt nhìn | The side of the weapon visible to the player in first-person view. Most important for value. |+| **Backside** | Mặt sau | The opposite side of the weapon from playside. |++### Special Items++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **StatTrak™** | StatTrak™ | Special variant with kill counter. Drops at ~10% rate. Premium 20-100% over normal. |+| **Souvenir** | Hàng lưu niệm | Exclusive drops from Major tournaments with pre-applied tournament stickers. Supply permanently capped. |+| **Sticker** | Tem / Sticker | Cosmetic item applied to weapons. Types: Paper, Holo, Foil, Gold. |+| **Sticker Craft** | Bộ tem | The combination of a skin with applied stickers. Position and condition matter for value. |+| **Sticker Slot** | Khe tem | Fixed positions on weapons where stickers can be applied (typically 4 slots). |+| **Scrape Level** | Mức cào | Sticker degradation: 100% → 75% → 50% → 25%. Affects value significantly. |+| **Name Tag** | Thẻ tên | Item that lets you rename a weapon. Cosmetic only. |+| **Charm** | Charms | Decorative items that hang from weapons. |+| **Collection** | Bộ sưu tập | Groups of skins that drop together. Some collections are discontinued, increasing rarity. |++### CS2 Economy Terms++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **Market Hash Name** | Tên hash thị trường | Exact name Steam uses for listing (e.g., "StatTrak™ AK-47 | Redline (Field-Tested)"). |+| **Paint Index** | Chỉ số sơn | Numeric ID for a specific finish + variant (e.g., 415 = Doppler Ruby). |+| **Rarity Grade** | Phân loại hiếm | Item rarity: Consumer Grade → Industrial Grade → Mil-Spec → Restricted → Classified → Covert → Contraband. |+| **Exterior** | Ngoại quan | The wear tier label shown in inventory (FN, MW, FT, WW, BS). |+| **Inspect Link** | Liên kết kiểm tra | Steam URL that reveals float, pattern, and sticker details for an item. |+| **Game Coordinator (GC)** | Điều phối trò chơi | CS2's internal item server that provides item data to trading sites. |+| **Trade-Up Contract** | Hợp đồng nâng cấp | Combining 10 items of same rarity to receive 1 item of next higher rarity. Float is averaged. |++---++## 5. 3D File Formats++### Exchange Formats++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **OBJ** | OBJ | Wavefront OBJ. Simple text-based format for geometry + normals + UVs. No animation. |+| **FBX** | FBX | Autodesk Filmbox. Primary exchange format for game engines. Supports geometry, animation, materials. |+| **glTF/GLB** | glTF/GLB | Graphics Language Transmission Format. Open standard for 3D on web. GLB = binary version. |+| **STL** | STL | Stereolithography. Geometry-only format. Standard for 3D printing. |+| **PLY** | PLY | Stanford Polygon File Format. Often used for scanned point cloud data. |+| **USDZ** | USDZ | Apple's AR format for Quick Look and Reality Composer. |++### Game-Specific Formats++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **MDL** | MDL | Valve's model format for Source/Source 2 engine. |+| **VTF** | VTF | Valve Texture Format. Native texture format for Source engine. |+| **VMT** | VMT | Valve Material Type. Defines material properties in Source engine. |+| **VMF** | VMF | Valve Map Format. Source engine map editor format. |+| ** items_game.txt** | items_game.txt | CS2 configuration file defining all item properties, paint kits, wear ranges. |++### Format Comparison++| Format | Geometry | Animation | Materials | Web | Games | 3D Print |+|--------|----------|-----------|-----------|-----|-------|----------|+| OBJ | ✅ | ❌ | Limited | ✅ | ⚠️ | ✅ |+| FBX | ✅ | ✅ | ✅ | ⚠️ | ✅ | ❌ |+| glTF/GLB | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |+| STL | ✅ | ❌ | ❌ | ⚠️ | ❌ | ✅ |+| MDL | ✅ | ✅ | ✅ | ❌ | ✅ (Source) | ❌ |++---++## 6. Animation & Rigging++### Skeletal Animation++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **Skeleton** | Bộ xương | Hierarchical structure of bones that deforms a mesh. |+| **Bone** | Xương | Individual element in a skeleton hierarchy. Has position, rotation, and parent-child relationships. |+| **Joint** | Khớp | Connection point between bones. Defines pivot points for rotation. |+| **Rigging** | Rigging / Cấp xương | The process of creating and binding a skeleton to a mesh for animation. |+| **Weight Painting** | Vẽ trọng số | Defining how much each bone influences surrounding vertices. Controls deformation quality. |+| **Skinning** | Phủ da | Binding mesh vertices to skeleton bones with weighted influences. |++### Animation Types++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **Keyframe Animation** | Hoạt hình khoá khung | Animation defined by specific poses at specific times, interpolated in between. |+| **Procedural Animation** | Hoạt hình theo thủ tục | Animation generated by code/algorithms rather than manual keyframes. |+| **Motion Capture (Mocap)** | Bắt chuyển động | Recording real-world movement to drive digital skeleton. |+| **Inverse Kinematics (IK)** | Động học nghịch đảo | Calculating joint rotations from end-effector position. Used for feet/ground contact. |+| **Forward Kinematics (FK)** | Động học thuận | Setting joint rotations from root to tip. Standard bone manipulation. |+| **Blend Shapes / Morph Targets** | Hình dạng lai / Mục tiêu biến đổi | Pre-defined vertex positions that can be blended between. Used for facial expressions, damage states. |++### Three.js Animation++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **AnimationClip** | AnimationClip | A reusable animation containing keyframe tracks for multiple properties. |+| **AnimationMixer** | AnimationMixer | Controls playback and blending of AnimationClips on a model. |+| **SkinnedMesh** | SkinnedMesh | Three.js mesh that can be deformed by a skeleton. |++---++## 7. Rendering & Optimization++### Rendering Concepts++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **Draw Call** | Lệnh vẽ | A single command from CPU to GPU to render something. Too many draw calls = performance hit. |+| **Batching** | Gộp | Combining multiple objects into fewer draw calls for efficiency. |+| **Instancing** | Thực thể hóa | Rendering many copies of same mesh with one draw call. Each instance can have unique transforms/colors. |+| **GPU** | GPU | Graphics Processing Unit. Hardware that executes rendering calculations in parallel. |+| **Shader** | Shader | Program that runs on GPU to calculate vertex positions and pixel colors. |+| **Vertex Shader** | Vertex Shader | Runs per-vertex. Transforms positions from model space to screen space. |+| **Fragment/Pixel Shader** | Fragment/Pixel Shader | Runs per-pixel. Calculates final color based on materials, lights, textures. |+| **Render Pipeline** | Pipeline render | The sequence of steps from 3D scene to 2D screen output. |++### Optimization++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **LOD (Level of Detail)** | Chi tiết cấp độ | Using lower-poly models at distance. Reduces GPU load without visible quality loss. |+| **Polygon Budget** | Ngân sách đa giác | Maximum number of polygons allowed for an object/scene. |+| **Occlusion Culling** | Loại trừ che khuất | Not rendering objects hidden behind other objects. |+| **Frustum Culling** | Loại trừ ngoài khung hình | Not rendering objects outside camera's view frustum. |+| **Draw Call Batching** | Gộp lệnh vẽ | Merging static objects into fewer draw calls. |+| **Texture Atlasing** | Đóng gói texture atlas | Combining textures to reduce material switches and draw calls. |++---++## 8. Three.js / Web 3D++### Core Concepts++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **WebGL** | WebGL | Web Graphics Library. JavaScript API for hardware-accelerated 3D rendering in browsers. |+| **Scene** | Cảnh | Container for all 3D objects, lights, and cameras in Three.js. |+| **Camera** | Máy ảnh | Defines the viewpoint. Types: PerspectiveCamera (realistic), OrthographicCamera (2D-style). |+| **Renderer** | Bộ kết xuất | Converts Three.js scene to pixels on screen. WebGLRenderer is most common. |+| **Mesh** | Mesh | A 3D object combining geometry (shape) and material (appearance). |+| **Group** | Nhóm | Container for organizing multiple meshes/objects with shared transforms. |+| **Light** | Ánh sáng | Illumination sources. Types: AmbientLight, DirectionalLight, PointLight, SpotLight. |++### Three.js Materials++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **MeshStandardMaterial** | MeshStandardMaterial | PBR material using Metallic/Roughness workflow. Most realistic. |+| **MeshPhongMaterial** | MeshPhongMaterial | Simpler, faster material. Good for mobile/low-end devices. |+| **MeshBasicMaterial** | MeshBasicMaterial | Unlit material. No light interaction. Fastest rendering. |+| **ShaderMaterial** | ShaderMaterial | Custom material using GLSL vertex/fragment shaders. Full control. |+| **RawShaderMaterial** | RawShaderMaterial | ShaderMaterial with no built-in uniforms/attributes. Complete shader authoring. |+| **MeshLambertMaterial** | MeshLambertMaterial | Simple diffuse material. Faster than Phong but less realistic. |++### Three.js Geometry++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **BufferGeometry** | BufferGeometry | Core geometry class. Stores vertex data in typed arrays (positions, normals, UVs). |+| **BoxGeometry** | BoxGeometry | Creates a box/cube shape. |+| **SphereGeometry** | SphereGeometry | Creates a sphere shape. |+| **CylinderGeometry** | CylinderGeometry | Creates a cylinder shape. |+| **PlaneGeometry** | PlaneGeometry | Creates a flat 2D plane in 3D space. |+| **TorusGeometry** | TorusGeometry | Creates a donut/torus shape. |+| **ExtrudeGeometry** | ExtrudeGeometry | Creates 3D shape by extruding a 2D path. |+| **LatheGeometry** | LatheGeometry | Creates shape by rotating a profile around an axis. |++### Loaders & Export++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **GLTFLoader** | GLTFLoader | Loads glTF/GLB files into Three.js scenes. |+| **FBXLoader** | FBXLoader | Loads FBX files. |+| **OBJLoader** | OBJLoader | Loads OBJ files. |+| **TextureLoader** | TextureLoader | Loads image files as textures. |+| **GLTFExporter** | GLTFExporter | Exports Three.js scene to glTF/GLB format. |++### Performance++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **InstancedMesh** | InstancedMesh | Renders many copies of same geometry with one draw call. |+| **Frustum Culling** | Frustum Culling | Automatic Three.js optimization to skip objects outside camera view. |+| **Level of Detail (LOD)** | LOD | Three.js class that shows different detail levels based on camera distance. |+| **Morph Targets** | Morph Targets | Vertex-based animation stored in geometry. Used for facial expressions. |++---++## 9. CS2 Workshop Workflow++### Creation Pipeline++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **Workshop Submission** | Gửi lên Workshop | Process of submitting custom skins to CS2 for community voting. |+| **Substance Painter** | Substance Painter | Industry-standard texture painting tool. Primary tool for CS2 skin creation. |+| **Substance Designer** | Substance Designer | Node-based material creation tool. Used for procedural textures. |+| **Source 2** | Source 2 | Valve's game engine powering CS2. |+| **Source 2 Hammer** | Hammer | Level/asset editor for Source 2 engine. |+| **Workshop Tools** | Công cụ Workshop | Official Valve tools for creating CS2 workshop content. |+| **Workshop Preview** | Xem trước Workshop | How your skin appears in the workshop voting interface. |++### Material System++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **VMT (Valve Material Type)** | VMT | Material definition file in Source engine. Defines shaders, textures, and parameters. |+| **VTF (Valve Texture Format)** | VTF | Native texture format for Source engine. Converted from PNG/TGA. |+| **Material Proxy** | Proxy vật liệu | Dynamic material parameter changes based on game state (e.g., wear animation). |+| **Phong Shading** | Shading Phong | Legacy shading model in Source engine. Still used for some CS2 materials. |+| **PBR Material (Source 2)** | Vật liệu PBR | Modern material system in Source 2. Uses metallic/roughness workflow. |++### Workshop Requirements++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **Tri Count** | Số tam giác | Total triangle count of weapon model. Must meet Valve's limits. |+| **Texture Resolution** | Độ phân giải texture | Required texture sizes (typically 2048x2048 or 1024x1024). |+| **Normal Map** | Bản đồ Normal | Required for surface detail without extra geometry. |+| **AO Map** | Bản đồ AO | Ambient Occlusion map for added depth. |+| **Material Parameters** | Tham số vật liệu | Configurable values in VMT/shader (color, wear amount, pattern offset, etc.). |+| **Paint Pattern** | Mẫu sơn | The 2D texture pattern that gets projected onto the 3D model via UV mapping. |+| **Wear Overlay** | Lớp phủ mòn | Texture layer that adds scratches, fading, and damage based on float value. |++### File Structure++| English Term | Vietnamese | Definition |+|--------------|------------|------------|+| **QC File** | File QC | Model compilation script defining mesh, skeleton, sequences. |+| **DMX** | DMX | Data Model eXchange format. Source 2 model format. |+| **VCS** | VCS | Version Control System integration for Workshop tools. |+| **Workshop ID** | ID Workshop | Unique identifier for your submitted item. |+| **Tags** | Thẻ | Category labels for workshop items (e.g., Weapon, Knife, gloves). |++---++## Quick Reference: CS2 Item Identification++A CS2 skin is uniquely identified by:+1. **Skin Name** - e.g., "AK-47 Asiimov"+2. **Exterior/Wear Tier** - FN, MW, FT, WW, BS+3. **StatTrak/Souvenir Flag** - Normal, StatTrak, or Souvenir+4. **Float Value** - Exact decimal (e.g., 0.2234)+5. **Pattern Index** - Integer seed (e.g., 661 for blue gem)++Two items with the same name can have different values based on float, pattern, stickers, and StatTrak status.++---++## Glossary of Acronyms++| Acronym | Full Form | Vietnamese |+|---------|-----------|------------|+| PBR | Physically Based Rendering | Render dựa trên vật lý |+| UV | Ultraviolet (texture coordinates) | Tọa độ kết cấu |+| LOD | Level of Detail | Chi tiết cấp độ |+| AO | Ambient Occlusion | Che sáng môi trường |+| FN | Factory New | Mới từ nhà máy |+| MW | Minimal Wear | Mòn tối thiểu |+| FT | Field-Tested | Đã thử nghiệm |+| WW | Well-Worn | Mòn nhiều |+| BS | Battle-Scarred | Chiến tích |+| GLB/glTF | Graphics Language Transmission Format | Định dạng truyền ngôn ngữ đồ họa |+| FBX | Filmbox | Filmbox |+| OBJ | Wavefront OBJ | Wavefront OBJ |+| STL | Stereolithography | Mô hình hóa cứng |+| VMT | Valve Material Type | Loại vật liệu Valve |+| VTF | Valve Texture Format | Định dạng kết cấu Valve |+| IK | Inverse Kinematics | Động học nghịch đảo |+| FK | Forward Kinematics | Động học thuận |+| GPU | Graphics Processing Unit | Đồ họa đơn vị xử lý |++---++*Last updated: July 2026*+*Sources: Valve Developer Community, CS2 Workshop Documentation, Three.js Documentation, Blender Manual, Meshy Docs*diff --git a/docs/cs2/distill.md b/docs/cs2/distill.mdnew file mode 100644index 0000000..477d7f9--- /dev/null+++ b/docs/cs2/distill.md@@ -0,0 +1,210 @@+# CS2 Research Distill — Consolidated Findings from 13 NotebookLM Sessions++> Sources: 13 notebooks, ~130 sources total+> Generated: 2026-07-24+> Notebook IDs: 3302413b, 7b0376c6, ed67e020, 8430ab72, e20b3968, f783b110, 7b0376c6, 3302413b, 3a1c3eb9, 3957b5dc, e9c7dbee, 370faecc, ee512cf3++---++## 1. Knife Anatomy — Actionable Geometry Rules++| Knife Type | Signature Geometry | Three.js Primitive | Critical Detail |+|---|---|---|---|+| **Karambit** | Concave Hawkbill blade + Safety Ring at pommel | `ExtrudeGeometry` (curved profile) | Ring diameter ≈ 20mm, finger hole |+| **Bowie** | Massive Clip-point + brass crossguard | `ExtrudeGeometry` + `BoxGeometry` (guard) | Clip notch depth ≈ 15% blade length |+| **Skeleton Knife** | Full tang with large index finger hole, tape wrap | `ExtrudeGeometry` (perforated) | Hole diameter ≈ 18mm |+| **Balisong** | Two handles + pivot pins + stop pin + latch | `CylinderGeometry` (pins) | Pivot pin is rotation axis; detent ball holds blade closed |+| **M9 Bayonet** | Clip-point + sawback serrations (11 teeth) | `ExtrudeGeometry` + `BoxGeometry` ×11 | Tooth spacing ≈ 14mm, depth ≈ 15mm |++### Universal Knife Details (from all anatomy notebooks)+- **Jimping**: Notches on spine for thumb traction → Normal map, NOT geometry+- **Choil**: Notch near heel for sharpening → Small boolean subtract+- **Handle Belly**: Swell curving outward from centerline for palm grip+- **Tang types**: Full tang (visible at handle edges), Hidden tang (rat-tail), Skeletonized tang+- **Handle materials**: G10 (roughness 0.75), Micarta (0.7), Wood (0.6, clearcoat 0.2), Paracord wrap (roughness 0.9)++---++## 2. Pistol Anatomy — Key Technical Findings++### Mechanism Differences (Critical for animation)+| Pistol | Mechanism | Key Components |+|---|---|---|+| **Desert Eagle** | Gas-operated, rotating bolt | Piston, 3-lug bolt, polygonal rifling |+| **Tec-9** | Blowback | Tubular bolt inside steel-stamped upper receiver |+| **Glock/USP** | Striker-fired | No external hammer, polymer frame |+| **R8 Revolver** | Double-action | 8-shot cylinder, ejector rod, cylinder release latch |++### Material Mapping+- **Polymer frames** (Glock, P250, Tec-9): `metalness: 0.0, roughness: 0.75`+- **Steel slides/barrels**: `metalness: 1.0, roughness: 0.3`+- **Picatinny rails**: Standard 7/8" spacing → Box geometry with boolean slots+- **Threaded barrels**: For suppressor attachment → Cylinder with helical thread normal++---++## 3. Rifle/SMG/Sniper Key Details++### AK-47 vs M4A4 vs AWP+| Component | AK-47 | M4A4 | AWP |+|---|---|---|---|+| Receiver | Stamped steel, curved magazine | Forged aluminum, straight mag | Bolt-action, massive receiver |+| Handguard | Wooden/polymer, ventilated holes | M-LOK rail system | Minimal, barrel exposed |+| Stock | Fixed wood/polymer | Collapsible (6 positions) | Adjustable cheek rest |+| Magazine | 30-rd curved | 30-rd straight | 5-rd box |++### SMG Specifics+- **MP5**: Roller-delayed blowback, slim handguard, drum mag option+- **P90**: Bullpup, top-mounted magazine, 50-rd capacity+- **PP-Bizon**: Helical magazine under barrel++---++## 4. PBR Properties — Strict CS2 Ranges++### Binary Metalness Rule (CRITICAL)+> **CS2 uses a strict two-bit metalness model**: surfaces are either `0.0` (dielectric: wood, polymer, fabric) or `1.0` (conductive: steel, gold, chrome). Intermediate values cause lighting artifacts.++### Albedo Ranges+| Material | Albedo RGB Range | Metalness | Roughness |+|---|---|---|---|+| **Dielectric (polymer)** | [30, 240] per channel | 0.0 | 0.4–0.8 |+| **Conductive (steel)** | [180, 255] per channel | 1.0 | 0.2–0.5 |+| **Chrome/Anodized** | [180, 255] | 1.0 | 0.05–0.15 |+| **Patina (Case Hardened)** | [100, 200] | 0.80–0.95 | 0.20–0.35 |++### Environment Requirements+- **HDR cubemap** mandatory for anodized/chrome finishes+- `renderer.toneMapping = THREE.ACESFilmicToneMapping`+- `.colorSpace = THREE.SRGBColorSpace` for albedo/emissive maps+- `NoColorSpace` for normalMap, roughnessMap, metalnessMap++---++## 5. Finish Styles — Technical Recipes++| Finish | Metalness | Roughness | Key Property | Wear Behavior |+|---|---|---|---|---|+| **Anodized** | 0.90–1.00 | 0.05–0.15 | `envMapIntensity: 1.5–2.5` | Color peels from edges |+| **Anodized Multicolored** | 0.90–1.00 | 0.03–0.10 | Iridescence + noise ramp | Gloss fades, gradient shifts |+| **Custom Paint Job** | 0.0 | 0.3–0.5 | `clearcoat: 0.2–0.4` | Paint scratches from edges |+| **Hydrographic** | 0.0 | 0.5–0.7 | Dip-film swirl print | Large patches peel |+| **Patina** | 0.80–0.95 | 0.20–0.35 | Iridescence 0.3–0.6 | Color shifts, not peeling |+| **Gunsmith** | 0.7–0.9 | 0.2–0.4 | Patina + paint blend | Combined fading |+| **Solid Color** | 0.0 | 0.3–0.5 | `clearcoat: 0.2–0.3` | Scratches at edges |+| **Sprayed** | 0.0 | 0.6–0.8 | No clearcoat | Heavy base metal exposure |++---++## 6. Wear System — Shader Implementation++### Float Value → Visual Mapping+| Tier | Range | Roughness Delta | Metalness Delta | Albedo Shift |+|---|---|---|---|---|+| FN | 0.00–0.07 | +0.0 | +0.0 | None |+| MW | 0.07–0.15 | +0.1 | +0.05 | Slight darkening at edges |+| FT | 0.15–0.38 | +0.2 | +0.15 | Noticeable fading |+| WW | 0.38–0.45 | +0.3 | +0.3 | Significant desaturation |+| BS | 0.45–1.00 | +0.5 | +0.5 | Heavy oxidation appearance |++### Geometric-Driven Wear Masks+- **Convex curvature map** → concentrates scratches on sharp outer edges+- **Ambient Occlusion (AO)** → protects recesses from peeling; accumulates grime/dark oxidation+- **Paint Seed deterministic transform**: `A = T₂ × R × S × T₁` (centered translation → base scale → rotation → correction translation)++---++## 7. Pattern System — Technical Details++### Paint Seed / Pattern Index+- Integer 0–999, initialized at drop time+- Controls UV offset via deterministic affine matrix+- **Fade**: Gradient sequence Yellow → Orange → Pink → Purple; percentage = how much gradient visible from tip+- **Doppler**: Fixed indices (#415 Ruby, #416 Sapphire, #417 Black Pearl); iridescent reflections via 3D noise color-ramp lookup+- **Case Hardened**: Randomized charcoal-heated look; Blue Gem = mostly blue on playside (rare patterns exist in database)++### UV Mapping Rules for CS2+- Asymmetrical UV: playside gets larger UV island for higher detail+- LOD0 mesh required for inspect/viewmodel (maximum polygon density)+- UV scale formula: for Hydrographic/Anodized Multicolored → `s = weapon_length × 0.027777778`++---++## 8. Attachments & Special Items++### StatTrak™+- **On firearms**: Independent mesh module (ST_counter) with **orange LED emissive** (`#FF4500`)+- **On knives**: Dynamic tangent-space bump map procedurally engraves kill count into blade+- Drop rate: ~10% of normal drops++### Stickers+- Max 5 slots per weapon+- Parameters: `offset_x`, `offset_y` (float32), `rotation` (0–360°), `scale`+- Wear formula: `Base_Wear × (1.0 - (α_channel × UnWearStrength))`+- Scrape levels: 100% → 75% → 50% → 25%++### Charms+- Independent 3D mesh, attached via skeletal spring-joint+- Physics: spring-damper `τ = -kθ - cω` for swing motion+- Clasp bone attachment point++---++## 9. 3D Reconstruction Pipeline Insights++### Channel Packing (Source 2 → Three.js)+- Roughness + Metalness packed in single texture (R + G channels)+- Must unpack in shader: `roughness = texture2D(rmMap, uv).g; metalness = texture2D(rmMap, uv).b;`++### Structured Image Description Protocol (from 370faecc)+1. **Observation before inference** — state observable facts separately from inferences+2. **Controlled vocabulary** — use 3D terms, never "nice/sleek/aggressive"+3. **3D object-space, not 2D image-space** — describe by front/back/lateral/proximal+4. **Structural decomposition**: Macro → Meso → Micro+5. **Visual Triplets**: Subject-Predicate-Object for spatial relationships+6. **Single-image limits** — explicitly state what's occluded/hidden/uncertain++### 3D Types Taxonomy (from ee512cf3)+- **PBR workflow**: Albedo + Normal + Roughness + Metallic + AO+- **UV efficiency target**: 85–95%+- **Texel density**: 512–1024 px/m for hero assets+- **Web optimization**: glTF/GLB format, Draco compression (90–95% reduction), KTX2 for textures+- **LOD chains**: 50% reduction per level+- **Collision mesh**: Simplified primitives (`cdt_` prefix)++---++## 10. Texture Extraction Pipeline (from 3a1c3eb9)++### CSGO-API Metadata+- `weapon_id`, `paint_index`, `min_float`, `max_float` from ByMykel/CSGO-API+- CDN image URL for reference screenshots++### Valve Texture Format+- VTF → PNG conversion via Source2Viewer-CLI+- Channel packing: Roughness (R) + Metalness (G) in single file+- Must tangle channels for Three.js MeshPhysicalMaterial++### Legal Note+- Extracted textures are Valve IP — stay in local `cs2_textures/` workspace+- Never commit or redistribute+- "Extractive use" doctrine may apply for personal/research use++---++## 11. CS2 Detection Signals (for detect_cs2.py)++Visual markers that identify a CS2 weapon/item from a 2D image:++| Signal | Weight | Detection Method |+|---|---|---|+| **Weapon silhouette** (blade, rifle, pistol shape) | High | Aspect ratio + contour analysis |+| **CS2 skin patterns** (Doppler gradient, Fade, Crimson Web) | High | Color distribution + pattern recognition |+| **Steam Workshop aesthetics** (clean render, white/grey background) | Medium | Background color histogram |+| **StatTrak™ module** (orange LED counter) | High | Small emissive orange rectangle |+| **CS2-specific wear patterns** (edge wear on blade, patina on receiver) | Medium | Edge contrast analysis |+| **Knife guard/handle construction** (crossguard, tang, pommel) | Medium | Component decomposition |++---++*Distilled from 13 NotebookLM sessions covering: knives (3302413b), pistols (7b0376c6), rifles (ed67e020), heavy (8430ab72), snipers (e20b3968), SMGs (f783b110), gloves (d353b31a), texture extraction (3a1c3eb9), item attributes (3957b5dc), skin specs (e9c7dbee), image description (370faecc), 3D taxonomy (ee512cf3), and current session (30ec3dba).*diff --git a/docs/cs2/review-gates.md b/docs/cs2/review-gates.mdnew file mode 100644index 0000000..6d6765d--- /dev/null+++ b/docs/cs2/review-gates.md@@ -0,0 +1,49 @@+# CS2 knife review gates++The review contract is owned by `forge/stage4_review/cs2_review.py`. It consumes a+validated manifest, render metrics, painted-region results, projection coverage,+critical-feature scores, and two orbit results. It emits a machine-readable report+with family, route, exactness tier, scene metadata, per-region confidence,+approximation notes, and failed gates.++The versioned fixture is `forge/tests/fixtures/knife_review_scene.json`. It records+the camera, object transform, environment hash, exposure, tone mapping, resolution, background,+renderer version, visible regions, critical features, and frozen initial thresholds:++- silhouette IoU: at least `0.85`+- aspect-ratio delta: at most `0.05`+- scale delta: at most `0.08`+- projection coverage: at least `0.85` when projection is required+- finish/material response and identity detail: at least `0.80`+- painted-region score: at least `0.80`+- orbit collapse ratio: `0.15` maximum++These thresholds are fixture data, not caller-supplied prose. They are blocking for+the knife route. A wrong family, missing adapter, missing projection evidence,+insufficient coverage, critical-feature failure, or degenerate orbit cannot be+overridden by a global visual score.++The fixture freezes the initial targets but records calibration as pending until the+browser runtime supplies labeled positive and negative renders. `calibrate_eye.py`+must be run on both classes before these targets are treated as empirically calibrated.++Attach a report to the normal review record with:++```sh+python3 forge/stage4_review/append_review.py object-sculpt-spec.json \+ --pass-id material-pass --fidelity 0.9 --action continue --summary "knife review passed" \+ --cs2-review-json cs2-review.json \+ --review-scene-json forge/tests/fixtures/knife_review_scene.json --in-place+```++`append_review.py` rejects `action=continue` when the attached report is not a+passing knife review or when its scene fixture does not match. The report retains+single-view limitations: hidden-region confidence and approximation notes are+required evidence, not an exactness claim.++The fixture metadata labels the image as `user-supplied-review-required`. Do not+mark it rights-safe or commit extracted Valve pixels until provenance is verified.+Local extraction remains outside the repository under the existing `cs2_textures/`+IP boundary. Browser capture remains the responsibility of `runtime/cs2-preview`;+the Python review gate accepts its metrics and screenshots but does not pretend to+render them.diff --git a/docs/raw/.keep b/docs/raw/.keepnew file mode 100644index 0000000..e69de29diff --git a/docs/raw/img2threejs-skill-dataset.json b/docs/raw/img2threejs-skill-dataset.jsonnew file mode 100644index 0000000..052d047--- /dev/null+++ b/docs/raw/img2threejs-skill-dataset.json@@ -0,0 +1,1529 @@+{+ "version": "1.0",+ "source": "img2threejs NotebookLM research distillation",+ "categories": {+ "material_pbr": [+ {+ "name": "Metalness",+ "name_vi": "Độ kim loại",+ "definition": "Binary or scalar property defining whether a surface is dielectric (0.0) or conductive metal (1.0); intermediate values blend the two.",+ "definition_vi": "Thuộc tính nhị phân hoặc vô hướng xác định bề mặt là điện môi (0.0) hay kim loại dẫn điện (1.0); giá trị trung gian là pha trộn tuyến tính.",+ "recognition_cues": [+ "Metallic surfaces tint their reflections with the base color at grazing angles instead of showing white specular highlights",+ "CS2 specifically uses a strict binary model — pure metal (1.0) or pure dielectric (0.0), no soft gray transition zones"+ ],+ "recognition_cues_vi": [+ "Bề mặt kim loại nhuộm màu phản xạ theo màu nền ở góc nhìn xiên thay vì hiển thị điểm sáng specular trắng",+ "CS2 dùng mô hình nhị phân nghiêm ngặt — kim loại thuần (1.0) hoặc điện môi thuần (0.0), không có vùng chuyển xám mềm"+ ],+ "threejs_target": "MeshPhysicalMaterial.metalness (scalar) + .metalnessMap (blue channel of packed ORM texture, NoColorSpace)"+ },+ {+ "name": "Roughness",+ "name_vi": "Độ nhám",+ "definition": "Microfacet surface imperfection parameter; controls how tightly or diffusely light scatters off a surface.",+ "definition_vi": "Tham số vi mô bề mặt mô tả ánh sáng bị tán xạ tập trung hay khuếch tán khi phản xạ.",+ "recognition_cues": [+ "Low roughness = sharp, mirror-like, tight specular highlight",+ "High roughness = blurry, wide, dim highlight and matte appearance",+ "In a photo, worn/scratched regions show broken-up, uneven highlight shapes vs. the smooth highlight of pristine areas"+ ],+ "recognition_cues_vi": [+ "Độ nhám thấp = điểm sáng specular sắc nét, giống gương",+ "Độ nhám cao = điểm sáng mờ, rộng, tối, bề mặt trông mờ đục",+ "Trong ảnh, vùng bị mòn/trầy có hình dạng điểm sáng vỡ vụn, không đều so với vùng nguyên vẹn"+ ],+ "threejs_target": "MeshPhysicalMaterial.roughness (scalar) + .roughnessMap (green channel of packed ORM texture, NoColorSpace)"+ },+ {+ "name": "Normal Map",+ "name_vi": "Bản đồ pháp tuyến",+ "definition": "Tangent-space RGB texture that perturbs surface normals to simulate fine geometric detail (engravings, scratches, weave) without added polycount.",+ "definition_vi": "Kết cấu RGB không gian tiếp tuyến làm lệch pháp tuyến bề mặt để mô phỏng chi tiết hình học nhỏ (khắc chữ, vết trầy, dệt vải) mà không tăng số đa giác.",+ "recognition_cues": [+ "Fine surface relief (engraving, stippling, fabric weave, edge chips) visible under raking light but absent from the silhouette",+ "Typically stored as a blue/purple-tinted texture in extraction tools"+ ],+ "recognition_cues_vi": [+ "Chi tiết nổi trên bề mặt (khắc chữ, chấm nhám, dệt vải, mẻ cạnh) thấy rõ dưới ánh sáng chéo nhưng không có trên đường viền hình học",+ "Thường lưu dưới dạng kết cấu có tông màu xanh dương/tím trong công cụ trích xuất"+ ],+ "threejs_target": "MeshPhysicalMaterial.normalMap (RGB, NoColorSpace); invert green (Y) channel if source is OpenGL vs DirectX convention"+ },+ {+ "name": "Ambient Occlusion (AO)",+ "name_vi": "Bóng đổ môi trường (AO)",+ "definition": "Baked grayscale map darkening indirect light in crevices, seams, and recesses.",+ "definition_vi": "Bản đồ grayscale được nướng sẵn làm tối ánh sáng gián tiếp tại các khe, rãnh và chỗ lõm.",+ "recognition_cues": [+ "Soft, contact-shadow-like darkening in grooves, screw recesses, and part seams that doesn't move with the key light",+ "Protected/recessed regions accumulate dirt/grime under wear rather than losing paint"+ ],+ "recognition_cues_vi": [+ "Vùng tối mềm giống bóng tiếp xúc tại các rãnh, ốc vít, mối nối — không di chuyển theo hướng đèn chính",+ "Vùng lõm được bảo vệ tích tụ bụi bẩn khi mòn thay vì mất lớp sơn"+ ],+ "threejs_target": "MeshPhysicalMaterial.aoMap (red channel of packed ORM texture, NoColorSpace) + aoMapIntensity"+ },+ {+ "name": "Clearcoat",+ "name_vi": "Lớp phủ bóng (Clearcoat)",+ "definition": "Secondary reflective coating layer on top of the base material, simulating varnish, lacquer, or automotive paint.",+ "definition_vi": "Lớp phủ phản xạ thứ cấp nằm trên vật liệu nền, mô phỏng vecni, sơn mài hoặc sơn xe hơi.",+ "recognition_cues": [+ "A distinct, sharp secondary highlight sitting on top of a duller or differently-colored base layer",+ "Common on Custom Paint Job / Gunsmith style finishes with a glossy topcoat over illustrative artwork"+ ],+ "recognition_cues_vi": [+ "Có một điểm sáng thứ cấp sắc nét nằm trên lớp nền mờ hơn hoặc khác màu",+ "Thường gặp ở các finish kiểu Custom Paint Job / Gunsmith có lớp phủ bóng trên tranh vẽ minh họa"+ ],+ "threejs_target": "MeshPhysicalMaterial.clearcoat (weight) + .clearcoatRoughness"+ },+ {+ "name": "Subsurface Scattering (SSS)",+ "name_vi": "Tán xạ dưới bề mặt (SSS)",+ "definition": "Light transport property for opaque dielectrics where light penetrates and scatters internally before exiting (skin, wax, marble, some polymers).",+ "definition_vi": "Đặc tính truyền ánh sáng của vật liệu điện môi mờ đục, ánh sáng xuyên vào và tán xạ bên trong trước khi thoát ra (da, sáp, đá cẩm thạch, một số nhựa polymer).",+ "recognition_cues": [+ "Edges/thin sections of the material glow softly when backlit rather than showing a hard black silhouette",+ "Relevant mainly to glove leather/polymer trims and agent-model skin, not metal weapon parts"+ ],+ "recognition_cues_vi": [+ "Các cạnh/phần mỏng của vật liệu phát sáng mềm khi có ánh sáng ngược thay vì tạo bóng đen sắc nét",+ "Chủ yếu liên quan đến da/nhựa của găng tay và da người mẫu đặc vụ, không áp dụng cho các bộ phận kim loại của súng"+ ],+ "threejs_target": "MeshPhysicalMaterial.transmission + .thickness + .attenuationColor (approximates SSS on MeshPhysicalMaterial)"+ },+ {+ "name": "Anisotropy",+ "name_vi": "Dị hướng (Anisotropy)",+ "definition": "Directional specular stretching seen on brushed or grooved metal, where reflections elongate along the grain direction.",+ "definition_vi": "Hiện tượng phản xạ specular kéo dài theo một hướng, thấy trên kim loại được chải xước hoặc có rãnh, phản xạ kéo dài theo hướng vân.",+ "recognition_cues": [+ "Elongated, streaky highlights (not round) that stay aligned with visible brush/groove marks as the view angle changes",+ "Common on brushed steel/titanium knife finishes and gunsmith metal bases"+ ],+ "recognition_cues_vi": [+ "Điểm sáng kéo dài, có vệt (không tròn) luôn thẳng hàng với các vết chải/rãnh nhìn thấy khi góc nhìn thay đổi",+ "Thường gặp ở các finish thép/titan chải xước của dao và nền kim loại gunsmith"+ ],+ "threejs_target": "MeshPhysicalMaterial.anisotropy (scalar) + .anisotropyMap (direction/strength) + tangent map for groove direction"+ },+ {+ "name": "Emission",+ "name_vi": "Phát xạ (Emission)",+ "definition": "Self-illuminating surface layer independent of scene lighting, used for glowing indicators or self-illum masks.",+ "definition_vi": "Lớp bề mặt tự phát sáng độc lập với ánh sáng cảnh, dùng cho đèn báo phát sáng hoặc mặt nạ self-illum.",+ "recognition_cues": [+ "A region stays bright/colored regardless of light direction or shadow (e.g. StatTrak orange LED counter module)",+ "Often masked to a small, specific submesh rather than the whole surface"+ ],+ "recognition_cues_vi": [+ "Một vùng luôn sáng/có màu bất kể hướng ánh sáng hay bóng đổ (vd. module đèn LED cam của StatTrak)",+ "Thường được giới hạn (mask) vào một submesh nhỏ, cụ thể thay vì toàn bộ bề mặt"+ ],+ "threejs_target": "MeshPhysicalMaterial.emissive + .emissiveMap (SRGBColorSpace) + .emissiveIntensity"+ },+ {+ "name": "Opacity / Alpha",+ "name_vi": "Độ trong suốt / Alpha",+ "definition": "Controls material transparency and blend mode; in CS2 workflows the alpha channel of Base Color is repurposed as a non-transparency data channel.",+ "definition_vi": "Kiểm soát độ trong suốt và chế độ blend của vật liệu; trong quy trình CS2, kênh alpha của Base Color được tái sử dụng làm kênh dữ liệu, không phải độ trong suốt.",+ "recognition_cues": [+ "Standard opacity: soft edge fade or full transparency in glass/plastic parts",+ "CS2-specific: alpha channel of the base color texture instead encodes a Wearness Mask, not visual transparency"+ ],+ "recognition_cues_vi": [+ "Opacity tiêu chuẩn: cạnh mờ dần hoặc trong suốt hoàn toàn ở các bộ phận kính/nhựa",+ "Đặc thù CS2: kênh alpha của texture màu nền lại mã hóa Wearness Mask, không phải độ trong suốt thị giác"+ ],+ "threejs_target": "MeshPhysicalMaterial.opacity + .alphaTest / .transparent (standard); CS2 alpha channel routed to a custom wear shader input instead"+ },+ {+ "name": "Wearness Alpha Mask",+ "name_vi": "Mặt nạ độ bền (Wearness Mask)",+ "definition": "CS2-specific per-pixel durability control embedded in the alpha channel of the Base Color texture, independent of visible transparency.",+ "definition_vi": "Cơ chế điều khiển độ bền theo từng pixel đặc thù của CS2, nhúng trong kênh alpha của texture Base Color, độc lập với độ trong suốt thị giác.",+ "recognition_cues": [+ "Alpha ~196: paint erodes early, visible scratches/chips even at low float (Factory New range)",+ "Alpha <128: durable, resists scratching",+ "Alpha = 0 (black): absolute durability, paint never scratches regardless of float value"+ ],+ "recognition_cues_vi": [+ "Alpha ~196: sơn bong sớm, có vết trầy/mẻ ngay cả ở float thấp (khoảng Factory New)",+ "Alpha <128: bền, chống trầy",+ "Alpha = 0 (đen): bền tuyệt đối, sơn không bao giờ bị trầy dù float cao"+ ],+ "threejs_target": "Custom shader uniform sampling Base Color alpha to drive a wear-blend mix() between pristine and worn material states, keyed by a float value parameter"+ },+ {+ "name": "ORM Channel Packing",+ "name_vi": "Đóng gói kênh ORM",+ "definition": "Convention of packing AO, Roughness, and Metalness grayscale maps into the R, G, B channels of a single texture to cut texture-fetch and VRAM cost.",+ "definition_vi": "Quy ước đóng gói ba bản đồ grayscale AO, Roughness, Metalness vào các kênh R, G, B của một texture duy nhất để giảm chi phí lấy mẫu texture và VRAM.",+ "recognition_cues": [+ "Single texture file that looks like flat gray/colored noise, not a recognizable color or normal map",+ "Source 2 (CS2) packs Roughness/Metalness this way; the raw file needs channel-splitting before separate Three.js texture slots can use it"+ ],+ "recognition_cues_vi": [+ "Một file texture duy nhất trông như nhiễu xám/màu phẳng, không giống ảnh màu hay normal map thông thường",+ "Source 2 (CS2) đóng gói Roughness/Metalness theo cách này; file gốc cần tách kênh trước khi gán vào các khe texture riêng của Three.js"+ ],+ "threejs_target": "One packed texture assigned simultaneously to .aoMap (R), .roughnessMap (G), .metalnessMap (B) per the glTF ORM convention"+ },+ {+ "name": "Color Space: sRGB vs Linear/NoColorSpace",+ "name_vi": "Không gian màu: sRGB và Linear/NoColorSpace",+ "definition": "Distinction between human-viewable color data (needs gamma/sRGB) and mathematical data maps (must stay linear/uncorrected).",+ "definition_vi": "Phân biệt giữa dữ liệu màu để người xem (cần gamma/sRGB) và các bản đồ dữ liệu toán học (phải giữ tuyến tính/không hiệu chỉnh).",+ "recognition_cues": [+ "Base color/albedo and emissive textures are the only ones that should look like natural photographic color",+ "Normal, roughness, metalness, and AO textures look like flat/desaturated data patterns and must never be gamma-corrected"+ ],+ "recognition_cues_vi": [+ "Chỉ có base color/albedo và emissive texture nên trông như ảnh màu tự nhiên",+ "Normal, roughness, metalness, AO trông như các mẫu dữ liệu phẳng/khử màu và không bao giờ được hiệu chỉnh gamma"+ ],+ "threejs_target": "texture.colorSpace = THREE.SRGBColorSpace for .map/.emissiveMap; THREE.NoColorSpace for .normalMap/.roughnessMap/.metalnessMap/.aoMap (Three.js r152+)"+ },+ {+ "name": "Hand-Painted vs PBR Texture",+ "name_vi": "Kết cấu vẽ tay và kết cấu PBR",+ "definition": "Distinguishes textures with lighting baked directly into color (static, stylized) from textures that respond dynamically to scene lighting via separate PBR channels.",+ "definition_vi": "Phân biệt kết cấu có ánh sáng được nướng trực tiếp vào màu (tĩnh, cách điệu) với kết cấu phản hồi động theo ánh sáng cảnh qua các kênh PBR riêng.",+ "recognition_cues": [+ "Hand-painted: shadows/highlights stay fixed in place even as the object rotates or lighting changes; visible brushstrokes; single diffuse-only map",+ "PBR: specular highlights and shadow shapes move logically with view/light angle; micro-detail (pores, scratches) shows directional shading from normal/roughness maps"+ ],+ "recognition_cues_vi": [+ "Vẽ tay: bóng tối/điểm sáng cố định vị trí dù vật xoay hay ánh sáng đổi; thấy vết cọ; chỉ có một map diffuse duy nhất",+ "PBR: điểm sáng specular và hình dạng bóng di chuyển hợp lý theo góc nhìn/ánh sáng; chi tiết vi mô (lỗ chân lông, vết xước) có bóng đổ theo hướng từ normal/roughness map"+ ],+ "threejs_target": "Hand-painted → single .map (baked lighting, SRGBColorSpace); PBR → full MeshPhysicalMaterial channel set (map/normalMap/roughnessMap/metalnessMap/aoMap)"+ },+ {+ "name": "Tangent-Space Normal Encoding (DirectX vs OpenGL)",+ "name_vi": "Mã hóa Normal Map không gian tiếp tuyến (DirectX và OpenGL)",+ "definition": "Convention difference in the green (Y) channel of tangent-space normal maps between DirectX-style and OpenGL-style encoding.",+ "definition_vi": "Sự khác biệt quy ước ở kênh xanh lá (Y) của normal map không gian tiếp tuyến giữa mã hóa kiểu DirectX và kiểu OpenGL.",+ "recognition_cues": [+ "Bumps rendering as dents (or vice versa) after import is the visual symptom of a Y-channel mismatch",+ "CS2/Source 2 extracted normals may need the green channel inverted depending on export convention"+ ],+ "recognition_cues_vi": [+ "Hiện tượng chỗ lồi hiển thị thành chỗ lõm (hoặc ngược lại) sau khi import là dấu hiệu sai lệch kênh Y",+ "Normal map trích xuất từ CS2/Source 2 có thể cần đảo kênh xanh lá tùy theo quy ước xuất"+ ],+ "threejs_target": "Invert the green channel of the source normal texture (texture data flip) before assigning to MeshPhysicalMaterial.normalMap if bump direction reads inverted"+ }+ ],+ "geometry_anatomy": {+ "rifle": [+ {+ "name": "Upper Receiver",+ "name_vi": "Thân trên",+ "definition": "Top housing of the rifle containing the bolt carrier group and providing the barrel mounting point.",+ "definition_vi": "Phần vỏ trên của súng trường chứa cụm bệ khóa nòng và là điểm gắn nòng súng.",+ "recognition_cues": [+ "Long central body spanning from the rear sight area to the barrel root, sits above the trigger/lower assembly"+ ],+ "recognition_cues_vi": [+ "Thân dài trung tâm kéo dài từ khu vực thước ngắm đến gốc nòng súng, nằm phía trên cụm cò/thân dưới"+ ],+ "threejs_target": "BoxGeometry-based blocked-out shell as the parent node for barrel, sight, and handguard child meshes"+ },+ {+ "name": "Lower Receiver",+ "name_vi": "Thân dưới",+ "definition": "Bottom housing containing the trigger assembly, magazine well, and fire-selector.",+ "definition_vi": "Phần vỏ dưới chứa cụm cò, ổ tiếp đạn (magazine well) và cần chọn chế độ bắn.",+ "recognition_cues": [+ "Contains the trigger guard opening and the magazine insertion slot; grip attaches to its rear"+ ],+ "recognition_cues_vi": [+ "Chứa lỗ vành bảo vệ cò và khe lắp hộp tiếp đạn; tay cầm gắn ở phía sau"+ ],+ "threejs_target": "BoxGeometry parent hosting trigger, magazine-well cavity (CSG subtract), and grip attachment socket"+ },+ {+ "name": "Barrel",+ "name_vi": "Nòng súng",+ "definition": "Steel tube that chambers the cartridge and directs the projectile down its bore.",+ "definition_vi": "Ống thép chứa buồng đạn và định hướng viên đạn dọc theo lòng nòng.",+ "recognition_cues": [+ "Long cylindrical tube protruding from the front of the receiver, tapering slightly, ending at the muzzle"+ ],+ "recognition_cues_vi": [+ "Ống trụ dài nhô ra phía trước thân súng, hơi thon dần, kết thúc ở miệng nòng"+ ],+ "threejs_target": "CylinderGeometry(radiusTop≈radiusBottom, height=barrel length)"+ },+ {+ "name": "Muzzle Device (Flash Hider / Compensator / Suppressor)",+ "name_vi": "Đầu nòng (Loa che lửa / Bù giật / Giảm thanh)",+ "definition": "End-of-barrel attachment reducing muzzle flash, redirecting gas to counter recoil, or suppressing sound.",+ "definition_vi": "Phụ kiện gắn ở đầu nòng để giảm lóe lửa, dẫn hướng khí để chống giật, hoặc giảm thanh.",+ "recognition_cues": [+ "Distinct slotted or perforated cylindrical/conical cap at the very tip of the barrel, wider than the bore"+ ],+ "recognition_cues_vi": [+ "Nắp hình trụ/nón có rãnh hoặc lỗ thủng rõ rệt ở đầu nòng, rộng hơn lòng nòng"+ ],+ "threejs_target": "Small CylinderGeometry or ConeGeometry child node parented to the barrel tip socket"+ },+ {+ "name": "Gas Tube",+ "name_vi": "Ống dẫn khí",+ "definition": "Thin tube channeling propellant gas from the barrel to cycle the action.",+ "definition_vi": "Ống nhỏ dẫn khí thuốc súng từ nòng để vận hành chu trình nạp đạn.",+ "recognition_cues": [+ "Thin parallel rod running above/alongside the barrel under the handguard, often barely visible externally"+ ],+ "recognition_cues_vi": [+ "Thanh mảnh song song chạy phía trên/dọc nòng súng dưới ốp lót tay, thường khó thấy từ bên ngoài"+ ],+ "threejs_target": "Thin CylinderGeometry hidden mostly inside the handguard mesh"+ },+ {+ "name": "Handguard",+ "name_vi": "Ốp lót tay",+ "definition": "Protective sleeve around the barrel preventing burns and providing a forward gripping surface.",+ "definition_vi": "Vỏ bảo vệ quanh nòng súng ngăn bỏng tay và tạo bề mặt cầm nắm phía trước.",+ "recognition_cues": [+ "Ribbed or railed sleeve surrounding the barrel between the receiver and muzzle, often with visible vents or rail slots"+ ],+ "recognition_cues_vi": [+ "Vỏ có gân hoặc rãnh rail bao quanh nòng súng giữa thân súng và đầu nòng, thường có khe thông gió hoặc rail lộ rõ"+ ],+ "threejs_target": "Hollow CylinderGeometry or BoxGeometry shell surrounding the barrel (CSG subtract for hollow interior)"+ },+ {+ "name": "Pistol Grip",+ "name_vi": "Tay cầm khai hỏa",+ "definition": "Handle behind the trigger used to hold and control the rifle.",+ "definition_vi": "Tay cầm phía sau cò dùng để giữ và điều khiển súng.",+ "recognition_cues": [+ "Angled handle protruding downward directly behind/below the trigger guard, textured for grip"+ ],+ "recognition_cues_vi": [+ "Tay cầm nghiêng nhô xuống ngay phía sau/dưới vành bảo vệ cò, có vân tăng ma sát"+ ],+ "threejs_target": "BoxGeometry, angled ~15-20° from vertical, child of lower receiver"+ },+ {+ "name": "Buttstock",+ "name_vi": "Báng súng",+ "definition": "Rear section resting against the shooter's shoulder; may be fixed, folding, or collapsible.",+ "definition_vi": "Phần đuôi tì vào vai xạ thủ; có thể cố định, gấp được hoặc thu gọn được.",+ "recognition_cues": [+ "Rearmost component, either a solid contoured shoulder piece (fixed) or a skeletal/folding frame (collapsible)"+ ],+ "recognition_cues_vi": [+ "Bộ phận cuối cùng, hoặc là khối tì vai đặc có đường cong (cố định) hoặc khung xương/gấp được (thu gọn)"+ ],+ "threejs_target": "BoxGeometry/ExtrudeGeometry child node parented to rear of lower receiver, with a hinge pivot if foldable"+ },+ {+ "name": "Magazine",+ "name_vi": "Hộp tiếp đạn / Băng đạn",+ "definition": "Detachable ammunition container; shape varies by platform (curved 'banana' for AK-type, straight/translucent for AUG).",+ "definition_vi": "Hộp chứa đạn tháo rời được; hình dạng khác nhau theo dòng súng (cong hình chuối với AK, thẳng/trong suốt với AUG).",+ "recognition_cues": [+ "Protrudes downward from the magazine well, curved profile signals AK-pattern rifle, straight signals M4/AR-pattern"+ ],+ "recognition_cues_vi": [+ "Nhô xuống dưới từ ổ tiếp đạn, hình cong báo hiệu súng dòng AK, hình thẳng báo hiệu dòng M4/AR"+ ],+ "threejs_target": "ExtrudeGeometry (curved 2D profile extruded) for banana magazines; BoxGeometry for straight magazines"+ },+ {+ "name": "Bolt Carrier Group (BCG) & Charging Handle",+ "name_vi": "Cụm bệ khóa nòng và Cần kéo nạp đạn",+ "definition": "Internal mechanism performing chambering/locking/firing/extraction, manually cycled via an external handle.",+ "definition_vi": "Cơ cấu bên trong thực hiện nạp đạn/khóa nòng/khai hỏa/hất vỏ đạn, được lên đạn thủ công qua cần kéo bên ngoài.",+ "recognition_cues": [+ "Mostly hidden internally; visible externally only as the charging handle protrusion (top or side of receiver, AK top cover)"+ ],+ "recognition_cues_vi": [+ "Chủ yếu ẩn bên trong; chỉ thấy được bên ngoài qua cần kéo nạp đạn nhô ra (trên hoặc bên hông thân súng, nắp trên với AK)"+ ],+ "threejs_target": "Internal geometry usually omitted/low-detail for closed-bolt weapons; charging handle modeled as small BoxGeometry/CylinderGeometry knob"+ }+ ],+ "pistol": [+ {+ "name": "Slide",+ "name_vi": "Khóa nòng",+ "definition": "Top moving assembly of a semi-auto pistol that reciprocates rearward on firing to cycle the action.",+ "definition_vi": "Cụm di động phía trên của súng lục bán tự động, giật lùi khi bắn để thực hiện chu trình nạp đạn.",+ "recognition_cues": [+ "Large metal block wrapping the barrel with serrated grip grooves at the rear for manual racking, houses the rear sight"+ ],+ "recognition_cues_vi": [+ "Khối kim loại lớn bao quanh nòng súng, có rãnh răng cưa phía sau để kéo tay, chứa thước ngắm phía sau"+ ],+ "threejs_target": "BoxGeometry (rounded top edges) sliding along a rail axis relative to the frame, parent node for rear sight"+ },+ {+ "name": "Barrel (Pistol)",+ "name_vi": "Nòng súng",+ "definition": "Tube through which the bullet travels on firing; largely enclosed by the slide in most pistols.",+ "definition_vi": "Ống mà viên đạn di chuyển qua khi bắn; phần lớn được bao bọc bởi khóa nòng ở hầu hết súng lục.",+ "recognition_cues": [+ "Visible mainly at the muzzle opening in the slide; on revolvers it's exposed and fixed, sometimes railed for accessories"+ ],+ "recognition_cues_vi": [+ "Chủ yếu thấy ở lỗ miệng nòng trên khóa nòng; ở súng ổ xoay thì lộ rõ và cố định, đôi khi có rail để gắn phụ kiện"+ ],+ "threejs_target": "CylinderGeometry nested inside the slide's CSG-subtracted bore channel"+ },+ {+ "name": "Cylinder (Revolver)",+ "name_vi": "Ổ xoay / Ổ đạn",+ "definition": "Rotating drum housing multiple ammunition chambers, characteristic of revolvers.",+ "definition_vi": "Trống xoay chứa nhiều buồng đạn, đặc trưng của súng ổ xoay.",+ "recognition_cues": [+ "Large round block at the mid-body of the weapon, visibly segmented into chamber holes (e.g. 8 for the R8 Revolver)"+ ],+ "recognition_cues_vi": [+ "Khối tròn lớn ở giữa thân súng, thấy rõ được chia thành các lỗ buồng đạn (vd. 8 lỗ ở R8 Revolver)"+ ],+ "threejs_target": "CylinderGeometry with radial array of small cylindrical CSG-subtracted chamber holes"+ },+ {+ "name": "Grip",+ "name_vi": "Tay cầm / Báng súng",+ "definition": "Frame section gripped by the shooter, with front strap, backstrap, and (on semi-autos) the magazine well running through it.",+ "definition_vi": "Phần khung mà xạ thủ nắm, gồm mặt trước, mặt sau, và (ở súng bán tự động) ổ tiếp đạn chạy xuyên qua.",+ "recognition_cues": [+ "Textured lower frame section below the trigger guard; on semi-autos the magazine inserts from its base"+ ],+ "recognition_cues_vi": [+ "Phần khung dưới có vân nằm dưới vành bảo vệ cò; ở súng bán tự động, hộp tiếp đạn lắp vào từ đáy tay cầm"+ ],+ "threejs_target": "BoxGeometry angled child of frame, with a CSG-subtracted magazine-well cavity for semi-autos"+ },+ {+ "name": "Trigger Guard",+ "name_vi": "Vành bảo vệ cò",+ "definition": "Loop encircling the trigger to prevent accidental discharge.",+ "definition_vi": "Vòng bao quanh cò súng để ngăn cò bị bóp vô ý.",+ "recognition_cues": [+ "Round or rectangular metal/polymer loop directly beneath the frame, encircling the trigger"+ ],+ "recognition_cues_vi": [+ "Vòng kim loại/nhựa hình tròn hoặc chữ nhật ngay dưới khung súng, bao quanh cò"+ ],+ "threejs_target": "TorusGeometry (partial) or ExtrudeGeometry loop child of the frame"+ },+ {+ "name": "Hammer",+ "name_vi": "Búa đập",+ "definition": "Component that strikes the firing pin or primer directly to discharge the round.",+ "definition_vi": "Bộ phận đập vào kim hỏa hoặc trực tiếp vào hạt nổ để khai hỏa viên đạn.",+ "recognition_cues": [+ "Small protruding lever at the rear-top of the frame, often manually cockable (pulled back) before firing"+ ],+ "recognition_cues_vi": [+ "Cần nhỏ nhô ra ở phía sau-trên khung súng, thường có thể lên cò thủ công (kéo ra sau) trước khi bắn"+ ],+ "threejs_target": "Small hinged BoxGeometry/CylinderGeometry pivot node at the rear of the frame"+ },+ {+ "name": "Cocking Mechanism",+ "name_vi": "Cơ chế lên đạn / Lên búa",+ "definition": "Action of preparing the weapon to fire: racking the slide (pistol) or thumbing/fanning the hammer (revolver).",+ "definition_vi": "Thao tác chuẩn bị súng sẵn sàng bắn: kéo khóa nòng (súng lục) hoặc lên búa bằng ngón cái/kỹ thuật quạt búa (súng ổ xoay).",+ "recognition_cues": [+ "Pistol: serrated slide-grip grooves indicate the racking surface",+ "Revolver: exposed hammer spur sized for thumb cocking; some pistols (Tec-9) use a knob-style charging handle instead"+ ],+ "recognition_cues_vi": [+ "Súng lục: rãnh răng cưa trên khóa nòng cho biết bề mặt để kéo",+ "Súng ổ xoay: đuôi búa lộ ra đủ lớn để lên cò bằng ngón cái; một số súng lục (Tec-9) dùng cần kéo dạng núm thay thế"+ ],+ "threejs_target": "Not a distinct mesh — an animation/interaction state (slide travel distance or hammer rotation) rather than geometry"+ }+ ],+ "knife": [+ {+ "name": "Blade",+ "name_vi": "Lưỡi dao",+ "definition": "The entire working portion of the knife, encompassing both the cutting edge and the spine.",+ "definition_vi": "Toàn bộ phần làm việc của con dao, bao gồm cả cạnh sắc và sống dao.",+ "recognition_cues": [+ "Main metal body extending from the handle/bolster to the tip"+ ],+ "recognition_cues_vi": [+ "Khối kim loại chính kéo dài từ cán/đệm cán đến mũi dao"+ ],+ "threejs_target": "ExtrudeGeometry from a custom 2D THREE.Shape blade silhouette, beveled at the edge side"+ },+ {+ "name": "Edge",+ "name_vi": "Cạnh sắc / Lưỡi cắt",+ "definition": "The sharpened line running from heel to tip used for cutting.",+ "definition_vi": "Đường mài sắc chạy từ gót dao đến mũi dao dùng để cắt.",+ "recognition_cues": [+ "Thinnest, beveled, and typically brightest/most reflective line on the blade"+ ],+ "recognition_cues_vi": [+ "Đường mỏng nhất, được vát và thường sáng bóng/phản chiếu nhất trên lưỡi dao"+ ],+ "threejs_target": "Beveled edge geometry on the ExtrudeGeometry blade shape (narrow bevel angle on one side of the profile curve)"+ },+ {+ "name": "Spine (Back)",+ "name_vi": "Sống dao",+ "definition": "Thick, unsharpened back edge opposite the cutting edge, providing rigidity.",+ "definition_vi": "Phần lưng dày, không mài sắc, đối diện với cạnh sắc, tạo độ cứng cho lưỡi dao.",+ "recognition_cues": [+ "The thickest part of the blade cross-section, flat or gently curved, opposite the sharp edge"+ ],+ "recognition_cues_vi": [+ "Phần dày nhất trong tiết diện lưỡi dao, phẳng hoặc hơi cong, đối diện với cạnh sắc"+ ],+ "threejs_target": "CapsuleGeometry or thick unbeveled strip along the back of the ExtrudeGeometry blade profile"+ },+ {+ "name": "Tip / Point",+ "name_vi": "Mũi dao",+ "definition": "Convergence point of edge and spine at the front of the blade.",+ "definition_vi": "Điểm hội tụ giữa cạnh sắc và sống dao ở phía trước lưỡi dao.",+ "recognition_cues": [+ "Sharpest point of the whole knife; profile shape (drop point, clip point, karambit hook, tanto) is a strong sub-type identifier"+ ],+ "recognition_cues_vi": [+ "Điểm nhọn nhất của toàn bộ con dao; hình dạng mũi (drop point, clip point, móc karambit, tanto) là dấu hiệu phân loại quan trọng"+ ],+ "threejs_target": "Terminal vertex of the ExtrudeGeometry 2D silhouette path — shape of this path segment encodes knife sub-type (e.g. Karambit hook curve)"+ },+ {+ "name": "Tang",+ "name_vi": "Chuôi lưỡi / Tang",+ "definition": "Steel extension of the blade running into the handle.",+ "definition_vi": "Phần thép của lưỡi dao kéo dài vào bên trong cán dao.",+ "recognition_cues": [+ "Full tang: visible steel strip running the length of the handle between the scales",+ "Hidden tang: no visible steel, fully enclosed by handle material"+ ],+ "recognition_cues_vi": [+ "Full tang: dải thép lộ rõ chạy dọc cán dao giữa hai ốp cán",+ "Hidden tang: không thấy thép, được bọc hoàn toàn bởi vật liệu cán"+ ],+ "threejs_target": "Full tang: thin BoxGeometry strip visible between handle-scale meshes; Hidden tang: internal-only geometry, invisible child node"+ },+ {+ "name": "Bolster",+ "name_vi": "Đệm cán / Khâu dao",+ "definition": "Thick metal collar at the junction between blade and handle.",+ "definition_vi": "Miếng đệm kim loại dày nằm ở điểm tiếp giáp giữa lưỡi dao và cán dao.",+ "recognition_cues": [+ "Distinct metal band/thickening right where the blade meets the handle, often a different material/finish than both"+ ],+ "recognition_cues_vi": [+ "Dải kim loại/chỗ dày lên rõ rệt ngay tại điểm lưỡi dao gặp cán dao, thường khác vật liệu/finish với cả hai"+ ],+ "threejs_target": "Short CylinderGeometry or BoxGeometry collar node between blade and handle meshes"+ },+ {+ "name": "Handle Scales",+ "name_vi": "Ốp cán",+ "definition": "Two side panels (wood, G-10, stone, etc.) fastened to the tang to form the grip.",+ "definition_vi": "Hai miếng vật liệu (gỗ, nhựa G-10, đá,...) gắn vào hai bên chuôi dao để tạo thành tay cầm.",+ "recognition_cues": [+ "Paired flat panels on either side of the handle, visible fasteners (rivets/pins), distinct material texture from the blade"+ ],+ "recognition_cues_vi": [+ "Hai tấm phẳng đối xứng hai bên cán dao, thấy rõ đinh tán/chốt, kết cấu vật liệu khác biệt so với lưỡi dao"+ ],+ "threejs_target": "Two mirrored BoxGeometry/ExtrudeGeometry panels flanking the tang, with small CylinderGeometry rivets"+ },+ {+ "name": "Pommel (Butt Cap)",+ "name_vi": "Núm chuôi / Đuôi cán",+ "definition": "End cap at the terminus of the handle, decorative or functional (striking/counterweight).",+ "definition_vi": "Nắp chặn ở đầu cuối của cán dao, mang tính trang trí hoặc chức năng (đập/đối trọng).",+ "recognition_cues": [+ "Rounded or flat metal cap terminating the handle, often used to secure a hidden tang"+ ],+ "recognition_cues_vi": [+ "Nắp kim loại tròn hoặc phẳng kết thúc cán dao, thường dùng để cố định chuôi ẩn"+ ],+ "threejs_target": "SphereGeometry (flattened) or short CylinderGeometry cap child node at the rear of the handle"+ },+ {+ "name": "Balisong Bite/Safe Handle & Latch",+ "name_vi": "Cán nguy hiểm/Cán an toàn và Chốt khóa (Balisong)",+ "definition": "Butterfly-knife-specific split handle: the bite handle swings on the edge side, the safe handle on the spine side, locked shut by a latch pin.",+ "definition_vi": "Cán dao bướm đặc thù chia đôi: cán nguy hiểm ở phía cạnh sắc, cán an toàn ở phía sống dao, được khóa lại bởi chốt latch.",+ "recognition_cues": [+ "Two hinged handle halves that fold flat against the blade",+ "Bite handle closes against the sharp edge (dangerous to grip closed); safe handle closes against the spine",+ "Small rotating latch pin at the tail end locking the halves together"+ ],+ "recognition_cues_vi": [+ "Hai nửa cán có bản lề gấp phẳng áp vào lưỡi dao",+ "Cán nguy hiểm đóng về phía cạnh sắc (nguy hiểm khi cầm lúc đóng); cán an toàn đóng về phía sống dao",+ "Chốt xoay nhỏ ở đuôi cán khóa hai nửa lại với nhau"+ ],+ "threejs_target": "Two hinged handle-half meshes with pivot joints at the bolster, plus a small CylinderGeometry latch pin child node"+ }+ ],+ "smg": [+ {+ "name": "Stock (SMG-specific)",+ "name_vi": "Báng súng (đặc trưng SMG)",+ "definition": "Shoulder-stabilizing rear piece, typically foldable/retractable/collapsible on SMGs to keep the platform compact.",+ "definition_vi": "Bộ phận tì vai phía sau, thường gấp/rút được ở SMG để giữ súng nhỏ gọn.",+ "recognition_cues": [+ "Distinctly more compact and often skeletal/folding compared to a rifle's fixed stock — a strong SMG vs rifle discriminator"+ ],+ "recognition_cues_vi": [+ "Rõ ràng nhỏ gọn hơn và thường dạng khung/gấp được so với báng súng cố định của súng trường — dấu hiệu phân biệt SMG với súng trường"+ ],+ "threejs_target": "Hinged BoxGeometry/thin-frame ExtrudeGeometry child node with a fold pivot relative to the receiver"+ },+ {+ "name": "Curved Magazine (MP5-style)",+ "name_vi": "Băng đạn cong (kiểu MP5)",+ "definition": "Classic slightly-curved 30-round magazine seated forward of the trigger guard.",+ "definition_vi": "Băng đạn cong nhẹ cổ điển 30 viên, lắp phía trước vành bảo vệ cò.",+ "recognition_cues": [+ "Gentle curve, inserted vertically in front of the trigger guard — silhouette closely tied to the classic MP5 family"+ ],+ "recognition_cues_vi": [+ "Cong nhẹ, lắp thẳng đứng phía trước vành bảo vệ cò — hình dáng gắn liền với dòng MP5 cổ điển"+ ],+ "threejs_target": "ExtrudeGeometry with a shallow-curved 2D profile, inserted into a magazine-well socket forward of the grip"+ },+ {+ "name": "Integrated Silencer (MP5-SD)",+ "name_vi": "Ống giảm thanh tích hợp (MP5-SD)",+ "definition": "Large cylindrical suppressor sleeve permanently enclosing the barrel on the MP5-SD variant.",+ "definition_vi": "Vỏ giảm thanh hình trụ lớn bao trùm vĩnh viễn nòng súng ở biến thể MP5-SD.",+ "recognition_cues": [+ "Barrel appears uniformly thick/enclosed for its entire length rather than showing a distinct thin barrel + separate can"+ ],+ "recognition_cues_vi": [+ "Nòng súng trông đồng đều dày/được bao bọc suốt chiều dài thay vì có nòng mảnh riêng biệt + ống giảm thanh rời"+ ],+ "threejs_target": "Single large CylinderGeometry enclosing the barrel node, replacing separate barrel+suppressor children"+ },+ {+ "name": "Top-Mounted Horizontal Magazine (P90-style)",+ "name_vi": "Băng đạn nằm ngang phía trên (kiểu P90)",+ "definition": "Translucent polymer magazine running parallel to and above the barrel, bullpup layout.",+ "definition_vi": "Băng đạn nhựa trong suốt chạy song song và nằm phía trên nòng súng, bố cục bullpup.",+ "recognition_cues": [+ "Magazine lies flat along the top of the receiver rather than protruding downward — the single strongest P90 identifier",+ "Downward-facing ejection port in the stock area"+ ],+ "recognition_cues_vi": [+ "Băng đạn nằm phẳng dọc theo phía trên thân súng thay vì nhô xuống dưới — dấu hiệu nhận diện P90 mạnh nhất",+ "Cửa hất vỏ đạn hướng xuống dưới ở khu vực báng súng"+ ],+ "threejs_target": "BoxGeometry magazine node parented along the top rail axis instead of the bottom of the receiver"+ },+ {+ "name": "Helical Magazine (Bizon-style)",+ "name_vi": "Băng đạn hình trụ xoắn (kiểu Bizon)",+ "definition": "High-capacity (64-round) cylindrical magazine mounted beneath and along the barrel, doubling as a handguard.",+ "definition_vi": "Băng đạn hình trụ dung lượng lớn (64 viên) lắp dưới và dọc theo nòng súng, kiêm luôn vai trò ốp lót tay.",+ "recognition_cues": [+ "Long cylindrical magazine running parallel under the full barrel length, gripped directly by the support hand"+ ],+ "recognition_cues_vi": [+ "Băng đạn hình trụ dài chạy song song dưới suốt chiều dài nòng súng, được tay đỡ nắm trực tiếp"+ ],+ "threejs_target": "CylinderGeometry magazine node spanning the underside of the barrel, doubling as the handguard grip surface"+ }+ ],+ "sniper": [+ {+ "name": "Bolt Action",+ "name_vi": "Cơ cấu lên đạn (Bolt Action)",+ "definition": "Manually-operated locking/cycling mechanism characteristic of precision sniper rifles.",+ "definition_vi": "Cơ chế khóa nòng/lên đạn vận hành thủ công đặc trưng của súng bắn tỉa chính xác.",+ "recognition_cues": [+ "Protruding bolt handle is the visual proxy for this mechanism (see Bolt Handle entry)"+ ],+ "recognition_cues_vi": [+ "Cần kéo khóa nòng nhô ra là dấu hiệu thị giác đại diện cho cơ chế này (xem mục Cần kéo khóa nòng)"+ ],+ "threejs_target": "Internal action geometry usually low-detail; represented externally via the bolt handle child mesh"+ },+ {+ "name": "Bolt Handle",+ "name_vi": "Cần kéo khóa nòng",+ "definition": "Protruding manual handle used to cycle a bolt-action rifle.",+ "definition_vi": "Cần kéo thủ công nhô ra dùng để lên đạn cho súng bolt-action.",+ "recognition_cues": [+ "Prominent knob/lever extending from the side of the receiver — unlike the recessed charging handles of gas-operated rifles, this is the single strongest sniper-vs-assault-rifle discriminator"+ ],+ "recognition_cues_vi": [+ "Núm/cần nhô rõ rệt từ bên hông thân súng — khác với cần kéo nạp đạn thụt vào của súng trích khí, đây là dấu hiệu phân biệt súng bắn tỉa và súng trường mạnh nhất"+ ],+ "threejs_target": "SphereGeometry knob + thin CylinderGeometry arm, child node on the side of the receiver"+ },+ {+ "name": "Heavy/Bull, Free-Floating, Fluted Barrel",+ "name_vi": "Nòng nặng, Nòng tự do, Nòng có rãnh",+ "definition": "Thick match-grade barrel variants: bull barrel (vibration control), free-floating (no stock contact, for accuracy), fluted (grooved to save weight).",+ "definition_vi": "Các biến thể nòng match-grade dày: nòng bull (kiểm soát rung), nòng tự do (không chạm báng súng, tăng độ chính xác), nòng có rãnh (khoét rãnh để giảm trọng lượng).",+ "recognition_cues": [+ "Noticeably thicker barrel profile than assault rifles",+ "A visible air gap between barrel and handguard signals free-floating design",+ "Longitudinal grooves along the barrel signal fluting"+ ],+ "recognition_cues_vi": [+ "Tiết diện nòng dày rõ rệt hơn súng trường thường",+ "Khe hở rõ giữa nòng và ốp lót tay báo hiệu thiết kế free-floating",+ "Các rãnh dọc theo nòng báo hiệu nòng có rãnh (fluted)"+ ],+ "threejs_target": "Thicker CylinderGeometry barrel with optional longitudinal groove geometry (repeated thin CSG-subtracted channels) for fluting"+ },+ {+ "name": "Muzzle Brake / Compensator (Heavy)",+ "name_vi": "Bộ phận hãm giật / Bù giật (cỡ lớn)",+ "definition": "Oversized gas-redirecting device at the muzzle to counter significant recoil from high-caliber rounds.",+ "definition_vi": "Thiết bị dẫn hướng khí cỡ lớn ở đầu nòng để chống giật đáng kể từ đạn cỡ lớn.",+ "recognition_cues": [+ "Boxy, noticeably wider-than-barrel device with large venting ports at the muzzle tip"+ ],+ "recognition_cues_vi": [+ "Thiết bị dạng hộp, rõ ràng rộng hơn nòng súng, có các lỗ thoát khí lớn ở đầu nòng"+ ],+ "threejs_target": "BoxGeometry/CylinderGeometry hybrid, wider radius than the barrel, with CSG-subtracted vent slots"+ },+ {+ "name": "Scope Mount, Rings & Picatinny Rail",+ "name_vi": "Gá ống ngắm, vòng khuyên giữ và rail Picatinny",+ "definition": "Hardware (claw mounts, rings, standardized MIL-STD-1913 rail) securing a high-magnification optic well above the bore axis.",+ "definition_vi": "Phần cứng (gá kẹp, vòng khuyên, rail chuẩn MIL-STD-1913) cố định kính ngắm phóng đại cao, nằm cao hơn hẳn trục nòng.",+ "recognition_cues": [+ "Long flat rail spanning the top of the receiver, dominated by a tall scope sitting well above the standard iron-sight line"+ ],+ "recognition_cues_vi": [+ "Rail phẳng dài trải dọc phía trên thân súng, bị chi phối bởi ống ngắm cao nằm hẳn trên đường ngắm cơ bản tiêu chuẩn"+ ],+ "threejs_target": "BoxGeometry rail strip on top of receiver + CylinderGeometry scope body + Torus/ring mount clamps as child nodes"+ },+ {+ "name": "Cheek Riser / Adjustable Buttstock",+ "name_vi": "Ốp má / Báng súng có thể điều chỉnh",+ "definition": "Elevated, often adjustable stock component aligning the shooter's eye with a high-mounted scope; foldable on some platforms (SSG 08).",+ "definition_vi": "Bộ phận báng súng nâng cao, thường điều chỉnh được, giúp căn mắt xạ thủ với kính ngắm gắn cao; gấp được ở một số dòng (SSG 08).",+ "recognition_cues": [+ "Visible knobs/sliders/adjustment screws on the stock, giving a more 'modular' look than a simple fixed rifle stock"+ ],+ "recognition_cues_vi": [+ "Thấy rõ các núm/thanh trượt/ốc điều chỉnh trên báng súng, tạo cảm giác 'modular' hơn báng súng cố định đơn giản"+ ],+ "threejs_target": "ExtrudeGeometry stock body with small CylinderGeometry adjustment knob child nodes and a slide joint for the riser"+ },+ {+ "name": "Bipod / Monopod",+ "name_vi": "Chân chống hai chân / Chân chống đơn",+ "definition": "Front two-legged support (bipod) and rear retractable spike (monopod) creating a stable three-point stance when deployed.",+ "definition_vi": "Chân chống hai chân phía trước (bipod) và chân chống đơn/spike có thể thu vào phía sau (monopod) tạo thế đứng ba điểm ổn định khi triển khai.",+ "recognition_cues": [+ "Folding legs under the front handguard plus a small retractable spike under the rear of the stock — together create a distinct three-point silhouette when deployed"+ ],+ "recognition_cues_vi": [+ "Chân gấp dưới ốp lót tay phía trước cộng với spike nhỏ có thể thu vào dưới đuôi báng súng — cùng tạo hình dáng ba điểm rõ rệt khi triển khai"+ ],+ "threejs_target": "Two hinged thin CylinderGeometry legs (bipod) + one telescoping CylinderGeometry spike (monopod), child nodes with fold/extend joints"+ }+ ],+ "heavy": [+ {+ "name": "Pump Action Forend",+ "name_vi": "Ốp lót tay trượt",+ "definition": "Sliding handguard beneath a shotgun barrel, racked back-and-forth to eject and chamber shells.",+ "definition_vi": "Ốp lót tay có thể trượt dưới nòng shotgun, kéo tới lui để hất vỏ đạn cũ và nạp đạn mới.",+ "recognition_cues": [+ "Grooved handguard with a visible forward/backward slide gap along the magazine tube"+ ],+ "recognition_cues_vi": [+ "Ốp lót tay có rãnh, thấy rõ khe trượt tới/lui dọc theo ống chứa đạn"+ ],+ "threejs_target": "CylinderGeometry sleeve constrained to slide along the magazine-tube axis (translate-only joint)"+ },+ {+ "name": "Barrel Shroud",+ "name_vi": "Ốp bao nòng",+ "definition": "Perforated protective jacket around a heavy-fire barrel (shotgun or MG), dissipating heat and shielding the shooter's hand.",+ "definition_vi": "Vỏ bảo vệ có lỗ thông quanh nòng súng bắn nhanh (shotgun hoặc súng máy), tản nhiệt và bảo vệ tay xạ thủ.",+ "recognition_cues": [+ "Perforated/vented outer sleeve visibly separate from the inner barrel, common on sustained-fire weapons"+ ],+ "recognition_cues_vi": [+ "Vỏ ngoài có lỗ/thông gió, thấy rõ tách biệt với nòng bên trong, phổ biến ở vũ khí bắn liên tục"+ ],+ "threejs_target": "Hollow CylinderGeometry outer shell with an array of small CSG-subtracted vent holes, barrel visible inside via a see-through gap"+ },+ {+ "name": "Action Bars",+ "name_vi": "Thanh truyền động",+ "definition": "Metal rods linking the pump forend to the bolt, converting hand motion into the cycling action.",+ "definition_vi": "Thanh kim loại nối ốp lót tay trượt với khóa nòng, chuyển động tác tay thành chu trình nạp đạn.",+ "recognition_cues": [+ "Thin parallel rods visible in the gap between forend and receiver when the action is racked open"+ ],+ "recognition_cues_vi": [+ "Thanh mảnh song song thấy được ở khe hở giữa ốp lót tay và thân súng khi kéo mở"+ ],+ "threejs_target": "Thin paired CylinderGeometry rods linking forend and bolt-carrier nodes, mostly hidden when closed"+ },+ {+ "name": "Magazine Tube (Shotgun)",+ "name_vi": "Ống chứa đạn (Shotgun)",+ "definition": "Tubular ammunition reservoir running beneath and parallel to the barrel.",+ "definition_vi": "Kho chứa đạn dạng ống chạy dưới và song song với nòng súng.",+ "recognition_cues": [+ "Thin cylindrical tube directly under the barrel, terminating near the muzzle end"+ ],+ "recognition_cues_vi": [+ "Ống trụ mảnh ngay dưới nòng súng, kết thúc gần đầu nòng"+ ],+ "threejs_target": "Thin CylinderGeometry parallel to and below the main barrel node"+ },+ {+ "name": "Ammo Belt (Linked Ammunition)",+ "name_vi": "Dây băng đạn",+ "definition": "Chain of cartridges linked by metal links, feeding a machine gun continuously.",+ "definition_vi": "Chuỗi đạn liên kết bằng các mắt xích kim loại, tiếp đạn liên tục cho súng máy.",+ "recognition_cues": [+ "Segmented chain visible feeding into the top or side of the receiver, often draping from an ammo box or drum"+ ],+ "recognition_cues_vi": [+ "Chuỗi phân đoạn thấy được đang tiếp vào phía trên hoặc bên hông thân súng, thường thõng từ hộp đạn hoặc trống đạn"+ ],+ "threejs_target": "TubeGeometry following a curved path from a drum/box node into the feed-cover socket, with segment repetition for the link pattern"+ },+ {+ "name": "Drum Magazine",+ "name_vi": "Hộp tiếp đạn hình trống",+ "definition": "High-capacity circular magazine holding coiled belted ammunition.",+ "definition_vi": "Hộp tiếp đạn hình tròn dung lượng lớn chứa dây đạn cuộn tròn bên trong.",+ "recognition_cues": [+ "Large flat circular drum mounted at the feed point, distinctly rounder/flatter than a box or curved magazine"+ ],+ "recognition_cues_vi": [+ "Trống tròn phẳng lớn gắn tại điểm tiếp đạn, rõ ràng tròn/phẳng hơn hộp đạn thẳng hoặc cong"+ ],+ "threejs_target": "CylinderGeometry (short height, large radius) mounted at the receiver's feed socket"+ },+ {+ "name": "Bipod (Heavy)",+ "name_vi": "Giá hai chân",+ "definition": "Folding two-legged support for stable prone or bench firing of heavy automatic weapons.",+ "definition_vi": "Chân đỡ hai chân gấp được để bắn ổn định ở tư thế nằm hoặc trên bệ tì cho vũ khí tự động cỡ lớn.",+ "recognition_cues": [+ "Folding legs attached near the front of the barrel shroud/handguard"+ ],+ "recognition_cues_vi": [+ "Chân gấp gắn gần phía trước ốp bao nòng/ốp lót tay"+ ],+ "threejs_target": "Two hinged thin CylinderGeometry legs, child node with a fold joint near the front handguard"+ },+ {+ "name": "Feed Cover (Top Cover)",+ "name_vi": "Nắp hộp khóa nòng",+ "definition": "Hinged lid over the ammunition feed tray, keeping the belt aligned and shielding the loading mechanism.",+ "definition_vi": "Nắp có bản lề trên khay tiếp đạn, giữ dây đạn thẳng hàng và che chắn cơ cấu nạp đạn.",+ "recognition_cues": [+ "Flat hinged panel on top of the receiver, distinct seam line where it can flip open"+ ],+ "recognition_cues_vi": [+ "Tấm phẳng có bản lề phía trên thân súng, có đường nối rõ rệt nơi có thể lật mở"+ ],+ "threejs_target": "Flat BoxGeometry panel with a hinge joint at the rear edge of the receiver"+ },+ {+ "name": "Carrying Handle (Heavy)",+ "name_vi": "Tay xách",+ "definition": "Handle mounted atop the receiver for transport or rapid barrel changes.",+ "definition_vi": "Tay cầm gắn phía trên thân súng để vận chuyển hoặc thay nòng nhanh.",+ "recognition_cues": [+ "Small looped handle protruding from the top of the receiver, often near the barrel-change latch"+ ],+ "recognition_cues_vi": [+ "Tay cầm hình vòng nhỏ nhô ra từ phía trên thân súng, thường gần chốt thay nòng"+ ],+ "threejs_target": "TorusGeometry (partial loop) or thin ExtrudeGeometry handle child node on top of the receiver"+ }+ ],+ "gloves": [+ {+ "name": "Cuff",+ "name_vi": "Cổ găng tay",+ "definition": "Wrist-covering section of the glove; short cuff ends at/below the wrist, gauntlet extends up the forearm.",+ "definition_vi": "Phần che cổ tay của găng tay; cổ ngắn kết thúc tại/dưới cổ tay, gauntlet kéo dài lên cẳng tay.",+ "recognition_cues": [+ "Short cuff: fabric ends right at the wrist line",+ "Gauntlet: extended fabric/leather panel covering part of the forearm, often with its own strap"+ ],+ "recognition_cues_vi": [+ "Cổ ngắn: vải kết thúc ngay tại đường cổ tay",+ "Gauntlet: tấm vải/da kéo dài che một phần cẳng tay, thường có dây đai riêng"+ ],+ "threejs_target": "ExtrudeGeometry cuff sleeve, length parameter distinguishes short-cuff vs gauntlet variants"+ },+ {+ "name": "Palm & Palm Slider",+ "name_vi": "Lòng bàn tay và Miếng trượt lòng bàn tay",+ "definition": "Grip surface (often goat/kangaroo leather) with a rigid TPU slider puck at the heel to reduce impact injury.",+ "definition_vi": "Bề mặt cầm nắm (thường bằng da dê/da chuột túi) với miếng trượt TPU cứng ở gót bàn tay để giảm chấn thương khi va chạm.",+ "recognition_cues": [+ "Textured leather-like surface on the inner hand",+ "A distinct hard, smooth puck/patch at the base of the palm (heel), differing in material sheen from the surrounding leather"+ ],+ "recognition_cues_vi": [+ "Bề mặt trong lòng bàn tay có kết cấu giống da",+ "Có một miếng cứng, nhẵn, riêng biệt ở gốc lòng bàn tay (gót), khác độ bóng vật liệu so với da xung quanh"+ ],+ "threejs_target": "Palm mesh with a separate small BoxGeometry/rounded-plate submesh (different material slot: harder roughness, distinct color) at the heel"+ },+ {+ "name": "Knuckle Guard",+ "name_vi": "Gù bảo vệ khớp",+ "definition": "Rigid TPU or carbon-fiber plate over the main finger knuckles, dispersing impact and resisting abrasion.",+ "definition_vi": "Tấm cứng TPU hoặc sợi carbon trên các khớp ngón tay chính, phân tán lực va chạm và chống mài mòn.",+ "recognition_cues": [+ "Raised, segmented hard plates across the back of the hand at knuckle positions, visually distinct (matte/textured) from the surrounding soft material"+ ],+ "recognition_cues_vi": [+ "Các tấm cứng nhô lên, phân đoạn trên mu bàn tay tại vị trí khớp, khác biệt rõ (mờ/có kết cấu) so với vật liệu mềm xung quanh"+ ],+ "threejs_target": "Segmented ExtrudeGeometry plates (one per knuckle) overlaid on the back-of-hand mesh, separate material with higher roughness/lower sheen"+ },+ {+ "name": "Finger Segments & Gussets",+ "name_vi": "Đốt ngón tay và Vách ngăn",+ "definition": "Pre-curved individual finger sections joined by stretch-fabric or mesh gussets for flexibility and ventilation.",+ "definition_vi": "Các đốt ngón tay cong sẵn riêng lẻ, nối với nhau bằng vách ngăn vải co giãn hoặc lưới để tăng độ linh hoạt và thoáng khí.",+ "recognition_cues": [+ "Fingers show a natural pre-curved rest pose rather than lying flat",+ "Thin, differently-textured strips (mesh/stretch fabric) visible between adjacent fingers"+ ],+ "recognition_cues_vi": [+ "Ngón tay có tư thế nghỉ cong sẵn tự nhiên thay vì nằm thẳng",+ "Các dải mỏng, kết cấu khác biệt (lưới/vải co giãn) thấy được giữa các ngón tay liền kề"+ ],+ "threejs_target": "Slightly pre-curved CapsuleGeometry/tube segments per finger joint, thin plane-strip gusset geometry between finger meshes"+ },+ {+ "name": "Wrist Strap / Closure",+ "name_vi": "Đai khóa cổ tay",+ "definition": "Hook-and-loop (Velcro) strap combined with neoprene to secure the glove firmly at the wrist.",+ "definition_vi": "Dây đai khóa dán (Velcro) kết hợp với neoprene để cố định chắc chắn găng tay tại cổ tay.",+ "recognition_cues": [+ "Overlapping strap with a visible rough/looped fastener patch at the cuff, distinct stitched seam"+ ],+ "recognition_cues_vi": [+ "Dây đai chồng lên nhau có miếng khóa dán nhám/có móc thấy rõ ở cổ tay, đường may rõ rệt"+ ],+ "threejs_target": "Flat ExtrudeGeometry strap band wrapped around the cuff cylinder, with a small rectangular fastener-patch submesh"+ }+ ]+ },+ "finish_pattern_rarity": [+ {+ "name": "Case Hardened Blue Gem Pattern",+ "name_vi": "Mẫu Case Hardened Blue Gem",+ "definition": "A metallic oxidation pattern on Case Hardened skins where paint_seed determines the position/density of blue oxide clusters on the blade/gun surface; tiered by percentage of blue coverage on the playside.",+ "definition_vi": "Mẫu oxy hóa kim loại trên skin Case Hardened, trong đó paint_seed quyết định vị trí/mật độ cụm oxit xanh trên bề mặt lưỡi dao/súng; phân tầng theo phần trăm độ phủ xanh ở mặt playside.",+ "recognition_cues": [+ "Blend of blue (high-oxidation), purple (transition), and yellow/gold (base alloy steel) blotches",+ "Tier 1 'God Tier': one large continuous blue cluster covering most of the playside (examples reach 94-99% coverage)",+ "Tier 2-3: blue coverage interrupted by yellow/gold patches or concentrated more on the backside than playside",+ "Gold Gems are the visual inverse — near-total gold coverage with minimal blue"+ ],+ "recognition_cues_vi": [+ "Pha trộn các vệt xanh dương (oxy hóa cao), tím (chuyển tiếp) và vàng/vàng kim (thép hợp kim nền)",+ "Tier 1 'God Tier': một cụm xanh lớn liên tục che phủ gần hết mặt playside (một số ví dụ đạt 94-99% độ phủ)",+ "Tier 2-3: độ phủ xanh bị gián đoạn bởi mảng vàng/vàng kim hoặc tập trung nhiều ở mặt sau hơn mặt playside",+ "Gold Gems là hình ảnh đảo ngược — gần như toàn bộ phủ vàng kim, rất ít xanh"+ ],+ "threejs_target": "Procedural gradient/noise-driven vertex color or texture blend across the blade UV, parameterized by a seed value driving cluster position and blue/purple/gold color ramp",+ "applies_to": [+ "knife",+ "rifle"+ ]+ },+ {+ "name": "Doppler Phases & Gem Variants",+ "name_vi": "Các Phase Doppler và biến thể đá quý",+ "definition": "A family of Doppler knife finishes (Phase 1-4, Ruby, Sapphire, Black Pearl) distinguished by dominant color combination and the presence/absence of an iridescent color-shift effect.",+ "definition_vi": "Nhóm các finish dao Doppler (Phase 1-4, Ruby, Sapphire, Black Pearl) phân biệt qua tổ hợp màu chủ đạo và có/không có hiệu ứng đổi màu ngũ sắc.",+ "recognition_cues": [+ "Phase 1: black-dominant with sparse pink/purple streaks",+ "Phase 2: vivid pink+purple covering nearly the whole surface, most colorful phase",+ "Phase 3: black/deep-blue/green mix — green presence is the unique tell for this phase",+ "Phase 4: bright blue dominant with small black patches",+ "Ruby: 100% uniform red, no black patches",+ "Sapphire: 100% uniform blue, no black patches",+ "Black Pearl: dark purple/black base with a view-angle-dependent iridescent purple-to-green shift — unique among all phases"+ ],+ "recognition_cues_vi": [+ "Phase 1: đen chiếm ưu thế với vệt hồng/tím thưa thớt",+ "Phase 2: hồng+tím rực rỡ phủ gần toàn bộ bề mặt, phase nhiều màu nhất",+ "Phase 3: pha trộn đen/xanh dương đậm/xanh lá — sự xuất hiện của xanh lá là dấu hiệu riêng của phase này",+ "Phase 4: xanh dương sáng chiếm ưu thế với vài mảng đen nhỏ",+ "Ruby: đỏ đồng nhất 100%, không có mảng đen",+ "Sapphire: xanh dương đồng nhất 100%, không có mảng đen",+ "Black Pearl: nền tím đậm/đen với hiệu ứng đổi màu tím-sang-xanh lá ngũ sắc tùy góc nhìn — độc nhất trong các phase"+ ],+ "threejs_target": "Binary metalness (1.0) + dynamic color-ramp lookup driven by 3D noise coordinates and view-angle (fresnel-like) term for the iridescent shift; implement as a custom shader/TSL node reading a color-ramp texture keyed by noise + viewDir·normal",+ "applies_to": [+ "knife"+ ]+ },+ {+ "name": "Fade Pattern Percentage",+ "name_vi": "Tỷ lệ mẫu Fade",+ "definition": "A gradient finish (purple→pink/magenta→yellow/gold) whose 'fade %' is estimated from how much yellow coverage reaches the tip vs. how much unpainted gray substrate remains.",+ "definition_vi": "Finish dạng gradient (tím→hồng/magenta→vàng/vàng kim), tỷ lệ '% fade' được ước lượng qua độ phủ vàng đến mũi so với phần chất nền xám chưa sơn còn lại.",+ "recognition_cues": [+ "Purple/blue always at the base, magenta/pink in the middle, yellow/gold at the tip — yellow coverage is the key percentage indicator",+ "100% (Full Fade): yellow fully covers the tip, gradient runs its full length, no gray substrate visible",+ "80% (Minimum Fade): little to no yellow, dominated by pink/purple with visible gray patches",+ "Karambit/Talon knives are graded by ratio (e.g. 90/10 pink/purple) rather than gray-substrate percentage",+ "Some knives (Falchion) can exceed 100% when the gradient spills onto the handle"+ ],+ "recognition_cues_vi": [+ "Tím/xanh dương luôn ở gốc, hồng/magenta ở giữa, vàng/vàng kim ở mũi — độ phủ vàng là chỉ số phần trăm chính",+ "100% (Full Fade): vàng phủ kín mũi, gradient chạy hết chiều dài, không còn thấy nền xám",+ "80% (Fade tối thiểu): rất ít hoặc không có vàng, chủ yếu hồng/tím với các mảng xám còn thấy rõ",+ "Dao Karambit/Talon được đánh giá theo tỷ lệ (vd. 90/10 hồng/tím) thay vì phần trăm nền xám",+ "Một số dao (Falchion) có thể vượt quá 100% khi gradient tràn sang cả cán dao"+ ],+ "threejs_target": "Anodized Airbrushed rendering path (Style 5): triplanar-mapped radial gradient, parameterized by a rotation angle theta derived from paint_seed feeding a purple→pink→yellow color ramp",+ "applies_to": [+ "knife",+ "rifle",+ "pistol",+ "smg",+ "sniper"+ ]+ },+ {+ "name": "Sticker Placement & Layering",+ "name_vi": "Vị trí và Phân lớp Sticker",+ "definition": "Free-placement decal system using relative offset/rotation/scale within preset UV slots, with apply-order-based (not slot-order) layering.",+ "definition_vi": "Hệ thống decal đặt tự do dùng offset/xoay/tỷ lệ tương đối trong các slot UV cài sẵn, phân lớp theo thứ tự áp dụng (không phải thứ tự slot).",+ "recognition_cues": [+ "Decal-like flat graphic sitting on top of the base weapon skin, offset/rotated freely rather than fixed to a single spot",+ "Newer stickers always render on top of older ones regardless of slot number — layering order = application order",+ "Most weapons support 5 sticker slots (MP5-SD supports 8)"+ ],+ "recognition_cues_vi": [+ "Đồ họa phẳng dạng decal nằm trên skin súng gốc, có thể lệch/xoay tự do thay vì cố định một vị trí",+ "Sticker dán sau luôn hiển thị đè lên sticker cũ hơn bất kể số thứ tự slot — thứ tự lớp = thứ tự áp dụng",+ "Hầu hết súng hỗ trợ 5 slot sticker (MP5-SD hỗ trợ 8)"+ ],+ "threejs_target": "Multiple decal planes (PlaneGeometry or projected decal texture) parented to weapon UV reference nodes, z-offset ordered by application timestamp, transform driven by offset_x/offset_y/rotation/scale parameters",+ "applies_to": [+ "rifle",+ "pistol",+ "smg",+ "sniper",+ "heavy"+ ]+ },+ {+ "name": "CS2 Rarity Tier System",+ "name_vi": "Hệ thống cấp độ hiếm CS2",+ "definition": "Color-coded rarity ladder (Consumer Grade through Contraband/Extraordinary) shown as a UI border color, also loosely correlating with unbox probability.",+ "definition_vi": "Thang phân cấp độ hiếm có mã màu (từ Consumer Grade đến Contraband/Extraordinary) hiển thị dưới dạng màu viền UI, cũng tương quan lỏng lẻo với xác suất mở hòm.",+ "recognition_cues": [+ "Consumer Grade: light blue-gray #B0C3D9",+ "Industrial Grade: light blue #5E98D9",+ "Mil-Spec: blue #4B69FF",+ "Restricted: purple #8847FF",+ "Classified: pink/magenta #D32CE6",+ "Covert: red #EB4B4B",+ "Contraband / ★ Extraordinary: gold #E4AE39 or #FFD700"+ ],+ "recognition_cues_vi": [+ "Consumer Grade: xanh xám nhạt #B0C3D9",+ "Industrial Grade: xanh dương nhạt #5E98D9",+ "Mil-Spec: xanh dương #4B69FF",+ "Restricted: tím #8847FF",+ "Classified: hồng/magenta #D32CE6",+ "Covert: đỏ #EB4B4B",+ "Contraband / ★ Extraordinary: vàng kim #E4AE39 hoặc #FFD700"+ ],+ "threejs_target": "UI-only metadata field (rarity color) attached to the reconstruction metadata schema — not a shader input, but useful for labeling/QA of generated assets",+ "applies_to": [+ "rifle",+ "pistol",+ "knife",+ "smg",+ "sniper",+ "heavy",+ "gloves"+ ]+ },+ {+ "name": "CS2 Quality Types",+ "name_vi": "Các loại chất lượng CS2",+ "definition": "Item-quality prefixes (Normal, Genuine, Vintage, Unusual, StatTrak, Souvenir) that can alter the 3D model itself, not just rarity color.",+ "definition_vi": "Tiền tố chất lượng vật phẩm (Normal, Genuine, Vintage, Unusual, StatTrak, Souvenir) có thể thay đổi chính mô hình 3D, không chỉ màu độ hiếm.",+ "recognition_cues": [+ "StatTrak: an added orange-glow LED counter submesh on guns, or a kill-count number etched into the main color channel on knives",+ "Souvenir: always paired with 4 fixed gold-plated stickers representing tournament/team/MVP",+ "Unusual (gloves): triggers a custom inspect loop and swaps in a distinct glove model"+ ],+ "recognition_cues_vi": [+ "StatTrak: có thêm submesh bộ đếm LED phát sáng cam trên súng, hoặc số lần hạ gục khắc vào kênh màu chính trên dao",+ "Souvenir: luôn đi kèm 4 sticker mạ vàng cố định đại diện giải đấu/đội tuyển/MVP",+ "Unusual (găng tay): kích hoạt vòng lặp inspect tùy chỉnh và thay thế bằng mô hình găng tay riêng biệt"+ ],+ "threejs_target": "Conditional child-mesh injection in the asset graph (e.g. add ST_counter submesh with emissive #FF4500) driven by a quality metadata flag",+ "applies_to": [+ "rifle",+ "pistol",+ "knife",+ "smg",+ "sniper",+ "heavy",+ "gloves"+ ]+ },+ {+ "name": "Wear / Float Level System",+ "name_vi": "Hệ thống độ mòn / Float",+ "definition": "Permanent 0.00-1.00 float value fixed at item creation, mapped to five wear-level bands (Factory New, Minimal Wear, Field-Tested, Well-Worn, Battle-Scarred) each with characteristic surface degradation.",+ "definition_vi": "Giá trị float cố định vĩnh viễn từ 0.00-1.00 khi tạo vật phẩm, ánh xạ sang năm dải cấp độ mòn (Factory New, Minimal Wear, Field-Tested, Well-Worn, Battle-Scarred), mỗi cấp có đặc điểm xuống cấp bề mặt riêng.",+ "recognition_cues": [+ "Factory New [0.00-0.07): near-perfect finish, at most barely-visible edge scuffing",+ "Minimal Wear [0.07-0.15): small micro-scratches at corners, paint intact on ~95% of surface",+ "Field-Tested [0.15-0.38): clearly visible scratches/chips, paint starting to peel at edges, reduced gloss",+ "Well-Worn [0.38-0.45): large dense scratches exposing substrate, color oxidation/dulling",+ "Battle-Scarred [0.45-1.00]: near-total paint loss, deep gouges, dirt/grunge accumulation",+ "Weathering is geometry-aware: curvature maps concentrate scratches on sharp edges, AO maps protect recesses (which instead darken/accumulate grime)"+ ],+ "recognition_cues_vi": [+ "Factory New [0.00-0.07): finish gần hoàn hảo, cùng lắm là trầy nhẹ khó thấy ở cạnh",+ "Minimal Wear [0.07-0.15): vết trầy nhỏ li ti ở góc, sơn còn nguyên ~95% bề mặt",+ "Field-Tested [0.15-0.38): vết trầy/mẻ thấy rõ, sơn bắt đầu bong ở cạnh, độ bóng giảm",+ "Well-Worn [0.38-0.45): vết trầy lớn dày đặc lộ chất nền, màu bị oxy hóa/xỉn",+ "Battle-Scarred [0.45-1.00]: mất sơn gần như hoàn toàn, vết lõm sâu, tích tụ bụi bẩn",+ "Sự xuống cấp có nhận biết hình học: bản đồ độ cong tập trung vết xước ở cạnh sắc, bản đồ AO bảo vệ chỗ lõm (thay vào đó tối màu/tích bụi)"+ ],+ "threejs_target": "Float value drives a mix() between pristine and worn material states via the Wearness Alpha Mask, curvature map, and AO map — see rendering_shader_mapping 'Wear-State Material Blend'",+ "applies_to": [+ "rifle",+ "pistol",+ "knife",+ "smg",+ "sniper",+ "heavy",+ "gloves"+ ]+ },+ {+ "name": "Weapon Charm Attachment",+ "name_vi": "Gắn kết Weapon Charm",+ "definition": "Independent decorative 3D meshes hung from a weapon via a skeletal spring-joint constraint, reacting dynamically to player movement and recoil.",+ "definition_vi": "Lưới 3D trang trí độc lập treo trên vũ khí qua ràng buộc khớp lò xo xương, phản ứng động theo chuyển động người chơi và độ giật.",+ "recognition_cues": [+ "A small independent 3D object hanging off the gun body, swinging/bouncing with recoil or movement rather than staying rigid",+ "Cast soft contact shadows onto the weapon surface at its anchor socket",+ "One charm per weapon max; sockets number in the dozens (e.g. ~17 on AWP, ~20 on AK-47) but avoid the grip/hand-contact zone"+ ],+ "recognition_cues_vi": [+ "Vật thể 3D độc lập nhỏ treo trên thân súng, đung đưa/nảy theo độ giật hoặc chuyển động thay vì đứng yên cứng nhắc",+ "Đổ bóng tiếp xúc mềm lên bề mặt vũ khí tại điểm neo",+ "Tối đa một charm mỗi vũ khí; số điểm neo lên đến hàng chục (vd. ~17 ở AWP, ~20 ở AK-47) nhưng tránh vùng tay cầm/tiếp xúc tay"+ ],+ "threejs_target": "Independent mesh with a spring-joint (soft constraint) parented to a named attachment socket on the weapon skeleton, simulated via a simple physics/spring update each frame",+ "applies_to": [+ "rifle",+ "pistol",+ "smg",+ "sniper",+ "heavy"+ ]+ },+ {+ "name": "Glove Float Cap Range",+ "name_vi": "Giới hạn Float của Găng tay",+ "definition": "Gloves use a compressed float range (0.06-0.80) compared to weapons (0.00-1.00), making a given float value read as visually more worn on gloves than on a gun.",+ "definition_vi": "Găng tay dùng dải float bị nén (0.06-0.80) so với vũ khí (0.00-1.00), khiến cùng một giá trị float trông mòn hơn về mặt thị giác trên găng tay so với trên súng.",+ "recognition_cues": [+ "Factory New band is unusually narrow: 0.06-0.07 only",+ "A glove at float 0.15 (nominally 'Minimal Wear') can look as worn as a Field-Tested gun at 0.35",+ "Wear shows most prominently on the knuckle guard, fingertips, and palm edges"+ ],+ "recognition_cues_vi": [+ "Dải Factory New bất thường hẹp: chỉ 0.06-0.07",+ "Găng tay ở float 0.15 (danh nghĩa 'Minimal Wear') có thể trông mòn tương đương súng Field-Tested ở 0.35",+ "Vết mòn thể hiện rõ nhất ở gù bảo vệ khớp, đầu ngón tay và cạnh lòng bàn tay"+ ],+ "threejs_target": "Same wear-state mix() shader as weapons but with wear_remap_min=0.06/wear_remap_max=0.80 applied before sampling the float-driven blend",+ "applies_to": [+ "gloves"+ ]+ },+ {+ "name": "CS2 Weapon Finish Styles",+ "name_vi": "Các kiểu Finish vũ khí CS2",+ "definition": "Nine distinct paint_style render architectures (Solid, Spray-Paint, Hydrographic, three Anodized variants, Patina, Custom Paint Job, Gunsmith) each with a different wear-erosion behavior.",+ "definition_vi": "Chín kiến trúc render paint_style riêng biệt (Solid, Spray-Paint, Hydrographic, ba biến thể Anodized, Patina, Custom Paint Job, Gunsmith), mỗi loại có hành vi bào mòn khác nhau.",+ "recognition_cues": [+ "Solid Color: flat uniform color, no pattern texture, wears straight to substrate",+ "Spray-Paint: tiling pattern via triplanar mapping, wears through layers sequentially",+ "Hydrographic: pattern tiled over native UVs simulating hydro-dipping, wears to substrate",+ "Anodized (chrome base + single color) / Anodized Multicolored (custom roughness in alpha) / Anodized Airbrushed (soft radial gradients, used for Fade) — all wear TO CHROME first, exposing bright chrome before bare substrate",+ "Patina: full-color image + normal map, iridescent view-angle sheen, never peels — instead darkens/desaturates/accumulates oxide with wear",+ "Custom Paint Job: non-tiled illustrative texture, peels/flakes to dark metal substrate via a Wearness Mask",+ "Gunsmith: hybrid Custom-Paint + Patina, grayscale mask splits regions into peeling-paint zones vs darkening-metal zones"+ ],+ "recognition_cues_vi": [+ "Solid Color: màu phẳng đồng nhất, không có texture pattern, mòn thẳng xuống chất nền",+ "Spray-Paint: pattern lặp qua triplanar mapping, mòn tuần tự qua từng lớp",+ "Hydrographic: pattern lặp trên UV gốc mô phỏng hydro-dipping, mòn xuống chất nền",+ "Anodized (nền chrome + một màu) / Anodized Multicolored (roughness tùy chỉnh trong alpha) / Anodized Airbrushed (gradient tỏa tròn mềm, dùng cho Fade) — tất cả đều mòn RA CHROME trước, lộ chrome sáng trước khi lộ chất nền",+ "Patina: ảnh đầy màu + normal map, ánh ngũ sắc theo góc nhìn, không bong tróc — thay vào đó tối màu/mất bão hòa/tích oxit khi mòn",+ "Custom Paint Job: texture minh họa không lặp, bong tróc lộ chất nền kim loại tối qua Wearness Mask",+ "Gunsmith: lai giữa Custom-Paint và Patina, mặt nạ grayscale chia vùng bong tróc sơn và vùng kim loại tối màu"+ ],+ "threejs_target": "Distinct shader path per paint_style value: triplanar UV projection for spray/anodized-airbrushed, native-UV tiling for hydrographic/patina/custom, each feeding a style-specific wear mix() function",+ "applies_to": [+ "rifle",+ "pistol",+ "smg",+ "sniper",+ "heavy"+ ]+ }+ ],+ "rendering_shader_mapping": [+ {+ "name": "MeshPhysicalMaterial Core PBR Fields",+ "name_vi": "Các trường PBR cốt lõi của MeshPhysicalMaterial",+ "definition": "The baseline Three.js material exposing direct scalar/map fields for the standard PBR channel set.",+ "definition_vi": "Vật liệu Three.js cơ bản cung cấp trực tiếp các trường vô hướng/bản đồ cho bộ kênh PBR tiêu chuẩn.",+ "recognition_cues": [+ "Use whenever a static (non-procedural) material fully described by baked textures is sufficient — the majority of extracted CS2 skins"+ ],+ "recognition_cues_vi": [+ "Dùng khi vật liệu tĩnh (không thủ tục) được mô tả đầy đủ bằng texture nướng sẵn là đủ — phần lớn skin CS2 trích xuất"+ ],+ "threejs_target": "new THREE.MeshPhysicalMaterial({ map, normalMap, roughnessMap, metalnessMap, aoMap, clearcoat, clearcoatRoughness })"+ },+ {+ "name": "CustomShaderMaterial (CSM) Weathering Hooks",+ "name_vi": "Móc nối phong hóa của CustomShaderMaterial (CSM)",+ "definition": "Extension library exposing csm_* output variables to inject procedural noise/masks into an otherwise-standard lit material, used for dynamic tarnish/patina effects.",+ "definition_vi": "Thư viện mở rộng cung cấp các biến đầu ra csm_* để chèn nhiễu/mặt nạ thủ tục vào vật liệu chiếu sáng tiêu chuẩn, dùng cho hiệu ứng xỉn màu/patina động.",+ "recognition_cues": [+ "Needed when wear/tarnish must be computed procedurally at runtime rather than fully pre-baked into a texture"+ ],+ "recognition_cues_vi": [+ "Cần khi độ mòn/xỉn màu phải được tính thủ tục tại runtime thay vì nướng sẵn hoàn toàn vào texture"+ ],+ "threejs_target": "csm_Roughness / csm_Metalness (procedural noise-driven overrides), csm_FragNormal (custom bump for patina), csm_DiffuseColor (mix base color with oxide/dirt color by mask)"+ },+ {+ "name": "TSL Node Functions for Weathering",+ "name_vi": "Các hàm nút TSL cho hiệu ứng phong hóa",+ "definition": "Three.js Shading Language (WebGPU) node-graph functions used to build procedural PBR materials, especially for blending pristine vs. weathered states.",+ "definition_vi": "Các hàm đồ thị nút của Three.js Shading Language (WebGPU) dùng để xây dựng vật liệu PBR thủ tục, đặc biệt để pha trộn trạng thái nguyên vẹn và trạng thái phong hóa.",+ "recognition_cues": [+ "Preferred over CSM on WebGPU-targeted builds; needed for float-driven wear blending and terrain-style masked effects"+ ],+ "recognition_cues_vi": [+ "Ưu tiên hơn CSM trên các bản build nhắm WebGPU; cần cho pha trộn độ mòn theo float và hiệu ứng mặt nạ kiểu địa hình"+ ],+ "threejs_target": "material.roughnessNode / .metalnessNode / .normalNode assigned mix(pristineVal, wornVal, wearMask) with smoothstep() for soft transition edges and texture()/varying() for sampling and vertex-to-fragment data"+ },+ {+ "name": "CSG Boolean Operations for Sub-Mesh Composition",+ "name_vi": "Các phép toán Boolean CSG để kết hợp Sub-Mesh",+ "definition": "Constructive solid geometry (union/subtract/intersect) for combining or cutting weapon/knife sub-meshes procedurally instead of hand-modeling every variant.",+ "definition_vi": "Hình học rắn cấu trúc (hợp/trừ/giao) để kết hợp hoặc cắt các sub-mesh vũ khí/dao theo thủ tục thay vì mô hình hóa thủ công từng biến thể.",+ "recognition_cues": [+ "Needed for hollowing barrels/handguards, drilling accessory-mount holes, or generating chamfered/cut geometric variants from primitive stacks"+ ],+ "recognition_cues_vi": [+ "Cần khi khoét rỗng nòng súng/ốp lót tay, khoan lỗ gắn phụ kiện, hoặc tạo các biến thể hình học vát/cắt từ chồng khối nguyên thủy"+ ],+ "threejs_target": "three-csg-ts (BSP-tree based, TypeScript) or three-bvh-csg for Subtract/Union/Intersect operations between BufferGeometry meshes"+ },+ {+ "name": "CylinderGeometry → Barrels & Round Components",+ "name_vi": "CylinderGeometry cho Nòng súng và các bộ phận tròn",+ "definition": "Maps to any barrel-like round-cross-section part.",+ "definition_vi": "Ánh xạ tới mọi bộ phận có tiết diện tròn dạng nòng.",+ "recognition_cues": [+ "Long uniform-cross-section round part (barrel, suppressor, muzzle brake body, cleaning rod, magazine tube)"+ ],+ "recognition_cues_vi": [+ "Bộ phận tròn có tiết diện đều dài (nòng súng, ống giảm thanh, thân bù giật, cần thông nòng, ống chứa đạn)"+ ],+ "threejs_target": "CylinderGeometry(radiusTop, radiusBottom, height); radiusTop=0 for conical shapes"+ },+ {+ "name": "BoxGeometry → Slides, Receivers & Grips",+ "name_vi": "BoxGeometry cho Khóa nòng, Thân súng và Tay cầm",+ "definition": "Maps to rectangular/blocky sub-assemblies.",+ "definition_vi": "Ánh xạ tới các cụm lắp ráp hình chữ nhật/khối.",+ "recognition_cues": [+ "Flat-faced, roughly rectangular volume (pistol slide, receiver/frame, grip, panel)"+ ],+ "recognition_cues_vi": [+ "Khối gần chữ nhật với các mặt phẳng (khóa nòng súng lục, thân/khung súng, tay cầm, tấm phẳng)"+ ],+ "threejs_target": "BoxGeometry(width, height, depth)"+ },+ {+ "name": "CapsuleGeometry → Rounded-Edge Components",+ "name_vi": "CapsuleGeometry cho các bộ phận có cạnh bo tròn",+ "definition": "Maps to components with hemispherical rounded ends.",+ "definition_vi": "Ánh xạ tới các bộ phận có đầu bo tròn dạng bán cầu.",+ "recognition_cues": [+ "Rod-like part with distinctly rounded (not flat-cut) ends, e.g. a knife spine or a safety lever"+ ],+ "recognition_cues_vi": [+ "Bộ phận dạng thanh có đầu bo tròn rõ rệt (không cắt phẳng), vd. sống dao hoặc cần an toàn"+ ],+ "threejs_target": "CapsuleGeometry(radius, length)"+ },+ {+ "name": "ExtrudeGeometry → Custom Blade/Silhouette Profiles",+ "name_vi": "ExtrudeGeometry cho hồ sơ lưỡi dao/đường viền tùy chỉnh",+ "definition": "Maps to any part defined by a unique 2D silhouette pushed into 3D depth with a bevel.",+ "definition_vi": "Ánh xạ tới bất kỳ bộ phận nào được định nghĩa bằng đường viền 2D độc nhất, đẩy vào chiều sâu 3D với cạnh vát.",+ "recognition_cues": [+ "Blade shape that doesn't match a simple primitive — distinctive curved hook (Karambit), curved clip point (Bowie), or other custom silhouette"+ ],+ "recognition_cues_vi": [+ "Hình dạng lưỡi dao không khớp với khối nguyên thủy đơn giản — móc cong đặc trưng (Karambit), điểm clip cong (Bowie), hoặc đường viền tùy chỉnh khác"+ ],+ "threejs_target": "ExtrudeGeometry(customTHREEShape, { depth, bevelEnabled, bevelThickness })"+ },+ {+ "name": "TorusGeometry → Rings & Loops",+ "name_vi": "TorusGeometry cho Vòng khuyên và Vòng lặp",+ "definition": "Maps to donut-shaped circular features.",+ "definition_vi": "Ánh xạ tới các chi tiết hình vòng tròn kiểu donut.",+ "recognition_cues": [+ "Circular loop feature — bayonet handle ring, finger loop on a Talon knife, trigger guard loop, carrying handle"+ ],+ "recognition_cues_vi": [+ "Chi tiết vòng tròn — vòng cán lưỡi lê, vòng ngón tay trên dao Talon, vòng vành bảo vệ cò, tay xách"+ ],+ "threejs_target": "TorusGeometry(radius, tube, radialSegments, tubularSegments)"+ },+ {+ "name": "LatheGeometry → Turned/Radially-Symmetric Parts",+ "name_vi": "LatheGeometry cho các bộ phận tiện/đối xứng trục",+ "definition": "Maps to parts generated by revolving a 2D profile around an axis.",+ "definition_vi": "Ánh xạ tới các bộ phận tạo ra bằng cách xoay một biên dạng 2D quanh một trục.",+ "recognition_cues": [+ "Contoured, fully radially-symmetric part — turned wood/metal handle, some muzzle device shapes, adjustment knobs"+ ],+ "recognition_cues_vi": [+ "Bộ phận có biên dạng, đối xứng trục hoàn toàn — cán gỗ/kim loại tiện, một số hình dạng đầu nòng, núm điều chỉnh"+ ],+ "threejs_target": "LatheGeometry(points[], segments) where points is a 2D profile curve revolved around the Y-axis"+ },+ {+ "name": "TubeGeometry → Straps, Cables & Belts",+ "name_vi": "TubeGeometry cho Dây đai, Cáp và Dây băng đạn",+ "definition": "Maps to flexible components following a 3D curve.",+ "definition_vi": "Ánh xạ tới các bộ phận mềm dẻo chạy theo một đường cong 3D.",+ "recognition_cues": [+ "Flexible, curve-following linear component — sling strap, pressure-switch cable, ammo belt draping into a receiver"+ ],+ "recognition_cues_vi": [+ "Bộ phận tuyến tính mềm dẻo chạy theo đường cong — dây đeo súng, cáp công tắc áp lực, dây băng đạn thõng vào thân súng"+ ],+ "threejs_target": "TubeGeometry(curve, tubularSegments, radius, radialSegments)"+ },+ {+ "name": "ConeGeometry → Tapered Tips",+ "name_vi": "ConeGeometry cho các đầu thon nhọn",+ "definition": "Maps to tapered projectile-like or pointed components.",+ "definition_vi": "Ánh xạ tới các bộ phận thon nhọn giống đầu đạn hoặc có mũi nhọn.",+ "recognition_cues": [+ "Tapered pointed shape narrowing to a point — projectile tips, some conical muzzle device shapes"+ ],+ "recognition_cues_vi": [+ "Hình thon nhọn thu về một điểm — đầu đạn, một số hình dạng đầu nòng dạng nón"+ ],+ "threejs_target": "ConeGeometry(radius, height, radialSegments)"+ },+ {+ "name": "sRGB / Linear Color Space Assignment",+ "name_vi": "Gán không gian màu sRGB / Linear",+ "definition": "The mandatory Three.js r152+ rule for tagging each texture as human-viewable color vs. mathematical data before assigning it to a material slot.",+ "definition_vi": "Quy tắc bắt buộc từ Three.js r152+ để gán nhãn mỗi texture là màu để người xem hay dữ liệu toán học trước khi gán vào khe vật liệu.",+ "recognition_cues": [+ "Any imported texture that looks like a natural photo → sRGB; any texture that looks like flat gray/colored data noise → NoColorSpace"+ ],+ "recognition_cues_vi": [+ "Bất kỳ texture nhập vào trông như ảnh tự nhiên → sRGB; bất kỳ texture trông như nhiễu dữ liệu xám/màu phẳng → NoColorSpace"+ ],+ "threejs_target": "texture.colorSpace = THREE.SRGBColorSpace (map, emissiveMap) or THREE.NoColorSpace (normalMap, roughnessMap, metalnessMap, aoMap)"+ },+ {+ "name": "ORM Packed Texture Assignment",+ "name_vi": "Gán texture đóng gói ORM",+ "definition": "Assigning one R/G/B-packed texture file to three separate MeshPhysicalMaterial slots simultaneously, per the glTF ORM convention.",+ "definition_vi": "Gán một file texture đóng gói R/G/B vào ba khe riêng biệt của MeshPhysicalMaterial cùng lúc, theo quy ước ORM của glTF.",+ "recognition_cues": [+ "Source 2/CS2 exports often ship AO/Roughness/Metalness pre-packed into one file rather than three separate grayscale images"+ ],+ "recognition_cues_vi": [+ "Bản xuất từ Source 2/CS2 thường đóng gói sẵn AO/Roughness/Metalness vào một file thay vì ba ảnh grayscale riêng"+ ],+ "threejs_target": "material.aoMap = material.roughnessMap = material.metalnessMap = packedTexture (each field reads its designated R/G/B channel automatically)"+ },+ {+ "name": "UV/Coordinate System Conversion & Attachment Hierarchy",+ "name_vi": "Chuyển đổi hệ tọa độ UV và Phân cấp gắn kết",+ "definition": "Handling handedness/up-axis differences (Unity Y-up left-handed vs. USD/glTF right-handed) and representing sub-part attachment via parent-child scene-graph transforms.",+ "definition_vi": "Xử lý khác biệt tay thuận/trục lên (Unity Y-up trái vs. USD/glTF phải) và biểu diễn gắn kết sub-part qua transform cha-con trong scenegraph.",+ "recognition_cues": [+ "A sub-part (scope, blade, strap) that appears mirrored or flipped sideways after import signals a handedness mismatch",+ "Attachment points behave like named sockets/joints (Unreal sockets, USD UsdPhysicsFixedJoint, 'ghost links') — a local offset+rotation relative to a parent node"+ ],+ "recognition_cues_vi": [+ "Một sub-part (kính ngắm, lưỡi dao, dây đeo) bị lật ngược hoặc lệch sau khi import báo hiệu sai lệch tay thuận",+ "Điểm gắn kết hoạt động như socket/joint có tên (Unreal sockets, USD UsdPhysicsFixedJoint, 'ghost link') — một offset+xoay cục bộ tương đối với node cha"+ ],+ "threejs_target": "THREE.Object3D parent-child hierarchy with each sub-part's local .position/.quaternion set to the source engine's named attachment-socket transform; flip texture.flipY / negate one axis if handedness mismatches"+ },+ {+ "name": "Reconstruction Metadata Schema",+ "name_vi": "Schema Metadata cho Tái tạo",+ "definition": "A structured metadata envelope (identity, extraction provenance, geometry stats, texture-slot mapping, rights) accompanying each reconstructed asset to drive and audit the pipeline.",+ "definition_vi": "Một gói metadata có cấu trúc (định danh, nguồn gốc trích xuất, thống kê hình học, ánh xạ khe texture, quyền sở hữu) đi kèm mỗi tài sản tái tạo để điều khiển và kiểm tra pipeline.",+ "recognition_cues": [+ "Needed whenever an agent must trace a generated Three.js asset back to its source skin/paint_seed/rarity for QA or reproducibility"+ ],+ "recognition_cues_vi": [+ "Cần khi agent phải truy vết một tài sản Three.js đã tạo về lại skin/paint_seed/độ hiếm nguồn để QA hoặc tái lập"+ ],+ "threejs_target": "JSON sidecar: { weapon_id, paint_index, skin_id, min_float, max_float, rarity, category, source_tool, source_path, checksum, face_count, vertex_count, bounding_box, texture_slots: {slot: colorSpace}, paint_seed, rights }"+ }+ ],+ "description_conventions": [+ {+ "name": "CDWA Semantic Field Mapping",+ "name_vi": "Ánh xạ trường ngữ nghĩa CDWA",+ "definition": "Top-level object-description keys from the Categories for the Description of Works of Art standard (Object/Work Type, Classification, Measurements, Materials/Techniques, Subject Matter).",+ "definition_vi": "Các khóa mô tả đối tượng cấp cao nhất từ chuẩn Categories for the Description of Works of Art (Loại đối tượng, Phân loại, Kích thước, Vật liệu/Kỹ thuật, Chủ đề).",+ "recognition_cues": [+ "Use as the top-level schema keys whenever an agent must produce a structured (not prose) description of a reference image"+ ],+ "recognition_cues_vi": [+ "Dùng làm các khóa schema cấp cao nhất bất cứ khi nào agent phải tạo mô tả có cấu trúc (không phải văn xuôi) cho ảnh tham chiếu"+ ],+ "threejs_target": "Top-level JSON keys: objectType, classification, measurements, materials, subjectMatter — populated per reference image before any 3D generation step"+ },+ {+ "name": "VRA Core 4.0 Attribute-Value Schema",+ "name_vi": "Schema Thuộc tính-Giá trị VRA Core 4.0",+ "definition": "XML-derived global attribute qualifiers (vocab, refid, xml:lang, extent) that make every described data element machine-readable and scoped.",+ "definition_vi": "Các bộ định tính thuộc tính toàn cục có nguồn gốc XML (vocab, refid, xml:lang, extent) giúp mỗi phần tử dữ liệu được mô tả có thể đọc bằng máy và có phạm vi rõ ràng.",+ "recognition_cues": [+ "Any attribute-value pair should carry an 'extent' qualifier stating whether it describes the whole object or one sub-part — ambiguity here is the most common schema mistake"+ ],+ "recognition_cues_vi": [+ "Mọi cặp thuộc tính-giá trị nên mang bộ định tính 'extent' cho biết nó mô tả toàn bộ đối tượng hay một sub-part — sự mơ hồ này là lỗi schema phổ biến nhất"+ ],+ "threejs_target": "Per-field metadata: { value, vocab, extent } attached to each material/measurement/attribute entry in the reconstruction metadata schema"+ },+ {+ "name": "Scene-Graph Relational Triplets",+ "name_vi": "Bộ ba quan hệ Scene-Graph",+ "definition": "<Subject, Predicate, Object> statements capturing spatial/semantic relationships between parts (e.g. <blade, attached_to, handle>), plus per-node bounding box and class label.",+ "definition_vi": "Các phát biểu <Chủ thể, Vị ngữ, Đối tượng> nắm bắt quan hệ không gian/ngữ nghĩa giữa các bộ phận (vd. <lưỡi dao, gắn_vào, cán dao>), cộng với bounding box và nhãn lớp cho mỗi node.",+ "recognition_cues": [+ "Use whenever the pipeline needs a machine-readable assembly blueprint rather than a free-text description of how parts relate spatially"+ ],+ "recognition_cues_vi": [+ "Dùng khi pipeline cần một bản thiết kế lắp ráp máy đọc được thay vì mô tả văn bản tự do về cách các bộ phận liên hệ không gian"+ ],+ "threejs_target": "Array of {subject, predicate, object} triplets driving the THREE.Object3D parent-child attachment hierarchy (see 'UV/Coordinate System Conversion & Attachment Hierarchy')"+ },+ {+ "name": "Feldman Method (Description + Analysis Stages)",+ "name_vi": "Phương pháp Feldman (giai đoạn Mô tả + Phân tích)",+ "definition": "Structured visual-analysis discipline enforcing Description → Analysis → Interpretation → Judgment; only the first two stages matter for reconstruction, and value-laden adjectives are banned in favor of neutral visual pointers.",+ "definition_vi": "Kỷ luật phân tích thị giác có cấu trúc buộc theo trình tự Mô tả → Phân tích → Diễn giải → Đánh giá; chỉ hai giai đoạn đầu quan trọng cho tái tạo, và tính từ mang tính đánh giá bị cấm, thay bằng các chỉ điểm thị giác trung lập.",+ "recognition_cues": [+ "A description using words like 'beautiful' or 'elegant' has leaked into Interpretation/Judgment and should be rejected",+ "Acceptable pointers are strictly visual: straight, curved, large, small, symmetric, textured"+ ],+ "recognition_cues_vi": [+ "Một mô tả dùng từ như 'đẹp' hay 'tinh tế' đã lấn sang giai đoạn Diễn giải/Đánh giá và nên bị loại bỏ",+ "Các chỉ điểm chấp nhận được chỉ mang tính thị giác thuần túy: thẳng, cong, lớn, nhỏ, đối xứng, có kết cấu"+ ],+ "threejs_target": "A description-generation prompt/filter step that rejects or rewrites any adjective not drawn from a controlled visual-pointer vocabulary before the schema is populated"+ },+ {+ "name": "Drill-Down Macro-to-Micro Decomposition",+ "name_vi": "Phân rã Macro-đến-Micro (Drill-Down)",+ "definition": "Description ordering convention: start with a brief overall-form summary (the 'gist'), then decompose into parts, then into geometric primitives.",+ "definition_vi": "Quy ước thứ tự mô tả: bắt đầu bằng tóm tắt hình dạng tổng thể ngắn gọn ('gist'), sau đó phân rã thành các bộ phận, rồi thành các khối nguyên thủy hình học.",+ "recognition_cues": [+ "A good description names the whole object first ('a bowie-style knife'), then its components ('blade, bolster, handle scales'), then each component's basic solid shape"+ ],+ "recognition_cues_vi": [+ "Một mô tả tốt gọi tên toàn bộ đối tượng trước ('dao kiểu bowie'), sau đó các bộ phận ('lưỡi, đệm cán, ốp cán'), rồi hình khối cơ bản của từng bộ phận"+ ],+ "threejs_target": "Nested JSON structure: { gist, components: [{ name, primitiveShape, ... }] } mirroring the geometry_anatomy category's per-part entries"+ },+ {+ "name": "Controlled Vocabulary (AAT Facets)",+ "name_vi": "Từ vựng có kiểm soát (Facet AAT)",+ "definition": "Standardized terminology (Getty Art & Architecture Thesaurus facets for materials, activities, physical attributes) replacing vague or inconsistent free-text terms.",+ "definition_vi": "Thuật ngữ chuẩn hóa (các facet của Getty Art & Architecture Thesaurus cho vật liệu, hoạt động, thuộc tính vật lý) thay thế các từ tự do mơ hồ hoặc không nhất quán.",+ "recognition_cues": [+ "Material/attribute terms should be drawn from a fixed enumerated list (e.g. 'brushed steel', 'anodized aluminum') rather than free-form phrasing that varies between descriptions of the same material"+ ],+ "recognition_cues_vi": [+ "Thuật ngữ vật liệu/thuộc tính nên lấy từ danh sách liệt kê cố định (vd. 'thép chải xước', 'nhôm anod hóa') thay vì cách diễn đạt tự do thay đổi giữa các mô tả của cùng một vật liệu"+ ],+ "threejs_target": "Enum-constrained metadata fields (materialType, finishStyle) validated against a fixed controlled-vocabulary list before being written to the reconstruction schema"+ },+ {+ "name": "Honest-Uncertainty / Single-Image-Limits Convention",+ "name_vi": "Quy ước Trung thực về Bất định / Giới hạn Ảnh Đơn",+ "definition": "Explicit marking of occluded or back-face regions as 'undetermined' rather than inventing plausible-looking detail not visible in the reference.",+ "definition_vi": "Đánh dấu rõ ràng các vùng bị che khuất hoặc mặt sau là 'chưa xác định' thay vì bịa ra chi tiết trông hợp lý nhưng không thấy trong ảnh tham chiếu.",+ "recognition_cues": [+ "Any attribute for a surface not visible in the reference image should be flagged explicitly rather than filled with a guessed value",+ "This is a hard constraint against hallucinated geometry/material detail feeding into the reconstruction"+ ],+ "recognition_cues_vi": [+ "Bất kỳ thuộc tính nào của bề mặt không thấy được trong ảnh tham chiếu nên được đánh dấu rõ ràng thay vì điền giá trị đoán mò",+ "Đây là ràng buộc cứng chống lại việc bịa chi tiết hình học/vật liệu đưa vào tái tạo"+ ],+ "threejs_target": "Sentinel value \"undetermined\" (or null + a needsAnotherView:true flag) written into any metadata field the agent cannot verify from the given reference image(s)"+ },+ {+ "name": "PBR Vocabulary Caption Calibration",+ "name_vi": "Hiệu chỉnh Chú thích theo Từ vựng PBR",+ "definition": "Embedding a technical material-attribute block (Albedo, Metalness, Roughness, Normals) with measured reflectance ranges directly into the structured description, not just prose.",+ "definition_vi": "Nhúng một khối thuộc tính vật liệu kỹ thuật (Albedo, Metalness, Roughness, Normals) với các dải phản xạ đo lường được trực tiếp vào mô tả có cấu trúc, không chỉ văn xuôi.",+ "recognition_cues": [+ "A reconstruction-ready description states measured-style values, e.g. 'raw metal reflectance sRGB 180-255' or 'dielectric F0 ≈ 0.04', not just 'shiny' or 'metallic-looking'"+ ],+ "recognition_cues_vi": [+ "Một mô tả sẵn sàng cho tái tạo nêu giá trị kiểu đo lường, vd. 'phản xạ kim loại thô sRGB 180-255' hoặc 'F0 điện môi ≈ 0.04', không chỉ 'bóng' hay 'trông như kim loại'"+ ],+ "threejs_target": "A materialHints sub-object { albedoRangeSRGB, metalness: 0|1, roughnessEstimate, f0Estimate } embedded per-component in the structured description, feeding directly into initial MeshPhysicalMaterial parameter guesses"+ }+ ]+ }+}\ No newline at end of filediff --git a/docs/specs/vocabulary/README.md b/docs/specs/vocabulary/README.mdnew file mode 100644index 0000000..2d2d91a--- /dev/null+++ b/docs/specs/vocabulary/README.md@@ -0,0 +1,86 @@+# Normalized spec-record vocabulary++This directory holds reviewed, committed JSONL records for local specification+search. Each non-empty line is exactly one UTF-8 JSON object. A collection may+have no record file yet, but every row in a present record file must satisfy+this contract.++## Future ingestion seam++Todo 3 must expose `load_jsonl_records(path: Path)` from+`forge._shared.spec_search`. It returns validated records and raises+`SpecRecordValidationError` for malformed JSON, a non-object JSON value, a+missing required field, or a value with the wrong type. The error identifies+the input path and one-based line number. Invalid rows are never skipped or+silently repaired.++## Canonical row++```json+{+ "record_id": "cs2.karambit.safety-ring",+ "collection": "cs2",+ "domain": "weapon-anatomy",+ "kind": "component",+ "entity": "karambit safety ring",+ "title": "Karambit safety ring / Vòng ngón Karambit",+ "aliases": ["safety ring", "finger ring", "vòng ngón"],+ "content": "A retention ring at the Karambit's pommel.",+ "constraints": ["Preserve the opening as a distinct component."],+ "measurements": [+ {"name": "opening diameter", "value": "source-dependent", "unit": "mm"}+ ],+ "source_refs": [+ {+ "path": "docs/cs2/3D_Technical_Mapping.json",+ "key_path": "karambit.components.safety_ring"+ },+ {"path": "docs/cs2-anatomy/karambit.md", "heading": "Safety ring"}+ ],+ "evidence_refs": [+ {"kind": "source", "ref": "docs/cs2/3D_Technical_Mapping.json"}+ ],+ "observation_status": "observed",+ "confidence": 0.9,+ "assumptions": []+}+```++`record_id` is a stable, lowercase, dot-delimited identifier. It is never+derived from a display title and must remain stable when wording changes.+`collection` selects the owning search collection; `domain`, `kind`, and+`entity` classify the record without imposing a global taxonomy. `title`,+`aliases`, and `content` are searchable text. `aliases` preserve English and+Vietnamese terms as authored; normalization and query expansion happen later.++## Required fields and stable types++| Field | Type | Semantics |+| --- | --- | --- |+| `record_id` | non-empty string | Stable unique identifier within a collection. |+| `collection` | non-empty string | Collection key that owns the record. |+| `domain` | non-empty string | Domain grouping, such as `weapon-anatomy` or `pbr`. |+| `kind` | non-empty string | Record category, such as `component`, `material`, or `constraint`. |+| `entity` | non-empty string | Canonical entity or concept name. |+| `title` | non-empty string | Human-readable searchable title. |+| `aliases` | array of strings | Zero or more authored synonyms, including bilingual aliases where known. |+| `content` | string | Source-backed concise description; may be empty only when structured fields carry the searchable detail. |+| `constraints` | array of strings | Requirements, prohibitions, or caveats. |+| `measurements` | array of objects | Each object has non-empty string `name` and `value`; optional `unit` and `context` are strings. Values remain source text rather than invented numbers. |+| `source_refs` | non-empty array of objects | Provenance for the distilled statement. Every object has non-empty string `path` and may have non-empty string `heading` and/or `key_path`. |+| `evidence_refs` | array of objects | Supporting provenance. Every object has non-empty string `kind` and `ref`; optional `note` is a string. |+| `observation_status` | string | One of `observed`, `inferred`, or `unverified`. |+| `confidence` | number | Inclusive range `0.0` through `1.0`; confidence in the distilled statement, not search relevance. |+| `assumptions` | array of strings | Explicit assumptions that qualify the record. |++Records must preserve raw source locations. Use `heading` for a Markdown+section and `key_path` for a JSON location; a source reference may contain both+when a source format provides both forms of location. Paths are repository+relative and use forward slashes. `evidence_refs` may point to source files,+external identifiers, or review artifacts, but do not replace `source_refs`.++`observed` means directly supported by a cited source or reference artifact.+`inferred` means a reasoned interpretation retained with its assumptions.+`unverified` means useful terminology or a candidate claim that still needs+confirmation. Do not encode unsupported certainty: lower `confidence`, select+the appropriate status, and record the qualifying assumption instead.diff --git a/docs/specs/vocabulary/core_3d.jsonl b/docs/specs/vocabulary/core_3d.jsonlnew file mode 100644index 0000000..d6bf8ac--- /dev/null+++ b/docs/specs/vocabulary/core_3d.jsonl@@ -0,0 +1,12 @@+{"record_id":"core.component-hierarchy","collection":"core_3d","domain":"geometry","kind":"component","entity":"component hierarchy","title":"Component hierarchy / Phân cấp thành phần","aliases":["component","thành phần","macro","meso","micro","parent-child","cha-con"],"content":"Decompose an object into macro independent major parts, meso sub-assemblies, and micro feature groups in a parent-child hierarchy.","constraints":["Do not treat a component-based object as one monolithic mesh."],"measurements":[],"source_refs":[{"path":"grimoire/intake/image_analysis.md","heading":"Layer 3 — Macro → meso → micro decomposition"}],"evidence_refs":[{"kind":"source","ref":"grimoire/intake/image_analysis.md"},{"kind":"notebooklm-research","ref":"notebooklm:4b03c2f9-8393-411f-b5b4-039ab9532843","note":"Validated generic schema vocabulary; numeric claims remain backed by local source_refs."}],"observation_status":"observed","confidence":0.95,"assumptions":[]}+{"record_id":"core.transform-local-object-space","collection":"core_3d","domain":"transform","kind":"concept","entity":"local object-space relationship","title":"Local object-space relationship / Quan hệ không gian cục bộ","aliases":["object space","không gian đối tượng","local coordinates","tọa độ cục bộ","attached-to","gắn vào"],"content":"Describe connected parts in 3D object-space using spatial predicates and a contact type rather than 2D image-space placement.","constraints":["State how parts join; adjacency alone is insufficient."],"measurements":[],"source_refs":[{"path":"grimoire/intake/image_analysis.md","heading":"Layer 4 — Spatial relationships (scene-graph)"}],"evidence_refs":[{"kind":"source","ref":"grimoire/intake/image_analysis.md"},{"kind":"notebooklm-research","ref":"notebooklm:4b03c2f9-8393-411f-b5b4-039ab9532843","note":"Validated generic schema vocabulary; numeric claims remain backed by local source_refs."}],"observation_status":"observed","confidence":0.95,"assumptions":[]}+{"record_id":"core.coordinate-relative-units","collection":"core_3d","domain":"measurement","kind":"unit","entity":"object-relative unit","title":"Object-relative unit / Đơn vị tương đối theo đối tượng","aliases":["object-relative units","đơn vị tương đối","relative bevel radius","bán kính bo tương đối"],"content":"A bevel radius is sized in object-relative units.","constraints":["Use a named reference dimension when describing proportions instead of unsupported large/small claims."],"measurements":[{"name":"bevel radius","value":"object-relative units","context":"edge transition size"}],"source_refs":[{"path":"grimoire/glossary/3d_vocabulary.md","heading":"Geometry And Topology"},{"path":"grimoire/intake/image_analysis.md","heading":"Layer 2 — Overall form & silhouette"}],"evidence_refs":[{"kind":"source","ref":"grimoire/glossary/3d_vocabulary.md"},{"kind":"notebooklm-research","ref":"notebooklm:4b03c2f9-8393-411f-b5b4-039ab9532843","note":"Validated generic schema vocabulary; numeric claims remain backed by local source_refs."}],"observation_status":"observed","confidence":0.9,"assumptions":[]}+{"record_id":"core.measurement-source-text","collection":"core_3d","domain":"measurement","kind":"constraint","entity":"source-backed measurement","title":"Source-backed measurement / Đo lường có nguồn","aliases":["measurement","đo lường","proportion","tỷ lệ","reference dimension","kích thước tham chiếu"],"content":"Record proportions relative to a named reference dimension and keep observations separate from inference.","constraints":["Do not claim dimensions that are not supported by a source or visible reference."],"measurements":[{"name":"proportion basis","value":"named reference dimension"}],"source_refs":[{"path":"grimoire/intake/image_analysis.md","heading":"Layer 2 — Overall form & silhouette"},{"path":"grimoire/intake/image_analysis.md","heading":"The Rule"}],"evidence_refs":[{"kind":"source","ref":"grimoire/intake/image_analysis.md"},{"kind":"notebooklm-research","ref":"notebooklm:4b03c2f9-8393-411f-b5b4-039ab9532843","note":"Validated generic schema vocabulary; numeric claims remain backed by local source_refs."}],"observation_status":"observed","confidence":0.9,"assumptions":[]}+{"record_id":"core.topology-intent","collection":"core_3d","domain":"topology","kind":"concept","entity":"topology intent","title":"Topology intent / Mục đích cấu trúc lưới","aliases":["topology","cấu trúc lưới","topology intent","mục đích topology","edge loop","vòng cạnh"],"content":"Topology intent classifies a surface as hard-surface blockout, subdivision-ready, low-poly prop, organic deformed mesh, or alpha-card cluster.","constraints":["Choose topology intent before selecting a primitive."],"measurements":[],"source_refs":[{"path":"grimoire/glossary/3d_vocabulary.md","heading":"Geometry And Topology"}],"evidence_refs":[{"kind":"source","ref":"grimoire/glossary/3d_vocabulary.md"},{"kind":"notebooklm-research","ref":"notebooklm:4b03c2f9-8393-411f-b5b4-039ab9532843","note":"Validated generic schema vocabulary; numeric claims remain backed by local source_refs."}],"observation_status":"observed","confidence":0.95,"assumptions":[]}+{"record_id":"core.pbr-roughness","collection":"core_3d","domain":"pbr","kind":"material","entity":"roughness","title":"Roughness / Độ thô","aliases":["roughness","độ thô","độ nhám","matte","mờ","glossy","bóng"],"content":"Roughness is microfacet scatter: high roughness reads matte and low roughness reads glossy. Recognition cues: low roughness reads as a sharp, mirror-like, tight specular highlight; high roughness reads as a blurry, wide, dim highlight and matte appearance; worn/scratched regions show broken-up, uneven highlight shapes versus the smooth highlight of pristine areas. Dấu hiệu nhận diện: độ nhám thấp = điểm sáng specular sắc nét, giống gương; độ nhám cao = điểm sáng mờ, rộng, tối, bề mặt trông mờ đục; vùng bị mòn/trầy có hình dạng điểm sáng vỡ vụn so với vùng nguyên vẹn. Three.js target: MeshPhysicalMaterial.roughness (scalar) + .roughnessMap (green channel of packed ORM texture, NoColorSpace).","constraints":["Tie each material claim to a distinct component."],"measurements":[],"source_refs":[{"path":"grimoire/glossary/3d_vocabulary.md","heading":"Material And PBR"},{"path":"grimoire/intake/image_analysis.md","heading":"Layer 5 — Materials & surface (PBR)"},{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.material_pbr[1]"}],"evidence_refs":[{"kind":"source","ref":"grimoire/glossary/3d_vocabulary.md"},{"kind":"notebooklm-research","ref":"notebooklm:4b03c2f9-8393-411f-b5b4-039ab9532843","note":"Validated generic schema vocabulary; numeric claims remain backed by local source_refs."},{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation — merged recognition cues + Three.js target instead of duplicating this entity."}],"observation_status":"observed","confidence":0.95,"assumptions":[]}+{"record_id":"core.uv-strategy","collection":"core_3d","domain":"uv","kind":"concept","entity":"UV strategy","title":"UV strategy / Chiến lược UV","aliases":["UV","ánh xạ UV","UV strategy","chiến lược UV","cylindrical projection","chiếu trụ","atlas"],"content":"UV strategy can use generated procedural coordinates, cylindrical projection, triplanar-like mapping, or atlas-ready unwrapped regions.","constraints":["Select a mapping strategy appropriate to the surface and texture requirements."],"measurements":[],"source_refs":[{"path":"grimoire/glossary/3d_vocabulary.md","heading":"Geometry And Topology"}],"evidence_refs":[{"kind":"source","ref":"grimoire/glossary/3d_vocabulary.md"},{"kind":"notebooklm-research","ref":"notebooklm:4b03c2f9-8393-411f-b5b4-039ab9532843","note":"Validated generic schema vocabulary; numeric claims remain backed by local source_refs."}],"observation_status":"observed","confidence":0.95,"assumptions":[]}+{"record_id":"core.runtime-hierarchy","collection":"core_3d","domain":"runtime","kind":"hierarchy","entity":"action-ready runtime hierarchy","title":"Runtime hierarchy / Phân cấp thời gian chạy","aliases":["runtime hierarchy","phân cấp runtime","root","visual mesh","lưới hiển thị","collider","va chạm"],"content":"An action-ready model uses a root, component pivot groups, visual meshes, sockets, collider metadata or proxies, and destruction-group metadata.","constraints":["Do not deliver a single decorative mesh when future actions need named targets."],"measurements":[],"source_refs":[{"path":"grimoire/readiness/action_rigging.md","heading":"Hierarchy Pattern"}],"evidence_refs":[{"kind":"source","ref":"grimoire/readiness/action_rigging.md"},{"kind":"notebooklm-research","ref":"notebooklm:4b03c2f9-8393-411f-b5b4-039ab9532843","note":"Validated generic schema vocabulary; numeric claims remain backed by local source_refs."}],"observation_status":"observed","confidence":0.95,"assumptions":[]}+{"record_id":"core.socket-pivot","collection":"core_3d","domain":"runtime","kind":"component","entity":"socket and pivot","title":"Socket and pivot / Ổ cắm và điểm xoay","aliases":["socket","ổ cắm","pivot","điểm xoay","hinge","bản lề","local coordinates","tọa độ cục bộ"],"content":"A pivot is a local rotation origin; a socket is an attachment point for a child part. In a runtime hierarchy, a socket Object3D is a child of the relevant pivot.","constraints":["Name sockets and place them in local coordinates."],"measurements":[],"source_refs":[{"path":"grimoire/glossary/3d_vocabulary.md","heading":"Animation, Physics, And Destruction"},{"path":"grimoire/readiness/action_rigging.md","heading":"Hierarchy Pattern"}],"evidence_refs":[{"kind":"source","ref":"grimoire/readiness/action_rigging.md"},{"kind":"notebooklm-research","ref":"notebooklm:4b03c2f9-8393-411f-b5b4-039ab9532843","note":"Validated generic schema vocabulary; numeric claims remain backed by local source_refs."}],"observation_status":"observed","confidence":0.95,"assumptions":[]}+{"record_id":"core.attachment-contract","collection":"core_3d","domain":"attachment","kind":"constraint","entity":"attachment contract","title":"Attachment contract / Hợp đồng gắn kết","aliases":["attachment","gắn kết","parent socket","ổ cắm cha","local start","điểm bắt đầu cục bộ","embed depth","độ nhúng"],"content":"An attached child records its parent, parent socket, local start and end, contact type, and embed depth or overlap where applicable.","constraints":["Do not place an attached part in mid-air when its attachment cannot be inferred."],"measurements":[{"name":"gap tolerance","value":"maximum acceptable visible gap"}],"source_refs":[{"path":"grimoire/readiness/joint_attachment.md","heading":"Attachment Contract"}],"evidence_refs":[{"kind":"source","ref":"grimoire/readiness/joint_attachment.md"},{"kind":"notebooklm-research","ref":"notebooklm:4b03c2f9-8393-411f-b5b4-039ab9532843","note":"Validated generic schema vocabulary; numeric claims remain backed by local source_refs."}],"observation_status":"observed","confidence":0.95,"assumptions":[]}+{"record_id":"core.evidence-observation","collection":"core_3d","domain":"evidence","kind":"status","entity":"observation before inference","title":"Observation before inference / Quan sát trước suy luận","aliases":["observation","quan sát","evidence","bằng chứng","inference","suy luận","observed","đã quan sát"],"content":"State observable facts separately from inferred interpretations and mark every inference as inference.","constraints":["Do not present an interpretation as an observed fact."],"measurements":[],"source_refs":[{"path":"grimoire/intake/image_analysis.md","heading":"The Rule"}],"evidence_refs":[{"kind":"source","ref":"grimoire/intake/image_analysis.md"},{"kind":"notebooklm-research","ref":"notebooklm:4b03c2f9-8393-411f-b5b4-039ab9532843","note":"Validated generic schema vocabulary; numeric claims remain backed by local source_refs."}],"observation_status":"observed","confidence":0.95,"assumptions":[]}+{"record_id":"core.confidence-uncertainty","collection":"core_3d","domain":"evidence","kind":"status","entity":"confidence and uncertainty","title":"Confidence and uncertainty / Độ tin cậy và bất định","aliases":["confidence","độ tin cậy","uncertainty","bất định","occluded","bị che khuất","hidden","ẩn","request-input","yêu cầu thêm đầu vào"],"content":"For a single image, identify occluded, hidden, uncertain, or undetermined details and request another view when needed.","constraints":["Do not invent hidden detail without flagging it as speculative."],"measurements":[{"name":"confidence","value":"0–1","context":"identification and classification vocabulary"}],"source_refs":[{"path":"grimoire/intake/image_analysis.md","heading":"Layer 1 — Identification & classification"},{"path":"grimoire/intake/image_analysis.md","heading":"Layer 8 — Uncertainty & single-image limits"}],"evidence_refs":[{"kind":"source","ref":"grimoire/intake/image_analysis.md"},{"kind":"notebooklm-research","ref":"notebooklm:4b03c2f9-8393-411f-b5b4-039ab9532843","note":"Validated generic schema vocabulary; numeric claims remain backed by local source_refs."}],"observation_status":"observed","confidence":0.95,"assumptions":[]}diff --git a/docs/specs/vocabulary/core_3d_reconstruction.jsonl b/docs/specs/vocabulary/core_3d_reconstruction.jsonlnew file mode 100644index 0000000..de714c9--- /dev/null+++ b/docs/specs/vocabulary/core_3d_reconstruction.jsonl@@ -0,0 +1,37 @@+{"record_id":"core.description-cdwa-semantic-field-mapping","collection":"core_3d","domain":"description","kind":"convention","entity":"cdwa semantic field mapping","title":"CDWA Semantic Field Mapping / Ánh xạ trường ngữ nghĩa CDWA","aliases":["Ánh xạ trường ngữ nghĩa CDWA"],"content":"Top-level object-description keys from the Categories for the Description of Works of Art standard (Object/Work Type, Classification, Measurements, Materials/Techniques, Subject Matter).\n\nCác khóa mô tả đối tượng cấp cao nhất từ chuẩn Categories for the Description of Works of Art (Loại đối tượng, Phân loại, Kích thước, Vật liệu/Kỹ thuật, Chủ đề).\n\nRecognition cues: Use as the top-level schema keys whenever an agent must produce a structured (not prose) description of a reference image\nDấu hiệu nhận diện: Dùng làm các khóa schema cấp cao nhất bất cứ khi nào agent phải tạo mô tả có cấu trúc (không phải văn xuôi) cho ảnh tham chiếu\n\nThree.js target: Top-level JSON keys: objectType, classification, measurements, materials, subjectMatter — populated per reference image before any 3D generation step","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.description_conventions[0]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.description-controlled-vocabulary-aat-facets","collection":"core_3d","domain":"description","kind":"convention","entity":"controlled vocabulary (aat facets)","title":"Controlled Vocabulary (AAT Facets) / Từ vựng có kiểm soát (Facet AAT)","aliases":["Từ vựng có kiểm soát (Facet AAT)"],"content":"Standardized terminology (Getty Art & Architecture Thesaurus facets for materials, activities, physical attributes) replacing vague or inconsistent free-text terms.\n\nThuật ngữ chuẩn hóa (các facet của Getty Art & Architecture Thesaurus cho vật liệu, hoạt động, thuộc tính vật lý) thay thế các từ tự do mơ hồ hoặc không nhất quán.\n\nRecognition cues: Material/attribute terms should be drawn from a fixed enumerated list (e.g. 'brushed steel', 'anodized aluminum') rather than free-form phrasing that varies between descriptions of the same material\nDấu hiệu nhận diện: Thuật ngữ vật liệu/thuộc tính nên lấy từ danh sách liệt kê cố định (vd. 'thép chải xước', 'nhôm anod hóa') thay vì cách diễn đạt tự do thay đổi giữa các mô tả của cùng một vật liệu\n\nThree.js target: Enum-constrained metadata fields (materialType, finishStyle) validated against a fixed controlled-vocabulary list before being written to the reconstruction schema","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.description_conventions[5]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.description-drill-down-macro-to-micro-decomposition","collection":"core_3d","domain":"description","kind":"convention","entity":"drill-down macro-to-micro decomposition","title":"Drill-Down Macro-to-Micro Decomposition / Phân rã Macro-đến-Micro (Drill-Down)","aliases":["Phân rã Macro-đến-Micro (Drill-Down)"],"content":"Description ordering convention: start with a brief overall-form summary (the 'gist'), then decompose into parts, then into geometric primitives.\n\nQuy ước thứ tự mô tả: bắt đầu bằng tóm tắt hình dạng tổng thể ngắn gọn ('gist'), sau đó phân rã thành các bộ phận, rồi thành các khối nguyên thủy hình học.\n\nRecognition cues: A good description names the whole object first ('a bowie-style knife'), then its components ('blade, bolster, handle scales'), then each component's basic solid shape\nDấu hiệu nhận diện: Một mô tả tốt gọi tên toàn bộ đối tượng trước ('dao kiểu bowie'), sau đó các bộ phận ('lưỡi, đệm cán, ốp cán'), rồi hình khối cơ bản của từng bộ phận\n\nThree.js target: Nested JSON structure: { gist, components: [{ name, primitiveShape, ... }] } mirroring the geometry_anatomy category's per-part entries","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.description_conventions[4]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.description-feldman-method-description-analysis-stages","collection":"core_3d","domain":"description","kind":"convention","entity":"feldman method (description + analysis stages)","title":"Feldman Method (Description + Analysis Stages) / Phương pháp Feldman (giai đoạn Mô tả + Phân tích)","aliases":["Phương pháp Feldman (giai đoạn Mô tả + Phân tích)"],"content":"Structured visual-analysis discipline enforcing Description → Analysis → Interpretation → Judgment; only the first two stages matter for reconstruction, and value-laden adjectives are banned in favor of neutral visual pointers.\n\nKỷ luật phân tích thị giác có cấu trúc buộc theo trình tự Mô tả → Phân tích → Diễn giải → Đánh giá; chỉ hai giai đoạn đầu quan trọng cho tái tạo, và tính từ mang tính đánh giá bị cấm, thay bằng các chỉ điểm thị giác trung lập.\n\nRecognition cues: A description using words like 'beautiful' or 'elegant' has leaked into Interpretation/Judgment and should be rejected; Acceptable pointers are strictly visual: straight, curved, large, small, symmetric, textured\nDấu hiệu nhận diện: Một mô tả dùng từ như 'đẹp' hay 'tinh tế' đã lấn sang giai đoạn Diễn giải/Đánh giá và nên bị loại bỏ; Các chỉ điểm chấp nhận được chỉ mang tính thị giác thuần túy: thẳng, cong, lớn, nhỏ, đối xứng, có kết cấu\n\nThree.js target: A description-generation prompt/filter step that rejects or rewrites any adjective not drawn from a controlled visual-pointer vocabulary before the schema is populated","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.description_conventions[3]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.description-honest-uncertainty-single-image-limits-convention","collection":"core_3d","domain":"description","kind":"convention","entity":"honest-uncertainty / single-image-limits convention","title":"Honest-Uncertainty / Single-Image-Limits Convention / Quy ước Trung thực về Bất định / Giới hạn Ảnh Đơn","aliases":["Quy ước Trung thực về Bất định / Giới hạn Ảnh Đơn"],"content":"Explicit marking of occluded or back-face regions as 'undetermined' rather than inventing plausible-looking detail not visible in the reference.\n\nĐánh dấu rõ ràng các vùng bị che khuất hoặc mặt sau là 'chưa xác định' thay vì bịa ra chi tiết trông hợp lý nhưng không thấy trong ảnh tham chiếu.\n\nRecognition cues: Any attribute for a surface not visible in the reference image should be flagged explicitly rather than filled with a guessed value; This is a hard constraint against hallucinated geometry/material detail feeding into the reconstruction\nDấu hiệu nhận diện: Bất kỳ thuộc tính nào của bề mặt không thấy được trong ảnh tham chiếu nên được đánh dấu rõ ràng thay vì điền giá trị đoán mò; Đây là ràng buộc cứng chống lại việc bịa chi tiết hình học/vật liệu đưa vào tái tạo\n\nThree.js target: Sentinel value \"undetermined\" (or null + a needsAnotherView:true flag) written into any metadata field the agent cannot verify from the given reference image(s)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.description_conventions[6]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.description-pbr-vocabulary-caption-calibration","collection":"core_3d","domain":"description","kind":"convention","entity":"pbr vocabulary caption calibration","title":"PBR Vocabulary Caption Calibration / Hiệu chỉnh Chú thích theo Từ vựng PBR","aliases":["Hiệu chỉnh Chú thích theo Từ vựng PBR"],"content":"Embedding a technical material-attribute block (Albedo, Metalness, Roughness, Normals) with measured reflectance ranges directly into the structured description, not just prose.\n\nNhúng một khối thuộc tính vật liệu kỹ thuật (Albedo, Metalness, Roughness, Normals) với các dải phản xạ đo lường được trực tiếp vào mô tả có cấu trúc, không chỉ văn xuôi.\n\nRecognition cues: A reconstruction-ready description states measured-style values, e.g. 'raw metal reflectance sRGB 180-255' or 'dielectric F0 ≈ 0.04', not just 'shiny' or 'metallic-looking'\nDấu hiệu nhận diện: Một mô tả sẵn sàng cho tái tạo nêu giá trị kiểu đo lường, vd. 'phản xạ kim loại thô sRGB 180-255' hoặc 'F0 điện môi ≈ 0.04', không chỉ 'bóng' hay 'trông như kim loại'\n\nThree.js target: A materialHints sub-object { albedoRangeSRGB, metalness: 0|1, roughnessEstimate, f0Estimate } embedded per-component in the structured description, feeding directly into initial MeshPhysicalMaterial parameter guesses","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.description_conventions[7]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.description-scene-graph-relational-triplets","collection":"core_3d","domain":"description","kind":"convention","entity":"scene-graph relational triplets","title":"Scene-Graph Relational Triplets / Bộ ba quan hệ Scene-Graph","aliases":["Bộ ba quan hệ Scene-Graph"],"content":"<Subject, Predicate, Object> statements capturing spatial/semantic relationships between parts (e.g. <blade, attached_to, handle>), plus per-node bounding box and class label.\n\nCác phát biểu <Chủ thể, Vị ngữ, Đối tượng> nắm bắt quan hệ không gian/ngữ nghĩa giữa các bộ phận (vd. <lưỡi dao, gắn_vào, cán dao>), cộng với bounding box và nhãn lớp cho mỗi node.\n\nRecognition cues: Use whenever the pipeline needs a machine-readable assembly blueprint rather than a free-text description of how parts relate spatially\nDấu hiệu nhận diện: Dùng khi pipeline cần một bản thiết kế lắp ráp máy đọc được thay vì mô tả văn bản tự do về cách các bộ phận liên hệ không gian\n\nThree.js target: Array of {subject, predicate, object} triplets driving the THREE.Object3D parent-child attachment hierarchy (see 'UV/Coordinate System Conversion & Attachment Hierarchy')","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.description_conventions[2]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.description-vra-core-40-attribute-value-schema","collection":"core_3d","domain":"description","kind":"convention","entity":"vra core 4.0 attribute-value schema","title":"VRA Core 4.0 Attribute-Value Schema / Schema Thuộc tính-Giá trị VRA Core 4.0","aliases":["Schema Thuộc tính-Giá trị VRA Core 4.0"],"content":"XML-derived global attribute qualifiers (vocab, refid, xml:lang, extent) that make every described data element machine-readable and scoped.\n\nCác bộ định tính thuộc tính toàn cục có nguồn gốc XML (vocab, refid, xml:lang, extent) giúp mỗi phần tử dữ liệu được mô tả có thể đọc bằng máy và có phạm vi rõ ràng.\n\nRecognition cues: Any attribute-value pair should carry an 'extent' qualifier stating whether it describes the whole object or one sub-part — ambiguity here is the most common schema mistake\nDấu hiệu nhận diện: Mọi cặp thuộc tính-giá trị nên mang bộ định tính 'extent' cho biết nó mô tả toàn bộ đối tượng hay một sub-part — sự mơ hồ này là lỗi schema phổ biến nhất\n\nThree.js target: Per-field metadata: { value, vocab, extent } attached to each material/measurement/attribute entry in the reconstruction metadata schema","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.description_conventions[1]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.pbr-ambient-occlusion-ao","collection":"core_3d","domain":"pbr","kind":"material","entity":"ambient occlusion (ao)","title":"Ambient Occlusion (AO) / Bóng đổ môi trường (AO)","aliases":["Bóng đổ môi trường (AO)"],"content":"Baked grayscale map darkening indirect light in crevices, seams, and recesses.\n\nBản đồ grayscale được nướng sẵn làm tối ánh sáng gián tiếp tại các khe, rãnh và chỗ lõm.\n\nRecognition cues: Soft, contact-shadow-like darkening in grooves, screw recesses, and part seams that doesn't move with the key light; Protected/recessed regions accumulate dirt/grime under wear rather than losing paint\nDấu hiệu nhận diện: Vùng tối mềm giống bóng tiếp xúc tại các rãnh, ốc vít, mối nối — không di chuyển theo hướng đèn chính; Vùng lõm được bảo vệ tích tụ bụi bẩn khi mòn thay vì mất lớp sơn\n\nThree.js target: MeshPhysicalMaterial.aoMap (red channel of packed ORM texture, NoColorSpace) + aoMapIntensity","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.material_pbr[3]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.pbr-anisotropy","collection":"core_3d","domain":"pbr","kind":"material","entity":"anisotropy","title":"Anisotropy / Dị hướng (Anisotropy)","aliases":["Dị hướng (Anisotropy)"],"content":"Directional specular stretching seen on brushed or grooved metal, where reflections elongate along the grain direction.\n\nHiện tượng phản xạ specular kéo dài theo một hướng, thấy trên kim loại được chải xước hoặc có rãnh, phản xạ kéo dài theo hướng vân.\n\nRecognition cues: Elongated, streaky highlights (not round) that stay aligned with visible brush/groove marks as the view angle changes; Common on brushed steel/titanium knife finishes and gunsmith metal bases\nDấu hiệu nhận diện: Điểm sáng kéo dài, có vệt (không tròn) luôn thẳng hàng với các vết chải/rãnh nhìn thấy khi góc nhìn thay đổi; Thường gặp ở các finish thép/titan chải xước của dao và nền kim loại gunsmith\n\nThree.js target: MeshPhysicalMaterial.anisotropy (scalar) + .anisotropyMap (direction/strength) + tangent map for groove direction","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.material_pbr[6]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.pbr-clearcoat","collection":"core_3d","domain":"pbr","kind":"material","entity":"clearcoat","title":"Clearcoat / Lớp phủ bóng (Clearcoat)","aliases":["Lớp phủ bóng (Clearcoat)"],"content":"Secondary reflective coating layer on top of the base material, simulating varnish, lacquer, or automotive paint.\n\nLớp phủ phản xạ thứ cấp nằm trên vật liệu nền, mô phỏng vecni, sơn mài hoặc sơn xe hơi.\n\nRecognition cues: A distinct, sharp secondary highlight sitting on top of a duller or differently-colored base layer; Common on Custom Paint Job / Gunsmith style finishes with a glossy topcoat over illustrative artwork\nDấu hiệu nhận diện: Có một điểm sáng thứ cấp sắc nét nằm trên lớp nền mờ hơn hoặc khác màu; Thường gặp ở các finish kiểu Custom Paint Job / Gunsmith có lớp phủ bóng trên tranh vẽ minh họa\n\nThree.js target: MeshPhysicalMaterial.clearcoat (weight) + .clearcoatRoughness","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.material_pbr[4]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.pbr-color-space-srgb-vs-linearnocolorspace","collection":"core_3d","domain":"pbr","kind":"material","entity":"color space: srgb vs linear/nocolorspace","title":"Color Space: sRGB vs Linear/NoColorSpace / Không gian màu: sRGB và Linear/NoColorSpace","aliases":["Không gian màu: sRGB và Linear/NoColorSpace"],"content":"Distinction between human-viewable color data (needs gamma/sRGB) and mathematical data maps (must stay linear/uncorrected).\n\nPhân biệt giữa dữ liệu màu để người xem (cần gamma/sRGB) và các bản đồ dữ liệu toán học (phải giữ tuyến tính/không hiệu chỉnh).\n\nRecognition cues: Base color/albedo and emissive textures are the only ones that should look like natural photographic color; Normal, roughness, metalness, and AO textures look like flat/desaturated data patterns and must never be gamma-corrected\nDấu hiệu nhận diện: Chỉ có base color/albedo và emissive texture nên trông như ảnh màu tự nhiên; Normal, roughness, metalness, AO trông như các mẫu dữ liệu phẳng/khử màu và không bao giờ được hiệu chỉnh gamma\n\nThree.js target: texture.colorSpace = THREE.SRGBColorSpace for .map/.emissiveMap; THREE.NoColorSpace for .normalMap/.roughnessMap/.metalnessMap/.aoMap (Three.js r152+)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.material_pbr[11]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.pbr-emission","collection":"core_3d","domain":"pbr","kind":"material","entity":"emission","title":"Emission / Phát xạ (Emission)","aliases":["Phát xạ (Emission)"],"content":"Self-illuminating surface layer independent of scene lighting, used for glowing indicators or self-illum masks.\n\nLớp bề mặt tự phát sáng độc lập với ánh sáng cảnh, dùng cho đèn báo phát sáng hoặc mặt nạ self-illum.\n\nRecognition cues: A region stays bright/colored regardless of light direction or shadow (e.g. StatTrak orange LED counter module); Often masked to a small, specific submesh rather than the whole surface\nDấu hiệu nhận diện: Một vùng luôn sáng/có màu bất kể hướng ánh sáng hay bóng đổ (vd. module đèn LED cam của StatTrak); Thường được giới hạn (mask) vào một submesh nhỏ, cụ thể thay vì toàn bộ bề mặt\n\nThree.js target: MeshPhysicalMaterial.emissive + .emissiveMap (SRGBColorSpace) + .emissiveIntensity","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.material_pbr[7]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.pbr-hand-painted-vs-pbr-texture","collection":"core_3d","domain":"pbr","kind":"material","entity":"hand-painted vs pbr texture","title":"Hand-Painted vs PBR Texture / Kết cấu vẽ tay và kết cấu PBR","aliases":["Kết cấu vẽ tay và kết cấu PBR"],"content":"Distinguishes textures with lighting baked directly into color (static, stylized) from textures that respond dynamically to scene lighting via separate PBR channels.\n\nPhân biệt kết cấu có ánh sáng được nướng trực tiếp vào màu (tĩnh, cách điệu) với kết cấu phản hồi động theo ánh sáng cảnh qua các kênh PBR riêng.\n\nRecognition cues: Hand-painted: shadows/highlights stay fixed in place even as the object rotates or lighting changes; visible brushstrokes; single diffuse-only map; PBR: specular highlights and shadow shapes move logically with view/light angle; micro-detail (pores, scratches) shows directional shading from normal/roughness maps\nDấu hiệu nhận diện: Vẽ tay: bóng tối/điểm sáng cố định vị trí dù vật xoay hay ánh sáng đổi; thấy vết cọ; chỉ có một map diffuse duy nhất; PBR: điểm sáng specular và hình dạng bóng di chuyển hợp lý theo góc nhìn/ánh sáng; chi tiết vi mô (lỗ chân lông, vết xước) có bóng đổ theo hướng từ normal/roughness map\n\nThree.js target: Hand-painted → single .map (baked lighting, SRGBColorSpace); PBR → full MeshPhysicalMaterial channel set (map/normalMap/roughnessMap/metalnessMap/aoMap)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.material_pbr[12]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.pbr-metalness","collection":"core_3d","domain":"pbr","kind":"material","entity":"metalness","title":"Metalness / Độ kim loại","aliases":["Độ kim loại"],"content":"Binary or scalar property defining whether a surface is dielectric (0.0) or conductive metal (1.0); intermediate values blend the two.\n\nThuộc tính nhị phân hoặc vô hướng xác định bề mặt là điện môi (0.0) hay kim loại dẫn điện (1.0); giá trị trung gian là pha trộn tuyến tính.\n\nRecognition cues: Metallic surfaces tint their reflections with the base color at grazing angles instead of showing white specular highlights; CS2 specifically uses a strict binary model — pure metal (1.0) or pure dielectric (0.0), no soft gray transition zones\nDấu hiệu nhận diện: Bề mặt kim loại nhuộm màu phản xạ theo màu nền ở góc nhìn xiên thay vì hiển thị điểm sáng specular trắng; CS2 dùng mô hình nhị phân nghiêm ngặt — kim loại thuần (1.0) hoặc điện môi thuần (0.0), không có vùng chuyển xám mềm\n\nThree.js target: MeshPhysicalMaterial.metalness (scalar) + .metalnessMap (blue channel of packed ORM texture, NoColorSpace)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.material_pbr[0]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.pbr-normal-map","collection":"core_3d","domain":"pbr","kind":"material","entity":"normal map","title":"Normal Map / Bản đồ pháp tuyến","aliases":["Bản đồ pháp tuyến"],"content":"Tangent-space RGB texture that perturbs surface normals to simulate fine geometric detail (engravings, scratches, weave) without added polycount.\n\nKết cấu RGB không gian tiếp tuyến làm lệch pháp tuyến bề mặt để mô phỏng chi tiết hình học nhỏ (khắc chữ, vết trầy, dệt vải) mà không tăng số đa giác.\n\nRecognition cues: Fine surface relief (engraving, stippling, fabric weave, edge chips) visible under raking light but absent from the silhouette; Typically stored as a blue/purple-tinted texture in extraction tools\nDấu hiệu nhận diện: Chi tiết nổi trên bề mặt (khắc chữ, chấm nhám, dệt vải, mẻ cạnh) thấy rõ dưới ánh sáng chéo nhưng không có trên đường viền hình học; Thường lưu dưới dạng kết cấu có tông màu xanh dương/tím trong công cụ trích xuất\n\nThree.js target: MeshPhysicalMaterial.normalMap (RGB, NoColorSpace); invert green (Y) channel if source is OpenGL vs DirectX convention","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.material_pbr[2]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.pbr-opacity-alpha","collection":"core_3d","domain":"pbr","kind":"material","entity":"opacity / alpha","title":"Opacity / Alpha / Độ trong suốt / Alpha","aliases":["Độ trong suốt / Alpha"],"content":"Controls material transparency and blend mode; in CS2 workflows the alpha channel of Base Color is repurposed as a non-transparency data channel.\n\nKiểm soát độ trong suốt và chế độ blend của vật liệu; trong quy trình CS2, kênh alpha của Base Color được tái sử dụng làm kênh dữ liệu, không phải độ trong suốt.\n\nRecognition cues: Standard opacity: soft edge fade or full transparency in glass/plastic parts; CS2-specific: alpha channel of the base color texture instead encodes a Wearness Mask, not visual transparency\nDấu hiệu nhận diện: Opacity tiêu chuẩn: cạnh mờ dần hoặc trong suốt hoàn toàn ở các bộ phận kính/nhựa; Đặc thù CS2: kênh alpha của texture màu nền lại mã hóa Wearness Mask, không phải độ trong suốt thị giác\n\nThree.js target: MeshPhysicalMaterial.opacity + .alphaTest / .transparent (standard); CS2 alpha channel routed to a custom wear shader input instead","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.material_pbr[8]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.pbr-orm-channel-packing","collection":"core_3d","domain":"pbr","kind":"material","entity":"orm channel packing","title":"ORM Channel Packing / Đóng gói kênh ORM","aliases":["Đóng gói kênh ORM"],"content":"Convention of packing AO, Roughness, and Metalness grayscale maps into the R, G, B channels of a single texture to cut texture-fetch and VRAM cost.\n\nQuy ước đóng gói ba bản đồ grayscale AO, Roughness, Metalness vào các kênh R, G, B của một texture duy nhất để giảm chi phí lấy mẫu texture và VRAM.\n\nRecognition cues: Single texture file that looks like flat gray/colored noise, not a recognizable color or normal map; Source 2 (CS2) packs Roughness/Metalness this way; the raw file needs channel-splitting before separate Three.js texture slots can use it\nDấu hiệu nhận diện: Một file texture duy nhất trông như nhiễu xám/màu phẳng, không giống ảnh màu hay normal map thông thường; Source 2 (CS2) đóng gói Roughness/Metalness theo cách này; file gốc cần tách kênh trước khi gán vào các khe texture riêng của Three.js\n\nThree.js target: One packed texture assigned simultaneously to .aoMap (R), .roughnessMap (G), .metalnessMap (B) per the glTF ORM convention","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.material_pbr[10]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.pbr-subsurface-scattering-sss","collection":"core_3d","domain":"pbr","kind":"material","entity":"subsurface scattering (sss)","title":"Subsurface Scattering (SSS) / Tán xạ dưới bề mặt (SSS)","aliases":["Tán xạ dưới bề mặt (SSS)"],"content":"Light transport property for opaque dielectrics where light penetrates and scatters internally before exiting (skin, wax, marble, some polymers).\n\nĐặc tính truyền ánh sáng của vật liệu điện môi mờ đục, ánh sáng xuyên vào và tán xạ bên trong trước khi thoát ra (da, sáp, đá cẩm thạch, một số nhựa polymer).\n\nRecognition cues: Edges/thin sections of the material glow softly when backlit rather than showing a hard black silhouette; Relevant mainly to glove leather/polymer trims and agent-model skin, not metal weapon parts\nDấu hiệu nhận diện: Các cạnh/phần mỏng của vật liệu phát sáng mềm khi có ánh sáng ngược thay vì tạo bóng đen sắc nét; Chủ yếu liên quan đến da/nhựa của găng tay và da người mẫu đặc vụ, không áp dụng cho các bộ phận kim loại của súng\n\nThree.js target: MeshPhysicalMaterial.transmission + .thickness + .attenuationColor (approximates SSS on MeshPhysicalMaterial)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.material_pbr[5]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.pbr-tangent-space-normal-encoding-directx-vs-opengl","collection":"core_3d","domain":"pbr","kind":"material","entity":"tangent-space normal encoding (directx vs opengl)","title":"Tangent-Space Normal Encoding (DirectX vs OpenGL) / Mã hóa Normal Map không gian tiếp tuyến (DirectX và OpenGL)","aliases":["Mã hóa Normal Map không gian tiếp tuyến (DirectX và OpenGL)"],"content":"Convention difference in the green (Y) channel of tangent-space normal maps between DirectX-style and OpenGL-style encoding.\n\nSự khác biệt quy ước ở kênh xanh lá (Y) của normal map không gian tiếp tuyến giữa mã hóa kiểu DirectX và kiểu OpenGL.\n\nRecognition cues: Bumps rendering as dents (or vice versa) after import is the visual symptom of a Y-channel mismatch; CS2/Source 2 extracted normals may need the green channel inverted depending on export convention\nDấu hiệu nhận diện: Hiện tượng chỗ lồi hiển thị thành chỗ lõm (hoặc ngược lại) sau khi import là dấu hiệu sai lệch kênh Y; Normal map trích xuất từ CS2/Source 2 có thể cần đảo kênh xanh lá tùy theo quy ước xuất\n\nThree.js target: Invert the green channel of the source normal texture (texture data flip) before assigning to MeshPhysicalMaterial.normalMap if bump direction reads inverted","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.material_pbr[13]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.pbr-wearness-alpha-mask","collection":"core_3d","domain":"pbr","kind":"material","entity":"wearness alpha mask","title":"Wearness Alpha Mask / Mặt nạ độ bền (Wearness Mask)","aliases":["Mặt nạ độ bền (Wearness Mask)"],"content":"CS2-specific per-pixel durability control embedded in the alpha channel of the Base Color texture, independent of visible transparency.\n\nCơ chế điều khiển độ bền theo từng pixel đặc thù của CS2, nhúng trong kênh alpha của texture Base Color, độc lập với độ trong suốt thị giác.\n\nRecognition cues: Alpha ~196: paint erodes early, visible scratches/chips even at low float (Factory New range); Alpha <128: durable, resists scratching; Alpha = 0 (black): absolute durability, paint never scratches regardless of float value\nDấu hiệu nhận diện: Alpha ~196: sơn bong sớm, có vết trầy/mẻ ngay cả ở float thấp (khoảng Factory New); Alpha <128: bền, chống trầy; Alpha = 0 (đen): bền tuyệt đối, sơn không bao giờ bị trầy dù float cao\n\nThree.js target: Custom shader uniform sampling Base Color alpha to drive a wear-blend mix() between pristine and worn material states, keyed by a float value parameter","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.material_pbr[9]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-boxgeometry-slides-receivers-grips","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"boxgeometry → slides, receivers & grips","title":"BoxGeometry → Slides, Receivers & Grips / BoxGeometry cho Khóa nòng, Thân súng và Tay cầm","aliases":["BoxGeometry cho Khóa nòng, Thân súng và Tay cầm"],"content":"Maps to rectangular/blocky sub-assemblies.\n\nÁnh xạ tới các cụm lắp ráp hình chữ nhật/khối.\n\nRecognition cues: Flat-faced, roughly rectangular volume (pistol slide, receiver/frame, grip, panel)\nDấu hiệu nhận diện: Khối gần chữ nhật với các mặt phẳng (khóa nòng súng lục, thân/khung súng, tay cầm, tấm phẳng)\n\nThree.js target: BoxGeometry(width, height, depth)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[5]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-capsulegeometry-rounded-edge-components","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"capsulegeometry → rounded-edge components","title":"CapsuleGeometry → Rounded-Edge Components / CapsuleGeometry cho các bộ phận có cạnh bo tròn","aliases":["CapsuleGeometry cho các bộ phận có cạnh bo tròn"],"content":"Maps to components with hemispherical rounded ends.\n\nÁnh xạ tới các bộ phận có đầu bo tròn dạng bán cầu.\n\nRecognition cues: Rod-like part with distinctly rounded (not flat-cut) ends, e.g. a knife spine or a safety lever\nDấu hiệu nhận diện: Bộ phận dạng thanh có đầu bo tròn rõ rệt (không cắt phẳng), vd. sống dao hoặc cần an toàn\n\nThree.js target: CapsuleGeometry(radius, length)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[6]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-conegeometry-tapered-tips","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"conegeometry → tapered tips","title":"ConeGeometry → Tapered Tips / ConeGeometry cho các đầu thon nhọn","aliases":["ConeGeometry cho các đầu thon nhọn"],"content":"Maps to tapered projectile-like or pointed components.\n\nÁnh xạ tới các bộ phận thon nhọn giống đầu đạn hoặc có mũi nhọn.\n\nRecognition cues: Tapered pointed shape narrowing to a point — projectile tips, some conical muzzle device shapes\nDấu hiệu nhận diện: Hình thon nhọn thu về một điểm — đầu đạn, một số hình dạng đầu nòng dạng nón\n\nThree.js target: ConeGeometry(radius, height, radialSegments)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[11]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-csg-boolean-operations-for-sub-mesh-composition","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"csg boolean operations for sub-mesh composition","title":"CSG Boolean Operations for Sub-Mesh Composition / Các phép toán Boolean CSG để kết hợp Sub-Mesh","aliases":["Các phép toán Boolean CSG để kết hợp Sub-Mesh"],"content":"Constructive solid geometry (union/subtract/intersect) for combining or cutting weapon/knife sub-meshes procedurally instead of hand-modeling every variant.\n\nHình học rắn cấu trúc (hợp/trừ/giao) để kết hợp hoặc cắt các sub-mesh vũ khí/dao theo thủ tục thay vì mô hình hóa thủ công từng biến thể.\n\nRecognition cues: Needed for hollowing barrels/handguards, drilling accessory-mount holes, or generating chamfered/cut geometric variants from primitive stacks\nDấu hiệu nhận diện: Cần khi khoét rỗng nòng súng/ốp lót tay, khoan lỗ gắn phụ kiện, hoặc tạo các biến thể hình học vát/cắt từ chồng khối nguyên thủy\n\nThree.js target: three-csg-ts (BSP-tree based, TypeScript) or three-bvh-csg for Subtract/Union/Intersect operations between BufferGeometry meshes","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[3]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-customshadermaterial-csm-weathering-hooks","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"customshadermaterial (csm) weathering hooks","title":"CustomShaderMaterial (CSM) Weathering Hooks / Móc nối phong hóa của CustomShaderMaterial (CSM)","aliases":["Móc nối phong hóa của CustomShaderMaterial (CSM)"],"content":"Extension library exposing csm_* output variables to inject procedural noise/masks into an otherwise-standard lit material, used for dynamic tarnish/patina effects.\n\nThư viện mở rộng cung cấp các biến đầu ra csm_* để chèn nhiễu/mặt nạ thủ tục vào vật liệu chiếu sáng tiêu chuẩn, dùng cho hiệu ứng xỉn màu/patina động.\n\nRecognition cues: Needed when wear/tarnish must be computed procedurally at runtime rather than fully pre-baked into a texture\nDấu hiệu nhận diện: Cần khi độ mòn/xỉn màu phải được tính thủ tục tại runtime thay vì nướng sẵn hoàn toàn vào texture\n\nThree.js target: csm_Roughness / csm_Metalness (procedural noise-driven overrides), csm_FragNormal (custom bump for patina), csm_DiffuseColor (mix base color with oxide/dirt color by mask)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[1]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-cylindergeometry-barrels-round-components","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"cylindergeometry → barrels & round components","title":"CylinderGeometry → Barrels & Round Components / CylinderGeometry cho Nòng súng và các bộ phận tròn","aliases":["CylinderGeometry cho Nòng súng và các bộ phận tròn"],"content":"Maps to any barrel-like round-cross-section part.\n\nÁnh xạ tới mọi bộ phận có tiết diện tròn dạng nòng.\n\nRecognition cues: Long uniform-cross-section round part (barrel, suppressor, muzzle brake body, cleaning rod, magazine tube)\nDấu hiệu nhận diện: Bộ phận tròn có tiết diện đều dài (nòng súng, ống giảm thanh, thân bù giật, cần thông nòng, ống chứa đạn)\n\nThree.js target: CylinderGeometry(radiusTop, radiusBottom, height); radiusTop=0 for conical shapes","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[4]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-extrudegeometry-custom-bladesilhouette-profiles","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"extrudegeometry → custom blade/silhouette profiles","title":"ExtrudeGeometry → Custom Blade/Silhouette Profiles / ExtrudeGeometry cho hồ sơ lưỡi dao/đường viền tùy chỉnh","aliases":["ExtrudeGeometry cho hồ sơ lưỡi dao/đường viền tùy chỉnh"],"content":"Maps to any part defined by a unique 2D silhouette pushed into 3D depth with a bevel.\n\nÁnh xạ tới bất kỳ bộ phận nào được định nghĩa bằng đường viền 2D độc nhất, đẩy vào chiều sâu 3D với cạnh vát.\n\nRecognition cues: Blade shape that doesn't match a simple primitive — distinctive curved hook (Karambit), curved clip point (Bowie), or other custom silhouette\nDấu hiệu nhận diện: Hình dạng lưỡi dao không khớp với khối nguyên thủy đơn giản — móc cong đặc trưng (Karambit), điểm clip cong (Bowie), hoặc đường viền tùy chỉnh khác\n\nThree.js target: ExtrudeGeometry(customTHREEShape, { depth, bevelEnabled, bevelThickness })","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[7]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-lathegeometry-turnedradially-symmetric-parts","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"lathegeometry → turned/radially-symmetric parts","title":"LatheGeometry → Turned/Radially-Symmetric Parts / LatheGeometry cho các bộ phận tiện/đối xứng trục","aliases":["LatheGeometry cho các bộ phận tiện/đối xứng trục"],"content":"Maps to parts generated by revolving a 2D profile around an axis.\n\nÁnh xạ tới các bộ phận tạo ra bằng cách xoay một biên dạng 2D quanh một trục.\n\nRecognition cues: Contoured, fully radially-symmetric part — turned wood/metal handle, some muzzle device shapes, adjustment knobs\nDấu hiệu nhận diện: Bộ phận có biên dạng, đối xứng trục hoàn toàn — cán gỗ/kim loại tiện, một số hình dạng đầu nòng, núm điều chỉnh\n\nThree.js target: LatheGeometry(points[], segments) where points is a 2D profile curve revolved around the Y-axis","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[9]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-meshphysicalmaterial-core-pbr-fields","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"meshphysicalmaterial core pbr fields","title":"MeshPhysicalMaterial Core PBR Fields / Các trường PBR cốt lõi của MeshPhysicalMaterial","aliases":["Các trường PBR cốt lõi của MeshPhysicalMaterial"],"content":"The baseline Three.js material exposing direct scalar/map fields for the standard PBR channel set.\n\nVật liệu Three.js cơ bản cung cấp trực tiếp các trường vô hướng/bản đồ cho bộ kênh PBR tiêu chuẩn.\n\nRecognition cues: Use whenever a static (non-procedural) material fully described by baked textures is sufficient — the majority of extracted CS2 skins\nDấu hiệu nhận diện: Dùng khi vật liệu tĩnh (không thủ tục) được mô tả đầy đủ bằng texture nướng sẵn là đủ — phần lớn skin CS2 trích xuất\n\nThree.js target: new THREE.MeshPhysicalMaterial({ map, normalMap, roughnessMap, metalnessMap, aoMap, clearcoat, clearcoatRoughness })","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[0]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-orm-packed-texture-assignment","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"orm packed texture assignment","title":"ORM Packed Texture Assignment / Gán texture đóng gói ORM","aliases":["Gán texture đóng gói ORM"],"content":"Assigning one R/G/B-packed texture file to three separate MeshPhysicalMaterial slots simultaneously, per the glTF ORM convention.\n\nGán một file texture đóng gói R/G/B vào ba khe riêng biệt của MeshPhysicalMaterial cùng lúc, theo quy ước ORM của glTF.\n\nRecognition cues: Source 2/CS2 exports often ship AO/Roughness/Metalness pre-packed into one file rather than three separate grayscale images\nDấu hiệu nhận diện: Bản xuất từ Source 2/CS2 thường đóng gói sẵn AO/Roughness/Metalness vào một file thay vì ba ảnh grayscale riêng\n\nThree.js target: material.aoMap = material.roughnessMap = material.metalnessMap = packedTexture (each field reads its designated R/G/B channel automatically)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[13]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-reconstruction-metadata-schema","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"reconstruction metadata schema","title":"Reconstruction Metadata Schema / Schema Metadata cho Tái tạo","aliases":["Schema Metadata cho Tái tạo"],"content":"A structured metadata envelope (identity, extraction provenance, geometry stats, texture-slot mapping, rights) accompanying each reconstructed asset to drive and audit the pipeline.\n\nMột gói metadata có cấu trúc (định danh, nguồn gốc trích xuất, thống kê hình học, ánh xạ khe texture, quyền sở hữu) đi kèm mỗi tài sản tái tạo để điều khiển và kiểm tra pipeline.\n\nRecognition cues: Needed whenever an agent must trace a generated Three.js asset back to its source skin/paint_seed/rarity for QA or reproducibility\nDấu hiệu nhận diện: Cần khi agent phải truy vết một tài sản Three.js đã tạo về lại skin/paint_seed/độ hiếm nguồn để QA hoặc tái lập\n\nThree.js target: JSON sidecar: { weapon_id, paint_index, skin_id, min_float, max_float, rarity, category, source_tool, source_path, checksum, face_count, vertex_count, bounding_box, texture_slots: {slot: colorSpace}, paint_seed, rights }","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[15]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-srgb-linear-color-space-assignment","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"srgb / linear color space assignment","title":"sRGB / Linear Color Space Assignment / Gán không gian màu sRGB / Linear","aliases":["Gán không gian màu sRGB / Linear"],"content":"The mandatory Three.js r152+ rule for tagging each texture as human-viewable color vs. mathematical data before assigning it to a material slot.\n\nQuy tắc bắt buộc từ Three.js r152+ để gán nhãn mỗi texture là màu để người xem hay dữ liệu toán học trước khi gán vào khe vật liệu.\n\nRecognition cues: Any imported texture that looks like a natural photo → sRGB; any texture that looks like flat gray/colored data noise → NoColorSpace\nDấu hiệu nhận diện: Bất kỳ texture nhập vào trông như ảnh tự nhiên → sRGB; bất kỳ texture trông như nhiễu dữ liệu xám/màu phẳng → NoColorSpace\n\nThree.js target: texture.colorSpace = THREE.SRGBColorSpace (map, emissiveMap) or THREE.NoColorSpace (normalMap, roughnessMap, metalnessMap, aoMap)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[12]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-torusgeometry-rings-loops","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"torusgeometry → rings & loops","title":"TorusGeometry → Rings & Loops / TorusGeometry cho Vòng khuyên và Vòng lặp","aliases":["TorusGeometry cho Vòng khuyên và Vòng lặp"],"content":"Maps to donut-shaped circular features.\n\nÁnh xạ tới các chi tiết hình vòng tròn kiểu donut.\n\nRecognition cues: Circular loop feature — bayonet handle ring, finger loop on a Talon knife, trigger guard loop, carrying handle\nDấu hiệu nhận diện: Chi tiết vòng tròn — vòng cán lưỡi lê, vòng ngón tay trên dao Talon, vòng vành bảo vệ cò, tay xách\n\nThree.js target: TorusGeometry(radius, tube, radialSegments, tubularSegments)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[8]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-tsl-node-functions-for-weathering","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"tsl node functions for weathering","title":"TSL Node Functions for Weathering / Các hàm nút TSL cho hiệu ứng phong hóa","aliases":["Các hàm nút TSL cho hiệu ứng phong hóa"],"content":"Three.js Shading Language (WebGPU) node-graph functions used to build procedural PBR materials, especially for blending pristine vs. weathered states.\n\nCác hàm đồ thị nút của Three.js Shading Language (WebGPU) dùng để xây dựng vật liệu PBR thủ tục, đặc biệt để pha trộn trạng thái nguyên vẹn và trạng thái phong hóa.\n\nRecognition cues: Preferred over CSM on WebGPU-targeted builds; needed for float-driven wear blending and terrain-style masked effects\nDấu hiệu nhận diện: Ưu tiên hơn CSM trên các bản build nhắm WebGPU; cần cho pha trộn độ mòn theo float và hiệu ứng mặt nạ kiểu địa hình\n\nThree.js target: material.roughnessNode / .metalnessNode / .normalNode assigned mix(pristineVal, wornVal, wearMask) with smoothstep() for soft transition edges and texture()/varying() for sampling and vertex-to-fragment data","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[2]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-tubegeometry-straps-cables-belts","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"tubegeometry → straps, cables & belts","title":"TubeGeometry → Straps, Cables & Belts / TubeGeometry cho Dây đai, Cáp và Dây băng đạn","aliases":["TubeGeometry cho Dây đai, Cáp và Dây băng đạn"],"content":"Maps to flexible components following a 3D curve.\n\nÁnh xạ tới các bộ phận mềm dẻo chạy theo một đường cong 3D.\n\nRecognition cues: Flexible, curve-following linear component — sling strap, pressure-switch cable, ammo belt draping into a receiver\nDấu hiệu nhận diện: Bộ phận tuyến tính mềm dẻo chạy theo đường cong — dây đeo súng, cáp công tắc áp lực, dây băng đạn thõng vào thân súng\n\nThree.js target: TubeGeometry(curve, tubularSegments, radius, radialSegments)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[10]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"core.shader-mapping-uvcoordinate-system-conversion-attachment-hierarchy","collection":"core_3d","domain":"shader-mapping","kind":"concept","entity":"uv/coordinate system conversion & attachment hierarchy","title":"UV/Coordinate System Conversion & Attachment Hierarchy / Chuyển đổi hệ tọa độ UV và Phân cấp gắn kết","aliases":["Chuyển đổi hệ tọa độ UV và Phân cấp gắn kết"],"content":"Handling handedness/up-axis differences (Unity Y-up left-handed vs. USD/glTF right-handed) and representing sub-part attachment via parent-child scene-graph transforms.\n\nXử lý khác biệt tay thuận/trục lên (Unity Y-up trái vs. USD/glTF phải) và biểu diễn gắn kết sub-part qua transform cha-con trong scenegraph.\n\nRecognition cues: A sub-part (scope, blade, strap) that appears mirrored or flipped sideways after import signals a handedness mismatch; Attachment points behave like named sockets/joints (Unreal sockets, USD UsdPhysicsFixedJoint, 'ghost links') — a local offset+rotation relative to a parent node\nDấu hiệu nhận diện: Một sub-part (kính ngắm, lưỡi dao, dây đeo) bị lật ngược hoặc lệch sau khi import báo hiệu sai lệch tay thuận; Điểm gắn kết hoạt động như socket/joint có tên (Unreal sockets, USD UsdPhysicsFixedJoint, 'ghost link') — một offset+xoay cục bộ tương đối với node cha\n\nThree.js target: THREE.Object3D parent-child hierarchy with each sub-part's local .position/.quaternion set to the source engine's named attachment-socket transform; flip texture.flipY / negate one axis if handedness mismatches","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.rendering_shader_mapping[14]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}diff --git a/docs/specs/vocabulary/cs2.jsonl b/docs/specs/vocabulary/cs2.jsonlnew file mode 100644index 0000000..060a459--- /dev/null+++ b/docs/specs/vocabulary/cs2.jsonl@@ -0,0 +1,8 @@+{"record_id":"cs2.karambit.safety-ring","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"karambit safety ring","title":"Karambit safety ring / Vòng ngón Karambit","aliases":["safety ring","finger ring","vòng ngón","karambit"],"content":"A Karambit has a concave hawkbill blade and a safety ring at the pommel; the source identifies the ring as a critical finger-hole detail.","constraints":["Preserve the safety-ring opening as a distinct anatomical feature."],"measurements":[{"name":"ring diameter","value":"≈ 20","unit":"mm","context":"local research distill"}],"source_refs":[{"path":"docs/cs2/distill.md","heading":"1. Knife Anatomy — Actionable Geometry Rules"},{"path":"docs/cs2-anatomy/knives.md","heading":"3. Dao găm Karambit — Karambit"}],"evidence_refs":[{"kind":"source","ref":"docs/cs2/distill.md","note":"Notebook IDs are retained only in the local source header."},{"kind":"source","ref":"docs/cs2-anatomy/knives.md"}],"observation_status":"observed","confidence":0.85,"assumptions":[]}+{"record_id":"cs2.knife.pommel","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"knife pommel","title":"Knife pommel / Chuôi cuối dao","aliases":["pommel","chuôi cuối","knife handle","cán dao"],"content":"The technical mapping lists pommel as a knife-handle component with CylinderGeometry, metalness 1.0, and roughness 0.35.","constraints":["Treat the pommel as a distinct handle component when the reference shows it."],"measurements":[{"name":"roughness","value":"0.35","context":"technical mapping"}],"source_refs":[{"path":"docs/cs2/3D_Technical_Mapping.json","key_path":"knife_components.handle.pommel"}],"evidence_refs":[{"kind":"source","ref":"docs/cs2/3D_Technical_Mapping.json"}],"observation_status":"observed","confidence":0.9,"assumptions":[]}+{"record_id":"cs2.balisong.pivot","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"balisong pivot pin","title":"Balisong pivot pin / Chốt xoay Balisong","aliases":["pivot","điểm xoay","pivot pin","chốt xoay","balisong"],"content":"A Balisong uses two handles with pivot pins, stop pin, and latch; the pivot pin is the rotation axis.","constraints":["Model the pivot as the rotation axis rather than a decorative centered pin."],"measurements":[],"source_refs":[{"path":"docs/cs2/distill.md","heading":"1. Knife Anatomy — Actionable Geometry Rules"}],"evidence_refs":[{"kind":"source","ref":"docs/cs2/distill.md"}],"observation_status":"observed","confidence":0.85,"assumptions":[]}+{"record_id":"cs2.attachment-socket","collection":"cs2","domain":"runtime","kind":"constraint","entity":"weapon attachment socket","title":"Weapon attachment socket / Ổ cắm gắn kết vũ khí","aliases":["socket","ổ cắm","attachment","gắn kết","suppressor attachment","gắn giảm thanh"],"content":"Use a named socket or contact region to describe a child attachment; the CS2 distill identifies threaded barrels as a suppressor-attachment case.","constraints":["Record the parent socket and contact type for an attached child part."],"measurements":[],"source_refs":[{"path":"grimoire/readiness/joint_attachment.md","heading":"Attachment Contract"},{"path":"docs/cs2/distill.md","heading":"2. Pistol Anatomy — Key Technical Findings"}],"evidence_refs":[{"kind":"source","ref":"grimoire/readiness/joint_attachment.md"},{"kind":"source","ref":"docs/cs2/distill.md"}],"observation_status":"observed","confidence":0.9,"assumptions":[]}+{"record_id":"cs2.finish.roughness","collection":"cs2","domain":"finish","kind":"material","entity":"CS2 finish roughness","title":"CS2 finish roughness / Độ thô bề mặt CS2","aliases":["roughness","độ thô","độ nhám","anodized","anodized multicolored","anodized nhiều màu"],"content":"The mapping gives anodized finish roughness 0.05–0.15 and anodized-multicolored roughness 0.05–0.10.","constraints":["Use the documented finish range instead of inventing a scalar."],"measurements":[{"name":"anodized roughness","value":"0.05–0.15"},{"name":"anodized multicolored roughness","value":"0.05–0.10"}],"source_refs":[{"path":"docs/cs2/3D_Technical_Mapping.json","key_path":"cs2_finish_styles.anodized"},{"path":"docs/cs2/3D_Technical_Mapping.json","key_path":"cs2_finish_styles.anodized_multicolored"}],"evidence_refs":[{"kind":"source","ref":"docs/cs2/3D_Technical_Mapping.json"}],"observation_status":"observed","confidence":0.9,"assumptions":[]}+{"record_id":"cs2.wear-edge-wear","collection":"cs2","domain":"wear","kind":"concept","entity":"edge wear","title":"Edge wear / Mòn cạnh viền","aliases":["wear","hao mòn","wear and tear","hao mòn sử dụng","edge wear","mòn cạnh viền"],"content":"Edge wear is damage concentrated along sharp corners or high-exposure edges; the mapping distinguishes it from general wear and tear.","constraints":["Place wear by its described spatial distribution rather than uniformly."],"measurements":[],"source_refs":[{"path":"docs/cs2/3D_Technical_Mapping.json","key_path":"spatial_wear_glossary.core_industry_terms.edge_wear"},{"path":"docs/cs2/3D_Technical_Mapping.json","key_path":"spatial_wear_glossary.core_industry_terms.wear_and_tear"}],"evidence_refs":[{"kind":"source","ref":"docs/cs2/3D_Technical_Mapping.json"}],"observation_status":"observed","confidence":0.9,"assumptions":[]}+{"record_id":"cs2.wear-float-ranges","collection":"cs2","domain":"wear","kind":"measurement","entity":"CS2 float wear range","title":"CS2 float wear ranges / Dải float mài mòn CS2","aliases":["float value","giá trị float","factory new","mới từ nhà máy","minimal wear","mòn tối thiểu","battle-scarred","chiến tích"],"content":"The local CS2 vocabulary defines float ranges from Factory New 0.00–0.07 through Battle-Scarred 0.45–1.00.","constraints":["Use the recorded ranges as terminology support, not as a claim about an unseen item's exact wear."],"measurements":[{"name":"Factory New","value":"0.00–0.07"},{"name":"Battle-Scarred","value":"0.45–1.00"}],"source_refs":[{"path":"docs/cs2/3D_Vocabulary_CS2.json","key_path":"cs2_wear_ranges.factory_new"},{"path":"docs/cs2/3D_Vocabulary_CS2.json","key_path":"cs2_wear_ranges.battle_scarred"}],"evidence_refs":[{"kind":"source","ref":"docs/cs2/3D_Vocabulary_CS2.json"}],"observation_status":"observed","confidence":0.9,"assumptions":[]}+{"record_id":"cs2.uv-paint-pattern","collection":"cs2","domain":"uv","kind":"concept","entity":"CS2 paint pattern UV projection","title":"CS2 paint pattern UV projection / Chiếu UV mẫu sơn CS2","aliases":["UV mapping","ánh xạ UV","paint pattern","mẫu sơn","wear overlay","lớp phủ mòn"],"content":"The CS2 vocabulary defines a paint pattern as a 2D texture projected onto 3D via UV and a wear overlay as texture adding damage based on float.","constraints":["Keep paint-pattern placement and wear-overlay behavior tied to UV-backed source terminology."],"measurements":[],"source_refs":[{"path":"docs/cs2/3D_Vocabulary_CS2.json","key_path":"categories.cs2_workshop.terms.paint_pattern"},{"path":"docs/cs2/3D_Vocabulary_CS2.json","key_path":"categories.cs2_workshop.terms.wear_overlay"}],"evidence_refs":[{"kind":"source","ref":"docs/cs2/3D_Vocabulary_CS2.json"}],"observation_status":"observed","confidence":0.9,"assumptions":[]}diff --git a/docs/specs/vocabulary/cs2_reconstruction.jsonl b/docs/specs/vocabulary/cs2_reconstruction.jsonlnew file mode 100644index 0000000..79c88d6--- /dev/null+++ b/docs/specs/vocabulary/cs2_reconstruction.jsonl@@ -0,0 +1,62 @@+{"record_id":"cs2.attachment.sticker-placement-layering","collection":"cs2","domain":"attachment","kind":"finish","entity":"Sticker Placement & Layering","title":"Sticker Placement & Layering / Vị trí và Phân lớp Sticker","aliases":["Vị trí và Phân lớp Sticker"],"content":"Free-placement decal system using relative offset/rotation/scale within preset UV slots, with apply-order-based (not slot-order) layering.\n\nHệ thống decal đặt tự do dùng offset/xoay/tỷ lệ tương đối trong các slot UV cài sẵn, phân lớp theo thứ tự áp dụng (không phải thứ tự slot).\n\nRecognition cues: Decal-like flat graphic sitting on top of the base weapon skin, offset/rotated freely rather than fixed to a single spot; Newer stickers always render on top of older ones regardless of slot number — layering order = application order; Most weapons support 5 sticker slots (MP5-SD supports 8)\nDấu hiệu nhận diện: Đồ họa phẳng dạng decal nằm trên skin súng gốc, có thể lệch/xoay tự do thay vì cố định một vị trí; Sticker dán sau luôn hiển thị đè lên sticker cũ hơn bất kể số thứ tự slot — thứ tự lớp = thứ tự áp dụng; Hầu hết súng hỗ trợ 5 slot sticker (MP5-SD hỗ trợ 8)\n\nThree.js target: Multiple decal planes (PlaneGeometry or projected decal texture) parented to weapon UV reference nodes, z-offset ordered by application timestamp, transform driven by offset_x/offset_y/rotation/scale parameters","constraints":["Do not apply to knife, gloves — documented only for rifle, pistol, smg, sniper, heavy in the source research."],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.finish_pattern_rarity[3]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.attachment.weapon-charm-attachment","collection":"cs2","domain":"attachment","kind":"finish","entity":"Weapon Charm Attachment","title":"Weapon Charm Attachment / Gắn kết Weapon Charm","aliases":["Gắn kết Weapon Charm"],"content":"Independent decorative 3D meshes hung from a weapon via a skeletal spring-joint constraint, reacting dynamically to player movement and recoil.\n\nLưới 3D trang trí độc lập treo trên vũ khí qua ràng buộc khớp lò xo xương, phản ứng động theo chuyển động người chơi và độ giật.\n\nRecognition cues: A small independent 3D object hanging off the gun body, swinging/bouncing with recoil or movement rather than staying rigid; Cast soft contact shadows onto the weapon surface at its anchor socket; One charm per weapon max; sockets number in the dozens (e.g. ~17 on AWP, ~20 on AK-47) but avoid the grip/hand-contact zone\nDấu hiệu nhận diện: Vật thể 3D độc lập nhỏ treo trên thân súng, đung đưa/nảy theo độ giật hoặc chuyển động thay vì đứng yên cứng nhắc; Đổ bóng tiếp xúc mềm lên bề mặt vũ khí tại điểm neo; Tối đa một charm mỗi vũ khí; số điểm neo lên đến hàng chục (vd. ~17 ở AWP, ~20 ở AK-47) nhưng tránh vùng tay cầm/tiếp xúc tay\n\nThree.js target: Independent mesh with a spring-joint (soft constraint) parented to a named attachment socket on the weapon skeleton, simulated via a simple physics/spring update each frame","constraints":["Do not apply to knife, gloves — documented only for rifle, pistol, smg, sniper, heavy in the source research."],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.finish_pattern_rarity[7]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.finish.case-hardened-blue-gem-pattern","collection":"cs2","domain":"finish","kind":"finish","entity":"Case Hardened Blue Gem Pattern","title":"Case Hardened Blue Gem Pattern / Mẫu Case Hardened Blue Gem","aliases":["Mẫu Case Hardened Blue Gem"],"content":"A metallic oxidation pattern on Case Hardened skins where paint_seed determines the position/density of blue oxide clusters on the blade/gun surface; tiered by percentage of blue coverage on the playside.\n\nMẫu oxy hóa kim loại trên skin Case Hardened, trong đó paint_seed quyết định vị trí/mật độ cụm oxit xanh trên bề mặt lưỡi dao/súng; phân tầng theo phần trăm độ phủ xanh ở mặt playside.\n\nRecognition cues: Blend of blue (high-oxidation), purple (transition), and yellow/gold (base alloy steel) blotches; Tier 1 'God Tier': one large continuous blue cluster covering most of the playside (examples reach 94-99% coverage); Tier 2-3: blue coverage interrupted by yellow/gold patches or concentrated more on the backside than playside; Gold Gems are the visual inverse — near-total gold coverage with minimal blue\nDấu hiệu nhận diện: Pha trộn các vệt xanh dương (oxy hóa cao), tím (chuyển tiếp) và vàng/vàng kim (thép hợp kim nền); Tier 1 'God Tier': một cụm xanh lớn liên tục che phủ gần hết mặt playside (một số ví dụ đạt 94-99% độ phủ); Tier 2-3: độ phủ xanh bị gián đoạn bởi mảng vàng/vàng kim hoặc tập trung nhiều ở mặt sau hơn mặt playside; Gold Gems là hình ảnh đảo ngược — gần như toàn bộ phủ vàng kim, rất ít xanh\n\nThree.js target: Procedural gradient/noise-driven vertex color or texture blend across the blade UV, parameterized by a seed value driving cluster position and blue/purple/gold color ramp","constraints":["Do not apply to pistol, smg, sniper, heavy, gloves — documented only for knife, rifle in the source research."],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.finish_pattern_rarity[0]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.finish.cs2-weapon-finish-styles","collection":"cs2","domain":"finish","kind":"finish","entity":"CS2 Weapon Finish Styles","title":"CS2 Weapon Finish Styles / Các kiểu Finish vũ khí CS2","aliases":["Các kiểu Finish vũ khí CS2"],"content":"Nine distinct paint_style render architectures (Solid, Spray-Paint, Hydrographic, three Anodized variants, Patina, Custom Paint Job, Gunsmith) each with a different wear-erosion behavior.\n\nChín kiến trúc render paint_style riêng biệt (Solid, Spray-Paint, Hydrographic, ba biến thể Anodized, Patina, Custom Paint Job, Gunsmith), mỗi loại có hành vi bào mòn khác nhau.\n\nRecognition cues: Solid Color: flat uniform color, no pattern texture, wears straight to substrate; Spray-Paint: tiling pattern via triplanar mapping, wears through layers sequentially; Hydrographic: pattern tiled over native UVs simulating hydro-dipping, wears to substrate; Anodized (chrome base + single color) / Anodized Multicolored (custom roughness in alpha) / Anodized Airbrushed (soft radial gradients, used for Fade) — all wear TO CHROME first, exposing bright chrome before bare substrate; Patina: full-color image + normal map, iridescent view-angle sheen, never peels — instead darkens/desaturates/accumulates oxide with wear; Custom Paint Job: non-tiled illustrative texture, peels/flakes to dark metal substrate via a Wearness Mask; Gunsmith: hybrid Custom-Paint + Patina, grayscale mask splits regions into peeling-paint zones vs darkening-metal zones\nDấu hiệu nhận diện: Solid Color: màu phẳng đồng nhất, không có texture pattern, mòn thẳng xuống chất nền; Spray-Paint: pattern lặp qua triplanar mapping, mòn tuần tự qua từng lớp; Hydrographic: pattern lặp trên UV gốc mô phỏng hydro-dipping, mòn xuống chất nền; Anodized (nền chrome + một màu) / Anodized Multicolored (roughness tùy chỉnh trong alpha) / Anodized Airbrushed (gradient tỏa tròn mềm, dùng cho Fade) — tất cả đều mòn RA CHROME trước, lộ chrome sáng trước khi lộ chất nền; Patina: ảnh đầy màu + normal map, ánh ngũ sắc theo góc nhìn, không bong tróc — thay vào đó tối màu/mất bão hòa/tích oxit khi mòn; Custom Paint Job: texture minh họa không lặp, bong tróc lộ chất nền kim loại tối qua Wearness Mask; Gunsmith: lai giữa Custom-Paint và Patina, mặt nạ grayscale chia vùng bong tróc sơn và vùng kim loại tối màu\n\nThree.js target: Distinct shader path per paint_style value: triplanar UV projection for spray/anodized-airbrushed, native-UV tiling for hydrographic/patina/custom, each feeding a style-specific wear mix() function","constraints":["Do not apply to knife, gloves — documented only for rifle, pistol, smg, sniper, heavy in the source research."],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.finish_pattern_rarity[9]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.finish.doppler-phases-gem-variants","collection":"cs2","domain":"finish","kind":"finish","entity":"Doppler Phases & Gem Variants","title":"Doppler Phases & Gem Variants / Các Phase Doppler và biến thể đá quý","aliases":["Các Phase Doppler và biến thể đá quý"],"content":"A family of Doppler knife finishes (Phase 1-4, Ruby, Sapphire, Black Pearl) distinguished by dominant color combination and the presence/absence of an iridescent color-shift effect.\n\nNhóm các finish dao Doppler (Phase 1-4, Ruby, Sapphire, Black Pearl) phân biệt qua tổ hợp màu chủ đạo và có/không có hiệu ứng đổi màu ngũ sắc.\n\nRecognition cues: Phase 1: black-dominant with sparse pink/purple streaks; Phase 2: vivid pink+purple covering nearly the whole surface, most colorful phase; Phase 3: black/deep-blue/green mix — green presence is the unique tell for this phase; Phase 4: bright blue dominant with small black patches; Ruby: 100% uniform red, no black patches; Sapphire: 100% uniform blue, no black patches; Black Pearl: dark purple/black base with a view-angle-dependent iridescent purple-to-green shift — unique among all phases\nDấu hiệu nhận diện: Phase 1: đen chiếm ưu thế với vệt hồng/tím thưa thớt; Phase 2: hồng+tím rực rỡ phủ gần toàn bộ bề mặt, phase nhiều màu nhất; Phase 3: pha trộn đen/xanh dương đậm/xanh lá — sự xuất hiện của xanh lá là dấu hiệu riêng của phase này; Phase 4: xanh dương sáng chiếm ưu thế với vài mảng đen nhỏ; Ruby: đỏ đồng nhất 100%, không có mảng đen; Sapphire: xanh dương đồng nhất 100%, không có mảng đen; Black Pearl: nền tím đậm/đen với hiệu ứng đổi màu tím-sang-xanh lá ngũ sắc tùy góc nhìn — độc nhất trong các phase\n\nThree.js target: Binary metalness (1.0) + dynamic color-ramp lookup driven by 3D noise coordinates and view-angle (fresnel-like) term for the iridescent shift; implement as a custom shader/TSL node reading a color-ramp texture keyed by noise + viewDir·normal","constraints":["Do not apply to rifle, pistol, smg, sniper, heavy, gloves — documented only for knife in the source research."],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.finish_pattern_rarity[1]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.finish.fade-pattern-percentage","collection":"cs2","domain":"finish","kind":"finish","entity":"Fade Pattern Percentage","title":"Fade Pattern Percentage / Tỷ lệ mẫu Fade","aliases":["Tỷ lệ mẫu Fade"],"content":"A gradient finish (purple→pink/magenta→yellow/gold) whose 'fade %' is estimated from how much yellow coverage reaches the tip vs. how much unpainted gray substrate remains.\n\nFinish dạng gradient (tím→hồng/magenta→vàng/vàng kim), tỷ lệ '% fade' được ước lượng qua độ phủ vàng đến mũi so với phần chất nền xám chưa sơn còn lại.\n\nRecognition cues: Purple/blue always at the base, magenta/pink in the middle, yellow/gold at the tip — yellow coverage is the key percentage indicator; 100% (Full Fade): yellow fully covers the tip, gradient runs its full length, no gray substrate visible; 80% (Minimum Fade): little to no yellow, dominated by pink/purple with visible gray patches; Karambit/Talon knives are graded by ratio (e.g. 90/10 pink/purple) rather than gray-substrate percentage; Some knives (Falchion) can exceed 100% when the gradient spills onto the handle\nDấu hiệu nhận diện: Tím/xanh dương luôn ở gốc, hồng/magenta ở giữa, vàng/vàng kim ở mũi — độ phủ vàng là chỉ số phần trăm chính; 100% (Full Fade): vàng phủ kín mũi, gradient chạy hết chiều dài, không còn thấy nền xám; 80% (Fade tối thiểu): rất ít hoặc không có vàng, chủ yếu hồng/tím với các mảng xám còn thấy rõ; Dao Karambit/Talon được đánh giá theo tỷ lệ (vd. 90/10 hồng/tím) thay vì phần trăm nền xám; Một số dao (Falchion) có thể vượt quá 100% khi gradient tràn sang cả cán dao\n\nThree.js target: Anodized Airbrushed rendering path (Style 5): triplanar-mapped radial gradient, parameterized by a rotation angle theta derived from paint_seed feeding a purple→pink→yellow color ramp","constraints":["Do not apply to heavy, gloves — documented only for knife, rifle, pistol, smg, sniper in the source research."],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.finish_pattern_rarity[2]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.gloves.cuff","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"gloves cuff","title":"Cuff / Cổ găng tay","aliases":["Cổ găng tay"],"content":"Wrist-covering section of the glove; short cuff ends at/below the wrist, gauntlet extends up the forearm.\n\nPhần che cổ tay của găng tay; cổ ngắn kết thúc tại/dưới cổ tay, gauntlet kéo dài lên cẳng tay.\n\nRecognition cues: Short cuff: fabric ends right at the wrist line; Gauntlet: extended fabric/leather panel covering part of the forearm, often with its own strap\nDấu hiệu nhận diện: Cổ ngắn: vải kết thúc ngay tại đường cổ tay; Gauntlet: tấm vải/da kéo dài che một phần cẳng tay, thường có dây đai riêng\n\nThree.js target: ExtrudeGeometry cuff sleeve, length parameter distinguishes short-cuff vs gauntlet variants","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.gloves[0]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.gloves.finger-segments-gussets","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"gloves finger segments & gussets","title":"Finger Segments & Gussets / Đốt ngón tay và Vách ngăn","aliases":["Đốt ngón tay và Vách ngăn"],"content":"Pre-curved individual finger sections joined by stretch-fabric or mesh gussets for flexibility and ventilation.\n\nCác đốt ngón tay cong sẵn riêng lẻ, nối với nhau bằng vách ngăn vải co giãn hoặc lưới để tăng độ linh hoạt và thoáng khí.\n\nRecognition cues: Fingers show a natural pre-curved rest pose rather than lying flat; Thin, differently-textured strips (mesh/stretch fabric) visible between adjacent fingers\nDấu hiệu nhận diện: Ngón tay có tư thế nghỉ cong sẵn tự nhiên thay vì nằm thẳng; Các dải mỏng, kết cấu khác biệt (lưới/vải co giãn) thấy được giữa các ngón tay liền kề\n\nThree.js target: Slightly pre-curved CapsuleGeometry/tube segments per finger joint, thin plane-strip gusset geometry between finger meshes","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.gloves[3]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.gloves.knuckle-guard","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"gloves knuckle guard","title":"Knuckle Guard / Gù bảo vệ khớp","aliases":["Gù bảo vệ khớp"],"content":"Rigid TPU or carbon-fiber plate over the main finger knuckles, dispersing impact and resisting abrasion.\n\nTấm cứng TPU hoặc sợi carbon trên các khớp ngón tay chính, phân tán lực va chạm và chống mài mòn.\n\nRecognition cues: Raised, segmented hard plates across the back of the hand at knuckle positions, visually distinct (matte/textured) from the surrounding soft material\nDấu hiệu nhận diện: Các tấm cứng nhô lên, phân đoạn trên mu bàn tay tại vị trí khớp, khác biệt rõ (mờ/có kết cấu) so với vật liệu mềm xung quanh\n\nThree.js target: Segmented ExtrudeGeometry plates (one per knuckle) overlaid on the back-of-hand mesh, separate material with higher roughness/lower sheen","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.gloves[2]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.gloves.palm-palm-slider","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"gloves palm & palm slider","title":"Palm & Palm Slider / Lòng bàn tay và Miếng trượt lòng bàn tay","aliases":["Lòng bàn tay và Miếng trượt lòng bàn tay"],"content":"Grip surface (often goat/kangaroo leather) with a rigid TPU slider puck at the heel to reduce impact injury.\n\nBề mặt cầm nắm (thường bằng da dê/da chuột túi) với miếng trượt TPU cứng ở gót bàn tay để giảm chấn thương khi va chạm.\n\nRecognition cues: Textured leather-like surface on the inner hand; A distinct hard, smooth puck/patch at the base of the palm (heel), differing in material sheen from the surrounding leather\nDấu hiệu nhận diện: Bề mặt trong lòng bàn tay có kết cấu giống da; Có một miếng cứng, nhẵn, riêng biệt ở gốc lòng bàn tay (gót), khác độ bóng vật liệu so với da xung quanh\n\nThree.js target: Palm mesh with a separate small BoxGeometry/rounded-plate submesh (different material slot: harder roughness, distinct color) at the heel","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.gloves[1]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.gloves.wrist-strap-closure","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"gloves wrist strap / closure","title":"Wrist Strap / Closure / Đai khóa cổ tay","aliases":["Đai khóa cổ tay"],"content":"Hook-and-loop (Velcro) strap combined with neoprene to secure the glove firmly at the wrist.\n\nDây đai khóa dán (Velcro) kết hợp với neoprene để cố định chắc chắn găng tay tại cổ tay.\n\nRecognition cues: Overlapping strap with a visible rough/looped fastener patch at the cuff, distinct stitched seam\nDấu hiệu nhận diện: Dây đai chồng lên nhau có miếng khóa dán nhám/có móc thấy rõ ở cổ tay, đường may rõ rệt\n\nThree.js target: Flat ExtrudeGeometry strap band wrapped around the cuff cylinder, with a small rectangular fastener-patch submesh","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.gloves[4]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.heavy.action-bars","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"heavy action bars","title":"Action Bars / Thanh truyền động","aliases":["Thanh truyền động"],"content":"Metal rods linking the pump forend to the bolt, converting hand motion into the cycling action.\n\nThanh kim loại nối ốp lót tay trượt với khóa nòng, chuyển động tác tay thành chu trình nạp đạn.\n\nRecognition cues: Thin parallel rods visible in the gap between forend and receiver when the action is racked open\nDấu hiệu nhận diện: Thanh mảnh song song thấy được ở khe hở giữa ốp lót tay và thân súng khi kéo mở\n\nThree.js target: Thin paired CylinderGeometry rods linking forend and bolt-carrier nodes, mostly hidden when closed","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.heavy[2]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.heavy.ammo-belt-linked-ammunition","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"heavy ammo belt (linked ammunition)","title":"Ammo Belt (Linked Ammunition) / Dây băng đạn","aliases":["Dây băng đạn"],"content":"Chain of cartridges linked by metal links, feeding a machine gun continuously.\n\nChuỗi đạn liên kết bằng các mắt xích kim loại, tiếp đạn liên tục cho súng máy.\n\nRecognition cues: Segmented chain visible feeding into the top or side of the receiver, often draping from an ammo box or drum\nDấu hiệu nhận diện: Chuỗi phân đoạn thấy được đang tiếp vào phía trên hoặc bên hông thân súng, thường thõng từ hộp đạn hoặc trống đạn\n\nThree.js target: TubeGeometry following a curved path from a drum/box node into the feed-cover socket, with segment repetition for the link pattern","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.heavy[4]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.heavy.barrel-shroud","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"heavy barrel shroud","title":"Barrel Shroud / Ốp bao nòng","aliases":["Ốp bao nòng"],"content":"Perforated protective jacket around a heavy-fire barrel (shotgun or MG), dissipating heat and shielding the shooter's hand.\n\nVỏ bảo vệ có lỗ thông quanh nòng súng bắn nhanh (shotgun hoặc súng máy), tản nhiệt và bảo vệ tay xạ thủ.\n\nRecognition cues: Perforated/vented outer sleeve visibly separate from the inner barrel, common on sustained-fire weapons\nDấu hiệu nhận diện: Vỏ ngoài có lỗ/thông gió, thấy rõ tách biệt với nòng bên trong, phổ biến ở vũ khí bắn liên tục\n\nThree.js target: Hollow CylinderGeometry outer shell with an array of small CSG-subtracted vent holes, barrel visible inside via a see-through gap","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.heavy[1]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.heavy.bipod-heavy","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"heavy bipod (heavy)","title":"Bipod (Heavy) / Giá hai chân","aliases":["Giá hai chân"],"content":"Folding two-legged support for stable prone or bench firing of heavy automatic weapons.\n\nChân đỡ hai chân gấp được để bắn ổn định ở tư thế nằm hoặc trên bệ tì cho vũ khí tự động cỡ lớn.\n\nRecognition cues: Folding legs attached near the front of the barrel shroud/handguard\nDấu hiệu nhận diện: Chân gấp gắn gần phía trước ốp bao nòng/ốp lót tay\n\nThree.js target: Two hinged thin CylinderGeometry legs, child node with a fold joint near the front handguard","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.heavy[6]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.heavy.carrying-handle-heavy","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"heavy carrying handle (heavy)","title":"Carrying Handle (Heavy) / Tay xách","aliases":["Tay xách"],"content":"Handle mounted atop the receiver for transport or rapid barrel changes.\n\nTay cầm gắn phía trên thân súng để vận chuyển hoặc thay nòng nhanh.\n\nRecognition cues: Small looped handle protruding from the top of the receiver, often near the barrel-change latch\nDấu hiệu nhận diện: Tay cầm hình vòng nhỏ nhô ra từ phía trên thân súng, thường gần chốt thay nòng\n\nThree.js target: TorusGeometry (partial loop) or thin ExtrudeGeometry handle child node on top of the receiver","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.heavy[8]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.heavy.drum-magazine","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"heavy drum magazine","title":"Drum Magazine / Hộp tiếp đạn hình trống","aliases":["Hộp tiếp đạn hình trống"],"content":"High-capacity circular magazine holding coiled belted ammunition.\n\nHộp tiếp đạn hình tròn dung lượng lớn chứa dây đạn cuộn tròn bên trong.\n\nRecognition cues: Large flat circular drum mounted at the feed point, distinctly rounder/flatter than a box or curved magazine\nDấu hiệu nhận diện: Trống tròn phẳng lớn gắn tại điểm tiếp đạn, rõ ràng tròn/phẳng hơn hộp đạn thẳng hoặc cong\n\nThree.js target: CylinderGeometry (short height, large radius) mounted at the receiver's feed socket","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.heavy[5]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.heavy.feed-cover-top-cover","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"heavy feed cover (top cover)","title":"Feed Cover (Top Cover) / Nắp hộp khóa nòng","aliases":["Nắp hộp khóa nòng"],"content":"Hinged lid over the ammunition feed tray, keeping the belt aligned and shielding the loading mechanism.\n\nNắp có bản lề trên khay tiếp đạn, giữ dây đạn thẳng hàng và che chắn cơ cấu nạp đạn.\n\nRecognition cues: Flat hinged panel on top of the receiver, distinct seam line where it can flip open\nDấu hiệu nhận diện: Tấm phẳng có bản lề phía trên thân súng, có đường nối rõ rệt nơi có thể lật mở\n\nThree.js target: Flat BoxGeometry panel with a hinge joint at the rear edge of the receiver","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.heavy[7]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.heavy.magazine-tube-shotgun","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"heavy magazine tube (shotgun)","title":"Magazine Tube (Shotgun) / Ống chứa đạn (Shotgun)","aliases":["Ống chứa đạn (Shotgun)"],"content":"Tubular ammunition reservoir running beneath and parallel to the barrel.\n\nKho chứa đạn dạng ống chạy dưới và song song với nòng súng.\n\nRecognition cues: Thin cylindrical tube directly under the barrel, terminating near the muzzle end\nDấu hiệu nhận diện: Ống trụ mảnh ngay dưới nòng súng, kết thúc gần đầu nòng\n\nThree.js target: Thin CylinderGeometry parallel to and below the main barrel node","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.heavy[3]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.heavy.pump-action-forend","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"heavy pump action forend","title":"Pump Action Forend / Ốp lót tay trượt","aliases":["Ốp lót tay trượt"],"content":"Sliding handguard beneath a shotgun barrel, racked back-and-forth to eject and chamber shells.\n\nỐp lót tay có thể trượt dưới nòng shotgun, kéo tới lui để hất vỏ đạn cũ và nạp đạn mới.\n\nRecognition cues: Grooved handguard with a visible forward/backward slide gap along the magazine tube\nDấu hiệu nhận diện: Ốp lót tay có rãnh, thấy rõ khe trượt tới/lui dọc theo ống chứa đạn\n\nThree.js target: CylinderGeometry sleeve constrained to slide along the magazine-tube axis (translate-only joint)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.heavy[0]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.knife.balisong-bitesafe-handle-latch","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"knife balisong bite/safe handle & latch","title":"Balisong Bite/Safe Handle & Latch / Cán nguy hiểm/Cán an toàn và Chốt khóa (Balisong)","aliases":["Cán nguy hiểm/Cán an toàn và Chốt khóa (Balisong)"],"content":"Butterfly-knife-specific split handle: the bite handle swings on the edge side, the safe handle on the spine side, locked shut by a latch pin.\n\nCán dao bướm đặc thù chia đôi: cán nguy hiểm ở phía cạnh sắc, cán an toàn ở phía sống dao, được khóa lại bởi chốt latch.\n\nRecognition cues: Two hinged handle halves that fold flat against the blade; Bite handle closes against the sharp edge (dangerous to grip closed); safe handle closes against the spine; Small rotating latch pin at the tail end locking the halves together\nDấu hiệu nhận diện: Hai nửa cán có bản lề gấp phẳng áp vào lưỡi dao; Cán nguy hiểm đóng về phía cạnh sắc (nguy hiểm khi cầm lúc đóng); cán an toàn đóng về phía sống dao; Chốt xoay nhỏ ở đuôi cán khóa hai nửa lại với nhau\n\nThree.js target: Two hinged handle-half meshes with pivot joints at the bolster, plus a small CylinderGeometry latch pin child node","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.knife[8]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.knife.blade","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"knife blade","title":"Blade / Lưỡi dao","aliases":["Lưỡi dao"],"content":"The entire working portion of the knife, encompassing both the cutting edge and the spine.\n\nToàn bộ phần làm việc của con dao, bao gồm cả cạnh sắc và sống dao.\n\nRecognition cues: Main metal body extending from the handle/bolster to the tip\nDấu hiệu nhận diện: Khối kim loại chính kéo dài từ cán/đệm cán đến mũi dao\n\nThree.js target: ExtrudeGeometry from a custom 2D THREE.Shape blade silhouette, beveled at the edge side","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.knife[0]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.knife.bolster","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"knife bolster","title":"Bolster / Đệm cán / Khâu dao","aliases":["Đệm cán / Khâu dao"],"content":"Thick metal collar at the junction between blade and handle.\n\nMiếng đệm kim loại dày nằm ở điểm tiếp giáp giữa lưỡi dao và cán dao.\n\nRecognition cues: Distinct metal band/thickening right where the blade meets the handle, often a different material/finish than both\nDấu hiệu nhận diện: Dải kim loại/chỗ dày lên rõ rệt ngay tại điểm lưỡi dao gặp cán dao, thường khác vật liệu/finish với cả hai\n\nThree.js target: Short CylinderGeometry or BoxGeometry collar node between blade and handle meshes","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.knife[5]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.knife.edge","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"knife edge","title":"Edge / Cạnh sắc / Lưỡi cắt","aliases":["Cạnh sắc / Lưỡi cắt"],"content":"The sharpened line running from heel to tip used for cutting.\n\nĐường mài sắc chạy từ gót dao đến mũi dao dùng để cắt.\n\nRecognition cues: Thinnest, beveled, and typically brightest/most reflective line on the blade\nDấu hiệu nhận diện: Đường mỏng nhất, được vát và thường sáng bóng/phản chiếu nhất trên lưỡi dao\n\nThree.js target: Beveled edge geometry on the ExtrudeGeometry blade shape (narrow bevel angle on one side of the profile curve)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.knife[1]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.knife.handle-scales","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"knife handle scales","title":"Handle Scales / Ốp cán","aliases":["Ốp cán"],"content":"Two side panels (wood, G-10, stone, etc.) fastened to the tang to form the grip.\n\nHai miếng vật liệu (gỗ, nhựa G-10, đá,...) gắn vào hai bên chuôi dao để tạo thành tay cầm.\n\nRecognition cues: Paired flat panels on either side of the handle, visible fasteners (rivets/pins), distinct material texture from the blade\nDấu hiệu nhận diện: Hai tấm phẳng đối xứng hai bên cán dao, thấy rõ đinh tán/chốt, kết cấu vật liệu khác biệt so với lưỡi dao\n\nThree.js target: Two mirrored BoxGeometry/ExtrudeGeometry panels flanking the tang, with small CylinderGeometry rivets","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.knife[6]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.knife.pommel-butt-cap","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"knife pommel (butt cap)","title":"Pommel (Butt Cap) / Núm chuôi / Đuôi cán","aliases":["Núm chuôi / Đuôi cán"],"content":"End cap at the terminus of the handle, decorative or functional (striking/counterweight).\n\nNắp chặn ở đầu cuối của cán dao, mang tính trang trí hoặc chức năng (đập/đối trọng).\n\nRecognition cues: Rounded or flat metal cap terminating the handle, often used to secure a hidden tang\nDấu hiệu nhận diện: Nắp kim loại tròn hoặc phẳng kết thúc cán dao, thường dùng để cố định chuôi ẩn\n\nThree.js target: SphereGeometry (flattened) or short CylinderGeometry cap child node at the rear of the handle","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.knife[7]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.knife.spine-back","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"knife spine (back)","title":"Spine (Back) / Sống dao","aliases":["Sống dao"],"content":"Thick, unsharpened back edge opposite the cutting edge, providing rigidity.\n\nPhần lưng dày, không mài sắc, đối diện với cạnh sắc, tạo độ cứng cho lưỡi dao.\n\nRecognition cues: The thickest part of the blade cross-section, flat or gently curved, opposite the sharp edge\nDấu hiệu nhận diện: Phần dày nhất trong tiết diện lưỡi dao, phẳng hoặc hơi cong, đối diện với cạnh sắc\n\nThree.js target: CapsuleGeometry or thick unbeveled strip along the back of the ExtrudeGeometry blade profile","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.knife[2]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.knife.tang","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"knife tang","title":"Tang / Chuôi lưỡi / Tang","aliases":["Chuôi lưỡi / Tang"],"content":"Steel extension of the blade running into the handle.\n\nPhần thép của lưỡi dao kéo dài vào bên trong cán dao.\n\nRecognition cues: Full tang: visible steel strip running the length of the handle between the scales; Hidden tang: no visible steel, fully enclosed by handle material\nDấu hiệu nhận diện: Full tang: dải thép lộ rõ chạy dọc cán dao giữa hai ốp cán; Hidden tang: không thấy thép, được bọc hoàn toàn bởi vật liệu cán\n\nThree.js target: Full tang: thin BoxGeometry strip visible between handle-scale meshes; Hidden tang: internal-only geometry, invisible child node","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.knife[4]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.knife.tip-point","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"knife tip / point","title":"Tip / Point / Mũi dao","aliases":["Mũi dao"],"content":"Convergence point of edge and spine at the front of the blade.\n\nĐiểm hội tụ giữa cạnh sắc và sống dao ở phía trước lưỡi dao.\n\nRecognition cues: Sharpest point of the whole knife; profile shape (drop point, clip point, karambit hook, tanto) is a strong sub-type identifier\nDấu hiệu nhận diện: Điểm nhọn nhất của toàn bộ con dao; hình dạng mũi (drop point, clip point, móc karambit, tanto) là dấu hiệu phân loại quan trọng\n\nThree.js target: Terminal vertex of the ExtrudeGeometry 2D silhouette path — shape of this path segment encodes knife sub-type (e.g. Karambit hook curve)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.knife[3]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.pistol.barrel-pistol","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"pistol barrel (pistol)","title":"Barrel (Pistol) / Nòng súng","aliases":["Nòng súng"],"content":"Tube through which the bullet travels on firing; largely enclosed by the slide in most pistols.\n\nỐng mà viên đạn di chuyển qua khi bắn; phần lớn được bao bọc bởi khóa nòng ở hầu hết súng lục.\n\nRecognition cues: Visible mainly at the muzzle opening in the slide; on revolvers it's exposed and fixed, sometimes railed for accessories\nDấu hiệu nhận diện: Chủ yếu thấy ở lỗ miệng nòng trên khóa nòng; ở súng ổ xoay thì lộ rõ và cố định, đôi khi có rail để gắn phụ kiện\n\nThree.js target: CylinderGeometry nested inside the slide's CSG-subtracted bore channel","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.pistol[1]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.pistol.cocking-mechanism","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"pistol cocking mechanism","title":"Cocking Mechanism / Cơ chế lên đạn / Lên búa","aliases":["Cơ chế lên đạn / Lên búa"],"content":"Action of preparing the weapon to fire: racking the slide (pistol) or thumbing/fanning the hammer (revolver).\n\nThao tác chuẩn bị súng sẵn sàng bắn: kéo khóa nòng (súng lục) hoặc lên búa bằng ngón cái/kỹ thuật quạt búa (súng ổ xoay).\n\nRecognition cues: Pistol: serrated slide-grip grooves indicate the racking surface; Revolver: exposed hammer spur sized for thumb cocking; some pistols (Tec-9) use a knob-style charging handle instead\nDấu hiệu nhận diện: Súng lục: rãnh răng cưa trên khóa nòng cho biết bề mặt để kéo; Súng ổ xoay: đuôi búa lộ ra đủ lớn để lên cò bằng ngón cái; một số súng lục (Tec-9) dùng cần kéo dạng núm thay thế\n\nThree.js target: Not a distinct mesh — an animation/interaction state (slide travel distance or hammer rotation) rather than geometry","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.pistol[6]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.pistol.cylinder-revolver","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"pistol cylinder (revolver)","title":"Cylinder (Revolver) / Ổ xoay / Ổ đạn","aliases":["Ổ xoay / Ổ đạn"],"content":"Rotating drum housing multiple ammunition chambers, characteristic of revolvers.\n\nTrống xoay chứa nhiều buồng đạn, đặc trưng của súng ổ xoay.\n\nRecognition cues: Large round block at the mid-body of the weapon, visibly segmented into chamber holes (e.g. 8 for the R8 Revolver)\nDấu hiệu nhận diện: Khối tròn lớn ở giữa thân súng, thấy rõ được chia thành các lỗ buồng đạn (vd. 8 lỗ ở R8 Revolver)\n\nThree.js target: CylinderGeometry with radial array of small cylindrical CSG-subtracted chamber holes","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.pistol[2]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.pistol.grip","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"pistol grip","title":"Grip / Tay cầm / Báng súng","aliases":["Tay cầm / Báng súng"],"content":"Frame section gripped by the shooter, with front strap, backstrap, and (on semi-autos) the magazine well running through it.\n\nPhần khung mà xạ thủ nắm, gồm mặt trước, mặt sau, và (ở súng bán tự động) ổ tiếp đạn chạy xuyên qua.\n\nRecognition cues: Textured lower frame section below the trigger guard; on semi-autos the magazine inserts from its base\nDấu hiệu nhận diện: Phần khung dưới có vân nằm dưới vành bảo vệ cò; ở súng bán tự động, hộp tiếp đạn lắp vào từ đáy tay cầm\n\nThree.js target: BoxGeometry angled child of frame, with a CSG-subtracted magazine-well cavity for semi-autos","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.pistol[3]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.pistol.hammer","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"pistol hammer","title":"Hammer / Búa đập","aliases":["Búa đập"],"content":"Component that strikes the firing pin or primer directly to discharge the round.\n\nBộ phận đập vào kim hỏa hoặc trực tiếp vào hạt nổ để khai hỏa viên đạn.\n\nRecognition cues: Small protruding lever at the rear-top of the frame, often manually cockable (pulled back) before firing\nDấu hiệu nhận diện: Cần nhỏ nhô ra ở phía sau-trên khung súng, thường có thể lên cò thủ công (kéo ra sau) trước khi bắn\n\nThree.js target: Small hinged BoxGeometry/CylinderGeometry pivot node at the rear of the frame","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.pistol[5]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.pistol.slide","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"pistol slide","title":"Slide / Khóa nòng","aliases":["Khóa nòng"],"content":"Top moving assembly of a semi-auto pistol that reciprocates rearward on firing to cycle the action.\n\nCụm di động phía trên của súng lục bán tự động, giật lùi khi bắn để thực hiện chu trình nạp đạn.\n\nRecognition cues: Large metal block wrapping the barrel with serrated grip grooves at the rear for manual racking, houses the rear sight\nDấu hiệu nhận diện: Khối kim loại lớn bao quanh nòng súng, có rãnh răng cưa phía sau để kéo tay, chứa thước ngắm phía sau\n\nThree.js target: BoxGeometry (rounded top edges) sliding along a rail axis relative to the frame, parent node for rear sight","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.pistol[0]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.pistol.trigger-guard","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"pistol trigger guard","title":"Trigger Guard / Vành bảo vệ cò","aliases":["Vành bảo vệ cò"],"content":"Loop encircling the trigger to prevent accidental discharge.\n\nVòng bao quanh cò súng để ngăn cò bị bóp vô ý.\n\nRecognition cues: Round or rectangular metal/polymer loop directly beneath the frame, encircling the trigger\nDấu hiệu nhận diện: Vòng kim loại/nhựa hình tròn hoặc chữ nhật ngay dưới khung súng, bao quanh cò\n\nThree.js target: TorusGeometry (partial) or ExtrudeGeometry loop child of the frame","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.pistol[4]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.rarity.cs2-quality-types","collection":"cs2","domain":"rarity","kind":"finish","entity":"CS2 Quality Types","title":"CS2 Quality Types / Các loại chất lượng CS2","aliases":["Các loại chất lượng CS2"],"content":"Item-quality prefixes (Normal, Genuine, Vintage, Unusual, StatTrak, Souvenir) that can alter the 3D model itself, not just rarity color.\n\nTiền tố chất lượng vật phẩm (Normal, Genuine, Vintage, Unusual, StatTrak, Souvenir) có thể thay đổi chính mô hình 3D, không chỉ màu độ hiếm.\n\nRecognition cues: StatTrak: an added orange-glow LED counter submesh on guns, or a kill-count number etched into the main color channel on knives; Souvenir: always paired with 4 fixed gold-plated stickers representing tournament/team/MVP; Unusual (gloves): triggers a custom inspect loop and swaps in a distinct glove model\nDấu hiệu nhận diện: StatTrak: có thêm submesh bộ đếm LED phát sáng cam trên súng, hoặc số lần hạ gục khắc vào kênh màu chính trên dao; Souvenir: luôn đi kèm 4 sticker mạ vàng cố định đại diện giải đấu/đội tuyển/MVP; Unusual (găng tay): kích hoạt vòng lặp inspect tùy chỉnh và thay thế bằng mô hình găng tay riêng biệt\n\nThree.js target: Conditional child-mesh injection in the asset graph (e.g. add ST_counter submesh with emissive #FF4500) driven by a quality metadata flag","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.finish_pattern_rarity[5]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.rarity.cs2-rarity-tier-system","collection":"cs2","domain":"rarity","kind":"finish","entity":"CS2 Rarity Tier System","title":"CS2 Rarity Tier System / Hệ thống cấp độ hiếm CS2","aliases":["Hệ thống cấp độ hiếm CS2"],"content":"Color-coded rarity ladder (Consumer Grade through Contraband/Extraordinary) shown as a UI border color, also loosely correlating with unbox probability.\n\nThang phân cấp độ hiếm có mã màu (từ Consumer Grade đến Contraband/Extraordinary) hiển thị dưới dạng màu viền UI, cũng tương quan lỏng lẻo với xác suất mở hòm.\n\nRecognition cues: Consumer Grade: light blue-gray #B0C3D9; Industrial Grade: light blue #5E98D9; Mil-Spec: blue #4B69FF; Restricted: purple #8847FF; Classified: pink/magenta #D32CE6; Covert: red #EB4B4B; Contraband / ★ Extraordinary: gold #E4AE39 or #FFD700\nDấu hiệu nhận diện: Consumer Grade: xanh xám nhạt #B0C3D9; Industrial Grade: xanh dương nhạt #5E98D9; Mil-Spec: xanh dương #4B69FF; Restricted: tím #8847FF; Classified: hồng/magenta #D32CE6; Covert: đỏ #EB4B4B; Contraband / ★ Extraordinary: vàng kim #E4AE39 hoặc #FFD700\n\nThree.js target: UI-only metadata field (rarity color) attached to the reconstruction metadata schema — not a shader input, but useful for labeling/QA of generated assets","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.finish_pattern_rarity[4]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.rifle.barrel","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"rifle barrel","title":"Barrel / Nòng súng","aliases":["Nòng súng"],"content":"Steel tube that chambers the cartridge and directs the projectile down its bore.\n\nỐng thép chứa buồng đạn và định hướng viên đạn dọc theo lòng nòng.\n\nRecognition cues: Long cylindrical tube protruding from the front of the receiver, tapering slightly, ending at the muzzle\nDấu hiệu nhận diện: Ống trụ dài nhô ra phía trước thân súng, hơi thon dần, kết thúc ở miệng nòng\n\nThree.js target: CylinderGeometry(radiusTop≈radiusBottom, height=barrel length)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.rifle[2]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.rifle.bolt-carrier-group-bcg-charging-handle","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"rifle bolt carrier group (bcg) & charging handle","title":"Bolt Carrier Group (BCG) & Charging Handle / Cụm bệ khóa nòng và Cần kéo nạp đạn","aliases":["Cụm bệ khóa nòng và Cần kéo nạp đạn"],"content":"Internal mechanism performing chambering/locking/firing/extraction, manually cycled via an external handle.\n\nCơ cấu bên trong thực hiện nạp đạn/khóa nòng/khai hỏa/hất vỏ đạn, được lên đạn thủ công qua cần kéo bên ngoài.\n\nRecognition cues: Mostly hidden internally; visible externally only as the charging handle protrusion (top or side of receiver, AK top cover)\nDấu hiệu nhận diện: Chủ yếu ẩn bên trong; chỉ thấy được bên ngoài qua cần kéo nạp đạn nhô ra (trên hoặc bên hông thân súng, nắp trên với AK)\n\nThree.js target: Internal geometry usually omitted/low-detail for closed-bolt weapons; charging handle modeled as small BoxGeometry/CylinderGeometry knob","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.rifle[9]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.rifle.buttstock","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"rifle buttstock","title":"Buttstock / Báng súng","aliases":["Báng súng"],"content":"Rear section resting against the shooter's shoulder; may be fixed, folding, or collapsible.\n\nPhần đuôi tì vào vai xạ thủ; có thể cố định, gấp được hoặc thu gọn được.\n\nRecognition cues: Rearmost component, either a solid contoured shoulder piece (fixed) or a skeletal/folding frame (collapsible)\nDấu hiệu nhận diện: Bộ phận cuối cùng, hoặc là khối tì vai đặc có đường cong (cố định) hoặc khung xương/gấp được (thu gọn)\n\nThree.js target: BoxGeometry/ExtrudeGeometry child node parented to rear of lower receiver, with a hinge pivot if foldable","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.rifle[7]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.rifle.gas-tube","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"rifle gas tube","title":"Gas Tube / Ống dẫn khí","aliases":["Ống dẫn khí"],"content":"Thin tube channeling propellant gas from the barrel to cycle the action.\n\nỐng nhỏ dẫn khí thuốc súng từ nòng để vận hành chu trình nạp đạn.\n\nRecognition cues: Thin parallel rod running above/alongside the barrel under the handguard, often barely visible externally\nDấu hiệu nhận diện: Thanh mảnh song song chạy phía trên/dọc nòng súng dưới ốp lót tay, thường khó thấy từ bên ngoài\n\nThree.js target: Thin CylinderGeometry hidden mostly inside the handguard mesh","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.rifle[4]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.rifle.handguard","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"rifle handguard","title":"Handguard / Ốp lót tay","aliases":["Ốp lót tay"],"content":"Protective sleeve around the barrel preventing burns and providing a forward gripping surface.\n\nVỏ bảo vệ quanh nòng súng ngăn bỏng tay và tạo bề mặt cầm nắm phía trước.\n\nRecognition cues: Ribbed or railed sleeve surrounding the barrel between the receiver and muzzle, often with visible vents or rail slots\nDấu hiệu nhận diện: Vỏ có gân hoặc rãnh rail bao quanh nòng súng giữa thân súng và đầu nòng, thường có khe thông gió hoặc rail lộ rõ\n\nThree.js target: Hollow CylinderGeometry or BoxGeometry shell surrounding the barrel (CSG subtract for hollow interior)","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.rifle[5]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.rifle.lower-receiver","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"rifle lower receiver","title":"Lower Receiver / Thân dưới","aliases":["Thân dưới"],"content":"Bottom housing containing the trigger assembly, magazine well, and fire-selector.\n\nPhần vỏ dưới chứa cụm cò, ổ tiếp đạn (magazine well) và cần chọn chế độ bắn.\n\nRecognition cues: Contains the trigger guard opening and the magazine insertion slot; grip attaches to its rear\nDấu hiệu nhận diện: Chứa lỗ vành bảo vệ cò và khe lắp hộp tiếp đạn; tay cầm gắn ở phía sau\n\nThree.js target: BoxGeometry parent hosting trigger, magazine-well cavity (CSG subtract), and grip attachment socket","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.rifle[1]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.rifle.magazine","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"rifle magazine","title":"Magazine / Hộp tiếp đạn / Băng đạn","aliases":["Hộp tiếp đạn / Băng đạn"],"content":"Detachable ammunition container; shape varies by platform (curved 'banana' for AK-type, straight/translucent for AUG).\n\nHộp chứa đạn tháo rời được; hình dạng khác nhau theo dòng súng (cong hình chuối với AK, thẳng/trong suốt với AUG).\n\nRecognition cues: Protrudes downward from the magazine well, curved profile signals AK-pattern rifle, straight signals M4/AR-pattern\nDấu hiệu nhận diện: Nhô xuống dưới từ ổ tiếp đạn, hình cong báo hiệu súng dòng AK, hình thẳng báo hiệu dòng M4/AR\n\nThree.js target: ExtrudeGeometry (curved 2D profile extruded) for banana magazines; BoxGeometry for straight magazines","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.rifle[8]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.rifle.muzzle-device-flash-hider-compensator-suppressor","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"rifle muzzle device (flash hider / compensator / suppressor)","title":"Muzzle Device (Flash Hider / Compensator / Suppressor) / Đầu nòng (Loa che lửa / Bù giật / Giảm thanh)","aliases":["Đầu nòng (Loa che lửa / Bù giật / Giảm thanh)"],"content":"End-of-barrel attachment reducing muzzle flash, redirecting gas to counter recoil, or suppressing sound.\n\nPhụ kiện gắn ở đầu nòng để giảm lóe lửa, dẫn hướng khí để chống giật, hoặc giảm thanh.\n\nRecognition cues: Distinct slotted or perforated cylindrical/conical cap at the very tip of the barrel, wider than the bore\nDấu hiệu nhận diện: Nắp hình trụ/nón có rãnh hoặc lỗ thủng rõ rệt ở đầu nòng, rộng hơn lòng nòng\n\nThree.js target: Small CylinderGeometry or ConeGeometry child node parented to the barrel tip socket","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.rifle[3]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.rifle.pistol-grip","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"rifle pistol grip","title":"Pistol Grip / Tay cầm khai hỏa","aliases":["Tay cầm khai hỏa"],"content":"Handle behind the trigger used to hold and control the rifle.\n\nTay cầm phía sau cò dùng để giữ và điều khiển súng.\n\nRecognition cues: Angled handle protruding downward directly behind/below the trigger guard, textured for grip\nDấu hiệu nhận diện: Tay cầm nghiêng nhô xuống ngay phía sau/dưới vành bảo vệ cò, có vân tăng ma sát\n\nThree.js target: BoxGeometry, angled ~15-20° from vertical, child of lower receiver","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.rifle[6]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.rifle.upper-receiver","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"rifle upper receiver","title":"Upper Receiver / Thân trên","aliases":["Thân trên"],"content":"Top housing of the rifle containing the bolt carrier group and providing the barrel mounting point.\n\nPhần vỏ trên của súng trường chứa cụm bệ khóa nòng và là điểm gắn nòng súng.\n\nRecognition cues: Long central body spanning from the rear sight area to the barrel root, sits above the trigger/lower assembly\nDấu hiệu nhận diện: Thân dài trung tâm kéo dài từ khu vực thước ngắm đến gốc nòng súng, nằm phía trên cụm cò/thân dưới\n\nThree.js target: BoxGeometry-based blocked-out shell as the parent node for barrel, sight, and handguard child meshes","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.rifle[0]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.smg.curved-magazine-mp5-style","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"smg curved magazine (mp5-style)","title":"Curved Magazine (MP5-style) / Băng đạn cong (kiểu MP5)","aliases":["Băng đạn cong (kiểu MP5)"],"content":"Classic slightly-curved 30-round magazine seated forward of the trigger guard.\n\nBăng đạn cong nhẹ cổ điển 30 viên, lắp phía trước vành bảo vệ cò.\n\nRecognition cues: Gentle curve, inserted vertically in front of the trigger guard — silhouette closely tied to the classic MP5 family\nDấu hiệu nhận diện: Cong nhẹ, lắp thẳng đứng phía trước vành bảo vệ cò — hình dáng gắn liền với dòng MP5 cổ điển\n\nThree.js target: ExtrudeGeometry with a shallow-curved 2D profile, inserted into a magazine-well socket forward of the grip","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.smg[1]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.smg.helical-magazine-bizon-style","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"smg helical magazine (bizon-style)","title":"Helical Magazine (Bizon-style) / Băng đạn hình trụ xoắn (kiểu Bizon)","aliases":["Băng đạn hình trụ xoắn (kiểu Bizon)"],"content":"High-capacity (64-round) cylindrical magazine mounted beneath and along the barrel, doubling as a handguard.\n\nBăng đạn hình trụ dung lượng lớn (64 viên) lắp dưới và dọc theo nòng súng, kiêm luôn vai trò ốp lót tay.\n\nRecognition cues: Long cylindrical magazine running parallel under the full barrel length, gripped directly by the support hand\nDấu hiệu nhận diện: Băng đạn hình trụ dài chạy song song dưới suốt chiều dài nòng súng, được tay đỡ nắm trực tiếp\n\nThree.js target: CylinderGeometry magazine node spanning the underside of the barrel, doubling as the handguard grip surface","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.smg[4]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.smg.integrated-silencer-mp5-sd","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"smg integrated silencer (mp5-sd)","title":"Integrated Silencer (MP5-SD) / Ống giảm thanh tích hợp (MP5-SD)","aliases":["Ống giảm thanh tích hợp (MP5-SD)"],"content":"Large cylindrical suppressor sleeve permanently enclosing the barrel on the MP5-SD variant.\n\nVỏ giảm thanh hình trụ lớn bao trùm vĩnh viễn nòng súng ở biến thể MP5-SD.\n\nRecognition cues: Barrel appears uniformly thick/enclosed for its entire length rather than showing a distinct thin barrel + separate can\nDấu hiệu nhận diện: Nòng súng trông đồng đều dày/được bao bọc suốt chiều dài thay vì có nòng mảnh riêng biệt + ống giảm thanh rời\n\nThree.js target: Single large CylinderGeometry enclosing the barrel node, replacing separate barrel+suppressor children","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.smg[2]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.smg.stock-smg-specific","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"smg stock (smg-specific)","title":"Stock (SMG-specific) / Báng súng (đặc trưng SMG)","aliases":["Báng súng (đặc trưng SMG)"],"content":"Shoulder-stabilizing rear piece, typically foldable/retractable/collapsible on SMGs to keep the platform compact.\n\nBộ phận tì vai phía sau, thường gấp/rút được ở SMG để giữ súng nhỏ gọn.\n\nRecognition cues: Distinctly more compact and often skeletal/folding compared to a rifle's fixed stock — a strong SMG vs rifle discriminator\nDấu hiệu nhận diện: Rõ ràng nhỏ gọn hơn và thường dạng khung/gấp được so với báng súng cố định của súng trường — dấu hiệu phân biệt SMG với súng trường\n\nThree.js target: Hinged BoxGeometry/thin-frame ExtrudeGeometry child node with a fold pivot relative to the receiver","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.smg[0]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.smg.top-mounted-horizontal-magazine-p90-style","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"smg top-mounted horizontal magazine (p90-style)","title":"Top-Mounted Horizontal Magazine (P90-style) / Băng đạn nằm ngang phía trên (kiểu P90)","aliases":["Băng đạn nằm ngang phía trên (kiểu P90)"],"content":"Translucent polymer magazine running parallel to and above the barrel, bullpup layout.\n\nBăng đạn nhựa trong suốt chạy song song và nằm phía trên nòng súng, bố cục bullpup.\n\nRecognition cues: Magazine lies flat along the top of the receiver rather than protruding downward — the single strongest P90 identifier; Downward-facing ejection port in the stock area\nDấu hiệu nhận diện: Băng đạn nằm phẳng dọc theo phía trên thân súng thay vì nhô xuống dưới — dấu hiệu nhận diện P90 mạnh nhất; Cửa hất vỏ đạn hướng xuống dưới ở khu vực báng súng\n\nThree.js target: BoxGeometry magazine node parented along the top rail axis instead of the bottom of the receiver","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.smg[3]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.sniper.bipod-monopod","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"sniper bipod / monopod","title":"Bipod / Monopod / Chân chống hai chân / Chân chống đơn","aliases":["Chân chống hai chân / Chân chống đơn"],"content":"Front two-legged support (bipod) and rear retractable spike (monopod) creating a stable three-point stance when deployed.\n\nChân chống hai chân phía trước (bipod) và chân chống đơn/spike có thể thu vào phía sau (monopod) tạo thế đứng ba điểm ổn định khi triển khai.\n\nRecognition cues: Folding legs under the front handguard plus a small retractable spike under the rear of the stock — together create a distinct three-point silhouette when deployed\nDấu hiệu nhận diện: Chân gấp dưới ốp lót tay phía trước cộng với spike nhỏ có thể thu vào dưới đuôi báng súng — cùng tạo hình dáng ba điểm rõ rệt khi triển khai\n\nThree.js target: Two hinged thin CylinderGeometry legs (bipod) + one telescoping CylinderGeometry spike (monopod), child nodes with fold/extend joints","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.sniper[6]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.sniper.bolt-action","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"sniper bolt action","title":"Bolt Action / Cơ cấu lên đạn (Bolt Action)","aliases":["Cơ cấu lên đạn (Bolt Action)"],"content":"Manually-operated locking/cycling mechanism characteristic of precision sniper rifles.\n\nCơ chế khóa nòng/lên đạn vận hành thủ công đặc trưng của súng bắn tỉa chính xác.\n\nRecognition cues: Protruding bolt handle is the visual proxy for this mechanism (see Bolt Handle entry)\nDấu hiệu nhận diện: Cần kéo khóa nòng nhô ra là dấu hiệu thị giác đại diện cho cơ chế này (xem mục Cần kéo khóa nòng)\n\nThree.js target: Internal action geometry usually low-detail; represented externally via the bolt handle child mesh","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.sniper[0]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.sniper.bolt-handle","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"sniper bolt handle","title":"Bolt Handle / Cần kéo khóa nòng","aliases":["Cần kéo khóa nòng"],"content":"Protruding manual handle used to cycle a bolt-action rifle.\n\nCần kéo thủ công nhô ra dùng để lên đạn cho súng bolt-action.\n\nRecognition cues: Prominent knob/lever extending from the side of the receiver — unlike the recessed charging handles of gas-operated rifles, this is the single strongest sniper-vs-assault-rifle discriminator\nDấu hiệu nhận diện: Núm/cần nhô rõ rệt từ bên hông thân súng — khác với cần kéo nạp đạn thụt vào của súng trích khí, đây là dấu hiệu phân biệt súng bắn tỉa và súng trường mạnh nhất\n\nThree.js target: SphereGeometry knob + thin CylinderGeometry arm, child node on the side of the receiver","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.sniper[1]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.sniper.cheek-riser-adjustable-buttstock","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"sniper cheek riser / adjustable buttstock","title":"Cheek Riser / Adjustable Buttstock / Ốp má / Báng súng có thể điều chỉnh","aliases":["Ốp má / Báng súng có thể điều chỉnh"],"content":"Elevated, often adjustable stock component aligning the shooter's eye with a high-mounted scope; foldable on some platforms (SSG 08).\n\nBộ phận báng súng nâng cao, thường điều chỉnh được, giúp căn mắt xạ thủ với kính ngắm gắn cao; gấp được ở một số dòng (SSG 08).\n\nRecognition cues: Visible knobs/sliders/adjustment screws on the stock, giving a more 'modular' look than a simple fixed rifle stock\nDấu hiệu nhận diện: Thấy rõ các núm/thanh trượt/ốc điều chỉnh trên báng súng, tạo cảm giác 'modular' hơn báng súng cố định đơn giản\n\nThree.js target: ExtrudeGeometry stock body with small CylinderGeometry adjustment knob child nodes and a slide joint for the riser","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.sniper[5]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.sniper.heavybull-free-floating-fluted-barrel","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"sniper heavy/bull, free-floating, fluted barrel","title":"Heavy/Bull, Free-Floating, Fluted Barrel / Nòng nặng, Nòng tự do, Nòng có rãnh","aliases":["Nòng nặng, Nòng tự do, Nòng có rãnh"],"content":"Thick match-grade barrel variants: bull barrel (vibration control), free-floating (no stock contact, for accuracy), fluted (grooved to save weight).\n\nCác biến thể nòng match-grade dày: nòng bull (kiểm soát rung), nòng tự do (không chạm báng súng, tăng độ chính xác), nòng có rãnh (khoét rãnh để giảm trọng lượng).\n\nRecognition cues: Noticeably thicker barrel profile than assault rifles; A visible air gap between barrel and handguard signals free-floating design; Longitudinal grooves along the barrel signal fluting\nDấu hiệu nhận diện: Tiết diện nòng dày rõ rệt hơn súng trường thường; Khe hở rõ giữa nòng và ốp lót tay báo hiệu thiết kế free-floating; Các rãnh dọc theo nòng báo hiệu nòng có rãnh (fluted)\n\nThree.js target: Thicker CylinderGeometry barrel with optional longitudinal groove geometry (repeated thin CSG-subtracted channels) for fluting","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.sniper[2]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.sniper.muzzle-brake-compensator-heavy","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"sniper muzzle brake / compensator (heavy)","title":"Muzzle Brake / Compensator (Heavy) / Bộ phận hãm giật / Bù giật (cỡ lớn)","aliases":["Bộ phận hãm giật / Bù giật (cỡ lớn)"],"content":"Oversized gas-redirecting device at the muzzle to counter significant recoil from high-caliber rounds.\n\nThiết bị dẫn hướng khí cỡ lớn ở đầu nòng để chống giật đáng kể từ đạn cỡ lớn.\n\nRecognition cues: Boxy, noticeably wider-than-barrel device with large venting ports at the muzzle tip\nDấu hiệu nhận diện: Thiết bị dạng hộp, rõ ràng rộng hơn nòng súng, có các lỗ thoát khí lớn ở đầu nòng\n\nThree.js target: BoxGeometry/CylinderGeometry hybrid, wider radius than the barrel, with CSG-subtracted vent slots","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.sniper[3]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.sniper.scope-mount-rings-picatinny-rail","collection":"cs2","domain":"weapon-anatomy","kind":"component","entity":"sniper scope mount, rings & picatinny rail","title":"Scope Mount, Rings & Picatinny Rail / Gá ống ngắm, vòng khuyên giữ và rail Picatinny","aliases":["Gá ống ngắm, vòng khuyên giữ và rail Picatinny"],"content":"Hardware (claw mounts, rings, standardized MIL-STD-1913 rail) securing a high-magnification optic well above the bore axis.\n\nPhần cứng (gá kẹp, vòng khuyên, rail chuẩn MIL-STD-1913) cố định kính ngắm phóng đại cao, nằm cao hơn hẳn trục nòng.\n\nRecognition cues: Long flat rail spanning the top of the receiver, dominated by a tall scope sitting well above the standard iron-sight line\nDấu hiệu nhận diện: Rail phẳng dài trải dọc phía trên thân súng, bị chi phối bởi ống ngắm cao nằm hẳn trên đường ngắm cơ bản tiêu chuẩn\n\nThree.js target: BoxGeometry rail strip on top of receiver + CylinderGeometry scope body + Torus/ring mount clamps as child nodes","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.geometry_anatomy.sniper[4]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.wear.glove-float-cap-range","collection":"cs2","domain":"wear","kind":"finish","entity":"Glove Float Cap Range","title":"Glove Float Cap Range / Giới hạn Float của Găng tay","aliases":["Giới hạn Float của Găng tay"],"content":"Gloves use a compressed float range (0.06-0.80) compared to weapons (0.00-1.00), making a given float value read as visually more worn on gloves than on a gun.\n\nGăng tay dùng dải float bị nén (0.06-0.80) so với vũ khí (0.00-1.00), khiến cùng một giá trị float trông mòn hơn về mặt thị giác trên găng tay so với trên súng.\n\nRecognition cues: Factory New band is unusually narrow: 0.06-0.07 only; A glove at float 0.15 (nominally 'Minimal Wear') can look as worn as a Field-Tested gun at 0.35; Wear shows most prominently on the knuckle guard, fingertips, and palm edges\nDấu hiệu nhận diện: Dải Factory New bất thường hẹp: chỉ 0.06-0.07; Găng tay ở float 0.15 (danh nghĩa 'Minimal Wear') có thể trông mòn tương đương súng Field-Tested ở 0.35; Vết mòn thể hiện rõ nhất ở gù bảo vệ khớp, đầu ngón tay và cạnh lòng bàn tay\n\nThree.js target: Same wear-state mix() shader as weapons but with wear_remap_min=0.06/wear_remap_max=0.80 applied before sampling the float-driven blend","constraints":["Do not apply to rifle, pistol, knife, smg, sniper, heavy — documented only for gloves in the source research."],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.finish_pattern_rarity[8]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}+{"record_id":"cs2.wear.wear-float-level-system","collection":"cs2","domain":"wear","kind":"finish","entity":"Wear / Float Level System","title":"Wear / Float Level System / Hệ thống độ mòn / Float","aliases":["Hệ thống độ mòn / Float"],"content":"Permanent 0.00-1.00 float value fixed at item creation, mapped to five wear-level bands (Factory New, Minimal Wear, Field-Tested, Well-Worn, Battle-Scarred) each with characteristic surface degradation.\n\nGiá trị float cố định vĩnh viễn từ 0.00-1.00 khi tạo vật phẩm, ánh xạ sang năm dải cấp độ mòn (Factory New, Minimal Wear, Field-Tested, Well-Worn, Battle-Scarred), mỗi cấp có đặc điểm xuống cấp bề mặt riêng.\n\nRecognition cues: Factory New [0.00-0.07): near-perfect finish, at most barely-visible edge scuffing; Minimal Wear [0.07-0.15): small micro-scratches at corners, paint intact on ~95% of surface; Field-Tested [0.15-0.38): clearly visible scratches/chips, paint starting to peel at edges, reduced gloss; Well-Worn [0.38-0.45): large dense scratches exposing substrate, color oxidation/dulling; Battle-Scarred [0.45-1.00]: near-total paint loss, deep gouges, dirt/grunge accumulation; Weathering is geometry-aware: curvature maps concentrate scratches on sharp edges, AO maps protect recesses (which instead darken/accumulate grime)\nDấu hiệu nhận diện: Factory New [0.00-0.07): finish gần hoàn hảo, cùng lắm là trầy nhẹ khó thấy ở cạnh; Minimal Wear [0.07-0.15): vết trầy nhỏ li ti ở góc, sơn còn nguyên ~95% bề mặt; Field-Tested [0.15-0.38): vết trầy/mẻ thấy rõ, sơn bắt đầu bong ở cạnh, độ bóng giảm; Well-Worn [0.38-0.45): vết trầy lớn dày đặc lộ chất nền, màu bị oxy hóa/xỉn; Battle-Scarred [0.45-1.00]: mất sơn gần như hoàn toàn, vết lõm sâu, tích tụ bụi bẩn; Sự xuống cấp có nhận biết hình học: bản đồ độ cong tập trung vết xước ở cạnh sắc, bản đồ AO bảo vệ chỗ lõm (thay vào đó tối màu/tích bụi)\n\nThree.js target: Float value drives a mix() between pristine and worn material states via the Wearness Alpha Mask, curvature map, and AO map — see rendering_shader_mapping 'Wear-State Material Blend'","constraints":[],"measurements":[],"source_refs":[{"path":"docs/raw/img2threejs-skill-dataset.json","key_path":"categories.finish_pattern_rarity[6]"}],"evidence_refs":[{"kind":"source","ref":"docs/raw/img2threejs-skill-dataset.json","note":"img2threejs NotebookLM research distillation"}],"observation_status":"observed","confidence":0.8,"assumptions":[]}diff --git a/forge/_shared/spec_search.py b/forge/_shared/spec_search.pynew file mode 100644index 0000000..3513c01--- /dev/null+++ b/forge/_shared/spec_search.py@@ -0,0 +1,1792 @@+"""Profile, record, tokenizer, and source-ingestion boundary. # noqa: SIZE_OK"""++from __future__ import annotations++import json+import hashlib+import math+import os+import re+import stat+import tempfile+import unicodedata+from collections import Counter+from collections.abc import Mapping, Sequence+from dataclasses import dataclass+from pathlib import Path+from typing import Final, Literal, NoReturn, TypeAlias, TypedDict++JsonScalar: TypeAlias = str | int | float | bool | None+JsonValue: TypeAlias = JsonScalar | list["JsonValue"] | dict[str, "JsonValue"]+SourceKind: TypeAlias = Literal["markdown", "json", "jsonl"]+CacheStatus: TypeAlias = Literal["hit", "rebuilt"]+CacheReason: TypeAlias = Literal["current", "missing", "stale", "corrupt", "forced"]+UnicodeNormalization: TypeAlias = Literal["NFC", "NFD", "NFKC", "NFKD"]+AccentFold: TypeAlias = Literal["none", "vi"]+_SOURCE_KINDS: Final[dict[str, SourceKind]] = {+ ".md": "markdown",+ ".json": "json",+ ".jsonl": "jsonl",+}+++class TokenizerSettings(TypedDict):+ version: str+ unicode_normalization: UnicodeNormalization+ casefold: bool+ accent_fold: AccentFold+ preserve_identifiers: bool+ preserve_numbers: bool+++class AliasSettings(TypedDict):+ enabled: bool+ max_expansions: int+++class Bm25Settings(TypedDict):+ k1: float+ b: float+++class CollectionProfile(TypedDict):+ source_roots: list[str]+ optional_source_roots: list[str]+ distilled_records: list[str]+ cache: str+ documentation: str+ encoding: str+ languages: list[str]+ source_extensions: list[str]+ tokenizer: TokenizerSettings+ aliases: AliasSettings+ bm25: Bm25Settings+ term_aliases: dict[str, list[str]]+++class MeasurementRequired(TypedDict):+ name: str+ value: str+++class Measurement(MeasurementRequired, total=False):+ unit: str+ context: str+++class SourceRefRequired(TypedDict):+ path: str+++class SourceRef(SourceRefRequired, total=False):+ heading: str+ key_path: str+++class EvidenceRefRequired(TypedDict):+ kind: str+ ref: str+++class EvidenceRef(EvidenceRefRequired, total=False):+ note: str+++class SpecRecord(TypedDict):+ record_id: str+ collection: str+ domain: str+ kind: str+ entity: str+ title: str+ aliases: list[str]+ content: str+ constraints: list[str]+ measurements: list[Measurement]+ source_refs: list[SourceRef]+ evidence_refs: list[EvidenceRef]+ observation_status: str+ confidence: float+ assumptions: list[str]+++class CachedSourceReference(TypedDict):+ path: str+ heading: str | None+ key_path: str | None+++class CachedEvidenceReferenceRequired(TypedDict):+ kind: str+ ref: str+++class CachedEvidenceReference(CachedEvidenceReferenceRequired, total=False):+ note: str+++class CachedRecord(TypedDict):+ record_id: str+ collection: str+ title: str+ content: str+ file_path: str+ heading: str | None+ key_path: str | None+ aliases: list[str]+ source_refs: list[CachedSourceReference]+ evidence_refs: list[CachedEvidenceReference]+++class CachedPosting(TypedDict):+ record_id: str+ term_frequency: int+++class CachePayload(TypedDict):+ schema_version: int+ schema_fingerprint: str+ tokenizer_fingerprint: str+ config_fingerprint: str+ source_fingerprint: str+ fingerprint: str+ collection: str+ k1: float+ b: float+ tokenizer: TokenizerSettings+ document_lengths: dict[str, int]+ avgdl: float+ document_frequencies: dict[str, int]+ postings: dict[str, list[CachedPosting]]+ records: dict[str, CachedRecord]+ term_aliases: dict[str, list[str]]+++@dataclass(frozen=True, slots=True)+class SourceReference:+ path: str+ heading: str | None = None+ key_path: str | None = None+++@dataclass(frozen=True, slots=True)+class EvidenceReference:+ kind: str+ ref: str+ note: str | None = None+++@dataclass(frozen=True, slots=True)+class SourceDocument:+ record_id: str+ collection: str+ title: str+ content: str+ file_path: str+ heading: str | None = None+ key_path: str | None = None+ aliases: tuple[str, ...] = ()+ source_refs: tuple[SourceReference, ...] = ()+ evidence_refs: tuple[EvidenceReference, ...] = ()+++@dataclass(frozen=True, slots=True)+class TokenizerConfig:+ version: str = "1"+ unicode_normalization: UnicodeNormalization = "NFKC"+ casefold: bool = True+ accent_fold: AccentFold = "vi"+ preserve_identifiers: bool = True+ preserve_numbers: bool = True+++@dataclass(frozen=True, slots=True)+class Bm25Config:+ collection: str+ k1: float = 1.5+ b: float = 0.75+ tokenizer: TokenizerConfig = TokenizerConfig()+ term_aliases: tuple[tuple[str, tuple[str, ...]], ...] = ()+++@dataclass(frozen=True, slots=True)+class IndexFingerprints:+ schema: str = ""+ tokenizer: str = ""+ config: str = ""+ source: str = ""++ @property+ def combined(self) -> str:+ return _fingerprint(+ {+ "schema": self.schema,+ "tokenizer": self.tokenizer,+ "config": self.config,+ "source": self.source,+ }+ )+++@dataclass(frozen=True, slots=True)+class Posting:+ record_id: str+ term_frequency: int+++@dataclass(frozen=True, slots=True)+class Bm25Index:+ collection: str+ k1: float+ b: float+ tokenizer: TokenizerConfig+ fingerprints: IndexFingerprints+ document_lengths: Mapping[str, int]+ avgdl: float+ document_frequencies: Mapping[str, int]+ postings: Mapping[str, tuple[Posting, ...]]+ records: Mapping[str, SourceDocument]+ term_aliases: Mapping[str, tuple[str, ...]]++ @property+ def fingerprint(self) -> str:+ return self.fingerprints.combined+++@dataclass(frozen=True, slots=True)+class SearchMatch:+ record: SourceDocument+ score: float+++class SerializedSearchMatch(TypedDict):+ record_id: str+ file_path: str+ heading: str | None+ key_path: str | None+ score: float+ snippets: list[str]+ source_refs: list[CachedSourceReference]+ evidence_refs: list[CachedEvidenceReference]+++@dataclass(frozen=True, slots=True)+class SearchOutputRequest:+ query: str+ limit: int+ snippet_chars: int+++@dataclass(frozen=True, slots=True)+class IndexRequest:+ project_root: Path+ collection: str+ profile: CollectionProfile+ force_reindex: bool = False+++@dataclass(frozen=True, slots=True)+class IndexLoadResult:+ index: Bm25Index+ status: CacheStatus+ reason: CacheReason+ cache_path: Path++ @property+ def fingerprint(self) -> str:+ return self.index.fingerprint+++@dataclass(frozen=True, slots=True)+class ConfiguredSource:+ path: Path+ source_path: str+ kind: SourceKind+++@dataclass(frozen=True, slots=True)+class ProfileValidationError(ValueError):+ path: Path+ reason: str++ def __str__(self) -> str:+ return f"{self.path}: {self.reason}"+++@dataclass(frozen=True, slots=True)+class ProfileCachePathError(ValueError):+ reason: str++ def __str__(self) -> str:+ return self.reason+++@dataclass(frozen=True, slots=True)+class UnknownCollectionError(KeyError):+ collection: str++ def __str__(self) -> str:+ return f"unknown spec-search collection: {self.collection}"+++@dataclass(frozen=True, slots=True)+class SourceIngestionError(Exception):+ path: Path+ reason: str++ def __str__(self) -> str:+ return f"{self.path}: {self.reason}"+++@dataclass(frozen=True, slots=True)+class SpecRecordValidationError(ValueError):+ path: Path+ line_number: int+ reason: str++ def __str__(self) -> str:+ return f"{self.path}:{self.line_number}: {self.reason}"+++@dataclass(frozen=True, slots=True)+class IndexBuildError(ValueError):+ reason: str++ def __str__(self) -> str:+ return self.reason+++@dataclass(frozen=True, slots=True)+class CacheValidationError(ValueError):+ path: Path+ reason: str++ def __str__(self) -> str:+ return f"{self.path}: {self.reason}"+++@dataclass(frozen=True, slots=True)+class CacheReadError(Exception):+ path: Path+ reason: str++ def __str__(self) -> str:+ return f"{self.path}: {self.reason}"+++@dataclass(frozen=True, slots=True)+class CacheWriteError(Exception):+ path: Path+ reason: str++ def __str__(self) -> str:+ return f"{self.path}: {self.reason}"+++_DEFAULT_PROFILES_PATH: Final = Path(__file__).with_name("spec_search_profiles.json")+_CACHE_SCHEMA_VERSION: Final = 2+_TOKENIZER_SCHEMA_VERSION: Final = "2"+_DEFAULT_TOKENIZER_CONFIG: Final = TokenizerConfig()+_NORMALIZATION_BY_NAME: Final[dict[str, UnicodeNormalization]] = {+ "NFC": "NFC",+ "NFD": "NFD",+ "NFKC": "NFKC",+ "NFKD": "NFKD",+}+_ACCENT_FOLD_BY_NAME: Final[dict[str, AccentFold]] = {+ "none": "none",+ "vi": "vi",+}+_IDENTIFIER_TOKEN_PATTERN: Final = re.compile(+ r"[^\W_]+(?:[_.\-\u2010-\u2015][^\W_]+)*",+ re.UNICODE,+)+_WORD_TOKEN_PATTERN: Final = re.compile(r"[^\W_]+", re.UNICODE)+_DASH_TRANSLATION: Final = str.maketrans({character: "-" for character in "‐‑‒–—―"})+_VIETNAMESE_MARKED: Final = frozenset(+ "àáảãạăằắẳẵặâầấẩẫậèéẻẽẹêềếểễệìíỉĩịòóỏõọôồốổỗộơờớởỡợ"+ "ùúủũụưừứửữựỳýỷỹỵđ"+)+++def _profile_error(path: Path, reason: str) -> ProfileValidationError:+ return ProfileValidationError(path=path, reason=reason)+++def _mapping(value: JsonValue, path: Path, label: str) -> dict[str, JsonValue]:+ if type(value) is not dict:+ raise _profile_error(path, f"{label} must be an object")+ return value+++def _profile_string(mapping: dict[str, JsonValue], field: str, path: Path) -> str:+ value = mapping.get(field)+ if type(value) is not str or not value:+ raise _profile_error(path, f"{field} must be a non-empty string")+ return value+++def _profile_string_list(mapping: dict[str, JsonValue], field: str, path: Path) -> list[str]:+ value = mapping.get(field)+ if type(value) is not list:+ raise _profile_error(path, f"{field} must be an array of non-empty strings")+ parsed: list[str] = []+ for item in value:+ if type(item) is not str or not item:+ raise _profile_error(path, f"{field} must be an array of non-empty strings")+ parsed.append(item)+ return parsed+++def _profile_bool(mapping: dict[str, JsonValue], field: str, path: Path) -> bool:+ value = mapping.get(field)+ if type(value) is not bool:+ raise _profile_error(path, f"{field} must be a boolean")+ return value+++def _profile_number(mapping: dict[str, JsonValue], field: str, path: Path) -> float:+ value = mapping.get(field)+ if type(value) is bool or not isinstance(value, (int, float)):+ raise _profile_error(path, f"{field} must be a number")+ return float(value)+++def _profile_normalization(+ mapping: dict[str, JsonValue],+ field: str,+ path: Path,+) -> UnicodeNormalization:+ value = _profile_string(mapping, field, path)+ normalization = _NORMALIZATION_BY_NAME.get(value)+ if normalization is None:+ raise _profile_error(path, f"{field} must be NFC, NFD, NFKC, or NFKD")+ return normalization+++def _profile_accent_fold(+ mapping: dict[str, JsonValue],+ field: str,+ path: Path,+) -> AccentFold:+ value = _profile_string(mapping, field, path)+ accent_fold = _ACCENT_FOLD_BY_NAME.get(value)+ if accent_fold is None:+ raise _profile_error(path, f"{field} must be none or vi")+ return accent_fold+++def _profile_cache_path(mapping: dict[str, JsonValue], path: Path) -> str:+ configured = _profile_string(mapping, "cache", path)+ cache_path = Path(configured)+ if cache_path.is_absolute() or ".." in cache_path.parts:+ raise ProfileCachePathError(+ "cache path must be relative and stay within project_root"+ )+ return configured+++def load_profiles(path: Path | None = None) -> dict[str, CollectionProfile]:+ profile_path = _DEFAULT_PROFILES_PATH if path is None else path+ try:+ raw: JsonValue = json.loads(profile_path.read_text(encoding="utf-8"))+ except json.JSONDecodeError as error:+ raise _profile_error(profile_path, "invalid JSON profile") from error+ except (OSError, UnicodeError) as error:+ raise _profile_error(profile_path, "unable to read UTF-8 profile") from error+ root = _mapping(raw, profile_path, "profile")+ version = root.get("profile_schema_version")+ if type(version) is not int or version < 1:+ raise _profile_error(profile_path, "profile_schema_version must be a positive integer")+ defaults = _mapping(root.get("defaults"), profile_path, "defaults")+ tokenizer_raw = _mapping(defaults.get("tokenizer"), profile_path, "defaults.tokenizer")+ alias_raw = _mapping(defaults.get("aliases"), profile_path, "defaults.aliases")+ bm25_raw = _mapping(defaults.get("bm25"), profile_path, "defaults.bm25")+ max_expansions = alias_raw.get("max_expansions")+ if type(max_expansions) is not int or max_expansions < 0:+ raise _profile_error(profile_path, "defaults.aliases.max_expansions must be a non-negative integer")+ tokenizer: TokenizerSettings = {+ "version": _profile_string(tokenizer_raw, "version", profile_path),+ "unicode_normalization": _profile_normalization(+ tokenizer_raw,+ "unicode_normalization",+ profile_path,+ ),+ "casefold": _profile_bool(tokenizer_raw, "casefold", profile_path),+ "accent_fold": _profile_accent_fold(tokenizer_raw, "accent_fold", profile_path),+ "preserve_identifiers": _profile_bool(tokenizer_raw, "preserve_identifiers", profile_path),+ "preserve_numbers": _profile_bool(tokenizer_raw, "preserve_numbers", profile_path),+ }+ alias_settings: AliasSettings = {+ "enabled": _profile_bool(alias_raw, "enabled", profile_path),+ "max_expansions": max_expansions,+ }+ bm25: Bm25Settings = {+ "k1": _profile_number(bm25_raw, "k1", profile_path),+ "b": _profile_number(bm25_raw, "b", profile_path),+ }+ collections = _mapping(root.get("collections"), profile_path, "collections")+ parsed: dict[str, CollectionProfile] = {}+ for name in sorted(collections):+ collection = _mapping(collections[name], profile_path, f"collections.{name}")+ term_aliases_raw = collection.get("term_aliases", {})+ term_aliases_mapping = _mapping(term_aliases_raw, profile_path, f"collections.{name}.term_aliases")+ term_aliases = {+ term: _profile_string_list(term_aliases_mapping, term, profile_path)+ for term in sorted(term_aliases_mapping)+ }+ parsed[name] = {+ "source_roots": _profile_string_list(collection, "source_roots", profile_path),+ "optional_source_roots": _profile_string_list(+ collection,+ "optional_source_roots",+ profile_path,+ ),+ "distilled_records": _profile_string_list(collection, "distilled_records", profile_path),+ "documentation": _profile_string(collection, "documentation", profile_path),+ "cache": _profile_cache_path(collection, profile_path),+ "encoding": _profile_string(defaults, "encoding", profile_path),+ "languages": _profile_string_list(defaults, "languages", profile_path),+ "source_extensions": _profile_string_list(defaults, "source_extensions", profile_path),+ "tokenizer": tokenizer,+ "aliases": alias_settings,+ "bm25": bm25,+ "term_aliases": term_aliases,+ }+ return parsed+++def load_profile(collection: str, path: Path | None = None) -> CollectionProfile:+ profiles = load_profiles(path)+ if collection not in profiles:+ raise UnknownCollectionError(collection=collection)+ return profiles[collection]+++def _record_error(path: Path, line_number: int, reason: str) -> SpecRecordValidationError:+ return SpecRecordValidationError(path=path, line_number=line_number, reason=reason)+++def _record_mapping(value: JsonValue, path: Path, line_number: int) -> dict[str, JsonValue]:+ if type(value) is not dict:+ raise _record_error(path, line_number, "record must be a JSON object")+ return value+++def _record_string(+ record: dict[str, JsonValue],+ field: str,+ location: tuple[Path, int],+ *,+ allow_empty: bool = False,+) -> str:+ value = record.get(field)+ if type(value) is not str or (not allow_empty and not value):+ qualifier = "a string" if allow_empty else "a non-empty string"+ raise _record_error(location[0], location[1], f"{field} must be {qualifier}")+ return value+++def _record_string_list(+ record: dict[str, JsonValue],+ field: str,+ location: tuple[Path, int],+) -> list[str]:+ value = record.get(field)+ if type(value) is not list:+ raise _record_error(location[0], location[1], f"{field} must be an array of strings")+ parsed: list[str] = []+ for item in value:+ if type(item) is not str:+ raise _record_error(location[0], location[1], f"{field} must be an array of strings")+ parsed.append(item)+ return parsed+++def _measurements(record: dict[str, JsonValue], location: tuple[Path, int]) -> list[Measurement]:+ raw = record.get("measurements")+ if type(raw) is not list:+ raise _record_error(location[0], location[1], "measurements must be an array")+ parsed: list[Measurement] = []+ for value in raw:+ item = _record_mapping(value, *location)+ measurement: Measurement = {+ "name": _record_string(item, "name", location),+ "value": _record_string(item, "value", location),+ }+ for field in ("unit", "context"):+ if field in item:+ measurement[field] = _record_string(item, field, location, allow_empty=True)+ parsed.append(measurement)+ return parsed+++def _source_refs(record: dict[str, JsonValue], location: tuple[Path, int]) -> list[SourceRef]:+ raw = record.get("source_refs")+ if type(raw) is not list or not raw:+ raise _record_error(location[0], location[1], "source_refs must be a non-empty array")+ parsed: list[SourceRef] = []+ for value in raw:+ item = _record_mapping(value, *location)+ source_ref: SourceRef = {"path": _record_string(item, "path", location)}+ for field in ("heading", "key_path"):+ if field in item:+ source_ref[field] = _record_string(item, field, location)+ parsed.append(source_ref)+ return parsed+++def _evidence_refs(record: dict[str, JsonValue], location: tuple[Path, int]) -> list[EvidenceRef]:+ raw = record.get("evidence_refs")+ if type(raw) is not list:+ raise _record_error(location[0], location[1], "evidence_refs must be an array")+ parsed: list[EvidenceRef] = []+ for value in raw:+ item = _record_mapping(value, *location)+ evidence_ref: EvidenceRef = {+ "kind": _record_string(item, "kind", location),+ "ref": _record_string(item, "ref", location),+ }+ if "note" in item:+ evidence_ref["note"] = _record_string(item, "note", location, allow_empty=True)+ parsed.append(evidence_ref)+ return parsed+++def _parse_record(value: JsonValue, path: Path, line_number: int) -> SpecRecord:+ raw = _record_mapping(value, path, line_number)+ location = (path, line_number)+ status = _record_string(raw, "observation_status", location)+ if status not in {"observed", "inferred", "unverified"}:+ raise _record_error(path, line_number, "observation_status is invalid")+ confidence = raw.get("confidence")+ if type(confidence) is bool or not isinstance(confidence, (int, float)) or not 0 <= confidence <= 1:+ raise _record_error(path, line_number, "confidence must be a number from 0 through 1")+ return {+ "record_id": _record_string(raw, "record_id", location),+ "collection": _record_string(raw, "collection", location),+ "domain": _record_string(raw, "domain", location),+ "kind": _record_string(raw, "kind", location),+ "entity": _record_string(raw, "entity", location),+ "title": _record_string(raw, "title", location),+ "aliases": _record_string_list(raw, "aliases", location),+ "content": _record_string(raw, "content", location, allow_empty=True),+ "constraints": _record_string_list(raw, "constraints", location),+ "measurements": _measurements(raw, location),+ "source_refs": _source_refs(raw, location),+ "evidence_refs": _evidence_refs(raw, location),+ "observation_status": status,+ "confidence": float(confidence),+ "assumptions": _record_string_list(raw, "assumptions", location),+ }+++def load_jsonl_records(path: Path) -> list[SpecRecord]:+ try:+ lines = path.read_text(encoding="utf-8").splitlines()+ except (OSError, UnicodeError) as error:+ raise _record_error(path, 0, "unable to read UTF-8 JSONL") from error+ records: list[SpecRecord] = []+ for line_number, line in enumerate(lines, start=1):+ if not line.strip():+ continue+ try:+ value: JsonValue = json.loads(line)+ except json.JSONDecodeError as error:+ raise _record_error(path, line_number, "invalid JSON object") from error+ records.append(_parse_record(value, path, line_number))+ return records+++def _primary_tokens(text: str, tokenizer: TokenizerConfig) -> list[str]:+ normalized = unicodedata.normalize(tokenizer.unicode_normalization, text)+ if tokenizer.casefold:+ normalized = normalized.casefold()+ pattern = _IDENTIFIER_TOKEN_PATTERN if tokenizer.preserve_identifiers else _WORD_TOKEN_PATTERN+ tokens = [+ match.group(0).translate(_DASH_TRANSLATION)+ for match in pattern.finditer(normalized)+ ]+ if tokenizer.preserve_numbers:+ return tokens+ return [token for token in tokens if any(character.isalpha() for character in token)]+++def _accent_companion(token: str) -> str | None:+ if not any(character.casefold() in _VIETNAMESE_MARKED for character in token):+ return None+ decomposed = unicodedata.normalize("NFD", token)+ folded = "".join(character for character in decomposed if unicodedata.category(character) != "Mn")+ folded = folded.replace("đ", "d").replace("Đ", "D")+ return folded if folded != token else None+++def _with_accent_companions(+ tokens: Sequence[str],+ accent_fold: AccentFold,+) -> list[str]:+ if accent_fold == "none":+ return list(tokens)+ expanded: list[str] = []+ for token in tokens:+ expanded.append(token)+ companion = _accent_companion(token)+ if companion is not None:+ expanded.append(companion)+ return expanded+++def tokenize(+ text: str,+ aliases: Mapping[str, Sequence[str]] | None = None,+ tokenizer: TokenizerConfig = _DEFAULT_TOKENIZER_CONFIG,+) -> list[str]:+ primary = _primary_tokens(text, tokenizer)+ tokens = _with_accent_companions(primary, tokenizer.accent_fold)+ if aliases is None:+ return tokens+ normalized_aliases = sorted(+ (+ (_primary_tokens(term, tokenizer), tuple(values))+ for term, values in aliases.items()+ ),+ key=lambda item: item[0],+ )+ for alias_tokens, expansions in normalized_aliases:+ width = len(alias_tokens)+ if width == 0 or not any(primary[index : index + width] == alias_tokens for index in range(len(primary) - width + 1)):+ continue+ for expansion in sorted(+ expansions,+ key=lambda value: unicodedata.normalize(+ tokenizer.unicode_normalization,+ value,+ ).casefold(),+ ):+ tokens.extend(+ _with_accent_companions(+ _primary_tokens(expansion, tokenizer),+ tokenizer.accent_fold,+ )+ )+ return tokens+++def _read_source(path: Path) -> str:+ try:+ return path.read_text(encoding="utf-8")+ except (OSError, UnicodeError) as error:+ raise SourceIngestionError(path=path, reason="unable to read UTF-8 source") from error+++def _source_reference(file_path: str, heading: str | None, key_path: str | None) -> tuple[SourceReference, ...]:+ return (SourceReference(path=file_path, heading=heading, key_path=key_path),)+++def ingest_markdown(path: Path, source_path: str, collection: str) -> list[SourceDocument]:+ documents: list[SourceDocument] = []+ heading: str | None = None+ body: list[str] = []+ section_number = 0++ def append_section() -> None:+ nonlocal section_number+ content = "\n".join(body).strip()+ if heading is None and not content:+ return+ section_number += 1+ title = heading if heading is not None else path.stem+ documents.append(+ SourceDocument(+ record_id=f"{collection}.markdown.{source_path}#{section_number}",+ collection=collection,+ title=title,+ content=content,+ file_path=source_path,+ heading=heading,+ source_refs=_source_reference(source_path, heading, None),+ )+ )++ for line in _read_source(path).splitlines():+ match = re.match(r"^#{1,6}\s+(.+?)\s*#*\s*$", line)+ if match is None:+ body.append(line)+ continue+ append_section()+ heading = match.group(1)+ body = []+ append_section()+ return documents+++def _json_content(value: JsonScalar) -> str:+ return value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)+++def assert_never(value: NoReturn) -> NoReturn:+ raise AssertionError(f"unhandled JSON value: {value!r}")+++def ingest_json(path: Path, source_path: str, collection: str) -> list[SourceDocument]:+ try:+ root: JsonValue = json.loads(_read_source(path))+ except json.JSONDecodeError as error:+ raise SourceIngestionError(path=path, reason="invalid JSON source") from error+ documents: list[SourceDocument] = []++ def visit(value: JsonValue, key_path: str) -> None:+ match value:+ case dict() as mapping:+ for key in sorted(mapping):+ child_path = key if not key_path else f"{key_path}.{key}"+ visit(mapping[key], child_path)+ case list() as values:+ for index, item in enumerate(values):+ visit(item, f"{key_path}[{index}]" if key_path else f"[{index}]")+ case str() | int() | float() | bool() | None as scalar:+ location = key_path or "$"+ documents.append(+ SourceDocument(+ record_id=f"{collection}.json.{source_path}#{location}",+ collection=collection,+ title=location.rsplit(".", maxsplit=1)[-1],+ content=_json_content(scalar),+ file_path=source_path,+ key_path=location,+ source_refs=_source_reference(source_path, None, location),+ )+ )+ case unreachable:+ assert_never(unreachable)++ visit(root, "")+ return documents+++def _ingest_jsonl(path: Path, source_path: str) -> list[SourceDocument]:+ documents: list[SourceDocument] = []+ for record in load_jsonl_records(path):+ references = tuple(+ SourceReference(+ path=source_ref["path"],+ heading=source_ref.get("heading"),+ key_path=source_ref.get("key_path"),+ )+ for source_ref in record["source_refs"]+ )+ evidence_references = tuple(+ EvidenceReference(+ kind=evidence_ref["kind"],+ ref=evidence_ref["ref"],+ note=evidence_ref.get("note"),+ )+ for evidence_ref in record["evidence_refs"]+ )+ documents.append(+ SourceDocument(+ record_id=record["record_id"],+ collection=record["collection"],+ title=record["title"],+ content=record["content"],+ file_path=source_path,+ aliases=tuple(record["aliases"]),+ source_refs=references,+ evidence_refs=evidence_references,+ )+ )+ return documents+++def _source_kind(path: Path) -> SourceKind:+ kind = _SOURCE_KINDS.get(path.suffix.casefold())+ if kind is None:+ raise SourceIngestionError(path=path, reason="unsupported configured source extension")+ return kind+++def _source_tree_files(root: Path, *, optional: bool) -> list[Path]:+ try:+ root_mode = root.lstat().st_mode+ except FileNotFoundError as error:+ if optional:+ return []+ raise SourceIngestionError(+ path=root,+ reason="configured source root is not a directory",+ ) from error+ except OSError as error:+ raise SourceIngestionError(+ path=root,+ reason="unable to read configured source root",+ ) from error+ if stat.S_ISLNK(root_mode):+ raise SourceIngestionError(path=root, reason="symbolic links are not allowed")+ if not stat.S_ISDIR(root_mode):+ raise SourceIngestionError(+ path=root,+ reason="configured source root is not a directory",+ )++ files: list[Path] = []++ def visit(directory: Path) -> None:+ try:+ children = sorted(+ directory.iterdir(),+ key=lambda candidate: candidate.name,+ )+ except OSError as error:+ raise SourceIngestionError(+ path=directory,+ reason="unable to read configured source root",+ ) from error+ for child in children:+ try:+ child_mode = child.lstat().st_mode+ except OSError as error:+ raise SourceIngestionError(+ path=child,+ reason="unable to inspect configured source",+ ) from error+ if stat.S_ISLNK(child_mode):+ raise SourceIngestionError(+ path=child,+ reason="symbolic links are not allowed",+ )+ relative = child.relative_to(root)+ if _hidden_source(relative):+ continue+ if stat.S_ISDIR(child_mode):+ visit(child)+ elif stat.S_ISREG(child_mode):+ files.append(child)++ visit(root)+ return files+++def ingest_source_tree(+ root: Path,+ collection: str,+ extensions: Sequence[str],+) -> list[SourceDocument]:+ allowed = frozenset(extension.casefold() for extension in extensions)+ documents: list[SourceDocument] = []+ for path in _source_tree_files(root, optional=False):+ relative = path.relative_to(root)+ if path.suffix.casefold() not in allowed:+ continue+ source_path = relative.as_posix()+ match _source_kind(path):+ case "markdown":+ documents.extend(ingest_markdown(path, source_path, collection))+ case "json":+ documents.extend(ingest_json(path, source_path, collection))+ case "jsonl":+ documents.extend(_ingest_jsonl(path, source_path))+ case unreachable:+ assert_never(unreachable)+ return documents+++def _fingerprint(value: JsonValue | CollectionProfile) -> str:+ canonical = json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True)+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()+++def _alias_mapping(config: Bm25Config) -> dict[str, tuple[str, ...]]:+ return {term: expansions for term, expansions in config.term_aliases}+++def _searchable_text(document: SourceDocument) -> str:+ parts = [document.title]+ if document.heading is not None and document.heading != document.title:+ parts.append(document.heading)+ parts.extend(document.aliases)+ parts.append(document.content)+ return "\n".join(parts)+++def build_index(+ documents: Sequence[SourceDocument],+ config: Bm25Config,+ fingerprints: IndexFingerprints = IndexFingerprints(),+) -> Bm25Index:+ if config.k1 <= 0:+ raise IndexBuildError(reason="BM25 k1 must be greater than zero")+ if not 0 <= config.b <= 1:+ raise IndexBuildError(reason="BM25 b must be from zero through one")++ aliases = _alias_mapping(config)+ records: dict[str, SourceDocument] = {}+ document_lengths: dict[str, int] = {}+ posting_lists: dict[str, list[Posting]] = {}+ for document in sorted(documents, key=lambda item: item.record_id):+ if document.record_id in records:+ raise IndexBuildError(reason=f"duplicate record_id: {document.record_id}")+ records[document.record_id] = document+ term_frequencies = Counter(+ tokenize(_searchable_text(document), aliases, config.tokenizer)+ )+ document_lengths[document.record_id] = sum(term_frequencies.values())+ for term in sorted(term_frequencies):+ posting_lists.setdefault(term, []).append(+ Posting(record_id=document.record_id, term_frequency=term_frequencies[term])+ )++ document_count = len(records)+ avgdl = sum(document_lengths.values()) / document_count if document_count else 0.0+ postings = {term: tuple(values) for term, values in sorted(posting_lists.items())}+ document_frequencies = {term: len(values) for term, values in postings.items()}+ return Bm25Index(+ collection=config.collection,+ k1=config.k1,+ b=config.b,+ tokenizer=config.tokenizer,+ fingerprints=fingerprints,+ document_lengths=document_lengths,+ avgdl=avgdl,+ document_frequencies=document_frequencies,+ postings=postings,+ records=records,+ term_aliases=aliases,+ )+++def search_index(index: Bm25Index, query: str) -> list[SearchMatch]:+ if not index.records or index.avgdl == 0:+ return []+ query_terms = sorted(set(tokenize(query, index.term_aliases, index.tokenizer)))+ scores: dict[str, float] = {}+ document_count = len(index.records)+ for term in query_terms:+ term_postings = index.postings.get(term, ())+ if not term_postings:+ continue+ document_frequency = index.document_frequencies[term]+ inverse_document_frequency = math.log(+ 1 + (document_count - document_frequency + 0.5) / (document_frequency + 0.5)+ )+ for posting in term_postings:+ document_length = index.document_lengths[posting.record_id]+ length_normalization = 1 - index.b + index.b * document_length / index.avgdl+ numerator = posting.term_frequency * (index.k1 + 1)+ denominator = posting.term_frequency + index.k1 * length_normalization+ scores[posting.record_id] = scores.get(posting.record_id, 0.0) + (+ inverse_document_frequency * numerator / denominator+ )+ matches = [+ SearchMatch(record=index.records[record_id], score=score)+ for record_id, score in scores.items()+ if score > 0+ ]+ return sorted(matches, key=lambda match: (-match.score, match.record.record_id))+++def _earliest_token_offset(text: str, query: str) -> int:+ query_tokens = frozenset(tokenize(query))+ for token_match in _IDENTIFIER_TOKEN_PATTERN.finditer(text):+ if query_tokens.intersection(tokenize(token_match.group(0))):+ return token_match.start()+ return 0+++def _trim_word_boundaries(text: str, start: int, end: int) -> tuple[int, int]:+ if start > 0:+ next_space = text.find(" ", start, end)+ if next_space >= 0:+ start = next_space + 1+ if end < len(text):+ previous_space = text.rfind(" ", start, end)+ if previous_space > start:+ end = previous_space+ return start, end+++def section_snippet(text: str, query: str, max_chars: int) -> str:+ normalized = " ".join(text.split())+ if len(normalized) <= max_chars:+ return normalized+ if max_chars <= 3:+ return "." * max_chars+ suffix_capacity = max_chars - 4+ target = _earliest_token_offset(normalized, query)+ if target <= suffix_capacity // 2:+ raw_start, raw_end = 0, suffix_capacity+ else:+ body_capacity = max(1, max_chars - 8)+ raw_start = max(0, target - body_capacity // 2)+ raw_end = min(len(normalized), raw_start + body_capacity)+ if raw_end == len(normalized):+ raw_start = max(0, len(normalized) - suffix_capacity)+ start, end = _trim_word_boundaries(normalized, raw_start, raw_end)+ prefix = "... " if start > 0 else ""+ suffix = " ..." if end < len(normalized) else ""+ return f"{prefix}{normalized[start:end].strip()}{suffix}"[:max_chars]+++def _document_key(document: SourceDocument) -> tuple[str, str | None, str | None]:+ return document.file_path, document.heading, document.key_path+++def _reference_key(reference: SourceReference) -> tuple[str, str | None, str | None]:+ return reference.path, reference.heading, reference.key_path+++def _resolve_source_section(+ match: SearchMatch,+ sections: Mapping[tuple[str, str | None, str | None], SourceDocument],+) -> tuple[tuple[str, str | None, str | None], str]:+ own_key = _document_key(match.record)+ if match.record.heading is not None or match.record.key_path is not None:+ return own_key, match.record.content+ for reference in match.record.source_refs:+ key = _reference_key(reference)+ source_document = sections.get(key)+ if source_document is not None:+ return key, source_document.content+ if match.record.source_refs:+ return _reference_key(match.record.source_refs[0]), match.record.content+ return own_key, match.record.content+++def serialize_search_results(+ index: Bm25Index,+ request: SearchOutputRequest,+) -> list[SerializedSearchMatch]:+ sections = {+ _document_key(document): document+ for document in sorted(index.records.values(), key=lambda item: item.record_id)+ }+ results: list[SerializedSearchMatch] = []+ seen: set[tuple[str, str | None, str | None]] = set()+ for match in search_index(index, request.query):+ section_key, source_text = _resolve_source_section(match, sections)+ if section_key in seen:+ continue+ seen.add(section_key)+ file_path, heading, key_path = section_key+ results.append(+ {+ "record_id": match.record.record_id,+ "file_path": file_path,+ "heading": heading,+ "key_path": key_path,+ "score": round(match.score, 12),+ "snippets": [section_snippet(source_text, request.query, request.snippet_chars)],+ "source_refs": [+ {+ "path": reference.path,+ "heading": reference.heading,+ "key_path": reference.key_path,+ }+ for reference in match.record.source_refs+ ],+ "evidence_refs": [+ _cached_evidence_reference(reference)+ for reference in match.record.evidence_refs+ ],+ }+ )+ if len(results) == request.limit:+ break+ return results+++def _hidden_source(relative: Path) -> bool:+ return any(part.startswith(".") or part == "__pycache__" for part in relative.parts)+++def _configured_project_path(+ request: IndexRequest,+ configured: str,+) -> Path:+ relative = Path(configured)+ if relative.is_absolute() or ".." in relative.parts:+ raise SourceIngestionError(+ path=relative,+ reason="configured source path must be relative and stay within project_root",+ )+ candidate = request.project_root / relative+ current = request.project_root+ for part in relative.parts:+ current /= part+ try:+ current_mode = current.lstat().st_mode+ except FileNotFoundError:+ break+ except OSError as error:+ raise SourceIngestionError(+ path=current,+ reason="unable to inspect configured source path",+ ) from error+ if stat.S_ISLNK(current_mode):+ raise SourceIngestionError(+ path=current,+ reason="symbolic links are not allowed",+ )+ return candidate+++def _configured_sources(request: IndexRequest) -> list[ConfiguredSource]:+ allowed = frozenset(extension.casefold() for extension in request.profile["source_extensions"])+ sources: dict[str, ConfiguredSource] = {}+ configured_roots = (+ *((configured_root, False) for configured_root in request.profile["source_roots"]),+ *(+ (configured_root, True)+ for configured_root in request.profile["optional_source_roots"]+ ),+ )+ for configured_root, optional in configured_roots:+ root = _configured_project_path(request, configured_root)+ for path in _source_tree_files(root, optional=optional):+ if path.suffix.casefold() not in allowed:+ continue+ source_path = path.relative_to(request.project_root)+ source_key = source_path.as_posix()+ sources[source_key] = ConfiguredSource(+ path=path,+ source_path=source_key,+ kind=_source_kind(path),+ )+ for configured_record in request.profile["distilled_records"]:+ path = _configured_project_path(request, configured_record)+ try:+ record_mode = path.lstat().st_mode+ except OSError as error:+ raise SourceIngestionError(+ path=path,+ reason="configured distilled record source is not a file",+ ) from error+ if stat.S_ISLNK(record_mode):+ raise SourceIngestionError(path=path, reason="symbolic links are not allowed")+ if not stat.S_ISREG(record_mode):+ raise SourceIngestionError(path=path, reason="configured distilled record source is not a file")+ source_path = path.relative_to(request.project_root)+ source_key = source_path.as_posix()+ sources[source_key] = ConfiguredSource(+ path=path,+ source_path=source_key,+ kind=_source_kind(path),+ )+ return [sources[source_key] for source_key in sorted(sources)]+++def _source_fingerprint(sources: Sequence[ConfiguredSource]) -> str:+ digest = hashlib.sha256()+ for source in sources:+ digest.update(source.source_path.encode("utf-8"))+ digest.update(b"\0")+ try:+ with source.path.open("rb") as source_file:+ for chunk in iter(lambda: source_file.read(1024 * 1024), b""):+ digest.update(chunk)+ except OSError as error:+ raise SourceIngestionError(+ path=source.path,+ reason="unable to read source for freshness check",+ ) from error+ digest.update(b"\0")+ return digest.hexdigest()+++def _index_fingerprints(request: IndexRequest, sources: Sequence[ConfiguredSource]) -> IndexFingerprints:+ schema_fingerprint = _fingerprint(+ {+ "cache_schema_version": _CACHE_SCHEMA_VERSION,+ "record_metadata_version": 1,+ }+ )+ tokenizer = request.profile["tokenizer"]+ tokenizer_value: JsonValue = {+ "implementation_version": _TOKENIZER_SCHEMA_VERSION,+ "settings": {+ "version": tokenizer["version"],+ "unicode_normalization": tokenizer["unicode_normalization"],+ "casefold": tokenizer["casefold"],+ "accent_fold": tokenizer["accent_fold"],+ "preserve_identifiers": tokenizer["preserve_identifiers"],+ "preserve_numbers": tokenizer["preserve_numbers"],+ },+ }+ tokenizer_fingerprint = _fingerprint(tokenizer_value)+ config_fingerprint = _fingerprint(request.profile)+ return IndexFingerprints(+ schema=schema_fingerprint,+ tokenizer=tokenizer_fingerprint,+ config=config_fingerprint,+ source=_source_fingerprint(sources),+ )+++def _ingest_configured_sources(+ request: IndexRequest,+ sources: Sequence[ConfiguredSource],+) -> list[SourceDocument]:+ documents: list[SourceDocument] = []+ for source in sources:+ match source.kind:+ case "markdown":+ documents.extend(ingest_markdown(source.path, source.source_path, request.collection))+ case "json":+ documents.extend(ingest_json(source.path, source.source_path, request.collection))+ case "jsonl":+ documents.extend(_ingest_jsonl(source.path, source.source_path))+ case unreachable:+ assert_never(unreachable)+ return documents+++def _cached_source_reference(reference: SourceReference) -> CachedSourceReference:+ return {+ "path": reference.path,+ "heading": reference.heading,+ "key_path": reference.key_path,+ }+++def _cached_evidence_reference(+ reference: EvidenceReference,+) -> CachedEvidenceReference:+ cached: CachedEvidenceReference = {+ "kind": reference.kind,+ "ref": reference.ref,+ }+ if reference.note is not None:+ cached["note"] = reference.note+ return cached+++def _tokenizer_config(settings: TokenizerSettings) -> TokenizerConfig:+ return TokenizerConfig(+ version=settings["version"],+ unicode_normalization=settings["unicode_normalization"],+ casefold=settings["casefold"],+ accent_fold=settings["accent_fold"],+ preserve_identifiers=settings["preserve_identifiers"],+ preserve_numbers=settings["preserve_numbers"],+ )+++def _tokenizer_settings(config: TokenizerConfig) -> TokenizerSettings:+ return {+ "version": config.version,+ "unicode_normalization": config.unicode_normalization,+ "casefold": config.casefold,+ "accent_fold": config.accent_fold,+ "preserve_identifiers": config.preserve_identifiers,+ "preserve_numbers": config.preserve_numbers,+ }+++def _cached_record(document: SourceDocument) -> CachedRecord:+ return {+ "record_id": document.record_id,+ "collection": document.collection,+ "title": document.title,+ "content": document.content,+ "file_path": document.file_path,+ "heading": document.heading,+ "key_path": document.key_path,+ "aliases": list(document.aliases),+ "source_refs": [_cached_source_reference(reference) for reference in document.source_refs],+ "evidence_refs": [+ _cached_evidence_reference(reference)+ for reference in document.evidence_refs+ ],+ }+++def _cache_payload(index: Bm25Index) -> CachePayload:+ return {+ "schema_version": _CACHE_SCHEMA_VERSION,+ "schema_fingerprint": index.fingerprints.schema,+ "tokenizer_fingerprint": index.fingerprints.tokenizer,+ "config_fingerprint": index.fingerprints.config,+ "source_fingerprint": index.fingerprints.source,+ "fingerprint": index.fingerprint,+ "collection": index.collection,+ "k1": index.k1,+ "b": index.b,+ "tokenizer": _tokenizer_settings(index.tokenizer),+ "document_lengths": dict(index.document_lengths),+ "avgdl": index.avgdl,+ "document_frequencies": dict(index.document_frequencies),+ "postings": {+ term: [+ {"record_id": posting.record_id, "term_frequency": posting.term_frequency}+ for posting in postings+ ]+ for term, postings in index.postings.items()+ },+ "records": {+ record_id: _cached_record(document)+ for record_id, document in index.records.items()+ },+ "term_aliases": {+ term: list(expansions)+ for term, expansions in index.term_aliases.items()+ },+ }+++def _cache_validation_error(path: Path, reason: str) -> CacheValidationError:+ return CacheValidationError(path=path, reason=reason)+++def _cache_mapping(value: JsonValue, path: Path, label: str) -> dict[str, JsonValue]:+ if type(value) is not dict:+ raise _cache_validation_error(path, f"{label} must be an object")+ return value+++def _cache_string(mapping: dict[str, JsonValue], field: str, path: Path) -> str:+ value = mapping.get(field)+ if type(value) is not str:+ raise _cache_validation_error(path, f"{field} must be a string")+ return value+++def _cache_optional_string(mapping: dict[str, JsonValue], field: str, path: Path) -> str | None:+ value = mapping.get(field)+ if value is not None and type(value) is not str:+ raise _cache_validation_error(path, f"{field} must be a string or null")+ return value+++def _cache_float(mapping: dict[str, JsonValue], field: str, path: Path) -> float:+ value = mapping.get(field)+ if type(value) is bool or not isinstance(value, (int, float)):+ raise _cache_validation_error(path, f"{field} must be a number")+ return float(value)+++def _cache_integer(mapping: dict[str, JsonValue], field: str, path: Path) -> int:+ value = mapping.get(field)+ if type(value) is not int:+ raise _cache_validation_error(path, f"{field} must be an integer")+ return value+++def _cache_bool(mapping: dict[str, JsonValue], field: str, path: Path) -> bool:+ value = mapping.get(field)+ if type(value) is not bool:+ raise _cache_validation_error(path, f"{field} must be a boolean")+ return value+++def _cache_string_list(value: JsonValue, path: Path, label: str) -> list[str]:+ if type(value) is not list or not all(type(item) is str for item in value):+ raise _cache_validation_error(path, f"{label} must be an array of strings")+ parsed: list[str] = []+ for item in value:+ if type(item) is str:+ parsed.append(item)+ return parsed+++def _parse_cached_reference(value: JsonValue, path: Path) -> SourceReference:+ raw = _cache_mapping(value, path, "source reference")+ return SourceReference(+ path=_cache_string(raw, "path", path),+ heading=_cache_optional_string(raw, "heading", path),+ key_path=_cache_optional_string(raw, "key_path", path),+ )+++def _parse_cached_evidence_reference(+ value: JsonValue,+ path: Path,+) -> EvidenceReference:+ raw = _cache_mapping(value, path, "evidence reference")+ return EvidenceReference(+ kind=_cache_string(raw, "kind", path),+ ref=_cache_string(raw, "ref", path),+ note=_cache_optional_string(raw, "note", path),+ )+++def _parse_cached_record(record_id: str, value: JsonValue, path: Path) -> SourceDocument:+ raw = _cache_mapping(value, path, f"records.{record_id}")+ cached_record_id = _cache_string(raw, "record_id", path)+ if cached_record_id != record_id:+ raise _cache_validation_error(path, f"records.{record_id}.record_id does not match its key")+ references_raw = raw.get("source_refs")+ if type(references_raw) is not list:+ raise _cache_validation_error(path, f"records.{record_id}.source_refs must be an array")+ evidence_references_raw = raw.get("evidence_refs")+ if type(evidence_references_raw) is not list:+ raise _cache_validation_error(path, f"records.{record_id}.evidence_refs must be an array")+ return SourceDocument(+ record_id=record_id,+ collection=_cache_string(raw, "collection", path),+ title=_cache_string(raw, "title", path),+ content=_cache_string(raw, "content", path),+ file_path=_cache_string(raw, "file_path", path),+ heading=_cache_optional_string(raw, "heading", path),+ key_path=_cache_optional_string(raw, "key_path", path),+ aliases=tuple(_cache_string_list(raw.get("aliases"), path, f"records.{record_id}.aliases")),+ source_refs=tuple(_parse_cached_reference(reference, path) for reference in references_raw),+ evidence_refs=tuple(+ _parse_cached_evidence_reference(reference, path)+ for reference in evidence_references_raw+ ),+ )+++def _parse_integer_mapping(value: JsonValue, path: Path, label: str) -> dict[str, int]:+ raw = _cache_mapping(value, path, label)+ parsed: dict[str, int] = {}+ for key, item in raw.items():+ if type(item) is not int or item < 0:+ raise _cache_validation_error(path, f"{label}.{key} must be a non-negative integer")+ parsed[key] = item+ return parsed+++def _parse_postings(+ value: JsonValue,+ path: Path,+ records: Mapping[str, SourceDocument],+) -> dict[str, tuple[Posting, ...]]:+ raw = _cache_mapping(value, path, "postings")+ parsed: dict[str, tuple[Posting, ...]] = {}+ for term, values in raw.items():+ if type(values) is not list:+ raise _cache_validation_error(path, f"postings.{term} must be an array")+ postings: list[Posting] = []+ previous_record_id: str | None = None+ for value_item in values:+ item = _cache_mapping(value_item, path, f"postings.{term} entry")+ record_id = _cache_string(item, "record_id", path)+ term_frequency = _cache_integer(item, "term_frequency", path)+ if record_id not in records or term_frequency <= 0:+ raise _cache_validation_error(path, f"postings.{term} contains an invalid entry")+ if previous_record_id is not None and record_id <= previous_record_id:+ raise _cache_validation_error(path, f"postings.{term} is not record_id sorted")+ previous_record_id = record_id+ postings.append(Posting(record_id=record_id, term_frequency=term_frequency))+ parsed[term] = tuple(postings)+ return parsed+++def _parse_term_aliases(value: JsonValue, path: Path) -> dict[str, tuple[str, ...]]:+ raw = _cache_mapping(value, path, "term_aliases")+ return {+ term: tuple(_cache_string_list(expansions, path, f"term_aliases.{term}"))+ for term, expansions in raw.items()+ }+++def _parse_cached_tokenizer(value: JsonValue, path: Path) -> TokenizerConfig:+ raw = _cache_mapping(value, path, "tokenizer")+ normalization = _NORMALIZATION_BY_NAME.get(+ _cache_string(raw, "unicode_normalization", path)+ )+ if normalization is None:+ raise _cache_validation_error(+ path,+ "tokenizer.unicode_normalization is invalid",+ )+ accent_fold = _ACCENT_FOLD_BY_NAME.get(+ _cache_string(raw, "accent_fold", path)+ )+ if accent_fold is None:+ raise _cache_validation_error(path, "tokenizer.accent_fold is invalid")+ return TokenizerConfig(+ version=_cache_string(raw, "version", path),+ unicode_normalization=normalization,+ casefold=_cache_bool(raw, "casefold", path),+ accent_fold=accent_fold,+ preserve_identifiers=_cache_bool(raw, "preserve_identifiers", path),+ preserve_numbers=_cache_bool(raw, "preserve_numbers", path),+ )+++def _parse_cache(value: JsonValue, path: Path) -> Bm25Index:+ raw = _cache_mapping(value, path, "cache")+ records_raw = _cache_mapping(raw.get("records"), path, "records")+ records = {+ record_id: _parse_cached_record(record_id, record, path)+ for record_id, record in sorted(records_raw.items())+ }+ document_lengths = _parse_integer_mapping(raw.get("document_lengths"), path, "document_lengths")+ document_frequencies = _parse_integer_mapping(+ raw.get("document_frequencies"),+ path,+ "document_frequencies",+ )+ postings = _parse_postings(raw.get("postings"), path, records)+ if set(document_lengths) != set(records):+ raise _cache_validation_error(path, "document_lengths keys must match records")+ if {+ term: len(term_postings)+ for term, term_postings in postings.items()+ } != document_frequencies:+ raise _cache_validation_error(path, "document_frequencies must match postings")+ avgdl = _cache_float(raw, "avgdl", path)+ expected_avgdl = sum(document_lengths.values()) / len(records) if records else 0.0+ if not math.isclose(avgdl, expected_avgdl, rel_tol=0.0, abs_tol=1e-12):+ raise _cache_validation_error(path, "avgdl must match document_lengths")+ schema_version = _cache_integer(raw, "schema_version", path)+ if schema_version < 1:+ raise _cache_validation_error(path, "schema_version must be positive")+ fingerprints = IndexFingerprints(+ schema=_cache_string(raw, "schema_fingerprint", path),+ tokenizer=_cache_string(raw, "tokenizer_fingerprint", path),+ config=_cache_string(raw, "config_fingerprint", path),+ source=_cache_string(raw, "source_fingerprint", path),+ )+ if _cache_string(raw, "fingerprint", path) != fingerprints.combined:+ raise _cache_validation_error(path, "fingerprint does not match component fingerprints")+ return Bm25Index(+ collection=_cache_string(raw, "collection", path),+ k1=_cache_float(raw, "k1", path),+ b=_cache_float(raw, "b", path),+ tokenizer=_parse_cached_tokenizer(raw.get("tokenizer"), path),+ fingerprints=fingerprints,+ document_lengths=document_lengths,+ avgdl=avgdl,+ document_frequencies=document_frequencies,+ postings=postings,+ records=records,+ term_aliases=_parse_term_aliases(raw.get("term_aliases"), path),+ )+++def _read_cache(path: Path) -> Bm25Index:+ try:+ value: JsonValue = json.loads(path.read_text(encoding="utf-8"))+ except json.JSONDecodeError as error:+ raise _cache_validation_error(path, "invalid JSON cache") from error+ except UnicodeError as error:+ raise _cache_validation_error(path, "cache is not valid UTF-8") from error+ except OSError as error:+ raise CacheReadError(path=path, reason="unable to read cache") from error+ return _parse_cache(value, path)+++def _write_cache(path: Path, index: Bm25Index) -> None:+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ except OSError as error:+ raise CacheWriteError(path=path, reason="unable to create cache directory") from error+ temporary_path: Path | None = None+ try:+ with tempfile.NamedTemporaryFile(+ mode="w",+ encoding="utf-8",+ dir=path.parent,+ prefix=f".{path.name}.",+ suffix=".tmp",+ delete=False,+ ) as temporary_file:+ temporary_path = Path(temporary_file.name)+ json.dump(+ _cache_payload(index),+ temporary_file,+ ensure_ascii=False,+ separators=(",", ":"),+ sort_keys=True,+ )+ temporary_file.write("\n")+ temporary_file.flush()+ os.fsync(temporary_file.fileno())+ os.replace(temporary_path, path)+ temporary_path = None+ except OSError as error:+ if temporary_path is not None:+ try:+ temporary_path.unlink(missing_ok=True)+ except OSError as cleanup_error:+ raise CacheWriteError(+ path=path,+ reason=f"atomic cache replacement failed; temporary cleanup failed: {cleanup_error}",+ ) from error+ raise CacheWriteError(path=path, reason="atomic cache replacement failed") from error+++def _index_config(request: IndexRequest) -> Bm25Config:+ alias_settings = request.profile["aliases"]+ max_expansions = alias_settings["max_expansions"]+ term_aliases = request.profile["term_aliases"] if alias_settings["enabled"] else {}+ return Bm25Config(+ collection=request.collection,+ k1=request.profile["bm25"]["k1"],+ b=request.profile["bm25"]["b"],+ tokenizer=_tokenizer_config(request.profile["tokenizer"]),+ term_aliases=tuple(+ (term, tuple(expansions[:max_expansions]))+ for term, expansions in sorted(term_aliases.items())+ if max_expansions > 0+ ),+ )+++def _cache_path(request: IndexRequest) -> Path:+ configured = Path(request.profile["cache"])+ if configured.is_absolute() or ".." in configured.parts:+ raise _cache_validation_error(+ configured,+ "cache path must be relative and stay within project_root",+ )+ try:+ project_root = request.project_root.resolve()+ cache_path = (request.project_root / configured).resolve()+ cache_path.relative_to(project_root)+ except (OSError, RuntimeError, ValueError) as error:+ raise _cache_validation_error(+ configured,+ "cache path must be relative and stay within project_root",+ ) from error+ if cache_path == project_root:+ raise _cache_validation_error(+ configured,+ "cache path must be relative and stay within project_root",+ )+ return cache_path+++def load_or_build_index(request: IndexRequest) -> IndexLoadResult:+ cache_path = _cache_path(request)+ sources = _configured_sources(request)+ fingerprints = _index_fingerprints(request, sources)+ config = _index_config(request)+ reason: CacheReason+ if request.force_reindex:+ reason = "forced"+ elif not cache_path.is_file():+ reason = "missing"+ else:+ try:+ cached = _read_cache(cache_path)+ except CacheValidationError:+ reason = "corrupt"+ else:+ if (+ cached.collection == request.collection+ and cached.fingerprints == fingerprints+ and cached.k1 == config.k1+ and cached.b == config.b+ and cached.tokenizer == config.tokenizer+ and cached.term_aliases == _alias_mapping(config)+ ):+ return IndexLoadResult(+ index=cached,+ status="hit",+ reason="current",+ cache_path=cache_path,+ )+ reason = "stale"++ documents = _ingest_configured_sources(request, sources)+ index = build_index(documents, config, fingerprints)+ _write_cache(cache_path, index)+ return IndexLoadResult(+ index=index,+ status="rebuilt",+ reason=reason,+ cache_path=cache_path,+ )diff --git a/forge/_shared/spec_search_profiles.json b/forge/_shared/spec_search_profiles.jsonnew file mode 100644index 0000000..6fe5320--- /dev/null+++ b/forge/_shared/spec_search_profiles.json@@ -0,0 +1,58 @@+{+ "profile_schema_version": 1,+ "defaults": {+ "encoding": "utf-8",+ "languages": [+ "en",+ "vi"+ ],+ "source_extensions": [+ ".md",+ ".json",+ ".jsonl"+ ],+ "tokenizer": {+ "version": "1",+ "unicode_normalization": "NFKC",+ "casefold": true,+ "accent_fold": "vi",+ "preserve_identifiers": true,+ "preserve_numbers": true+ },+ "aliases": {+ "enabled": true,+ "max_expansions": 1+ },+ "bm25": {+ "k1": 1.5,+ "b": 0.75+ }+ },+ "collections": {+ "cs2": {+ "source_roots": [],+ "optional_source_roots": [+ "docs/cs2/",+ "docs/cs2-anatomy/"+ ],+ "distilled_records": [+ "docs/specs/vocabulary/cs2.jsonl",+ "docs/specs/vocabulary/cs2_reconstruction.jsonl",+ "docs/specs/vocabulary/core_3d.jsonl",+ "docs/specs/vocabulary/core_3d_reconstruction.jsonl"+ ],+ "documentation": "docs/specs/vocabulary/README.md",+ "cache": ".cache/spec-search/cs2.json"+ },+ "core_3d": {+ "source_roots": [],+ "optional_source_roots": [],+ "distilled_records": [+ "docs/specs/vocabulary/core_3d.jsonl",+ "docs/specs/vocabulary/core_3d_reconstruction.jsonl"+ ],+ "documentation": "docs/specs/vocabulary/README.md",+ "cache": ".cache/spec-search/core_3d.json"+ }+ }+}diff --git a/forge/_shared/status_banner.py b/forge/_shared/status_banner.pynew file mode 100644index 0000000..a3aaf23--- /dev/null+++ b/forge/_shared/status_banner.py@@ -0,0 +1,35 @@+from __future__ import annotations++import json+import sys+from pathlib import Path+from typing import Any, TextIO+++def _pipeline(spec: dict[str, Any] | None) -> tuple[str, int, str, str]:+ if not isinstance(spec, dict):+ return "unknown", 0, "spec not loaded", "forge/next.py <spec>"+ pipeline = spec.get("sculptPipeline")+ if not isinstance(pipeline, dict):+ return "unknown", 0, "sculptPipeline is missing", "forge/next.py <spec>"+ current = str(pipeline.get("currentPass") or "unknown")+ completed = pipeline.get("completedPasses", [])+ count = len(completed) if isinstance(completed, list) else 0+ reason = str(pipeline.get("blockedReason") or "none")+ next_command = "none (pipeline complete)" if current == "complete" else "forge/next.py <spec>"+ return current, count, reason, next_command+++def emit_status(spec: dict[str, Any] | None = None, *, next_command: str | None = None, stream: TextIO = sys.stdout) -> None:+ current, count, reason, default_next = _pipeline(spec)+ print(f"STATUS pass={current} completed={count} blocked={reason} next={next_command or default_next}", file=stream)+++def load_optional_spec(path: str | Path | None) -> dict[str, Any] | None:+ if not path:+ return None+ try:+ payload = json.loads(Path(path).expanduser().read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return None+ return payload if isinstance(payload, dict) else Nonediff --git a/forge/next.py b/forge/next.pynew file mode 100644index 0000000..fea8036--- /dev/null+++ b/forge/next.py@@ -0,0 +1,40 @@+from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "_shared"))+sys.path.insert(0, str(ROOT / "stage3_build"))+from status_banner import emit_status+from orchestrate_passes import current_pass, pass_acceptance, pass_order, completed_passes+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser(description="Report the exact next sculpt pipeline command")+ parser.add_argument("spec", type=Path)+ args = parser.parse_args(argv)+ spec = json.loads(args.spec.expanduser().read_text(encoding="utf-8"))+ if not isinstance(spec, dict):+ raise ValueError("spec must be an object")+ ids = pass_order(spec)+ completed = completed_passes(spec, ids)+ current = current_pass(ids, completed)+ emit_status(spec)+ if current == "complete":+ print("pipeline: complete")+ return 0+ acceptance = pass_acceptance(spec, current)+ command = f"python3 forge/stage3_build/orchestrate_passes.py check {args.spec} --pass-id {current}"+ print(f"current pass: {current}")+ print(f"next command: {command}")+ print("unmet acceptance criteria:")+ for item in acceptance or ["pass-specific evidence and a reviewHistory entry with action=continue"]:+ print(f"- {item}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))diff --git a/forge/report.py b/forge/report.pynew file mode 100644index 0000000..643c590--- /dev/null+++ b/forge/report.py@@ -0,0 +1,38 @@+from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "_shared"))+sys.path.insert(0, str(ROOT / "stage3_build"))+from status_banner import emit_status+from orchestrate_passes import completed_passes, current_pass, pass_order+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser(description="Generate a reconstruction report from the pass ledger")+ parser.add_argument("spec", type=Path)+ parser.add_argument("--out", type=Path)+ args = parser.parse_args(argv)+ spec = json.loads(args.spec.expanduser().read_text(encoding="utf-8"))+ if not isinstance(spec, dict):+ raise ValueError("spec must be an object")+ ids = pass_order(spec)+ completed = completed_passes(spec, ids)+ current = current_pass(ids, completed)+ missing = ids[len(completed):]+ opening = "PIPELINE COMPLETE through optimization-pass." if not missing else "INCOMPLETE: uncleared passes: " + ", ".join(missing) + "."+ emit_status(spec)+ report = "\n".join([opening, f"Target: {spec.get('targetName', '(unnamed)')}", f"Completed passes: {', '.join(completed) or '(none)'}", f"Current pass: {current}", "Review history entries: " + str(len(spec.get("reviewHistory", [])))]) + "\n"+ if args.out:+ args.out.expanduser().write_text(report, encoding="utf-8")+ else:+ print(report, end="")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))diff --git a/forge/stage1_intake/cs2_foundation.py b/forge/stage1_intake/cs2_foundation.pynew file mode 100644index 0000000..117a6d5--- /dev/null+++ b/forge/stage1_intake/cs2_foundation.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+from __future__ import annotations++from pathlib import Path+from typing import Any+++def resolve_identity(+ explicit: dict[str, Any] | None,+ resolved: dict[str, Any] | None,+ classification: dict[str, Any] | None,+) -> dict[str, Any]:+ if explicit:+ return {"status": "resolved", "identity": dict(explicit), "provenance": "explicit-user-metadata"}+ if resolved and resolved.get("status") == "ambiguous":+ return {"status": "ambiguous", "candidates": list(resolved.get("candidates", []))}+ if resolved and resolved.get("status") == "no-match":+ return {"status": "no-match", "reason": resolved.get("reason", "metadata lookup found no match")}+ if resolved and resolved.get("status") in {None, "resolved"}:+ return {"status": "resolved", "identity": dict(resolved), "provenance": "resolved-metadata"}+ if classification and classification.get("itemFamily"):+ return {"status": "resolved", "identity": dict(classification), "provenance": "classification-record"}+ return {"status": "request-input", "reason": "authoritative identity evidence is unavailable"}+++def normalize_cs2_metadata(metadata: dict[str, Any]) -> dict[str, Any]:+ float_value = metadata.get("float", metadata.get("floatValue"))+ paint_seed = metadata.get("paintSeed", metadata.get("paint_seed"))+ hidden_confidence = metadata.get("hiddenRegionConfidence")+ if not isinstance(hidden_confidence, (int, float)):+ hidden_confidence = 0.25+ return {+ "identity": {+ "name": metadata.get("name", metadata.get("itemName")),+ "paintIndex": metadata.get("paintIndex", metadata.get("paint_index")),+ "rarity": metadata.get("rarity"),+ "previewUrl": metadata.get("previewUrl", metadata.get("imageUrl")),+ "floatRange": metadata.get("floatRange", {"min": metadata.get("minFloat"), "max": metadata.get("maxFloat")}),+ },+ "float": float_value,+ "paintSeed": paint_seed,+ "finishStyle": metadata.get("finishStyle"),+ "approximations": {+ "float": {"value": float_value, "approximated": float_value is None, "confidence": 0.0 if float_value is None else 1.0},+ "paintSeed": {"value": paint_seed, "approximated": paint_seed is None, "confidence": 0.0 if paint_seed is None else 1.0},+ "hiddenRegions": {"confidence": float(hidden_confidence), "approximated": True},+ "finishStyle": {"value": metadata.get("finishStyle"), "approximated": metadata.get("finishStyle") is None},+ },+ }+++def enrich_manifest_with_metadata(manifest: dict[str, Any], resolution: dict[str, Any]) -> dict[str, Any]:+ result = dict(manifest)+ result["metadataResolution"] = dict(resolution)+ result.setdefault("warnings", [])+ warnings = list(result["warnings"])+ if resolution.get("status") in {"no-match", "ambiguous"}:+ if "metadata-unavailable" not in warnings:+ warnings.append("metadata-unavailable")+ result["exactnessTier"] = result.get("exactnessTier", "image-only")+ elif resolution.get("status") == "resolved":+ result["metadata"] = normalize_cs2_metadata(resolution.get("identity", resolution))+ if result.get("exactnessTier") == "image-only":+ result["exactnessTier"] = "metadata-assisted"+ result["warnings"] = warnings+ return result+++def classify_map_path(path: Path) -> dict[str, Any]:+ name = path.name.lower()+ if any(token in name for token in ("_orm", "_mrao", "_packed")):+ return {"mapClass": "packed", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard", "packedChannels": {"roughness": "r", "metalness": "g", "ao": "b"}}+ if any(token in name for token in ("_normal", "_nrm", "_bump")):+ return {"mapClass": "normal", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}+ if any(token in name for token in ("_rough", "_roughness")):+ return {"mapClass": "roughness", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}+ if any(token in name for token in ("_metal", "_metalness")):+ return {"mapClass": "metalness", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}+ if any(token in name for token in ("_ao", "_occlusion")):+ return {"mapClass": "ao", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}+ if any(token in name for token in ("_height", "_displacement")):+ return {"mapClass": "height", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}+ if any(token in name for token in ("_mask", "_wear", "_pattern")):+ return {"mapClass": "mask", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}+ return {"mapClass": "albedo", "path": str(path), "colorSpace": "srgb", "uvOrientation": "standard"}+++def adapt_texture_result(extraction: dict[str, Any], output_dir: Path) -> dict[str, Any]:+ if extraction.get("status") != "ok":+ return {"status": "fallback", "textureSource": "image-only", "reason": extraction.get("reason", "texture extraction unavailable")}+ records: list[dict[str, Any]] = []+ for path in sorted(output_dir.rglob("*")):+ if path.is_file():+ record = classify_map_path(path)+ record.update({"source": "local-vpk", "ipBoundary": "local-user-install-not-redistributable"})+ records.append(record)+ return {"status": "ok", "textureSource": "local-vpk", "assets": records}+++def map_assets_to_reference_pbr(records: list[dict[str, Any]]) -> dict[str, Any]:+ channels: dict[str, dict[str, Any]] = {}+ for record in records:+ map_class = record.get("mapClass")+ if map_class in {"albedo", "normal", "roughness", "metalness", "height", "ao", "mask"}:+ channels.setdefault(str(map_class), dict(record))+ elif map_class == "packed":+ for channel, packed_channel in record.get("packedChannels", {}).items():+ channels.setdefault(channel, {"path": record.get("path"), "source": record.get("source", "local-vpk"), "derived": True, "packedChannel": packed_channel, "colorSpace": "linear", "uvOrientation": record.get("uvOrientation", "standard")})+ missing = [channel for channel in ("albedo", "normal", "roughness", "metalness") if channel not in channels]+ if "ao" not in channels:+ channels["ao"] = {"derived": True, "from": "normal-or-geometry", "confidence": 0.25}+ return {"maps": channels, "missingRequired": missing, "complete": not missing}+++def validate_route_requirements(manifest: dict[str, Any], *, allow_fallback: bool = False) -> dict[str, Any]:+ result = dict(manifest)+ route = result.get("route")+ tier = result.get("exactnessTier")+ if route == "reference-projection":+ camera = result.get("camera", {})+ projection = result.get("projection", {})+ has_camera = camera.get("status") == "solved" or bool(camera.get("referenceCamera"))+ has_delit = bool(result.get("deLitAlbedo") or projection.get("deLitSource"))+ if not (has_camera and has_delit):+ if allow_fallback:+ result["route"] = "procedural-finish"+ result["state"] = "fallback"+ result.setdefault("warnings", []).append("projection-evidence-unavailable; procedural fallback selected")+ else:+ result["state"] = "request-input"+ return result+ if route == "authored-texture":+ assets = result.get("assets", {}).get("records", []) if isinstance(result.get("assets"), dict) else []+ channels = {item.get("mapClass") for item in assets if isinstance(item, dict)}+ if not {"albedo", "normal"}.issubset(channels) or not ({"roughness", "packed"} & channels):+ result["state"] = "request-input" if tier == "exact-texture" else "fallback"+ if tier == "exact-texture" and route != "authored-texture":+ result["state"] = "request-input"+ return resultdiff --git a/forge/stage1_intake/cs2_manifest.py b/forge/stage1_intake/cs2_manifest.pynew file mode 100644index 0000000..591c0c5--- /dev/null+++ b/forge/stage1_intake/cs2_manifest.py@@ -0,0 +1,230 @@+#!/usr/bin/env python3+from __future__ import annotations++import argparse+import json+import os+import sys+import tempfile+from pathlib import Path+from typing import Any, Final++from forge.stage1_intake.check_reference_admission import check_admission+from forge.stage1_intake.cs2_foundation import enrich_manifest_with_metadata, normalize_cs2_metadata, resolve_identity+from forge.stage1_intake.cs2_review_contract import build_review_scene+from forge.stage1_intake.detect_cs2 import detect_cs2_signals+from forge.stage1_intake.probe_image import probe++SCHEMA_VERSION: Final[int] = 1+SUPPORTED_FAMILIES: Final[frozenset[str]] = frozenset({"knife"})+UNSUPPORTED_FAMILIES: Final[frozenset[str]] = frozenset(+ {"pistol", "rifle", "smg", "sniper", "heavy", "glove"}+)+# Knife subtypes that have a dedicated geometry adapter. A subtype absent here is+# `unsupported-subtype`, never silently routed through another subtype's tree.+KNIFE_SUBTYPES: Final[frozenset[str]] = frozenset(+ {"karambit", "butterfly", "bayonet", "m9", "flip", "gut", "falchion", "bowie", "navaja",+ "talon", "classic"}+)+ROUTES: Final[frozenset[str]] = frozenset(+ {"reference-projection", "authored-texture", "procedural-finish"}+)+TIERS: Final[frozenset[str]] = frozenset(+ {"image-only", "metadata-assisted", "exact-texture"}+)+STATES: Final[frozenset[str]] = frozenset(+ {"proceed", "request-input", "fallback", "rejected", "unsupported-family", "unsupported-subtype"}+)+++def build_classification_record(+ item_family: str,+ subtype: str | None,+ confidence: float,+ evidence_refs: list[str],+ *,+ provider: str = "offline-fixture",+ version: str = "1",+ timeout: bool = False,+) -> dict[str, Any]:+ if item_family not in SUPPORTED_FAMILIES | UNSUPPORTED_FAMILIES:+ raise ValueError(f"unsupported item family label: {item_family}")+ if not 0.0 <= confidence <= 1.0:+ raise ValueError("classification confidence must be between 0 and 1")+ return {+ "itemFamily": item_family,+ "subtype": subtype,+ "confidence": round(confidence, 4),+ "evidenceRefs": list(evidence_refs),+ "provider": provider,+ "version": version,+ "timedOut": timeout,+ }+++def _classification_error(record: Any) -> str | None:+ if not isinstance(record, dict):+ return "authoritative classification record is required"+ family = record.get("itemFamily")+ confidence = record.get("confidence")+ refs = record.get("evidenceRefs")+ if not isinstance(family, str) or family not in SUPPORTED_FAMILIES | UNSUPPORTED_FAMILIES:+ return "classification itemFamily is missing or invalid"+ if not isinstance(confidence, (int, float)) or isinstance(confidence, bool) or not 0 <= confidence <= 1:+ return "classification confidence is missing or invalid"+ if not isinstance(refs, list) or not refs or not all(isinstance(item, str) and item for item in refs):+ return "classification evidenceRefs must contain at least one reference"+ if not isinstance(record.get("provider"), str) or not isinstance(record.get("version"), str):+ return "classification provider/version are required"+ return None+++def _heuristic_signal(reference: Path) -> dict[str, Any]:+ try:+ return detect_cs2_signals(reference)+ except (OSError, ValueError) as exc:+ return {"is_cs2_candidate": False, "confidence": 0.0, "signals": [], "error": str(exc)}+++def build_manifest(+ reference: Path,+ classification: dict[str, Any] | None,+ *,+ route: str = "reference-projection",+ exactness_tier: str = "image-only",+ metadata: dict[str, Any] | None = None,+ texture_source: str = "image-only",+ explicit_identity: dict[str, Any] | None = None,+) -> dict[str, Any]:+ resolved = reference.expanduser().resolve()+ technical: dict[str, Any] = probe(resolved) if resolved.exists() else {"path": str(resolved), "warnings": ["file does not exist"]}+ admission: dict[str, Any] = check_admission(resolved) if resolved.exists() else {"admitted": False, "reasons": ["reference does not exist"]}+ heuristic = _heuristic_signal(resolved) if resolved.exists() else {"is_cs2_candidate": False, "confidence": 0.0, "signals": []}+ warnings: list[str] = []+ if heuristic.get("is_cs2_candidate"):+ warnings.append("heuristicSignal")+ if technical.get("warnings"):+ warnings.extend(str(item) for item in technical["warnings"])+ if route not in ROUTES:+ raise ValueError(f"unknown route {route!r}")+ if exactness_tier not in TIERS:+ raise ValueError(f"unknown exactness tier {exactness_tier!r}")+ manifest: dict[str, Any] = {+ "schemaVersion": SCHEMA_VERSION,+ "state": "rejected" if not admission.get("admitted") else "request-input",+ "sourceViews": [{+ "role": "reference",+ "path": str(resolved),+ "hash": admission.get("provenance", {}).get("pHash"),+ "width": technical.get("width"),+ "height": technical.get("height"),+ "coverage": admission.get("provenance", {}).get("foregroundCoverage"),+ "duplicate": admission.get("provenance", {}).get("duplicateOfHash") is not None,+ }],+ "admission": admission,+ "probe": technical,+ "heuristicSignal": heuristic,+ "exactnessTier": exactness_tier,+ "route": route,+ "textureSource": texture_source,+ "identity": {"provenance": "unknown", "confidence": 0.0},+ "finish": {"provenance": "visual-observation", "confidence": 0.0},+ "assets": {"source": texture_source, "records": []},+ "camera": {"status": "unknown", "provenance": "not-supplied"},+ "provenance": {"reference": "user-supplied", "metadata": "not-supplied"},+ "assumptions": {"float": "unknown", "paintSeed": "unknown", "hiddenRegions": "inferred"},+ "confidence": {"overall": 0.0, "hiddenRegions": 0.25},+ "warnings": warnings,+ "extensions": {},+ "reviewScene": build_review_scene("not-supplied"),+ }+ if not admission.get("admitted"):+ manifest["rejectionReasons"] = admission.get("reasons", ["reference failed admission"])+ return manifest+ error = _classification_error(classification)+ if error:+ manifest["warnings"].append(error)+ return manifest+ assert isinstance(classification, dict)+ family = classification["itemFamily"]+ subtype = classification.get("subtype")+ manifest["classification"] = classification+ manifest["itemFamily"] = family+ manifest["subtype"] = subtype+ manifest["identity"] = {"provenance": "classification-record", "confidence": classification["confidence"]}+ manifest["confidence"] = {"overall": classification["confidence"], "hiddenRegions": 0.25}+ manifest["identity"] = resolve_identity(explicit_identity, metadata, classification)+ if family not in SUPPORTED_FAMILIES:+ manifest["state"] = "unsupported-family"+ manifest["unsupportedReason"] = f"no adapter registered for {family}"+ elif subtype and subtype not in KNIFE_SUBTYPES:+ manifest["state"] = "unsupported-subtype"+ manifest["unsupportedReason"] = f"no knife adapter fixture for {subtype}"+ else:+ manifest["state"] = "proceed"+ manifest["componentAdapter"] = "cs2-knife-v1"+ if metadata:+ manifest = enrich_manifest_with_metadata(manifest, {"status": "resolved", "identity": metadata})+ manifest["metadata"] = normalize_cs2_metadata(metadata)+ manifest["provenance"]["metadata"] = metadata.get("source", "provided")+ return manifest+++def validate_manifest(manifest: dict[str, Any]) -> bool:+ required = {"schemaVersion", "state", "sourceViews", "admission", "exactnessTier", "route", "warnings"}+ if not required.issubset(manifest):+ return False+ if manifest["schemaVersion"] != SCHEMA_VERSION or manifest["state"] not in STATES:+ return False+ if manifest["route"] not in ROUTES or manifest["exactnessTier"] not in TIERS:+ return False+ if not isinstance(manifest["sourceViews"], list) or not isinstance(manifest["warnings"], list):+ return False+ if manifest["state"] == "proceed" and manifest.get("itemFamily") != "knife":+ return False+ return True+++def persist_manifest(manifest: dict[str, Any], output: Path) -> None:+ if not validate_manifest(manifest):+ raise ValueError("refusing to persist invalid cs2-intake manifest")+ output = output.expanduser().resolve()+ output.parent.mkdir(parents=True, exist_ok=True)+ fd, temp_name = tempfile.mkstemp(prefix=f".{output.name}.", suffix=".tmp", dir=output.parent)+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ json.dump(manifest, handle, indent=2, ensure_ascii=False)+ handle.write("\n")+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(temp_name, output)+ finally:+ if os.path.exists(temp_name):+ os.unlink(temp_name)+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("reference", type=Path)+ parser.add_argument("--classification", type=Path, help="offline authoritative classification JSON")+ parser.add_argument("--out", type=Path, required=True)+ parser.add_argument("--route", choices=sorted(ROUTES), default="reference-projection")+ parser.add_argument("--exactness-tier", choices=sorted(TIERS), default="image-only")+ parser.add_argument("--cs2-pipeline", choices=("legacy", "manifest-v1"), default="manifest-v1")+ parser.add_argument("--resume", action="store_true", help="reuse a valid existing manifest at --out")+ args = parser.parse_args(argv)+ if args.resume and args.out.exists():+ existing = json.loads(args.out.read_text(encoding="utf-8"))+ if isinstance(existing, dict) and validate_manifest(existing):+ print(json.dumps({"state": existing["state"], "out": str(args.out.resolve()), "resumed": True}, ensure_ascii=False))+ return 0+ classification = json.loads(args.classification.read_text(encoding="utf-8")) if args.classification else None+ manifest = build_manifest(args.reference, classification, route=args.route, exactness_tier=args.exactness_tier)+ manifest["extensions"]["compatibilityMode"] = args.cs2_pipeline+ persist_manifest(manifest, args.out)+ print(json.dumps({"state": manifest["state"], "out": str(args.out.resolve())}, ensure_ascii=False))+ return 0 if manifest["state"] in {"proceed", "request-input", "fallback"} else 2+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))diff --git a/forge/stage1_intake/cs2_review_contract.py b/forge/stage1_intake/cs2_review_contract.pynew file mode 100644index 0000000..a18bfe8--- /dev/null+++ b/forge/stage1_intake/cs2_review_contract.py@@ -0,0 +1,42 @@+#!/usr/bin/env python3+from __future__ import annotations++from typing import Any++GOLDEN_THRESHOLDS = {+ "silhouetteIoU": 0.85,+ "aspectRatioDelta": 0.05,+ "scaleDelta": 0.08,+ "paintedRegionMask": 0.85,+ "colorRegion": 0.80,+ "patternRegion": 0.75,+ "wearRegion": 0.70,+}+++def build_review_scene(environment_hash: str) -> dict[str, Any]:+ return {+ "version": "cs2-knife-review-v1",+ "camera": {"fovDegrees": 40.0, "position": [0.0, 0.0, 3.0], "target": [0.0, 0.0, 0.0]},+ "objectTransform": {"position": [0.0, 0.0, 0.0], "rotation": [0.0, 0.0, 0.0], "scale": [1.0, 1.0, 1.0]},+ "environmentHash": environment_hash,+ "exposure": 1.0,+ "toneMapping": "ACESFilmic",+ "resolution": [1024, 1024],+ "background": "#20242a",+ "rendererVersion": "three-r170",+ "thresholds": dict(GOLDEN_THRESHOLDS),+ "orbitViewpoints": [{"yaw": 35.0, "pitch": 8.0}, {"yaw": -35.0, "pitch": 8.0}],+ }+++def validate_review_scene(scene: dict[str, Any]) -> list[str]:+ required = {"version", "camera", "objectTransform", "environmentHash", "exposure", "toneMapping", "resolution", "background", "rendererVersion", "thresholds", "orbitViewpoints"}+ errors = [f"missing {field}" for field in sorted(required - set(scene))]+ if scene.get("version") != "cs2-knife-review-v1":+ errors.append("unsupported review scene version")+ if scene.get("thresholds") != GOLDEN_THRESHOLDS:+ errors.append("golden thresholds do not match the frozen fixture contract")+ if len(scene.get("orbitViewpoints", [])) != 2:+ errors.append("exactly two orbit viewpoints are required")+ return errorsdiff --git a/forge/stage1_intake/detect_cs2.py b/forge/stage1_intake/detect_cs2.pynew file mode 100644index 0000000..56995d8--- /dev/null+++ b/forge/stage1_intake/detect_cs2.py@@ -0,0 +1,276 @@+#!/usr/bin/env python3+"""Detect whether a reference image depicts a CS2 weapon/item.++This is a pre-analysis guard that runs BEFORE visual analysis. It uses+heuristic signals (aspect ratio, color distribution, known CS2 weapon+silhouette ratios) to route the pipeline to the CS2-specific track.++This script does NOT do visual analysis — it only reads file metadata+and performs basic image statistics. The agent's vision layer does the+real CS2 identification later in the pipeline.++Usage:+ python3 detect_cs2.py <image_path> [--threshold 0.3]+ python3 detect_cs2.py <image_path> --json+"""++from __future__ import annotations++import argparse+import json+import math+import struct+import sys+from pathlib import Path+++# ---------------------------------------------------------------------------+# Image format readers (pure stdlib, no PIL)+# ---------------------------------------------------------------------------++def _png_dimensions(data: bytes) -> tuple[int, int] | None:+ if data.startswith(b"\x89PNG\r\n\x1a\n") and len(data) >= 24:+ return struct.unpack(">II", data[16:24])+ return None+++def _jpeg_dimensions(data: bytes) -> tuple[int, int] | None:+ if not data.startswith(b"\xff\xd8"):+ return None+ idx = 2+ while idx + 9 < len(data):+ if data[idx] != 0xFF:+ idx += 1+ continue+ marker = data[idx + 1]+ idx += 2+ if marker in {0xD8, 0xD9}:+ continue+ if idx + 2 > len(data):+ return None+ length = struct.unpack(">H", data[idx : idx + 2])[0]+ if length < 2 or idx + length > len(data):+ return None+ if marker in {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}:+ if length >= 7:+ height, width = struct.unpack(">HH", data[idx + 3 : idx + 7])+ return width, height+ idx += length+ return None+++def _gif_dimensions(data: bytes) -> tuple[int, int] | None:+ if data[:6] in {b"GIF87a", b"GIF89a"} and len(data) >= 10:+ return struct.unpack("<HH", data[6:10])+ return None+++def _webp_dimensions(data: bytes) -> tuple[int, int] | None:+ if len(data) < 30 or data[:4] != b"RIFF" or data[8:12] != b"WEBP":+ return None+ chunk = data[12:16]+ if chunk == b"VP8X" and len(data) >= 30:+ width = 1 + int.from_bytes(data[24:27], "little")+ height = 1 + int.from_bytes(data[27:30], "little")+ return width, height+ if chunk == b"VP8 " and len(data) >= 30:+ start = data.find(b"\x9d\x01\x2a")+ if start != -1 and start + 7 <= len(data):+ width, height = struct.unpack("<HH", data[start + 3 : start + 7])+ return width, height+ return None+++def _read_dimensions(data: bytes) -> tuple[int, int] | None:+ return (+ _png_dimensions(data)+ or _jpeg_dimensions(data)+ or _gif_dimensions(data)+ or _webp_dimensions(data)+ )+++# ---------------------------------------------------------------------------+# CS2 detection heuristics+# ---------------------------------------------------------------------------++# Known CS2 weapon aspect ratios (width / height) from inventory icons and+# standard workshop reference poses. These are *approximate* — a real CS2+# detection needs the agent vision layer, but these ratios help the guard+# route early.+CS2_WEAPON_ASPECT_RATIOS: dict[str, tuple[float, float]] = {+ # knives — typically shown at ~15-45° angle+ "knife_long": (1.8, 4.0), # Bowie, M9, Bayonet, Falchion+ "knife_curved": (0.8, 1.5), # Karambit, Talon+ "knife_folder": (1.2, 2.5), # Flip, Gut, Navaja+ "knife_butterfly": (0.6, 1.2),# Butterfly (open)+ # rifles — shown horizontally or at slight angle+ "rifle_horizontal": (2.5, 5.0), # AK-47, M4A4, AWP+ # pistols — shown at ~20-45° angle+ "pistol_angle": (1.0, 2.0), # Glock, USP, Deagle, AK pistol+ # gloves — shown as pair or single+ "gloves": (0.8, 1.5),+}+++def _aspect_in_cs2_ranges(aspect: float) -> list[str]:+ """Return list of CS2 weapon categories whose aspect ratio matches."""+ matches = []+ for category, (lo, hi) in CS2_WEAPON_ASPECT_RATIOS.items():+ if lo <= aspect <= hi:+ matches.append(category)+ return matches+++def _color_energy(data: bytes, sample_points: int = 200) -> dict[str, float]:+ """Sample raw byte energy at evenly-spaced points to detect dominant color ranges.++ This is a VERY rough heuristic — it reads raw file bytes, not decoded+ pixels. For real detection, the agent vision layer handles this.+ """+ if len(data) < sample_points * 4:+ return {"dominant_range": "unknown", "energy": 0.0}++ step = len(data) // sample_points+ r_sum = g_sum = b_sum = 0+ for i in range(sample_points):+ offset = i * step+ if offset + 3 < len(data):+ r_sum += data[offset]+ g_sum += data[offset + 1]+ b_sum += data[offset + 2]++ r_avg = r_sum / sample_points+ g_avg = g_sum / sample_points+ b_avg = b_sum / sample_points++ # Detect common CS2 backgrounds: white/grey workshop renders+ if r_avg > 200 and g_avg > 200 and b_avg > 200:+ dominant = "light_background"+ elif r_avg < 50 and g_avg < 50 and b_avg < 50:+ dominant = "dark_background"+ elif abs(r_avg - g_avg) < 20 and abs(g_avg - b_avg) < 20:+ dominant = "neutral_grey"+ else:+ dominant = "colored"++ energy = math.sqrt(r_avg**2 + g_avg**2 + b_avg**2)+ return {"dominant_range": dominant, "energy": round(energy, 2)}+++def detect_cs2_signals(path: Path) -> dict:+ """Analyze a reference image for CS2 weapon/item detection signals.++ Returns a dict with:+ - is_cs2_candidate: bool+ - confidence: 0.0-1.0+ - signals: list of detected signal descriptions+ - weapon_categories: possible CS2 weapon categories+ - dimensions: {width, height, aspectRatio}+ - color_profile: dominant color range info+ - note: explanation of detection limits+ """+ data = path.read_bytes()+ dims = _read_dimensions(data)+ signals: list[str] = []+ score = 0.0++ # Signal 1: Aspect ratio matches known CS2 weapon profiles+ if dims:+ width, height = dims+ aspect = width / height if height else 1.0+ categories = _aspect_in_cs2_ranges(aspect)+ if categories:+ score += 0.3+ signals.append(f"aspect_ratio_matches:{','.join(categories)}")+ else:+ aspect = None+ categories = []++ # Signal 2: Image dimensions suggest inventory/workshop render+ if dims:+ w, h = dims+ # CS2 inventory icons are typically 512×512 or 256×256+ if w == h and w in {256, 512, 1024}:+ score += 0.2+ signals.append("square_format_inventory_icon")+ # Workshop renders are often wide format+ elif w > h and w >= 512:+ score += 0.1+ signals.append("wide_format_workshop_render")++ # Signal 3: Color profile suggests workshop render+ color = _color_energy(data)+ if color["dominant_range"] == "light_background":+ score += 0.15+ signals.append("light_background_workshop_style")+ elif color["dominant_range"] == "neutral_grey":+ score += 0.1+ signals.append("neutral_background_steam_style")++ # Signal 4: File size suggests rendered image (not photo)+ file_size = len(data)+ if 50_000 < file_size < 5_000_000:+ score += 0.05+ signals.append("typical_render_file_size")++ is_cs2_candidate = score >= 0.3++ return {+ "path": str(path),+ "is_cs2_candidate": is_cs2_candidate,+ "confidence": min(round(score, 2), 1.0),+ "signals": signals,+ "weapon_categories": categories,+ "dimensions": {+ "width": dims[0] if dims else None,+ "height": dims[1] if dims else None,+ "aspectRatio": round(aspect, 3) if aspect else None,+ },+ "color_profile": color,+ "note": (+ "This is a heuristic pre-analysis guard using file metadata and "+ "basic byte statistics. It does NOT perform visual analysis. "+ "The agent's vision layer (Step 1) performs definitive CS2 "+ "identification using the M.C.M.T framework in "+ "grimoire/intake/cs2_technical_analysis.md"+ ),+ }+++# ---------------------------------------------------------------------------+# CLI+# ---------------------------------------------------------------------------++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("image", type=Path, help="Path to reference image")+ parser.add_argument("--json", action="store_true", help="Output raw JSON")+ parser.add_argument("--threshold", type=float, default=0.3, help="CS2 candidate threshold (default: 0.3)")+ args = parser.parse_args(argv)++ if not args.image.exists():+ print(json.dumps({"error": f"File not found: {args.image}"}))+ return 1++ result = detect_cs2_signals(args.image)++ if args.json:+ print(json.dumps(result, indent=2))+ else:+ status = "CS2_CANDIDATE" if result["is_cs2_candidate"] else "NON_CS2"+ print(f"Status: {status}")+ print(f"Confidence: {result['confidence']}")+ print(f"Signals: {', '.join(result['signals']) or 'none'}")+ if result["weapon_categories"]:+ print(f"Weapon categories: {', '.join(result['weapon_categories'])}")+ dims = result["dimensions"]+ if dims["width"]:+ print(f"Dimensions: {dims['width']}×{dims['height']} (aspect {dims['aspectRatio']})")+ print(f"\n{result['note']}")++ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/forge/stage1_intake/extract_cs2_textures.py b/forge/stage1_intake/extract_cs2_textures.pynew file mode 100644index 0000000..4367d53--- /dev/null+++ b/forge/stage1_intake/extract_cs2_textures.py@@ -0,0 +1,126 @@+#!/usr/bin/env python3+"""Optional exactness upgrade: extract a CS2 skin's authored paint textures from the user's own+legal install using Source2Viewer-CLI, then classify the output maps by convention. Degrades+gracefully -- every failure (no VPK, no extractor binary, subprocess error, non-zero exit) returns+a {"status": "fallback", "reason": ...} result so the pipeline can fall back to the image-only+path, never a wrong render. Extracted pixels are Valve IP: they stay in the gitignored cs2_textures/+workspace and are never committed. See grimoire/intake/cs2_texture_acquisition.md and openspec+add-cs2-item-reconstruction tasks 5.4/5.5.+"""++from __future__ import annotations++import argparse+import json+import shutil+import subprocess+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+import locate_cs2_vpk # noqa: E402 (sibling module, resolved via the path insert above)+from cs2_foundation import classify_map_path # noqa: E402++SOURCE2VIEWER_BINARY = "Source2Viewer-CLI"++# Filename-convention buckets for Source 2 material maps. A map that matches nothing lands in+# "other" rather than being dropped, so an unexpected naming convention is visible, not silent.+_MAP_CLASSIFIERS = (+ ("color", ("_color", "_albedo", "_basecolor", "_diffuse")),+ ("normal", ("_normal", "_bump", "_nrm")),+ ("roughness_metalness", ("_rough", "_metal", "_orm", "_mrao", "_packed")),+ ("mask", ("_mask", "_ao", "_occlusion", "_pattern", "_wear")),+)+++def source2viewer_available() -> bool:+ """True when the Source2Viewer-CLI binary is on PATH (it needs the .NET runtime to run)."""+ return shutil.which(SOURCE2VIEWER_BINARY) is not None+++def run_source2viewer(vpk: Path, out_dir: Path, filter_glob: str | None = None) -> subprocess.CompletedProcess:+ """Wrap the Source2Viewer-CLI extraction call. Raises FileNotFoundError if the binary is+ absent; returns the CompletedProcess otherwise (caller inspects returncode)."""+ cmd = [SOURCE2VIEWER_BINARY, "-i", str(vpk), "-o", str(out_dir), "-d", "-e", "vtex_c"]+ if filter_glob:+ cmd += ["-f", filter_glob]+ return subprocess.run(cmd, capture_output=True, text=True)+++def classify_extracted_maps(out_dir: Path) -> dict[str, list[str]]:+ """Bucket the files under out_dir into color / normal / roughness_metalness / mask / other by+ filename convention."""+ buckets: dict[str, list[str]] = {name: [] for name, _ in _MAP_CLASSIFIERS}+ buckets["other"] = []+ if not out_dir.is_dir():+ return buckets+ for path in sorted(out_dir.rglob("*")):+ if not path.is_file():+ continue+ lower = path.name.lower()+ for name, suffixes in _MAP_CLASSIFIERS:+ if any(token in lower for token in suffixes):+ buckets[name].append(str(path))+ break+ else:+ buckets["other"].append(str(path))+ return buckets+++def build_asset_records(out_dir: Path) -> list[dict]:+ records = []+ for path in sorted(out_dir.rglob("*")):+ if path.is_file():+ record = classify_map_path(path)+ record.update({"source": "local-vpk", "ipBoundary": "local-user-install-not-redistributable"})+ records.append(record)+ return records+++def extract(out_dir: Path, vpk: Path | None, roots: list[Path] | None, filter_glob: str | None) -> dict:+ if vpk is None:+ vpk = locate_cs2_vpk.locate_vpk(roots)+ if vpk is None:+ return {"status": "fallback",+ "reason": "no local CS2 VPK found; falling back to image-only reconstruction "+ "(exact texture likeness unavailable)"}+ if not source2viewer_available():+ return {"status": "fallback",+ "reason": f"{SOURCE2VIEWER_BINARY} not found on PATH; falling back to image-only "+ "reconstruction (exact texture likeness unavailable)"}+ out_dir.mkdir(parents=True, exist_ok=True)+ try:+ result = run_source2viewer(vpk, out_dir, filter_glob)+ except OSError as exc:+ return {"status": "fallback", "reason": f"{SOURCE2VIEWER_BINARY} failed to run ({exc}); "+ "falling back to image-only reconstruction"}+ if result.returncode != 0:+ return {"status": "fallback",+ "reason": f"{SOURCE2VIEWER_BINARY} exited {result.returncode}: "+ f"{(result.stderr or '').strip()[:200]}; falling back to image-only"}+ return {"status": "ok", "vpk": str(vpk), "outDir": str(out_dir),+ "maps": classify_extracted_maps(out_dir), "assets": build_asset_records(out_dir)}+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--out", type=Path, required=True, help="Output directory (gitignored cs2_textures/)")+ parser.add_argument("--vpk", type=Path, help="Explicit pak01_dir.vpk path (skips locating)")+ parser.add_argument("--root", type=Path, action="append", dest="roots",+ help="Steam root to search when --vpk is omitted (repeatable)")+ parser.add_argument("--filter", dest="filter_glob", help="Source2Viewer -f filter, e.g. a paint kit name")+ parser.add_argument("--json", action="store_true", help="Emit a JSON result object")+ args = parser.parse_args(argv)++ result = extract(args.out.expanduser(), args.vpk, args.roots, args.filter_glob)+ if args.json:+ print(json.dumps(result, indent=2))+ elif result["status"] == "ok":+ print(f"extracted to {result['outDir']}")+ else:+ print(result["reason"], file=sys.stderr)+ return 0 if result["status"] == "ok" else 1+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))diff --git a/forge/stage1_intake/fetch_cs2_metadata.py b/forge/stage1_intake/fetch_cs2_metadata.pynew file mode 100644index 0000000..a9e7cd0--- /dev/null+++ b/forge/stage1_intake/fetch_cs2_metadata.py@@ -0,0 +1,147 @@+#!/usr/bin/env python3+"""Resolve CS2 skin metadata (paint index, float range, rarity, CDN image) from the CSGO-API+skins index -- an optional exactness upgrade over the image-only default. Never guesses: a+no-match or an ambiguous multi-match is an error, not a silent pick. See+grimoire/intake/cs2_texture_acquisition.md and openspec add-cs2-item-reconstruction task 5.2.++The index is the public CSGO-API `skins.json` shape: a list of records like+ {"name": "Karambit | Doppler (Phase 2)", "weapon": {"name": "Karambit"},+ "paint_index": 419, "min_float": 0.0, "max_float": 0.08,+ "rarity": {"name": "Covert"}, "image": "https://.../419.png"}+Load it locally with --index-file (no network) or fetch it with --index-url.+"""++from __future__ import annotations++import argparse+import json+import sys+import urllib.request+from pathlib import Path+++def load_index(index_file: Path | None, index_url: str | None) -> list[dict]:+ if index_file is not None:+ data = json.loads(index_file.expanduser().read_text(encoding="utf-8"))+ elif index_url is not None:+ with urllib.request.urlopen(index_url, timeout=30) as response: # noqa: S310 (user-supplied trusted URL)+ data = json.loads(response.read().decode("utf-8"))+ else:+ raise ValueError("provide --index-file or --index-url")+ if isinstance(data, dict): # some CSGO-API mirrors key by id+ data = list(data.values())+ if not isinstance(data, list):+ raise ValueError("index must be a JSON list (or id-keyed object) of skin records")+ return [record for record in data if isinstance(record, dict)]+++def _weapon_name(record: dict) -> str:+ weapon = record.get("weapon")+ if isinstance(weapon, dict):+ return str(weapon.get("name") or "")+ return str(weapon or "")+++def _rarity_name(record: dict) -> str:+ rarity = record.get("rarity")+ if isinstance(rarity, dict):+ return str(rarity.get("name") or "")+ return str(rarity or "")+++def match_records(records: list[dict], weapon: str, skin: str, phase: str | None,+ paint_index: int | None = None) -> list[dict]:+ weapon_l, skin_l = weapon.lower(), skin.lower()+ phase_l = phase.lower() if phase else None+ matches = []+ for record in records:+ name_l = str(record.get("name") or "").lower()+ if _weapon_name(record).lower() != weapon_l:+ continue+ if skin_l not in name_l:+ continue+ if phase_l is not None and phase_l not in name_l:+ continue+ if paint_index is not None and str(record.get("paint_index")) != str(paint_index):+ continue+ matches.append(record)+ return matches+++def to_metadata(record: dict, source: str | None = None) -> dict:+ metadata = {+ "name": record.get("name"),+ "weapon": _weapon_name(record),+ "paintIndex": record.get("paint_index"),+ "minFloat": record.get("min_float"),+ "maxFloat": record.get("max_float"),+ "floatRange": {"min": record.get("min_float"), "max": record.get("max_float")},+ "rarity": _rarity_name(record),+ "imageUrl": record.get("image"),+ }+ if source:+ metadata["source"] = source+ metadata["provenance"] = {"kind": "metadata-index", "source": source or "unspecified"}+ return metadata+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--weapon", required=True, help="Weapon name, e.g. 'Karambit'")+ parser.add_argument("--skin", required=True, help="Skin/paint kit name substring, e.g. 'Doppler'")+ parser.add_argument("--phase", help="Disambiguating phase substring, e.g. 'Phase 2' or 'Emerald'")+ parser.add_argument("--paint-index", type=int, dest="paint_index",+ help="Exact paint_index to disambiguate when names collide (e.g. CSGO-API lists "+ "every Doppler phase as the same name; --paint-index 419 picks Phase 2).")+ parser.add_argument("--index-file", type=Path, help="Local CSGO-API skins JSON")+ parser.add_argument("--index-url", help="Remote CSGO-API skins JSON URL")+ parser.add_argument("--out", type=Path, help="Write the resolved metadata JSON here")+ parser.add_argument("--force", action="store_true", help="Overwrite --out if it exists")+ parser.add_argument("--download-image", type=Path,+ help="Directory to download the resolved CDN image into (optional)")+ args = parser.parse_args(argv)++ try:+ records = load_index(args.index_file, args.index_url)+ except (ValueError, OSError, json.JSONDecodeError) as exc:+ print(f"error: could not load skin index: {exc}", file=sys.stderr)+ return 2++ matches = match_records(records, args.weapon, args.skin, args.phase, args.paint_index)+ if not matches:+ print(f"error: no match for weapon={args.weapon!r} skin={args.skin!r} "+ f"phase={args.phase!r}; refine the query (nothing guessed)", file=sys.stderr)+ return 2+ if len(matches) > 1:+ names = "; ".join(f"{m.get('name')} (paint_index={m.get('paint_index')})" for m in matches)+ print(f"error: ambiguous match ({len(matches)}): {names}. Add --phase or --paint-index to "+ "disambiguate (nothing guessed).", file=sys.stderr)+ return 2++ source = str(args.index_file.expanduser().resolve()) if args.index_file else args.index_url+ metadata = to_metadata(matches[0], source)++ if args.download_image and metadata.get("imageUrl"):+ args.download_image.expanduser().mkdir(parents=True, exist_ok=True)+ target = args.download_image.expanduser() / f"{metadata.get('paintIndex')}.png"+ try:+ urllib.request.urlretrieve(metadata["imageUrl"], target) # noqa: S310+ metadata["imagePath"] = str(target)+ except OSError as exc:+ print(f"warning: image download failed ({exc}); metadata still resolved", file=sys.stderr)++ payload = json.dumps(metadata, indent=2, ensure_ascii=False) + "\n"+ if args.out:+ output = args.out.expanduser().resolve()+ if output.exists() and not args.force:+ print(f"error: {output} exists (use --force)", file=sys.stderr)+ return 2+ output.write_text(payload, encoding="utf-8")+ print(f"wrote {output}")+ else:+ sys.stdout.write(payload)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))diff --git a/forge/stage1_intake/locate_cs2_vpk.py b/forge/stage1_intake/locate_cs2_vpk.pynew file mode 100644index 0000000..b82be6d--- /dev/null+++ b/forge/stage1_intake/locate_cs2_vpk.py@@ -0,0 +1,73 @@+#!/usr/bin/env python3+"""Locate a local CS2 install's paks VPK (`pak01_dir.vpk`) so the optional exact-texture upgrade+can extract Valve's authored paint textures from the user's own legal copy. Best-effort and+non-fatal: returns None / {"found": false} when nothing is located, never raises -- the pipeline+falls back to the image-only path. See grimoire/intake/cs2_texture_acquisition.md and openspec+add-cs2-item-reconstruction task 5.3.+"""++from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++# CS2 (Source 2) ships the paints under game/csgo relative to the install dir.+_VPK_RELATIVE = Path("steamapps/common/Counter-Strike Global Offensive/game/csgo/pak01_dir.vpk")+++def default_steam_roots() -> list[Path]:+ """Per-OS default Steam library roots. Missing paths are harmless -- they just don't match."""+ home = Path.home()+ if sys.platform == "darwin":+ return [home / "Library/Application Support/Steam"]+ if sys.platform.startswith("win"):+ return [Path("C:/Program Files (x86)/Steam"), Path("C:/Program Files/Steam")]+ # linux / other+ return [+ home / ".steam/steam",+ home / ".local/share/Steam",+ home / ".steam/root",+ ]+++def locate_vpk(roots: list[Path] | None = None) -> Path | None:+ """Return the first existing pak01_dir.vpk across the given (or default) Steam roots.+ Dependency-injectable `roots` keeps this testable offline."""+ search_roots = list(roots) if roots else default_steam_roots()+ seen: set[Path] = set()+ for root in search_roots:+ root = Path(root)+ if root in seen:+ continue+ seen.add(root)+ vpk = root / _VPK_RELATIVE+ if vpk.is_file():+ return vpk+ return None+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--root", type=Path, action="append", dest="roots",+ help="Steam root to search (repeatable); defaults to per-OS Steam locations")+ parser.add_argument("--json", action="store_true", help="Emit a JSON result object")+ args = parser.parse_args(argv)++ vpk = locate_vpk(args.roots)+ found = vpk is not None+ if args.json:+ result = {"found": found, "path": str(vpk) if vpk else None}+ if not found:+ result["reason"] = "no local CS2 VPK found in the searched Steam roots"+ print(json.dumps(result, indent=2))+ elif found:+ print(str(vpk))+ else:+ print("no local CS2 VPK found", file=sys.stderr)+ return 0 if found else 1+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))diff --git a/forge/stage1_intake/search_specs.py b/forge/stage1_intake/search_specs.pynew file mode 100644index 0000000..a663ffb--- /dev/null+++ b/forge/stage1_intake/search_specs.py@@ -0,0 +1,258 @@+#!/usr/bin/env python3++from __future__ import annotations++import argparse+import contextlib+import io+import json+import sys+from collections.abc import Sequence+from dataclasses import dataclass+from pathlib import Path+from typing import Final, TypeAlias, TypedDict++PROJECT_ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(PROJECT_ROOT))++from forge._shared.spec_search import ( # noqa: E402+ CacheReadError,+ CacheValidationError,+ CacheWriteError,+ IndexBuildError,+ IndexLoadResult,+ IndexRequest,+ ProfileValidationError,+ ProfileCachePathError,+ SearchOutputRequest,+ SerializedSearchMatch,+ SourceIngestionError,+ SpecRecordValidationError,+ UnknownCollectionError,+ load_or_build_index,+ load_profile,+ serialize_search_results,+)++JsonScalar: TypeAlias = str | int | float | bool | None+JsonValue: TypeAlias = JsonScalar | list["JsonValue"] | dict[str, "JsonValue"]+MIN_SNIPPET_CHARS: Final = 5+++class OutputIndex(TypedDict):+ status: str+ reason: str+ fingerprint: str+ cache_path: str+++class SuccessPayload(TypedDict):+ query: str+ collection: str+ index: OutputIndex+ matches: list[SerializedSearchMatch]+++@dataclass(frozen=True, slots=True)+class CliOptions:+ query: str+ collection: str+ limit: int+ snippet_chars: int+ reindex: bool+ json_output: bool+++@dataclass(frozen=True, slots=True)+class ErrorContext:+ query: str+ collection: str+ json_output: bool+++@dataclass(frozen=True, slots=True)+class CliFailure:+ code: str+ message: str+ exit_code: int+++class CliArgumentError(ValueError):+ pass+++class CliNamespace(argparse.Namespace):+ def __init__(self) -> None:+ super().__init__()+ self.query: list[str] = []+ self.collection: str = "cs2"+ self.limit: int = 3+ self.snippet_chars: int = 250+ self.reindex: bool = False+ self.json_output: bool = False+++def _parse_options(argv: Sequence[str]) -> CliOptions:+ parser = argparse.ArgumentParser(+ description="Search registered specification collections with local BM25."+ )+ _ = parser.add_argument("query", nargs="*", help="Search terms")+ _ = parser.add_argument("--collection", default="cs2")+ _ = parser.add_argument("--limit", type=int, default=3)+ _ = parser.add_argument(+ "--snippet-chars",+ type=int,+ default=250,+ help=f"Maximum snippet length; must be at least {MIN_SNIPPET_CHARS}.",+ )+ _ = parser.add_argument("--reindex", action="store_true")+ _ = parser.add_argument("--json", action="store_true", dest="json_output")+ namespace = CliNamespace()+ diagnostics = io.StringIO()+ try:+ with contextlib.redirect_stderr(diagnostics):+ _ = parser.parse_args(argv, namespace=namespace)+ except SystemExit as error:+ if error.code == 0:+ raise+ raise CliArgumentError(diagnostics.getvalue().strip()) from None+ return CliOptions(+ query=" ".join(namespace.query).strip(),+ collection=namespace.collection,+ limit=namespace.limit,+ snippet_chars=namespace.snippet_chars,+ reindex=namespace.reindex,+ json_output=namespace.json_output,+ )+++def _index_payload(result: IndexLoadResult) -> OutputIndex:+ return {+ "status": result.status,+ "reason": result.reason,+ "fingerprint": result.fingerprint,+ "cache_path": str(result.cache_path),+ }+++def _print_json(payload: SuccessPayload | dict[str, JsonValue]) -> None:+ print(json.dumps(payload, ensure_ascii=False, separators=(",", ":")))+++def _print_human(payload: SuccessPayload) -> None:+ print(f"Query: {payload['query']}")+ print(f"Collection: {payload['collection']}")+ index = payload["index"]+ print(f"Index: {index['status']} ({index['reason']}) {index['fingerprint']}")+ if not payload["matches"]:+ print("No matches.")+ return+ for position, match in enumerate(payload["matches"], start=1):+ location = match["file_path"]+ if match["heading"] is not None:+ location += f" :: {match['heading']}"+ if match["key_path"] is not None:+ location += f" :: {match['key_path']}"+ print(f"{position}. {match['record_id']} score={match['score']:.6f}")+ print(f" source: {location}")+ print(f" {match['snippets'][0]}")+++def _emit_error(context: ErrorContext, failure: CliFailure) -> int:+ print(f"error: {failure.message}", file=sys.stderr)+ if context.json_output:+ _print_json(+ {+ "query": context.query,+ "collection": context.collection,+ "index": None,+ "matches": [],+ "error": {"code": failure.code, "message": failure.message},+ }+ )+ return failure.exit_code+++def main(argv: Sequence[str]) -> int:+ json_requested = "--json" in argv+ try:+ options = _parse_options(argv)+ except CliArgumentError as error:+ return _emit_error(+ ErrorContext("", "cs2", json_requested),+ CliFailure("invalid_arguments", str(error), 2),+ )++ context = ErrorContext(options.query, options.collection, options.json_output)+ if not options.query:+ return _emit_error(context, CliFailure("empty_query", "query must not be empty", 2))+ if options.limit <= 0:+ return _emit_error(+ context,+ CliFailure("invalid_limit", "--limit must be greater than zero", 2),+ )+ if options.snippet_chars < MIN_SNIPPET_CHARS:+ return _emit_error(+ context,+ CliFailure(+ "invalid_snippet_chars",+ f"--snippet-chars must be at least {MIN_SNIPPET_CHARS} to include source text",+ 2,+ ),+ )++ try:+ profile = load_profile(options.collection)+ loaded = load_or_build_index(+ IndexRequest(PROJECT_ROOT, options.collection, profile, options.reindex)+ )+ matches = serialize_search_results(+ loaded.index,+ SearchOutputRequest(options.query, options.limit, options.snippet_chars),+ )+ except UnknownCollectionError as error:+ return _emit_error(+ context,+ CliFailure("unknown_collection", str(error), 2),+ )+ except ProfileCachePathError as error:+ return _emit_error(+ context,+ CliFailure("cache_failure", str(error), 3),+ )+ except ProfileValidationError as error:+ return _emit_error(+ context,+ CliFailure("profile_failure", str(error), 3),+ )+ except (SourceIngestionError, SpecRecordValidationError) as error:+ return _emit_error(+ context,+ CliFailure("source_failure", str(error), 3),+ )+ except IndexBuildError as error:+ return _emit_error(+ context,+ CliFailure("index_failure", str(error), 3),+ )+ except (CacheReadError, CacheValidationError, CacheWriteError) as error:+ return _emit_error(+ context,+ CliFailure("cache_failure", str(error), 3),+ )++ payload: SuccessPayload = {+ "query": options.query,+ "collection": options.collection,+ "index": _index_payload(loaded),+ "matches": matches,+ }+ if options.json_output:+ _print_json(payload)+ else:+ _print_human(payload)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))diff --git a/forge/stage2_spec/cs2_adapters.py b/forge/stage2_spec/cs2_adapters.pynew file mode 100644index 0000000..d94198a--- /dev/null+++ b/forge/stage2_spec/cs2_adapters.py@@ -0,0 +1,39 @@+#!/usr/bin/env python3+from __future__ import annotations++from dataclasses import dataclass, replace+from typing import Any+++@dataclass(frozen=True, slots=True)+class FamilyAdapter:+ family: str+ subtype: str+ topology: tuple[str, ...]+ painted_regions: tuple[str, ...]+ material_assignments: tuple[str, ...]+ feature_targets: tuple[str, ...]+ attachment_rules: tuple[str, ...]+ review_viewpoints: tuple[str, ...]++ def component_tree_contract(self) -> dict[str, Any]:+ return {"family": self.family, "subtype": self.subtype, "topology": self.topology, "paintedRegions": self.painted_regions, "materialAssignments": self.material_assignments, "featureTargets": self.feature_targets, "attachmentRules": self.attachment_rules, "reviewViewpoints": self.review_viewpoints}+++_KNIFE = FamilyAdapter(+ "knife", "generic-supported", ("ground-blade", "curve-sweep", "extrude", "assembled-solid"),+ ("blade-painted", "grip-painted", "guard-bare-metal", "pommel-bare-metal"),+ ("skin-finish", "substrate"),+ ("silhouette", "blade-edge-spine", "grip", "guard-quillon", "fastener", "pommel"),+ ("guard-to-blade", "grip-to-guard", "pommel-to-grip"),+ ("reference", "orbit-left", "orbit-right"),+)+SUPPORTED_KNIFE_SUBTYPES = frozenset({"karambit", "butterfly", "bayonet", "m9", "flip", "gut", "falchion", "bowie", "navaja", "talon", "classic"})+++def get_family_adapter(family: str, subtype: str | None = None) -> FamilyAdapter:+ if family != "knife":+ raise ValueError(f"unsupported-family: {family}")+ if subtype and subtype not in SUPPORTED_KNIFE_SUBTYPES:+ raise ValueError(f"unsupported-subtype: {subtype}")+ return _KNIFE if subtype is None else replace(_KNIFE, subtype=subtype)diff --git a/forge/stage2_spec/new_pre_spec_assessment.py b/forge/stage2_spec/new_pre_spec_assessment.pyindex a9f6aad..0c35151 100755--- a/forge/stage2_spec/new_pre_spec_assessment.py+++ b/forge/stage2_spec/new_pre_spec_assessment.py@@ -7,8 +7,33 @@ import argparseimport jsonimport sysfrom pathlib import Path+from typing import Final, TypedDict-from new_sculpt_spec import make_pre_spec_assessment, make_quality_contract+PROJECT_ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(PROJECT_ROOT))++from forge._shared.spec_search import ( # noqa: E402+ CacheReadError,+ CacheValidationError,+ CacheWriteError,+ IndexBuildError,+ IndexRequest,+ ProfileCachePathError,+ ProfileValidationError,+ JsonValue,+ SearchOutputRequest,+ SerializedSearchMatch,+ SourceIngestionError,+ SpecRecordValidationError,+ UnknownCollectionError,+ load_or_build_index,+ load_profile,+ serialize_search_results,+)+from forge.stage2_spec.new_sculpt_spec import ( # noqa: E402+ make_pre_spec_assessment,+ make_quality_contract,+)COMPLEXITY_MINIMUMS = {@@ -54,14 +79,111 @@ DETAIL_MINIMUMS = {"ultra-complex": 16,}+# CS2 weapon/knife/glove skins always carry more identity-defining detail (finish pattern,+# wear layer, hardware, stitching/fasteners) than a generic object at the same structural+# complexity tier -- so --cs2 defaults to the ultra-complex tier (targetMinDetails 16), and the+# detail-count floor never drops below this even if --complexity is explicitly set lower.+CS2_DETAIL_MINIMUM = 9++# Lightweight keyword heuristic, not exhaustive: catches the common phrasing ("CS2 skin",+# "AK-47 | Redline", "Karambit Doppler") so --cs2 doesn't have to be typed by hand for the+# obvious case. A miss here just means the agent (or the user) sets --cs2 explicitly --+# vision/prompt-based detection beyond this heuristic is inherently the agent's judgment call.+CS2_INTENT_KEYWORDS = (+ "cs2", "csgo", "counter-strike", "counter strike", "weapon skin", "knife skin", "glove skin",+ "doppler", "gamma doppler", "marble fade", "case hardened", "fade",+ "karambit", "butterfly knife", "bayonet", "gut knife", "falchion", "bowie knife",+ "classic knife",+)++DEFAULT_SPEC_SEARCH_LIMIT: Final = 3+DEFAULT_SPEC_SEARCH_SNIPPET_CHARS: Final = 250+++class LocalSpecSearchIndex(TypedDict):+ status: str+ reason: str+ fingerprint: str+++class LocalSpecSearchPayload(TypedDict):+ collection: str+ query: str+ index: LocalSpecSearchIndex+ matches: list[SerializedSearchMatch]+++class PreSpecPayloadRequired(TypedDict):+ targetName: str+ sourceImage: str+ preSpecAssessment: dict[str, JsonValue]+ qualityContract: dict[str, JsonValue]+ authoringInstruction: str+++class PreSpecPayload(PreSpecPayloadRequired, total=False):+ localSpecSearch: LocalSpecSearchPayload+++def detect_cs2_intent(target_name: str) -> bool:+ lowered = target_name.lower()+ return " | " in target_name or any(keyword in lowered for keyword in CS2_INTENT_KEYWORDS)+++def select_spec_collection(target_name: str, requested_collection: str | None) -> str:+ """Choose the local specification collection for a pipeline target."""+ if requested_collection:+ return requested_collection+ return "cs2" if detect_cs2_intent(target_name) else "core_3d"+-def make_payload(target_name: str, image: str | None, complexity: str) -> dict:+def search_local_specs(+ target_name: str,+ collection: str,+ extra_terms: list[str],+ force_reindex: bool,+) -> LocalSpecSearchPayload:+ """Search local specs and return a portable evidence bundle for the assessment."""+ query = " ".join([target_name, *extra_terms]).strip()+ profile = load_profile(collection)+ loaded = load_or_build_index(+ IndexRequest(PROJECT_ROOT, collection, profile, force_reindex)+ )+ matches = serialize_search_results(+ loaded.index,+ SearchOutputRequest(query, DEFAULT_SPEC_SEARCH_LIMIT, DEFAULT_SPEC_SEARCH_SNIPPET_CHARS),+ )+ return {+ "collection": collection,+ "query": query,+ "index": {+ "status": loaded.status,+ "reason": loaded.reason,+ "fingerprint": loaded.fingerprint,+ },+ "matches": matches,+ }+++def make_payload(+ target_name: str,+ image: str | None,+ complexity: str,+ is_cs2: bool = False,+ manifest: dict | None = None,+) -> PreSpecPayload:assessment = make_pre_spec_assessment(target_name)contract = make_quality_contract()+ is_cs2 = is_cs2 or detect_cs2_intent(target_name)+ if is_cs2:+ assessment["objectClass"]["cs2"] = Trueassessment["sourceImage"] = image or ""assessment["complexity"]["tier"] = complexityassessment["specDepthDecision"]["requiredDepth"] = complexity- assessment["detailInventory"]["targetMinDetails"] = DETAIL_MINIMUMS[complexity]+ target_min_details = DETAIL_MINIMUMS[complexity]+ if is_cs2:+ target_min_details = max(target_min_details, CS2_DETAIL_MINIMUM)+ assessment["detailInventory"]["targetMinDetails"] = target_min_detailsif complexity in {"complex", "ultra-complex"}:assessment["specDepthDecision"]["needsRepetitionSystems"] = Trueassessment["specDepthDecision"]["needsMaterialLocalOverrides"] = True@@ -70,7 +192,7 @@ def make_payload(target_name: str, image: str | None, complexity: str) -> dict:assessment["specDepthDecision"]["minimumComponentLevels"] = ["macro", "meso"]contract["qualityBar"] = complexitycontract["minimumSpecDepth"] = COMPLEXITY_MINIMUMS[complexity]- return {+ payload: PreSpecPayload = {"targetName": target_name,"sourceImage": image or "","preSpecAssessment": assessment,@@ -80,6 +202,24 @@ def make_payload(target_name: str, image: str | None, complexity: str) -> dict:"and unknowns before generating or implementing ObjectSculptSpec."),}+ if manifest is not None:+ intake = {+ "schemaVersion": manifest.get("schemaVersion"),+ "itemFamily": manifest.get("itemFamily"),+ "subtype": manifest.get("subtype"),+ "route": manifest.get("route"),+ "exactnessTier": manifest.get("exactnessTier"),+ "confidence": manifest.get("confidence", {}),+ "provenance": manifest.get("provenance", {}),+ "warnings": manifest.get("warnings", []),+ }+ payload["cs2Intake"] = intake+ payload["preSpecAssessment"]["cs2Intake"] = intake+ payload["preSpecAssessment"]["objectClass"]["itemFamily"] = manifest.get("itemFamily")+ payload["preSpecAssessment"]["objectClass"]["subtype"] = manifest.get("subtype")+ payload["preSpecAssessment"]["objectClass"]["route"] = manifest.get("route")+ payload["preSpecAssessment"]["objectClass"]["exactnessTier"] = manifest.get("exactnessTier")+ return payloaddef main(argv: list[str]) -> int:@@ -89,14 +229,68 @@ def main(argv: list[str]) -> int:parser.add_argument("--complexity",choices=sorted(COMPLEXITY_MINIMUMS),- default="moderate",- help="Initial complexity estimate. Refine after visual inspection.",+ default=None,+ help="Initial complexity estimate. Refine after visual inspection. "+ "Default: ultra-complex for CS2 skins, moderate otherwise.",)parser.add_argument("--out", type=Path, help="Output JSON path")parser.add_argument("--force", action="store_true", help="Overwrite output file")+ parser.add_argument(+ "--cs2",+ action="store_true",+ help=f"CS2 weapon/knife/glove skin -- defaults complexity to ultra-complex (targetMinDetails 16); "+ f"never below the {CS2_DETAIL_MINIMUM} floor even if --complexity is set lower.",+ )+ parser.add_argument("--manifest", type=Path, help="CS2 intake manifest")+ parser.add_argument(+ "--collection",+ help="Spec-search collection; defaults to cs2 for CS2 targets and core_3d otherwise.",+ )+ parser.add_argument(+ "--spec-query",+ action="append",+ default=[],+ help="Additional observed terms to add to the automatic local-spec query; repeatable.",+ )+ parser.add_argument(+ "--reindex-specs",+ action="store_true",+ help="Force rebuilding the local BM25 index before creating the assessment.",+ )args = parser.parse_args(argv)- payload = json.dumps(make_payload(args.target_name, args.image, args.complexity), indent=2, ensure_ascii=False) + "\n"+ is_cs2 = args.cs2 or detect_cs2_intent(args.target_name)+ complexity = args.complexity or ("ultra-complex" if is_cs2 else "moderate")+ manifest = None+ if args.manifest:+ manifest = json.loads(args.manifest.read_text(encoding="utf-8"))+ if not isinstance(manifest, dict):+ parser.error("CS2 intake manifest must be a JSON object")+ if manifest.get("state") not in {"proceed", "fallback"}:+ parser.error(f"CS2 intake is not ready for assessment: {manifest.get('state', 'unknown')}")+ is_cs2 = True+ payload_object = make_payload(args.target_name, args.image, complexity, is_cs2, manifest)+ collection = select_spec_collection(args.target_name, args.collection)+ try:+ payload_object["localSpecSearch"] = search_local_specs(+ args.target_name,+ collection,+ args.spec_query,+ args.reindex_specs,+ )+ except (+ CacheReadError,+ CacheValidationError,+ CacheWriteError,+ IndexBuildError,+ ProfileCachePathError,+ ProfileValidationError,+ SourceIngestionError,+ SpecRecordValidationError,+ UnknownCollectionError,+ ) as error:+ parser.error(f"local spec search failed: {error}")+ payload = json.dumps(payload_object, indent=2, ensure_ascii=False) + "\n"if args.out:output = args.out.expanduser().resolve()if output.exists() and not args.force:diff --git a/forge/stage2_spec/new_sculpt_spec.py b/forge/stage2_spec/new_sculpt_spec.pyindex 1609ef6..a598cc7 100755--- a/forge/stage2_spec/new_sculpt_spec.py+++ b/forge/stage2_spec/new_sculpt_spec.py@@ -5,9 +5,12 @@ from __future__ import annotationsimport argparseimport json+import mathimport reimport sysfrom pathlib import Path+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))+from status_banner import emit_statusdef slugify(value: str) -> str:@@ -203,6 +206,8 @@ def make_quality_contract() -> dict:"Do not pass material look-dev without macro, meso, and micro surface frequency bands for close-up materials.","Do not pass reference-fidelity material look-dev from a source image without usable referencePbr maps or an explicit documented limitation.","Do not patch a spec with extracted PBR maps when extraction confidence is below the target threshold unless the user explicitly accepts lower fidelity.",+ "Do not place adjacent separate-geometry parts below 0.02 world-unit seam overlap (source: grimoire/build/geometry_patterns.md).",+ "Do not satisfy raised or recessed relief, fasteners, or grip structure with a map alone when the feature affects form; use geometry or displacement (source: grimoire/build/geometry_patterns.md).",],}@@ -216,6 +221,36 @@ def load_assessment(path: Path | None) -> dict | None:return payload+def inject_geometry_rules(spec: dict, target_name: str) -> None:+ contract = spec.setdefault("qualityContract", {})+ prohibitions = contract.setdefault("mustNotDo", contract.get("antiShallowSpecRules", []))+ if not isinstance(prohibitions, list):+ prohibitions = []+ source = "source: grimoire/build/geometry_patterns.md"+ rules = [+ f"Adjacent components must overlap by at least 0.02 world units at shared seams ({source}).",+ f"Raised or recessed relief and fasteners must be geometry, instanced micro-parts, or displacement; a map alone is an approximation ({source}).",+ ]+ object_tokens = set(re.findall(r"[a-z0-9]+", target_name.lower()))+ if object_tokens & {"blade", "knife", "sword", "dagger", "spear", "bowie"}:+ rules.append(f"Blade components must vary in thickness from spine to edge and taper from ricasso toward the tip ({source}).")+ for rule in rules:+ if rule not in prohibitions:+ prohibitions.append(rule)+ contract["mustNotDo"] = prohibitions+ spec["qualityContract"] = contract+ inventory = spec.get("preSpecAssessment", {}).get("detailInventory", {})+ details = inventory.get("details", []) if isinstance(inventory, dict) else []+ if isinstance(details, list):+ for detail in details:+ if not isinstance(detail, dict):+ continue+ mapping = detail.get("mapsTo")+ detail["realization"] = detail.get("realization") or ("map-only" if isinstance(mapping, dict) and mapping.get("type") == "map" else "unreported")+ if detail["realization"] == "map-only" and detail.get("kind") in {"fastener", "relief", "linework"}:+ detail["approximation"] = f"Map-only detail; geometry guidance requires physical relief ({source})."++def _cnode(cid, name, primitive, parent, position, scale,material="skin", role="body", level="meso", rotation=(0, 0, 0),importance=0.7, sockets=None, local_features=None, anim_role="static",@@ -419,18 +454,440 @@ def apply_character_template(spec: dict, anatomy: dict | None = None) -> dict:return spec+# --- CS2 weapon-skin finish profile (image-first Tier 1) ---------------------+# Each finish style maps to a PBR recipe. View-dependent finishes (anodized /+# anodized-multicolored, e.g. Doppler) need a low roughness + high metalness ++# strong environment reflection or they render muddy; see+# grimoire/build/cs2_finishes.md and grimoire/intake/cs2_texture_acquisition.md.+CS2_FINISH_STYLES = [+ "solid", "hydrographic", "anodized", "spray-paint",+ "anodized-multicolored", "custom-paint-job", "patina", "gunsmith",+]++CS2_FINISH_PROFILES = {+ "solid": {"baseColor": "#7a4b2b", "metalness": 0.15, "roughness": 0.55, "clearcoat": 0.0, "env": 0.9, "viewDependent": False,+ "pattern": "flat", "bands": [+ {"id": "macro", "frequency": 1.0, "amplitude": 0.05, "role": "near-uniform lacquer color"},+ {"id": "meso", "frequency": 8.0, "amplitude": 0.03, "role": "faint brush-out streaks"},+ {"id": "micro", "frequency": 40.0, "amplitude": 0.02, "role": "edge-wear scratches under grazing light"},+ ]},+ "hydrographic": {"baseColor": "#5b6357", "metalness": 0.20, "roughness": 0.50, "clearcoat": 0.10, "env": 1.0, "viewDependent": False,+ "pattern": "swirl", "bands": [+ {"id": "macro", "frequency": 3.0, "amplitude": 0.5, "role": "dip-film swirl distortion"},+ {"id": "meso", "frequency": 10.0, "amplitude": 0.15, "role": "print-pattern fine detail"},+ {"id": "micro", "frequency": 50.0, "amplitude": 0.05, "role": "edge-wear scratches under grazing light"},+ ]},+ "anodized": {"baseColor": "#3a4a9a", "metalness": 0.92, "roughness": 0.12, "clearcoat": 0.30, "env": 1.8, "viewDependent": True,+ "pattern": "brushed", "bands": [+ {"id": "macro", "frequency": 1.5, "amplitude": 0.1, "role": "dyed-metal color breakup"},+ {"id": "meso", "frequency": 20.0, "amplitude": 0.1, "role": "directional brushed-metal streaks"},+ {"id": "micro", "frequency": 70.0, "amplitude": 0.05, "role": "edge-wear scratches under grazing light"},+ ]},+ "spray-paint": {"baseColor": "#6a6a6a", "metalness": 0.10, "roughness": 0.60, "clearcoat": 0.0, "env": 0.9, "viewDependent": False,+ "pattern": "speckle", "bands": [+ {"id": "macro", "frequency": 1.0, "amplitude": 0.05, "role": "matte overspray base"},+ {"id": "meso", "frequency": 30.0, "amplitude": 0.25, "role": "overspray speckle clusters"},+ {"id": "micro", "frequency": 90.0, "amplitude": 0.1, "role": "edge-wear scratches under grazing light"},+ ]},+ "anodized-multicolored": {"baseColor": "#b0417a", "metalness": 0.95, "roughness": 0.08, "clearcoat": 0.60, "env": 2.0, "viewDependent": True,+ "pattern": "marble", "bands": [+ {"id": "macro", "frequency": 2.0, "amplitude": 0.4, "role": "broad pattern/color breakup"},+ {"id": "meso", "frequency": 14.0, "amplitude": 0.2, "role": "brushed grain / marble swirl relief"},+ {"id": "micro", "frequency": 60.0, "amplitude": 0.07, "role": "edge-wear scratches under grazing light"},+ ]},+ "custom-paint-job": {"baseColor": "#9a2b2b", "metalness": 0.20, "roughness": 0.45, "clearcoat": 0.20, "env": 1.1, "viewDependent": False,+ "pattern": "illustrative", "bands": [+ {"id": "macro", "frequency": 0.8, "amplitude": 0.6, "role": "large non-tiled artwork blocks"},+ {"id": "meso", "frequency": 6.0, "amplitude": 0.1, "role": "artwork edge detail"},+ {"id": "micro", "frequency": 40.0, "amplitude": 0.04, "role": "peel-wear scratches under grazing light"},+ ]},+ "patina": {"baseColor": "#7a6a3a", "metalness": 0.60, "roughness": 0.40, "clearcoat": 0.0, "env": 1.2, "viewDependent": False,+ "pattern": "blotch", "bands": [+ {"id": "macro", "frequency": 1.2, "amplitude": 0.35, "role": "oxidation blotch breakup"},+ {"id": "meso", "frequency": 9.0, "amplitude": 0.25, "role": "hue-shift oxidation detail"},+ {"id": "micro", "frequency": 45.0, "amplitude": 0.1, "role": "darkened edge wear under grazing light"},+ ]},+ "gunsmith": {"baseColor": "#8a7a5a", "metalness": 0.70, "roughness": 0.35, "clearcoat": 0.10, "env": 1.3, "viewDependent": False,+ "pattern": "mask-blend", "bands": [+ {"id": "macro", "frequency": 1.5, "amplitude": 0.3, "role": "custom-paint/patina mask blend"},+ {"id": "meso", "frequency": 12.0, "amplitude": 0.2, "role": "peel + oxidize transition detail"},+ {"id": "micro", "frequency": 55.0, "amplitude": 0.09, "role": "edge-wear scratches under grazing light"},+ ]},+}+++def _cs2_wear_mask(float_value: float | None) -> dict:+ """Map a CS2 float (0.0 Factory New .. 1.0 Battle-Scarred) to wear-mask parameters. With no+ float (image-only default) approximate a light-moderate condition from the visible reference+ instead of silently guessing -- see grimoire/build/cs2_finishes.md ('Float -> wear')."""+ if float_value is None:+ return {+ "edgeWear": 0.35, "scratches": ["approximated-light-edge-scratch"], "chips": [],+ "alphaCurve": "curvature-weighted", "aoBias": 0.3, "approximated": True,+ "notes": "No float supplied: estimated apparent condition from the reference image.",+ }+ clamped = max(0.0, min(1.0, float_value))+ return {+ "edgeWear": round(0.1 + clamped * 0.8, 3),+ "scratches": ["edge-scratch"] if clamped > 0.15 else [],+ "chips": ["edge-chip"] if clamped > 0.55 else [],+ "alphaCurve": "curvature-weighted",+ "aoBias": round(0.15 + clamped * 0.25, 3),+ "approximated": False,+ "notes": f"Wear mask derived from float={clamped}.",+ }+++def _cs2_pattern_affine(paint_seed: int | None) -> dict:+ """Deterministic T2*R*S*T1 affine placement for the pattern layer, seeded by paintSeed. With+ no paintSeed (image-only default) use a fixed centered placement and report it approximated --+ never claim it matches a specific item's actual pattern (see grimoire/build/cs2_finishes.md)."""+ if paint_seed is None:+ return {+ "paintSeed": None, "affine": "T2*R*S*T1",+ "translation": [0.5, 0.5], "rotation": 0.0, "scale": [1.0, 1.0],+ "matrix": [1.0, 0.0, 0.0, 1.0, 0.5, 0.5],+ "approximated": True,+ "notes": "No paintSeed in image-first mode: deterministic default placement, reported approximated.",+ }+ rng = paint_seed & 0xFFFFFFFF+ angle = ((rng % 360) / 360.0) * 2 * math.pi+ tx = ((rng >> 8) % 1000) / 1000.0+ ty = ((rng >> 16) % 1000) / 1000.0+ scale = 0.85 + ((rng >> 24) % 30) / 100.0+ cos_a, sin_a = math.cos(angle), math.sin(angle)+ return {+ "paintSeed": paint_seed, "affine": "T2*R*S*T1",+ "translation": [round(tx, 4), round(ty, 4)], "rotation": round(angle, 4),+ "scale": [round(scale, 4), round(scale, 4)],+ "matrix": [round(cos_a * scale, 4), round(sin_a * scale, 4),+ round(-sin_a * scale, 4), round(cos_a * scale, 4),+ round(tx, 4), round(ty, 4)],+ "approximated": False,+ "notes": f"Deterministic placement from paintSeed={paint_seed}.",+ }+++# Minimal skin-name -> finish-style hints for the identity precedence resolver. Not exhaustive+# (thousands of CS2 skins exist); a name that doesn't match falls through to vision/default.+SKIN_NAME_FINISH_HINTS = {+ "doppler": "anodized-multicolored", "gamma doppler": "anodized-multicolored",+ "marble fade": "anodized-multicolored", "fade": "anodized",+ "damascus": "patina", "case hardened": "patina",+ "hydrographic": "hydrographic", "hydro dip": "hydrographic",+ "urban": "spray-paint", "spray": "spray-paint",+ "custom": "custom-paint-job", "gunsmith": "gunsmith",+}+++def infer_finish_style_from_skin_name(skin_name: str) -> str | None:+ lowered = skin_name.lower()+ for keyword, style in SKIN_NAME_FINISH_HINTS.items():+ if keyword in lowered:+ return style+ return None+++def resolve_cs2_finish_style(+ descriptor_finish_style: str | None,+ skin_name: str | None,+ vision_finish_style: str | None,+ vision_confidence: float | None = None,+ vision_confidence_threshold: float = 0.55,+) -> tuple[str, list[str]]:+ """Identity precedence: explicit descriptor > skin name (parsed) > vision inference > default.+ A low-confidence vision read is still used (never silently dropped) but flagged. Disagreements+ between sources are reported, never silently overwritten -- see design.md 'Vision inference'."""+ conflicts: list[str] = []+ skin_inferred = infer_finish_style_from_skin_name(skin_name) if skin_name else None+ candidates: list[tuple[str, str]] = []+ if descriptor_finish_style:+ candidates.append(("descriptor", descriptor_finish_style))+ if skin_inferred:+ candidates.append(("skin name", skin_inferred))+ if vision_finish_style and (vision_confidence is None or vision_confidence >= vision_confidence_threshold):+ candidates.append(("vision", vision_finish_style))+ if len(candidates) >= 2 and len({style for _, style in candidates}) > 1:+ sources = ", ".join(f"{source}={style}" for source, style in candidates)+ conflicts.append(+ f"CS2 finish style conflict: {sources} disagree; using {candidates[0][1]!r} "+ f"({candidates[0][0]} takes precedence). Confirm before implementation."+ )+ if candidates:+ return candidates[0][1], conflicts+ if vision_finish_style:+ conflicts.append(+ f"CS2 finish style {vision_finish_style!r} inferred by vision below confidence "+ f"threshold ({vision_confidence}); confirm before implementation."+ )+ return vision_finish_style, conflicts+ return "anodized-multicolored", conflicts+++def _cs2_finish_material(finish_style: str, float_value: float | None = None, paint_seed: int | None = None) -> dict:+ profile = CS2_FINISH_PROFILES[finish_style]+ base = profile["baseColor"]+ shade = _shade_hex(base, 0.8)+ bands = profile["bands"]+ return {+ "id": "skin-finish", "name": f"CS2 {finish_style} finish", "type": "standard",+ "shaderModel": "MeshPhysicalMaterial / metallic-roughness PBR",+ "baseColor": base, "color": base,+ "albedo": {"dominant": base, "secondary": [shade],+ "samplingNotes": "Image-first: estimate from the reference; report as approximated (not the exact Valve paint texture)."},+ "colorVariation": {"palette": [base, shade], "pattern": profile["pattern"], "amplitude": bands[0]["amplitude"], "heightCorrelation": 0.25},+ "textureResolution": 1024,+ "textureProjection": {"mode": "uv", "repeat": [1.0, 1.0], "anisotropy": 8,+ "texelDensityIntent": "Preserve stable blade-scale detail; do not stretch pattern with component scale."},+ "surfaceFrequencyBands": bands,+ "roughness": {"base": profile["roughness"], "variation": 0.06, "map": "independent-procedural-field",+ "localResponse": "lower roughness on worn edges, higher in recesses"},+ "metalness": {"base": profile["metalness"], "variation": 0.03},+ "clearcoat": {"base": profile["clearcoat"]},+ "clearcoatRoughness": {"base": 0.12},+ "normal": {"pattern": "derived-from-independent-height-field", "strength": 0.3, "scale": 28.0, "space": "tangent"},+ "ambientOcclusion": {"cavityStrength": 0.3, "contactShadowBias": 0.35,+ "notes": "Darken guard/pommel seams and engraving recesses."},+ "wear": _cs2_wear_mask(float_value),+ "envMapIntensity": profile["env"],+ "finishStyle": finish_style,+ "viewDependent": profile["viewDependent"],+ "needsEnvironment": profile["viewDependent"],+ "patternPlacement": _cs2_pattern_affine(paint_seed),+ "shaderNotes": [+ "Use MeshPhysicalMaterial: metallic-roughness with independent map channels.",+ "View-dependent finishes require scene.environment (code-generated default is fine) + ACESFilmic tonemapping in sRGB.",+ "Never bake lighting/pattern into a single flat albedo.",+ ],+ "notes": f"{finish_style} finish recipe; see grimoire/build/cs2_finishes.md.",+ }+++_CS2_SUBSTRATE_BANDS = [+ {"id": "macro", "frequency": 2.0, "amplitude": 0.4, "role": "broad pattern/color breakup"},+ {"id": "meso", "frequency": 14.0, "amplitude": 0.2, "role": "brushed grain relief"},+ {"id": "micro", "frequency": 60.0, "amplitude": 0.07, "role": "edge-wear scratches under grazing light"},+]+++def _cs2_substrate_material() -> dict:+ return {+ "id": "substrate", "name": "Bare metal substrate", "type": "standard",+ "shaderModel": "MeshPhysicalMaterial / metallic-roughness PBR",+ "baseColor": "#3b3b40", "color": "#3b3b40",+ "colorVariation": {"palette": ["#3b3b40", "#2b2b30"], "pattern": "flat", "amplitude": 0.05, "heightCorrelation": 0.0},+ "textureResolution": 1024,+ "textureProjection": {"mode": "uv", "repeat": [2.0, 2.0], "anisotropy": 8,+ "texelDensityIntent": "Preserve stable metal-scale detail on exposed substrate."},+ "surfaceFrequencyBands": _CS2_SUBSTRATE_BANDS,+ "roughness": {"base": 0.34, "variation": 0.08, "map": "independent-procedural-field"},+ "metalness": {"base": 1.0, "variation": 0.0},+ "ambientOcclusion": {"cavityStrength": 0.3, "contactShadowBias": 0.35},+ "envMapIntensity": 1.4,+ "notes": "Exposed metal revealed by wear on painted/anodized finishes.",+ }+++def _cs2_hidden_material() -> dict:+ """Invisible material (opacity 0) for the organizing root group -- same trick as the+ character template's 'hidden' material, so the root component's mesh never renders."""+ return {+ "id": "hidden", "name": "Hidden (root group)", "type": "standard",+ "baseColor": "#000000", "color": "#000000",+ "colorVariation": {"palette": ["#000000", "#000000"], "pattern": "flat", "amplitude": 0.0, "heightCorrelation": 0.0},+ "albedo": {"dominant": "#000000", "secondary": ["#000000"]},+ "roughness": {"base": 1.0, "variation": 0.0},+ "opacity": {"base": 0.0},+ "notes": "Root organizing group only; not a visible surface.",+ }+++def _cs2node(cid, name, primitive, position, scale, material, role, level,+ importance=0.7, local_features=None):+ """Weapon-part node. All parts parent to root with safe (non-attachment) primitives+ and names so strict-quality does not demand attachment contracts."""+ return _cnode(cid, name, primitive, "root", position, scale, material=material,+ role=role, level=level, importance=importance,+ local_features=local_features or [], evidence=["full-object"])+++CS2_KNIFE_SUBTYPES = frozenset(+ {"karambit", "butterfly", "bayonet", "m9", "flip", "gut", "falchion", "bowie", "navaja",+ "talon", "classic"}+)+++def make_cs2_component_tree(item_family: str = "knife", subtype: str | None = None) -> list:+ if item_family != "knife":+ raise ValueError(f"unsupported CS2 family {item_family!r}; only knife is implemented")+ if subtype and subtype not in CS2_KNIFE_SUBTYPES:+ raise ValueError(f"unsupported CS2 knife subtype {subtype!r}")+ # Root is an organizing group only: use the invisible 'hidden' material (opacity 0) exactly+ # like the character template, so the generator's per-component mesh for root never renders as+ # a stray box over the weapon -- no generic generator change needed.+ root = _cnode("root", "Weapon (root)", "box", None, (0, 0, 0), (1, 1, 1),+ material="hidden", role="body", level="macro", importance=1.0, anim_role="root")+ parts = [+ _cs2node("blade", "Blade", "ground-blade", (0, 0.55, 0), (1.0, 1.0, 1.0), "skin-finish", "blade", "macro", 1.0,+ ["edge bevel highlight", "engraved pattern swirl"]),+ _cs2node("grip", "Grip", "curve-sweep", (0, -0.55, 0), (1.0, 1.0, 1.0), "skin-finish", "grip", "macro", 0.9,+ ["checkered grip relief"]),+ _cs2node("guard", "Guard", "extrude", (0, 0.0, 0), (1.0, 1.0, 1.0), "substrate", "guard", "meso", 0.7),+ _cs2node("pommel", "Pommel", "sphere", (0, -0.95, 0), (0.2, 0.2, 0.2), "substrate", "pommel", "meso", 0.6),+ _cs2node("bolster", "Bolster", "box", (0, 0.02, 0), (0.2, 0.18, 0.26), "substrate", "bolster", "meso", 0.6),+ ]+ return [root, *parts]+++def make_cs2_feature_targets() -> list:+ return [+ {"id": "cs2-silhouette", "name": "Weapon silhouette and proportions", "tier": "critical",+ "passIds": ["blockout"], "minimumScore": 0.8, "mustPass": True,+ "componentRefs": ["root", "blade", "grip"], "evidenceRefs": ["full-object"]},+ {"id": "cs2-finish-style-read", "name": "Finish style reads correctly", "tier": "critical",+ "passIds": ["material-pass"], "minimumScore": 0.75, "mustPass": True,+ "componentRefs": ["blade"], "evidenceRefs": ["full-object"]},+ {"id": "cs2-metal-response", "name": "Metal / anodized environment response", "tier": "critical",+ "passIds": ["lighting-pass"], "minimumScore": 0.75, "mustPass": True,+ "componentRefs": ["blade", "guard"], "evidenceRefs": ["full-object"]},+ {"id": "cs2-pattern-placement", "name": "Pattern placement (approximated)", "tier": "important",+ "passIds": ["material-pass"], "minimumScore": 0.65, "mustPass": False,+ "componentRefs": ["blade"], "evidenceRefs": ["full-object"]},+ {"id": "cs2-wear-read", "name": "Wear / float reads plausibly", "tier": "important",+ "passIds": ["surface-pass"], "minimumScore": 0.65, "mustPass": False,+ "componentRefs": ["blade", "grip"], "evidenceRefs": ["full-object"]},+ ]+++def apply_cs2_template(+ spec: dict,+ finish_style: str | None = None,+ *,+ skin_name: str | None = None,+ vision_finish_style: str | None = None,+ vision_confidence: float | None = None,+ float_value: float | None = None,+ paint_seed: int | None = None,+ environment_available: bool = True,+ item_family: str = "knife",+ subtype: str | None = None,+) -> dict:+ """Seed a self-consistent image-first CS2 weapon-skin spec. Object geometry reuses the+ hard-surface path (primaryDomain=object); only the finish/material recipe is CS2-specific.+ Leaves object specs untouched unless invoked. `finish_style` is treated as the explicit+ descriptor tier; resolve_cs2_finish_style() applies identity precedence against skin_name /+ vision when finish_style is not itself given."""+ resolved_style, conflicts = resolve_cs2_finish_style(+ finish_style, skin_name, vision_finish_style, vision_confidence+ )+ if resolved_style not in CS2_FINISH_PROFILES:+ raise ValueError(f"unknown finish style {resolved_style!r}; expected one of: {', '.join(CS2_FINISH_STYLES)}")+ profile = CS2_FINISH_PROFILES[resolved_style]+ spec["componentTree"] = make_cs2_component_tree(item_family, subtype)+ spec["materials"] = [_cs2_finish_material(resolved_style, float_value, paint_seed), _cs2_substrate_material(), _cs2_hidden_material()]+ spec["featureReviewTargets"] = make_cs2_feature_targets()+ # top-level signal for the pre-render environment gate (mirrors the material value)+ spec["envMapIntensity"] = profile["env"]+ spec["cs2Finish"] = {"finishStyle": resolved_style, "viewDependent": profile["viewDependent"],+ "environment": "code-generated-default (RoomEnvironment->PMREM); user HDRI optional",+ "environmentAvailable": environment_available,+ "tier": "image-first"}+ # fill the assessment/contract so a normal validate passes; CS2 is held to the ultra-complex+ # bar, so strict-quality still requires the agent to enumerate the CS2 detail inventory first.+ pre = spec.setdefault("preSpecAssessment", {})+ if conflicts:+ unknowns = pre.setdefault("unknownsToResolveBeforeImplementation", [])+ unknowns.extend(conflict for conflict in conflicts if conflict not in unknowns)+ oc = pre.setdefault("objectClass", {})+ oc["primaryType"] = "weapon-skin"+ oc["primaryDomain"] = "object"+ oc["formLanguage"] = ["hard-surface", "bladed"]+ oc["structureKind"] = ["blade", "grip", "guard"]+ oc["motionPotential"] = ["static", "inspect-orbit"]+ oc["materialFamilies"] = ["metal", "anodized-coat" if profile["viewDependent"] else "painted-coat"]+ oc["cs2"] = True+ complexity = pre.setdefault("complexity", {})+ complexity["tier"] = "ultra-complex"+ decision = pre.setdefault("specDepthDecision", {})+ decision["requiredDepth"] = "ultra-complex"+ decision["needsRepetitionSystems"] = True+ decision["needsMaterialLocalOverrides"] = True+ decision["minimumComponentLevels"] = ["macro", "meso", "micro"]+ inv = pre.setdefault("detailInventory", {})+ # CS2 skins are treated as ultra-complex: the finish/wear/hardware IS the item, so the detail+ # gate demands the ultra count (16). strict-quality then blocks code-gen until the agent+ # enumerates the identity-defining details -- it does not pass on the bare seed.+ inv["targetMinDetails"] = 16+ contract = spec.setdefault("qualityContract", {})+ contract["qualityBar"] = "ultra-complex"+ contract.setdefault("minimumSpecDepth", {}).update(+ {"macroComponents": 5, "mesoComponents": 16, "microFeatureGroups": 8,+ "materialLayers": 4, "repetitionSystems": 2, "reviewViewpoints": 5}+ )+ return spec+++def apply_cs2_manifest_evidence(spec: dict, manifest: dict) -> dict:+ intake = {+ "schemaVersion": manifest.get("schemaVersion"),+ "state": manifest.get("state"),+ "itemFamily": manifest.get("itemFamily"),+ "subtype": manifest.get("subtype"),+ "route": manifest.get("route"),+ "exactnessTier": manifest.get("exactnessTier"),+ "identity": manifest.get("identity", {}),+ "finish": manifest.get("finish", {}),+ "paintedRegions": manifest.get("paintedRegions", []),+ "unpaintedRegions": manifest.get("unpaintedRegions", []),+ "assets": manifest.get("assets", {}),+ "camera": manifest.get("camera", {}),+ "assumptions": manifest.get("assumptions", {}),+ "confidence": manifest.get("confidence", {}),+ "provenance": manifest.get("provenance", {}),+ "warnings": manifest.get("warnings", []),+ }+ spec["cs2Intake"] = intake+ spec["exactnessTier"] = manifest.get("exactnessTier")+ if isinstance(manifest.get("camera"), dict) and manifest["camera"].get("referenceCamera"):+ spec["referenceCamera"] = manifest["camera"]["referenceCamera"]+ materials = spec.get("materials", [])+ skin = next((item for item in materials if isinstance(item, dict) and item.get("id") == "skin-finish"), None)+ if isinstance(skin, dict):+ route = manifest.get("route")+ projection = skin.setdefault("textureProjection", {})+ if route == "reference-projection":+ projection["mode"] = "projective"+ projection["source"] = manifest.get("deLitAlbedo") or manifest.get("sourceImage")+ elif route == "authored-texture":+ projection["mode"] = "uv"+ reference_pbr = manifest.get("referencePbr")+ if isinstance(reference_pbr, dict):+ skin["referencePbr"] = reference_pbr+ elif route == "procedural-finish":+ projection["mode"] = "procedural"+ skin["route"] = route+ skin["exactnessTier"] = manifest.get("exactnessTier")+ skin["paintedRegions"] = manifest.get("paintedRegions", [])+ skin["unpaintedRegions"] = manifest.get("unpaintedRegions", [])+ return spec++def make_spec(target_name: str, image: str | None, assessment_payload: dict | None = None) -> dict:target_id = slugify(target_name)pre_spec_assessment = make_pre_spec_assessment(target_name)quality_contract = make_quality_contract()+ local_spec_search = Noneif assessment_payload:incoming_assessment = assessment_payload.get("preSpecAssessment")incoming_contract = assessment_payload.get("qualityContract")+ incoming_local_spec_search = assessment_payload.get("localSpecSearch")if isinstance(incoming_assessment, dict):pre_spec_assessment = incoming_assessmentif isinstance(incoming_contract, dict):quality_contract = incoming_contract- return {+ if isinstance(incoming_local_spec_search, dict):+ local_spec_search = incoming_local_spec_search+ spec = {"targetName": target_name,"targetId": target_id,"schemaVersion": "2.1",@@ -507,7 +964,7 @@ def make_spec(target_name: str, image: str | None, assessment_payload: dict | No"secondary lighting match",],"fpsTarget": 60,- "reviewViewpoints": ["front", "three-quarter", "side"],+ "reviewViewpoints": ["front", "three-quarter", "side", "thickness-axis", "long-axis"],},"selfCorrectLoop": {"enabled": True,@@ -1099,6 +1556,10 @@ def make_spec(target_name: str, image: str | None, assessment_payload: dict | No],"risks": [],}+ if local_spec_search is not None:+ spec["localSpecSearch"] = local_spec_search+ inject_geometry_rules(spec, target_name)+ return specdef main(argv: list[str]) -> int:@@ -1106,20 +1567,68 @@ def main(argv: list[str]) -> int:parser.add_argument("target_name", help="Human-readable object name")parser.add_argument("--image", help="Reference image path or URL")parser.add_argument("--assessment", type=Path, help="Pre-spec assessment JSON from stage2_spec/new_pre_spec_assessment.py")+ parser.add_argument("--manifest", type=Path, help="Validated cs2-intake.json produced by stage1 intake")parser.add_argument("--out", type=Path, help="Output JSON path")parser.add_argument("--force", action="store_true", help="Overwrite output file")parser.add_argument("--character", action="store_true",help="Use the humanoid character template (auto-enabled when the assessment primaryDomain is character/hybrid)")+ parser.add_argument("--cs2", action="store_true",+ help="Use the CS2 weapon-skin finish profile (image-first; auto-enabled when the assessment objectClass.cs2 is true)")+ parser.add_argument("--finish-style", choices=CS2_FINISH_STYLES, default=None,+ help="CS2 finish style descriptor (explicit; takes precedence over --skin-name/--vision-finish-style). "+ "Falls back to anodized-multicolored if nothing else resolves it.")+ parser.add_argument("--skin-name", help="CS2 skin name, e.g. 'Karambit | Doppler' (used to infer finish style)")+ parser.add_argument("--vision-finish-style", choices=CS2_FINISH_STYLES,+ help="Finish style inferred by vision from the reference image (image-only mode)")+ parser.add_argument("--vision-confidence", type=float,+ help="Confidence (0-1) of --vision-finish-style; below threshold it is still used but flagged")+ parser.add_argument("--float", dest="cs2_float", type=float,+ help="CS2 item float (0.0 Factory New .. 1.0 Battle-Scarred); approximated from the image if omitted")+ parser.add_argument("--paint-seed", type=int, help="CS2 paint seed; deterministic default placement if omitted")+ parser.add_argument("--no-environment", action="store_true",+ help="Mark the code-generated default environment as unavailable (testing/last-resort only) "+ "-- validate_sculpt_spec.py blocks view-dependent finishes when set")args = parser.parse_args(argv)+ emit_status(None, next_command="forge/stage2_spec/new_sculpt_spec.py")assessment = load_assessment(args.assessment)+ manifest = None+ if args.manifest:+ manifest = json.loads(args.manifest.read_text(encoding="utf-8"))+ if not isinstance(manifest, dict):+ parser.error("CS2 intake manifest must be a JSON object")+ if manifest.get("state") != "proceed":+ parser.error(f"CS2 intake is not ready for spec authoring: {manifest.get('state', 'unknown')}")+ if manifest.get("itemFamily") != "knife":+ parser.error("CS2 spec authoring currently supports only the knife family")spec = make_spec(args.target_name, args.image, assessment)domain = None+ cs2_marker = Falseif isinstance(assessment, dict):pre = assessment.get("preSpecAssessment", {})oc = pre.get("objectClass", {}) if isinstance(pre, dict) else {}domain = oc.get("primaryDomain") if isinstance(oc, dict) else None- if args.character or domain in {"character", "hybrid"}:+ cs2_marker = bool(oc.get("cs2")) if isinstance(oc, dict) else False+ if args.cs2 or cs2_marker or manifest is not None:+ finish_style = args.finish_style+ if finish_style is None and isinstance(assessment, dict):+ oc = assessment.get("preSpecAssessment", {}).get("objectClass", {})+ if isinstance(oc, dict) and oc.get("finishStyle") in CS2_FINISH_PROFILES:+ finish_style = oc["finishStyle"]+ apply_cs2_template(+ spec, finish_style,+ skin_name=args.skin_name,+ vision_finish_style=args.vision_finish_style,+ vision_confidence=args.vision_confidence,+ float_value=args.cs2_float,+ paint_seed=args.paint_seed,+ environment_available=not args.no_environment,+ item_family=str(manifest.get("itemFamily", "knife")) if manifest else "knife",+ subtype=str(manifest["subtype"]) if manifest and manifest.get("subtype") else None,+ )+ if manifest:+ apply_cs2_manifest_evidence(spec, manifest)+ elif args.character or domain in {"character", "hybrid"}:anatomy = Noneif isinstance(assessment, dict) and isinstance(assessment.get("preSpecAssessment"), dict):anatomy = assessment["preSpecAssessment"].get("anatomy")diff --git a/forge/stage2_spec/validate_sculpt_spec.py b/forge/stage2_spec/validate_sculpt_spec.pyindex 61c4e9e..2df7e8a 100755--- a/forge/stage2_spec/validate_sculpt_spec.py+++ b/forge/stage2_spec/validate_sculpt_spec.py@@ -52,6 +52,8 @@ VALID_TOPOLOGY_CLASSES = {"fiber-strand","material-only",}+CS2_ROUTES = {"reference-projection", "authored-texture", "procedural-finish"}+CS2_EXACTNESS_TIERS = {"image-only", "metadata-assisted", "exact-texture"}# Plan 1.3 Workstream A: primitives that are structurally wrong for a given topology class.# Prevents "Flat-Projection Bias" (e.g. a continuous organic bulge picked as a box-stack).DISALLOWED_TOPOLOGY_PRIMITIVE_PAIRS: dict[str, set[str]] = {@@ -396,6 +398,62 @@ def validate_reference_pbr(material_id: str, value: Any, errors: list[str], warnvalidate_reference_pbr_map(maps[channel], f"material {material_id!r} referencePbr.maps.{channel}", errors)+def validate_cs2_view_dependent_environment(spec: dict[str, Any], errors: list[str]) -> None:+ """View-dependent CS2 finishes (anodized / anodized-multicolored) read their color from+ environment reflections -- rendering one with no environment at all is a muddy-render gate+ failure, not a quality nit. The code-generated default environment always exists unless+ explicitly disabled (cs2Finish.environmentAvailable = false), so this only fires as the+ last-resort guard described in design.md, never on the default image-only path.+ See grimoire/build/cs2_finishes.md."""+ materials = [m for m in spec.get("materials", []) if isinstance(m, dict)]+ view_dependent = [m for m in materials if m.get("needsEnvironment") is True]+ if not view_dependent:+ return+ cs2_finish = spec.get("cs2Finish")+ environment_available = not (isinstance(cs2_finish, dict) and cs2_finish.get("environmentAvailable") is False)+ if not environment_available:+ names = ", ".join(str(m.get("id")) for m in view_dependent)+ errors.append(+ f"material(s) {names} are view-dependent and need an environment map (scene.environment) "+ "or they render muddy, but cs2Finish.environmentAvailable is false -- enable the "+ "code-generated default environment or supply a user HDRI before generating "+ "(see grimoire/build/cs2_finishes.md)"+ )+++def validate_cs2_contract(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> None:+ intake = spec.get("cs2Intake")+ if intake is None:+ return+ if not isinstance(intake, dict):+ errors.append("cs2Intake must be an object")+ return+ route = intake.get("route")+ tier = intake.get("exactnessTier")+ if route not in CS2_ROUTES:+ errors.append("cs2Intake.route must be a supported CS2 route")+ if tier not in CS2_EXACTNESS_TIERS:+ errors.append("cs2Intake.exactnessTier must be a supported exactness tier")+ if intake.get("itemFamily") != "knife":+ errors.append("cs2Intake requires the registered knife adapter")+ if route == "reference-projection":+ camera = spec.get("referenceCamera")+ source = intake.get("deLitAlbedo") or intake.get("sourceImage")+ if not isinstance(camera, dict) or camera.get("solved") is not True:+ warnings.append("quality: reference-projection needs solved referenceCamera")+ if not isinstance(source, str) or not source.strip():+ errors.append("reference-projection requires a de-lit source image")+ if route == "authored-texture":+ materials = [item for item in spec.get("materials", []) if isinstance(item, dict)]+ pbr = next((item.get("referencePbr") for item in materials if item.get("id") == "skin-finish"), None)+ maps = pbr.get("maps") if isinstance(pbr, dict) else None+ required = ("albedo", "normal", "roughness", "metalness")+ if tier == "exact-texture" and (not isinstance(maps, dict) or not all(key in maps for key in required)):+ errors.append("exact-texture authored route requires independent albedo, normal, roughness, and metalness maps")+ if route == "procedural-finish" and tier == "exact-texture":+ errors.append("procedural-finish cannot claim exact-texture")++def validate_materials(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> set[str]:material_ids: set[str] = set()for index, material in enumerate(spec.get("materials", [])):@@ -962,7 +1020,7 @@ def validate_quality_contract(spec: dict[str, Any], errors: list[str], warnings:validate_string_array(group.get("failureModes"), f"qualityContract.featureGroups[{index}].failureModes", errors)if group.get("required") is True and not group.get("qualityCriteria"):warnings.append(f"quality: required feature group {group.get('id', index)!r} has no qualityCriteria")- for field in ("visualDeltaChecks", "antiShallowSpecRules"):+ for field in ("visualDeltaChecks", "antiShallowSpecRules", "mustNotDo"):validate_string_array(contract.get(field), f"qualityContract.{field}", errors)if isinstance(contract.get(field), list) and not contract[field]:warnings.append(f"quality: qualityContract.{field} is empty")@@ -1722,8 +1780,13 @@ def _has_gloss_response(spec: dict[str, Any]) -> bool:def _has_repetition_or_small_parts(spec: dict[str, Any]) -> bool:- if [r for r in spec.get("repetitionSystems", []) if isinstance(r, dict)]:- return True+ for repetition in spec.get("repetitionSystems", []):+ if not isinstance(repetition, dict):+ continue+ if repetition.get("realization") == "map-only" or repetition.get("buildsGeometry") is False:+ continue+ if repetition.get("geometry") is not None or repetition.get("instances") is not None or repetition.get("buildsGeometry") is True:+ return Truereturn any(isinstance(c, dict) and c.get("level") == "micro"for c in spec.get("componentTree", [])@@ -1846,6 +1909,8 @@ def validate_spec(spec: dict[str, Any]) -> tuple[list[str], list[str]]:validate_look_dev_targets(spec, errors, warnings)evidence_ids = validate_evidence(spec, errors, warnings)material_ids = validate_materials(spec, errors, warnings)+ validate_cs2_contract(spec, errors, warnings)+ validate_cs2_view_dependent_environment(spec, errors)validate_components(spec, material_ids, evidence_ids, errors, warnings)lod_plan = spec.get("lodPlan")if lod_plan is not None and not isinstance(lod_plan, list):diff --git a/forge/stage3_build/bake_projected_texture.py b/forge/stage3_build/bake_projected_texture.pyindex 2b56e5e..1194b9f 100755--- a/forge/stage3_build/bake_projected_texture.py+++ b/forge/stage3_build/bake_projected_texture.py@@ -52,6 +52,23 @@ def load_camera(camera_arg: str | None) -> tuple[dict[str, Any] | None, list[strdef build_descriptor(args: argparse.Namespace) -> dict[str, Any]:+ intake = None+ if getattr(args, "manifest", None):+ manifest_path = Path(args.manifest).expanduser()+ intake_value = json.loads(manifest_path.read_text(encoding="utf-8"))+ if not isinstance(intake_value, dict):+ raise ValueError("CS2 intake manifest must be a JSON object")+ intake = intake_value+ if not args.reference_image:+ views = intake.get("sourceViews", [])+ if isinstance(views, list) and views and isinstance(views[0], dict):+ source_path = views[0].get("path")+ if isinstance(source_path, str):+ args.reference_image = source_path+ if intake.get("state") != "proceed":+ return {"projectedTextureBake": {"version": "1.0", "status": "request-input", "reason": f"intake state is {intake.get('state', 'unknown')}"}}+ if not args.reference_image:+ raise ValueError("--reference-image or --manifest with a source view is required")camera, camera_warnings = load_camera(args.camera)warnings = list(camera_warnings)@@ -122,7 +139,8 @@ def build_descriptor(args: argparse.Namespace) -> dict[str, Any]:def main(argv: list[str]) -> int:parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)- parser.add_argument("--reference-image", required=True, help="Path to the original reference photo")+ parser.add_argument("--reference-image", help="Path to the original reference photo")+ parser.add_argument("--manifest", type=Path, help="Validated cs2-intake.json with source view and camera evidence")parser.add_argument("--delit-image", help="Path to a de-lit albedo produced by stage1_intake/delight_albedo.py, if available")parser.add_argument("--camera", help="Path to a referenceCamera JSON produced by stage1_intake/solve_camera_pose.py")parser.add_argument("--mesh-id", required=True, help="Identifier of the target mesh/node to project onto")diff --git a/forge/stage3_build/generate_threejs_factory.py b/forge/stage3_build/generate_threejs_factory.pyindex 233da26..df6e3f9 100755--- a/forge/stage3_build/generate_threejs_factory.py+++ b/forge/stage3_build/generate_threejs_factory.py@@ -305,6 +305,15 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:target = str(spec.get("targetName") or "Procedural Object")type_name = pascal_case(target)function_name = f"create{type_name}Model"+ reconstruction_evidence = {+ "itemFamily": spec.get("itemFamily"),+ "subtype": spec.get("subtype"),+ "componentAdapter": spec.get("componentAdapter"),+ "route": spec.get("route"),+ "exactnessTier": spec.get("exactnessTier"),+ "referenceCamera": spec.get("referenceCamera"),+ "approximationNotes": spec.get("approximationNotes", []),+ }materials = {str(material.get("id") or f"material{index}"): materialfor index, material in enumerate(spec.get("materials", []))@@ -320,6 +329,7 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:"import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js';","import { BokehPass } from 'three/examples/jsm/postprocessing/BokehPass.js';","import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js';",+ "import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';","","export type ProceduralModelOptions = {"," wireframe?: boolean;",@@ -1013,6 +1023,7 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:f"export function {function_name}(options: ProceduralModelOptions = {{}}): THREE.Group {{"," const root = new THREE.Group();",f" root.name = {json.dumps(target)};",+ f" root.userData.reconstructionEvidence = {json_literal(reconstruction_evidence)};",""," const materialMap: Record<string, THREE.Material> = {};",]@@ -1318,6 +1329,27 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:" return composer;","}","",+ f"export function configure{type_name}Renderer(renderer: THREE.WebGLRenderer): void {{",+ " // Load-bearing for view-dependent finishes (anodized / Doppler): without ACES + sRGB",+ " // the environment reflection reads flat/washed instead of a believable metal response.",+ " renderer.toneMapping = THREE.ACESFilmicToneMapping;",+ " renderer.outputColorSpace = THREE.SRGBColorSpace;",+ "}",+ "",+ f"export function create{type_name}InspectControls(",+ " camera: THREE.Camera,",+ " domElement: HTMLElement,",+ "): OrbitControls {",+ " // View-dependent finishes only read correctly once the user orbits — their color",+ " // comes from the environment reflection, not albedo, so free rotation matters here.",+ " const controls = new OrbitControls(camera, domElement);",+ " controls.enableDamping = true;",+ " controls.minDistance = 1.0;",+ " controls.maxDistance = 8.0;",+ " controls.autoRotate = false;",+ " return controls;",+ "}",+ "",])return "\n".join(lines)diff --git a/forge/stage3_build/orchestrate_passes.py b/forge/stage3_build/orchestrate_passes.pyindex 25febbd..3d67090 100755--- a/forge/stage3_build/orchestrate_passes.py+++ b/forge/stage3_build/orchestrate_passes.py@@ -12,6 +12,7 @@ from typing import Anysys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))from feature_acceptance_policy import feature_gate_failures+from status_banner import emit_statusDEFAULT_PASS_ORDER = [@@ -443,6 +444,28 @@ def sync_pipeline(spec: dict[str, Any]) -> dict[str, Any]:return pipeline+def ledger_disagreements(spec: dict[str, Any], completed: list[str]) -> list[str]:+ credited = set(completed)+ ids = pass_order(spec)+ disagreements: list[str] = []+ history = spec.get("reviewHistory", [])+ if not isinstance(history, list):+ return disagreements+ for entry in history:+ if not isinstance(entry, dict) or entry.get("action") != "continue":+ continue+ pass_id = entry.get("passId")+ if not isinstance(pass_id, str) or pass_id in credited:+ continue+ if pass_id in ids:+ index = ids.index(pass_id)+ blocker = ids[index - 1] if index > 0 else pass_id+ disagreements.append(f"{pass_id}: reviewed but not credited because {blocker} is incomplete or its evidence/gates failed")+ else:+ disagreements.append(f"{pass_id}: reviewed but is not in the declared pass order")+ return disagreements++def has_passing_tier1_result(spec: dict[str, Any], pass_id: str) -> bool:"""Plan 1.3 Workstream D: Tier 2 (AI-vision) must never run against a renderthat has not passed Tier 1. Checked here rather than in append_review.py so@@ -521,6 +544,7 @@ def main(argv: list[str]) -> int:args = parser.parse_args(argv)spec_path = args.spec.expanduser().resolve()spec = load_spec(spec_path)+ emit_status(spec, next_command=f"forge/stage3_build/orchestrate_passes.py {args.command} {spec_path}", stream=sys.stderr if getattr(args, "json", False) else sys.stdout)if args.command == "status":payload = status_payload(spec)@@ -544,6 +568,14 @@ def main(argv: list[str]) -> int:return 0 if ok else 1if args.command == "sync":+ ids = pass_order(spec)+ completed = completed_passes(spec, ids)+ disagreements = ledger_disagreements(spec, completed)+ if disagreements:+ print("ledger disagreement: review history contains uncredited passes", file=sys.stderr)+ for item in disagreements:+ print(f"- {item}", file=sys.stderr)+ return 1payload = status_payload(spec)output = spec_path if args.in_place else (args.out.expanduser().resolve() if args.out else None)if output:diff --git a/forge/stage4_review/append_review.py b/forge/stage4_review/append_review.pyindex c011c7f..35b880f 100755--- a/forge/stage4_review/append_review.py+++ b/forge/stage4_review/append_review.py@@ -10,7 +10,10 @@ from datetime import datetime, timezonefrom pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))+sys.path.insert(0, str(Path(__file__).resolve().parent))from feature_acceptance_policy import feature_gate_failures+from cs2_review import load_review_scene+from status_banner import emit_statusVALID_ACTIONS = {"continue", "refine-spec", "refine-code", "request-input", "stop"}@@ -141,6 +144,12 @@ def review_completes_pass(spec: dict, entry: dict, pass_id: str) -> bool:if entry.get("passId") != pass_id or entry.get("action") != "continue":return Falsevisual = entry.get("visualEvidence")+ if pass_id == "blockout" and not entry.get("mapStrippedRender"):+ return False+ viewpoints = entry.get("reviewViewpoints")+ if isinstance(viewpoints, list) and pass_id in VISUAL_PASS_IDS:+ if not {"thickness-axis", "long-axis"}.issubset(set(viewpoints)):+ return Falseif pass_id in VISUAL_PASS_IDS and not (isinstance(visual, dict) and visual.get("renderScreenshot")):return Falseif pass_id in VISUAL_PASS_IDS:@@ -221,6 +230,17 @@ def main(argv: list[str]) -> int:parser.add_argument("--visual-threshold", type=float, help="Override visual acceptance threshold for this review")parser.add_argument("--camera-view", help="Camera/viewpoint label, e.g. front, three-quarter, side, close-up")parser.add_argument("--visual-notes", help="Short notes from screenshot comparison")+ parser.add_argument("--map-stripped-render", help="Blockout render captured with all material maps disabled")+ parser.add_argument("--review-viewpoints-json", help="JSON array or file containing review viewpoint labels")+ parser.add_argument("--force-out-of-order", action="store_true", help="Record deliberate re-review outside the unlocked pass")+ parser.add_argument(+ "--cs2-review-json",+ help="Machine-readable CS2 review report JSON or a JSON file path",+ )+ parser.add_argument(+ "--review-scene-json",+ help="Versioned CS2 review-scene metadata JSON used to validate the report",+ )parser.add_argument("--require-screenshot-files",action="store_true",@@ -242,9 +262,25 @@ def main(argv: list[str]) -> int:spec_path = args.spec.expanduser().resolve()spec = load_spec(spec_path)+ emit_status(spec, next_command=f"forge/stage4_review/append_review.py {spec_path} --pass-id {args.pass_id}")history = spec.setdefault("reviewHistory", [])if not isinstance(history, list):raise ValueError("reviewHistory must be an array")+ ids = pass_order(spec)+ completed: list[str] = []+ for pass_id in ids:+ if any(isinstance(item, dict) and review_completes_pass(spec, item, pass_id) for item in history):+ completed.append(pass_id)+ else:+ break+ expected_pass = "complete" if len(completed) == len(ids) else ids[len(completed)]+ if args.pass_id != expected_pass and not args.force_out_of_order:+ raise ValueError(+ f"cannot record submitted pass {args.pass_id!r}; current unlocked pass is {expected_pass!r}. "+ f"Complete {expected_pass!r} before recording {args.pass_id!r}, or use --force-out-of-order for deliberate re-review."+ )+ if args.pass_id == "blockout" and args.action == "continue" and not args.map_stripped_render:+ raise ValueError("blockout cannot be credited without --map-stripped-render (unlit, map-stripped evidence)")threshold = clamp_score(args.visual_threshold) if args.visual_threshold is not None else visual_acceptance_threshold(spec)layer_scores = Noneif args.layer_scores_json:@@ -307,6 +343,24 @@ def main(argv: list[str]) -> int:+ ", ".join(missing_layers))+ cs2_review = load_json_argument(args.cs2_review_json, "--cs2-review-json")+ if cs2_review is not None:+ if not isinstance(cs2_review, dict):+ raise ValueError("--cs2-review-json must be a JSON object")+ if args.review_scene_json:+ scene_path = Path(args.review_scene_json).expanduser()+ if not scene_path.is_file():+ raise FileNotFoundError(f"--review-scene-json does not exist: {scene_path}")+ scene = load_review_scene(scene_path)+ expected = scene.get("fixtureId")+ if cs2_review.get("reviewScene", {}).get("fixtureId") != expected:+ raise ValueError("CS2 review report does not match --review-scene-json")+ if args.action == "continue" and cs2_review.get("verdict") != "pass":+ raise ValueError(+ "CS2 review gate is blocking continuation: "+ + ", ".join(str(item) for item in cs2_review.get("failedGates", []))+ )+entry = {"timestamp": datetime.now(timezone.utc).isoformat(),"passId": args.pass_id,@@ -323,6 +377,21 @@ def main(argv: list[str]) -> int:"codeFixes": split_items(args.code_fixes),"evidence": split_items(args.evidence),}+ if args.force_out_of_order:+ entry["outOfSequence"] = True+ if args.map_stripped_render:+ entry["mapStrippedRender"] = args.map_stripped_render+ if args.review_viewpoints_json:+ viewpoints = load_json_argument(args.review_viewpoints_json, "--review-viewpoints-json")+ if not isinstance(viewpoints, list) or not all(isinstance(value, str) for value in viewpoints):+ raise ValueError("--review-viewpoints-json must be an array of viewpoint labels")+ entry["reviewViewpoints"] = viewpoints+ required = {"thickness-axis", "long-axis"}+ missing = sorted(required - set(viewpoints))+ if missing and args.action == "continue":+ raise ValueError("review evidence is missing axial viewpoints: " + ", ".join(missing))+ if cs2_review is not None:+ entry["cs2Review"] = cs2_reviewif args.pass_id in VISUAL_PASS_IDS and args.action == "continue":feature_failures = feature_gate_failures(spec, entry, args.pass_id)if feature_failures:diff --git a/forge/stage4_review/cs2_review.py b/forge/stage4_review/cs2_review.pynew file mode 100644index 0000000..1af67e1--- /dev/null+++ b/forge/stage4_review/cs2_review.py@@ -0,0 +1,168 @@+from __future__ import annotations++import json+from pathlib import Path+from typing import Any++REQUIRED_SCENE_KEYS = {+ "version",+ "fixtureId",+ "reference",+ "identity",+ "camera",+ "transform",+ "environment",+ "resolution",+ "background",+ "rendererVersion",+ "calibration",+ "thresholds",+}+REQUIRED_THRESHOLDS = {+ "silhouetteIoU",+ "aspectRatioDelta",+ "scaleDelta",+ "projectionCoverage",+ "finishMaterialResponse",+ "identityDetail",+ "paintedRegion",+ "maxOrbitCollapseRatio",+}+++def load_review_scene(path: Path) -> dict[str, Any]:+ payload = json.loads(path.read_text(encoding="utf-8"))+ if not isinstance(payload, dict):+ raise ValueError("review scene must be a JSON object")+ missing = REQUIRED_SCENE_KEYS - payload.keys()+ if missing:+ raise ValueError("review scene is missing: " + ", ".join(sorted(missing)))+ thresholds = payload.get("thresholds")+ if not isinstance(thresholds, dict) or not REQUIRED_THRESHOLDS.issubset(thresholds):+ raise ValueError("review scene thresholds are incomplete")+ if payload.get("version") != 1:+ raise ValueError("unsupported review scene version")+ return payload+++def _number(value: Any) -> bool:+ return isinstance(value, (int, float)) and not isinstance(value, bool)+++def _failed_threshold(metrics: dict[str, Any], key: str, threshold: float, *, maximum: bool) -> bool:+ value = metrics.get(key)+ if not _number(value):+ return True+ return float(value) > threshold if maximum else float(value) < threshold+++def _region_results(inputs: dict[str, Any], threshold: float) -> tuple[list[dict[str, Any]], list[str]]:+ raw = inputs.get("paintedRegions", [])+ if not isinstance(raw, list):+ return [], ["painted-regions-invalid"]+ results: list[dict[str, Any]] = []+ failures: list[str] = []+ for region in raw:+ if not isinstance(region, dict) or not isinstance(region.get("id"), str):+ failures.append("painted-region-invalid")+ continue+ score = region.get("score")+ confidence = region.get("confidence")+ result = {"id": region["id"], "score": score, "confidence": confidence}+ results.append(result)+ if not _number(score) or float(score) < threshold:+ failures.append(f"painted-region:{region['id']}")+ if not _number(confidence):+ failures.append(f"painted-region-confidence:{region['id']}")+ return results, failures+++def _critical_feature_failures(inputs: dict[str, Any], default_threshold: float) -> list[str]:+ raw = inputs.get("criticalFeatures", [])+ if not isinstance(raw, list):+ return ["critical-features-invalid"]+ failures: list[str] = []+ for feature in raw:+ if not isinstance(feature, dict) or not isinstance(feature.get("id"), str):+ failures.append("critical-feature-invalid")+ continue+ threshold = feature.get("threshold", default_threshold)+ if not _number(feature.get("score")) or not _number(threshold):+ failures.append(f"critical-feature:{feature['id']}")+ elif float(feature["score"]) < float(threshold):+ failures.append(f"critical-feature:{feature['id']}")+ return failures+++def evaluate_knife_review(+ manifest: dict[str, Any],+ inputs: dict[str, Any],+ review_scene: dict[str, Any],+) -> dict[str, Any]:+ thresholds = review_scene["thresholds"]+ failed: list[str] = []+ family = manifest.get("itemFamily")+ if family != "knife":+ failed.append(f"unsupported-family:{family or 'missing'}")+ if manifest.get("componentAdapter") != "cs2-knife-v1":+ failed.append("knife-adapter-missing")+ if manifest.get("state") != "proceed":+ failed.append(f"manifest-state:{manifest.get('state', 'missing')}")++ for key in ("silhouetteIoU", "aspectRatioDelta", "scaleDelta"):+ maximum = key != "silhouetteIoU"+ if _failed_threshold(inputs, key, float(thresholds[key]), maximum=maximum):+ failed.append(key)+ for key in ("finishMaterialResponse", "identityDetail"):+ if _failed_threshold(inputs, key, float(thresholds[key]), maximum=False):+ failed.append(key)++ region_results, region_failures = _region_results(inputs, float(thresholds["paintedRegion"]))+ failed.extend(region_failures)+ failed.extend(_critical_feature_failures(inputs, float(thresholds["identityDetail"])))++ projection = inputs.get("projection")+ if manifest.get("route") == "reference-projection":+ if not isinstance(projection, dict) or projection.get("required") is not True:+ failed.append("projection-evidence-missing")+ elif _failed_threshold(projection, "coverage", float(thresholds["projectionCoverage"]), maximum=False):+ failed.append("projection-coverage")++ multi_angle = inputs.get("multiAngle")+ if not isinstance(multi_angle, dict) or multi_angle.get("degenerate") is True:+ failed.append("degenerate-orbit")+ elif len(multi_angle.get("angles", [])) < 2:+ failed.append("orbit-coverage-missing")++ notes = manifest.get("approximationNotes", inputs.get("approximationNotes", []))+ approximation_notes = [str(note) for note in notes] if isinstance(notes, list) else []+ hidden_confidence = manifest.get("confidence", {}).get("hiddenRegions")+ report = {+ "verdict": "pass" if not failed else "reject",+ "action": "continue" if not failed else ("request-input" if any(+ item.startswith(("unsupported-family", "manifest-state", "projection-evidence", "orbit-coverage"))+ for item in failed+ ) else "refine-code"),+ "family": family,+ "subtype": manifest.get("subtype"),+ "exactnessTier": manifest.get("exactnessTier"),+ "route": manifest.get("route"),+ "reviewScene": {+ "version": review_scene["version"],+ "fixtureId": review_scene["fixtureId"],+ "camera": review_scene["camera"],+ "transform": review_scene["transform"],+ "environment": review_scene["environment"],+ "resolution": review_scene["resolution"],+ "background": review_scene["background"],+ "rendererVersion": review_scene["rendererVersion"],+ "calibration": review_scene["calibration"],+ },+ "metrics": inputs,+ "paintedRegions": region_results,+ "perRegionConfidence": {region["id"]: region["confidence"] for region in region_results},+ "hiddenRegionConfidence": hidden_confidence,+ "approximationNotes": approximation_notes,+ "failedGates": failed,+ }+ return reportdiff --git a/forge/stage4_review/diagnose_render.py b/forge/stage4_review/diagnose_render.pyindex 4c70a2b..7c6a1d3 100644--- a/forge/stage4_review/diagnose_render.py+++ b/forge/stage4_review/diagnose_render.py@@ -32,6 +32,8 @@ from extract_part_color_recipe import lab_distance, lab_kmeans_palette, srgb_to_sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage3_build"))from orchestrate_passes import DEFAULT_PASS_ORDER, load_spec # noqa: E402+from geometry_integrity import measure_geometry_integrity # noqa: E402+from status_banner import emit_status, load_optional_spec # noqa: E402def color_is_gated(pass_id: str | None) -> bool:@@ -158,6 +160,18 @@ def render_hash(render_path: Path) -> str:return hashlib.sha256(render_path.read_bytes()).hexdigest()[:16]+def strip_material_maps(scene: object) -> object:+ if isinstance(scene, list):+ return [strip_material_maps(item) for item in scene]+ if not isinstance(scene, dict):+ return scene+ result = {key: strip_material_maps(value) for key, value in scene.items()}+ for key in ("map", "normalMap", "roughnessMap", "metalnessMap", "aoMap"):+ if key in result:+ result[key] = None+ return result++def run_tier1(reference_path: Path,render_path: Path,@@ -206,6 +220,11 @@ def run_tier1(f"max per-part color delta-E {color_report['maxDeltaE']} exceeds "f"threshold {COLOR_DELTA_E_THRESHOLD}")+ geometry = spec.get("builtGeometry") or spec.get("geometry")+ if isinstance(geometry, dict):+ structural = measure_geometry_integrity(geometry)+ checks["geometryIntegrity"] = structural+ failures.extend(structural["failures"])return {"passed": not failures,@@ -233,10 +252,16 @@ def main(argv: list[str]) -> int:parser.add_argument("--pass-id")parser.add_argument("--in-place", action="store_true", help="Record the result into --spec")parser.add_argument("--out-spec", type=Path, help="Write the spec with the recorded result to this path")+ parser.add_argument("--map-stripped-scene", type=Path, help="Write a scene JSON with material maps disabled")+ parser.add_argument("--map-stripped-render", type=Path, help="Existing unlit/map-stripped render evidence")parser.add_argument("--json", action="store_true")args = parser.parse_args(argv)try:+ emit_status(load_optional_spec(args.spec), next_command="diagnose_render.py", stream=sys.stderr if args.json else sys.stdout)+ if args.map_stripped_scene:+ scene = json.loads(args.map_stripped_scene.read_text(encoding="utf-8"))+ args.map_stripped_scene.write_text(json.dumps(strip_material_maps(scene), indent=2) + "\n", encoding="utf-8")spec_path = args.spec.expanduser().resolve() if args.spec else Noneresult = run_tier1(args.reference.expanduser().resolve(),@@ -244,6 +269,12 @@ def main(argv: list[str]) -> int:spec_path,args.pass_id,)+ if args.pass_id == "blockout":+ if not args.map_stripped_render:+ result.setdefault("failures", []).append("blockout requires --map-stripped-render evidence")+ result["passed"] = False+ else:+ result["mapStrippedRender"] = str(args.map_stripped_render)if spec_path and (args.in_place or args.out_spec):spec = json.loads(spec_path.read_text(encoding="utf-8"))record_tier1_result(spec, result)diff --git a/forge/stage4_review/divine_eye.py b/forge/stage4_review/divine_eye.pyindex f5a8079..4abca71 100644--- a/forge/stage4_review/divine_eye.py+++ b/forge/stage4_review/divine_eye.py@@ -60,6 +60,7 @@ SCALE_HARD_MAX = 0.08# Ensemble: fidelity target + disagreement (self-uncertainty) spread.FIDELITY_TARGET = 0.85DISAGREEMENT_SPREAD = 0.35 # if soft-signal spread exceeds this ⇒ low-confidence → probe+ASPECT_SOFT_MAX = 0.05 # aspect-ratio delta allowed for a reconstruction-mode soft pass.RECON_OBJ_MIN = 0.48 # objectness ≥ this rescues an IoU-only hard reject → probe (recon mode).# Separates same-object-different-framing (real pairs ~0.53–0.58) from a# genuinely different shape (~0.43). Rescue only ever downgrades reject→probe.@@ -284,8 +285,10 @@ def evaluate(reference_png: Path, render_png: Path) -> dict[str, Any]:iou = silhouette_iou(ref_mask, ren_mask)prop = proportion_delta(bbox_of(ref_mask), bbox_of(ren_mask))- scale_delta = prop.get("scaleDelta", 0.0)- aspect_delta = prop.get("aspectRatioDelta", 0.0)+ # proportion_delta returns snake_case keys; reading camelCase here silently defaulted both+ # to 0.0, which dead-coded the scale HARD gate and pinned the proportion soft signal at 1.0.+ scale_delta = prop.get("scale_delta", 0.0)+ aspect_delta = prop.get("aspect_ratio_delta", 0.0)# symmetry + flat-region are PARITY signals (render vs reference), NOT absolute —# a legitimately asymmetric or flat-lit subject must not be penalized when the# render matches the reference. score = 1 when render is as (a)symmetric / as flat@@ -370,7 +373,18 @@ def evaluate(reference_png: Path, render_png: Path) -> dict[str, Any]:if hard_failures and objectness is not None and objectness >= RECON_OBJ_MIN:if all("silhouette IoU" in f for f in hard_failures):reconstruction_suspected = True- verdict, action = "low-confidence", "probe"+ # Per-track calibration: silhouette IoU 0.85 is unreachable for a procedural-primitive+ # reconstruction of a detailed photo (solid primitives structurally over-fill cutouts,+ # serrations and AA curves), so IoU alone must not veto forever — otherwise the loop can+ # only ever bounded-stop. When objectness confirms the same object AND the soft ensemble+ # already meets the fidelity target AND scale/aspect are within gate, promote the+ # IoU-only reject to a real pass; otherwise route to probe (human/VLM look). Genuinely+ # wrong geometry still fails: low objectness isn't rescued at all, and a weak soft+ # ensemble (< target) or an out-of-gate scale/aspect can only reach probe, never pass.+ if fidelity >= FIDELITY_TARGET and scale_delta <= SCALE_HARD_MAX and aspect_delta <= ASPECT_SOFT_MAX:+ verdict, action = "pass", "continue"+ else:+ verdict, action = "low-confidence", "probe"return {"verdict": verdict,diff --git a/forge/stage4_review/geometry_integrity.py b/forge/stage4_review/geometry_integrity.pynew file mode 100644index 0000000..f2adb7a--- /dev/null+++ b/forge/stage4_review/geometry_integrity.py@@ -0,0 +1,131 @@+from __future__ import annotations++from collections import Counter+from itertools import combinations+from typing import Any, TypeAlias++SEAM_MIN_OVERLAP = 0.02+SEAM_MAX_OVERLAP = 0.05+SEAM_SOURCE = "grimoire/build/geometry_patterns.md"+EdgeKey: TypeAlias = tuple[tuple[float, ...], tuple[float, ...]]+++def _vertex_key(vertex: Any, precision: int = 6) -> tuple[float, ...]:+ if not isinstance(vertex, (list, tuple)) or len(vertex) < 3:+ raise ValueError("vertices must contain 3D positions")+ return tuple(round(float(value), precision) for value in vertex[:3])+++def mesh_edge_counts(vertices: list[Any], indices: list[Any], *, precision: int = 6) -> dict[str, int]:+ keys = [_vertex_key(vertex, precision) for vertex in vertices]+ edges: Counter[EdgeKey] = Counter()+ triangles: list[Any] = indices if indices and isinstance(indices[0], (list, tuple)) else [indices[i:i + 3] for i in range(0, len(indices), 3)]+ if any(len(triangle) != 3 for triangle in triangles):+ raise ValueError("triangle indices must contain groups of three")+ for triangle in triangles:+ points = [keys[int(index)] for index in triangle]+ for left, right in ((points[0], points[1]), (points[1], points[2]), (points[2], points[0])):+ edge: EdgeKey = (left, right) if left <= right else (right, left)+ edges[edge] += 1+ return {"boundaryEdges": sum(count == 1 for count in edges.values()),+ "nonManifoldEdges": sum(count > 2 for count in edges.values()), "edgeCount": len(edges)}+++def _bounds(mesh: dict[str, Any]) -> list[list[float]] | None:+ bounds = mesh.get("bounds") or mesh.get("boundingBox")+ if isinstance(bounds, dict):+ bounds = [bounds.get("min"), bounds.get("max")]+ if isinstance(bounds, (list, tuple)) and len(bounds) == 2 and all(isinstance(point, (list, tuple)) and len(point) >= 3 for point in bounds):+ points = [point for point in bounds if isinstance(point, (list, tuple))]+ if len(points) == 2:+ return [[float(value) for value in points[index][:3]] for index in range(2)]+ vertices = mesh.get("vertices")+ if not isinstance(vertices, list) or not vertices:+ return None+ points = [_vertex_key(point, 12) for point in vertices]+ return [[min(point[axis] for point in points) for axis in range(3)], [max(point[axis] for point in points) for axis in range(3)]]+++def _axis_index(value: Any) -> int:+ if isinstance(value, int) and value in (0, 1, 2):+ return value+ return {"x": 0, "y": 1, "z": 2, "long": 0, "length": 0, "thickness": 2}.get(str(value or "").lower(), 0)+++def _seam_overlap(first: dict[str, Any], second: dict[str, Any]) -> tuple[float, int] | None:+ raw_attachment = second.get("attachment")+ attachment: dict[str, Any] = raw_attachment if isinstance(raw_attachment, dict) else {}+ axis = attachment.get("seamAxis", second.get("seamAxis", first.get("seamAxis")))+ a, b = _bounds(first), _bounds(second)+ if axis is None or a is None or b is None:+ return None+ index = _axis_index(axis)+ return min(a[1][index], b[1][index]) - max(a[0][index], b[0][index]), index+++def _blade_thickness(mesh: dict[str, Any]) -> dict[str, Any]:+ samples = mesh.get("thicknessSamples") or mesh.get("crossSections")+ grind_samples = mesh.get("grindSamples") or samples+ distal_samples = mesh.get("distalThicknessSamples") or samples+ values = []+ def numeric_values(source: Any) -> list[float]:+ result: list[float] = []+ if isinstance(source, list):+ for sample in source:+ value = sample.get("thickness") if isinstance(sample, dict) else sample+ if isinstance(value, (int, float)):+ result.append(float(value))+ return result+ if isinstance(samples, list):+ for sample in samples:+ value = sample.get("thickness") if isinstance(sample, dict) else sample+ if isinstance(value, (int, float)):+ values.append(float(value))+ grind_values = numeric_values(grind_samples)+ distal_values = numeric_values(distal_samples)+ grind_variation = max(grind_values) - min(grind_values) if grind_values else 0.0+ distal_variation = max(distal_values) - min(distal_values) if distal_values else 0.0+ return {"grindVariation": grind_variation, "distalVariation": distal_variation,+ "constantGrind": grind_variation <= 1e-6, "missingDistalTaper": distal_variation <= 1e-6,+ "reported": bool(values)}+++def measure_geometry_integrity(payload: dict[str, Any]) -> dict[str, Any]:+ meshes = payload.get("meshes") or payload.get("components") or []+ if isinstance(meshes, dict):+ meshes = [dict(value, id=key) if isinstance(value, dict) else {"id": key} for key, value in meshes.items()]+ if not isinstance(meshes, list):+ raise ValueError("built geometry meshes/components must be an array or object")+ reports: list[dict[str, Any]] = []+ failures: list[str] = []+ for index, mesh in enumerate(meshes):+ if not isinstance(mesh, dict):+ continue+ item: dict[str, Any] = {"id": mesh.get("id") or mesh.get("name") or f"mesh-{index}", "realization": mesh.get("realization", "separate-geometry")}+ if isinstance(mesh.get("vertices"), list) and isinstance(mesh.get("indices"), list):+ item.update(mesh_edge_counts(mesh["vertices"], mesh["indices"]))+ else:+ item.update({"boundaryEdges": None, "nonManifoldEdges": None, "note": "mesh topology not supplied"})+ role = str(mesh.get("role") or "").lower()+ if role == "blade" or "blade" in str(item["id"]).lower():+ item["thickness"] = _blade_thickness(mesh)+ if item["thickness"]["constantGrind"] or item["thickness"]["missingDistalTaper"]:+ failures.append(f"{item['id']}: blade has constant thickness or missing distal taper")+ if item["realization"] == "separate-geometry" and item.get("boundaryEdges", 0) not in (0, None):+ failures.append(f"{item['id']}: openEdges={item['boundaryEdges']} (separate geometry)")+ reports.append(item)+ seams: list[dict[str, Any]] = []+ for first, second in combinations([item for item in meshes if isinstance(item, dict)], 2):+ relation = second.get("adjacentTo") or first.get("adjacentTo")+ attached = isinstance(second.get("attachment"), dict) and second["attachment"].get("parentId") == first.get("id")+ if relation not in (None, first.get("id"), second.get("id")) and not attached:+ continue+ result = _seam_overlap(first, second)+ if result is None:+ continue+ overlap, axis = result+ seam = {"a": first.get("id"), "b": second.get("id"), "axis": axis, "overlap": round(overlap, 6), "minimum": SEAM_MIN_OVERLAP, "source": SEAM_SOURCE}+ seams.append(seam)+ if overlap < SEAM_MIN_OVERLAP:+ failures.append(f"seam {seam['a']}↔{seam['b']}: overlap={overlap:.3f} < {SEAM_MIN_OVERLAP:.2f}")+ return {"passed": not failures, "source": SEAM_SOURCE, "minimumSeamOverlap": SEAM_MIN_OVERLAP, "maximumDocumentedSeamOverlap": SEAM_MAX_OVERLAP, "meshes": reports, "seams": seams, "failures": failures}diff --git a/forge/tests/fixtures/knife_review_scene.json b/forge/tests/fixtures/knife_review_scene.jsonnew file mode 100644index 0000000..67edd9e--- /dev/null+++ b/forge/tests/fixtures/knife_review_scene.json@@ -0,0 +1,40 @@+{+ "version": 1,+ "fixtureId": "cs2-knife-front-v1",+ "rightsSafeStatus": "user-supplied-review-required",+ "reference": "assets/knife_reference/knife_front.png",+ "identity": {+ "family": "knife",+ "visibleRegions": ["blade", "edge", "spine", "grip", "guard", "fastener", "pommel"],+ "criticalFeatures": ["blade_profile", "edge_curve", "guard_quillon", "grip_ring"],+ "hiddenRegionStrategy": "infer-with-confidence",+ "hiddenRegionConfidence": 0.25+ },+ "camera": {+ "projection": "orthographic",+ "azimuthDegrees": 0,+ "elevationDegrees": 0,+ "rollDegrees": 0,+ "target": [0, 0, 0]+ },+ "transform": {"position": [0, 0, 0], "rotationDegrees": [0, 0, 0], "scale": [1, 1, 1]},+ "environment": {"hash": "code-generated-room-v1", "exposure": 0, "toneMapping": "ACESFilmic"},+ "resolution": {"width": 1024, "height": 1024},+ "background": "neutral-white",+ "rendererVersion": "three-runtime-contract-v1",+ "calibration": {+ "status": "thresholds-frozen-awaiting-positive-negative-render-corpus",+ "positiveFixtures": [],+ "negativeFixtures": []+ },+ "thresholds": {+ "silhouetteIoU": 0.85,+ "aspectRatioDelta": 0.05,+ "scaleDelta": 0.08,+ "projectionCoverage": 0.85,+ "finishMaterialResponse": 0.8,+ "identityDetail": 0.8,+ "paintedRegion": 0.8,+ "maxOrbitCollapseRatio": 0.15+ }+}diff --git a/forge/tests/test_cs2_foundation.py b/forge/tests/test_cs2_foundation.pynew file mode 100644index 0000000..5f34411--- /dev/null+++ b/forge/tests/test_cs2_foundation.py@@ -0,0 +1,134 @@+from __future__ import annotations++import unittest+from pathlib import Path++from forge.stage1_intake.cs2_foundation import (+ classify_map_path,+ enrich_manifest_with_metadata,+ normalize_cs2_metadata,+ map_assets_to_reference_pbr,+ resolve_identity,+ validate_route_requirements,+)+from forge.stage1_intake.cs2_review_contract import (+ GOLDEN_THRESHOLDS,+ build_review_scene,+ validate_review_scene,+)+from forge.stage2_spec.cs2_adapters import get_family_adapter+from forge.stage2_spec.new_pre_spec_assessment import make_payload+from forge.stage2_spec.new_sculpt_spec import apply_cs2_manifest_evidence, apply_cs2_template, make_spec+from forge.stage2_spec.validate_sculpt_spec import validate_cs2_contract+++class IdentityFoundationTests(unittest.TestCase):+ def test_explicit_metadata_wins_over_resolved_and_classification(self) -> None:+ result = resolve_identity(+ {"itemName": "Karambit | Fade", "source": "user"},+ {"itemName": "Karambit | Doppler", "source": "index"},+ {"itemFamily": "knife", "subtype": "karambit", "confidence": 0.9},+ )+ self.assertEqual(result["status"], "resolved")+ self.assertEqual(result["identity"]["itemName"], "Karambit | Fade")+ self.assertEqual(result["provenance"], "explicit-user-metadata")++ def test_ambiguous_metadata_preserves_candidates(self) -> None:+ result = resolve_identity(+ None,+ {"status": "ambiguous", "candidates": [{"name": "A"}, {"name": "B"}]},+ {"itemFamily": "knife", "confidence": 0.9},+ )+ self.assertEqual(result["status"], "ambiguous")+ self.assertEqual(len(result["candidates"]), 2)++ def test_missing_float_seed_and_hidden_view_are_explicit_approximations(self) -> None:+ normalized = normalize_cs2_metadata({"name": "Karambit | Fade"})+ self.assertTrue(normalized["approximations"]["float"]["approximated"])+ self.assertTrue(normalized["approximations"]["paintSeed"]["approximated"])+ self.assertEqual(normalized["approximations"]["hiddenRegions"]["confidence"], 0.25)++ def test_manifest_enrichment_keeps_image_only_tier(self) -> None:+ manifest = {"exactnessTier": "image-only", "provenance": {}, "warnings": []}+ enriched = enrich_manifest_with_metadata(manifest, {"status": "no-match"})+ self.assertEqual(enriched["exactnessTier"], "image-only")+ self.assertEqual(enriched["metadataResolution"]["status"], "no-match")+ self.assertIn("metadata-unavailable", enriched["warnings"])+++class TextureFoundationTests(unittest.TestCase):+ def test_map_classifier_maps_independent_channels(self) -> None:+ self.assertEqual(classify_map_path(Path("knife_color.png"))["mapClass"], "albedo")+ self.assertEqual(classify_map_path(Path("knife_normal.png"))["mapClass"], "normal")+ packed = classify_map_path(Path("knife_orm.png"))+ self.assertEqual(packed["mapClass"], "packed")+ self.assertEqual(packed["packedChannels"], {"roughness": "r", "metalness": "g", "ao": "b"})++ def test_packed_and_direct_assets_map_to_independent_pbr_channels(self) -> None:+ result = map_assets_to_reference_pbr([+ {"mapClass": "albedo", "path": "a.png"},+ {"mapClass": "normal", "path": "n.png"},+ {"mapClass": "packed", "path": "orm.png", "packedChannels": {"roughness": "r", "metalness": "g", "ao": "b"}},+ ])+ self.assertTrue(result["complete"])+ self.assertTrue(result["maps"]["roughness"]["derived"])+ self.assertEqual(result["maps"]["metalness"]["packedChannel"], "g")++ def test_projection_requires_camera_and_delit_unless_fallback(self) -> None:+ missing = validate_route_requirements(+ {"route": "reference-projection", "exactnessTier": "image-only"}+ )+ self.assertEqual(missing["state"], "request-input")+ fallback = validate_route_requirements(+ {"route": "reference-projection", "exactnessTier": "image-only"},+ allow_fallback=True,+ )+ self.assertEqual(fallback["route"], "procedural-finish")+ self.assertEqual(fallback["exactnessTier"], "image-only")+++class AdapterAndReviewTests(unittest.TestCase):+ def test_only_knife_adapter_is_registered(self) -> None:+ self.assertEqual(get_family_adapter("knife", "karambit").family, "knife")+ with self.assertRaises(ValueError):+ get_family_adapter("rifle", "ak47")++ def test_review_scene_is_versioned_and_thresholds_are_frozen(self) -> None:+ scene = build_review_scene("fixture-sha256")+ self.assertEqual(scene["version"], "cs2-knife-review-v1")+ self.assertEqual(scene["environmentHash"], "fixture-sha256")+ self.assertEqual(GOLDEN_THRESHOLDS["silhouetteIoU"], 0.85)+ self.assertEqual(validate_review_scene(scene), [])++ def test_manifest_evidence_reaches_assessment_and_spec(self) -> None:+ manifest = {+ "schemaVersion": 1,+ "state": "proceed",+ "itemFamily": "knife",+ "subtype": "karambit",+ "route": "procedural-finish",+ "exactnessTier": "metadata-assisted",+ "confidence": {"overall": 0.9},+ "provenance": {"reference": "fixture"},+ "warnings": ["paintSeed-approximated"],+ }+ assessment = make_payload("Karambit | Fade", None, "ultra-complex", True, manifest)+ self.assertEqual(assessment["preSpecAssessment"]["objectClass"]["itemFamily"], "knife")+ spec = make_spec("Karambit | Fade", None)+ apply_cs2_template(spec)+ apply_cs2_manifest_evidence(spec, manifest)+ self.assertEqual(spec["cs2Intake"]["exactnessTier"], "metadata-assisted")+ self.assertEqual(spec["materials"][0]["route"], "procedural-finish")++ def test_validator_rejects_invalid_exactness_route_pair(self) -> None:+ errors: list[str] = []+ validate_cs2_contract(+ {"cs2Intake": {"itemFamily": "knife", "route": "procedural-finish", "exactnessTier": "exact-texture"}},+ errors,+ [],+ )+ self.assertTrue(any("cannot claim exact-texture" in error for error in errors))+++if __name__ == "__main__":+ unittest.main()diff --git a/forge/tests/test_cs2_manifest.py b/forge/tests/test_cs2_manifest.pynew file mode 100644index 0000000..a351ccd--- /dev/null+++ b/forge/tests/test_cs2_manifest.py@@ -0,0 +1,81 @@+from __future__ import annotations++import json+import struct+import tempfile+import unittest+import zlib+from pathlib import Path++from forge.stage1_intake.cs2_manifest import (+ build_classification_record,+ build_manifest,+ persist_manifest,+ validate_manifest,+)+++def write_png(path: Path, width: int = 128, height: int = 128) -> None:+ rows = []+ for y in range(height):+ row = bytearray()+ for x in range(width):+ value = 40 if 28 <= x < 100 and 12 <= y < 116 else 240+ row.extend((value, value, value))+ rows.append(b"\x00" + bytes(row))+ raw = b"".join(rows)++ def chunk(kind: bytes, payload: bytes) -> bytes:+ return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", zlib.crc32(kind + payload) & 0xFFFFFFFF)++ payload = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)+ path.write_bytes(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", payload) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))+++class Cs2ManifestTests(unittest.TestCase):+ def test_image_only_knife_manifest_requires_authoritative_classification(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ reference = Path(directory) / "knife.png"+ write_png(reference)+ manifest = build_manifest(reference, None)+ self.assertEqual(manifest["state"], "request-input")+ self.assertEqual(manifest["exactnessTier"], "image-only")+ self.assertTrue(validate_manifest(manifest))++ def test_classified_knife_proceeds_and_preserves_heuristic_signal(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ reference = Path(directory) / "knife.png"+ write_png(reference)+ classification = build_classification_record(+ "knife", "karambit", 0.98, ["view:front:subject"], provider="offline-fixture"+ )+ manifest = build_manifest(reference, classification)+ self.assertEqual(manifest["state"], "proceed")+ self.assertEqual(manifest["itemFamily"], "knife")+ self.assertEqual(manifest["route"], "reference-projection")+ self.assertIn("heuristicSignal", manifest["warnings"])+ self.assertTrue(validate_manifest(manifest))++ def test_unsupported_family_never_receives_knife_adapter(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ reference = Path(directory) / "rifle.png"+ write_png(reference)+ classification = build_classification_record("rifle", "ak47", 0.99, ["view:front:subject"])+ manifest = build_manifest(reference, classification)+ self.assertEqual(manifest["state"], "unsupported-family")+ self.assertNotIn("componentAdapter", manifest)++ def test_manifest_write_is_atomic_and_round_trips(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ reference = Path(directory) / "knife.png"+ output = Path(directory) / "cs2-intake.json"+ write_png(reference)+ classification = build_classification_record("knife", "karambit", 0.9, ["view:front:subject"])+ manifest = build_manifest(reference, classification)+ persist_manifest(manifest, output)+ self.assertEqual(json.loads(output.read_text())["schemaVersion"], 1)+ self.assertFalse(output.with_suffix(".json.tmp").exists())+++if __name__ == "__main__":+ unittest.main()diff --git a/forge/tests/test_cs2_review.py b/forge/tests/test_cs2_review.pynew file mode 100644index 0000000..8ddfc63--- /dev/null+++ b/forge/tests/test_cs2_review.py@@ -0,0 +1,121 @@+from __future__ import annotations++import json+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(ROOT / "stage4_review"))++from cs2_review import evaluate_knife_review, load_review_scene # noqa: E402+from append_review import main as append_review_main # noqa: E402+++class Cs2ReviewGateTest(unittest.TestCase):+ def setUp(self) -> None:+ self.scene = load_review_scene(ROOT / "tests" / "fixtures" / "knife_review_scene.json")+ self.manifest = {+ "schemaVersion": 1,+ "state": "proceed",+ "itemFamily": "knife",+ "subtype": "karambit",+ "componentAdapter": "cs2-knife-v1",+ "route": "reference-projection",+ "exactnessTier": "image-only",+ "confidence": {"overall": 0.86, "hiddenRegions": 0.25},+ "assumptions": {"hiddenRegions": "inferred"},+ }++ def passing_inputs(self) -> dict:+ return {+ "silhouetteIoU": 0.91,+ "aspectRatioDelta": 0.02,+ "scaleDelta": 0.04,+ "finishMaterialResponse": 0.88,+ "identityDetail": 0.9,+ "paintedRegions": [{"id": "blade_finish", "score": 0.9, "confidence": 0.8}],+ "projection": {"coverage": 0.94, "required": True},+ "multiAngle": {"degenerate": False, "angles": [{"id": "orbit-a"}, {"id": "orbit-b"}]},+ "criticalFeatures": [{"id": "karambit_ring", "score": 0.9, "threshold": 0.8}],+ "approximationNotes": ["hidden blade side inferred from single view"],+ }++ def test_passing_knife_review_returns_machine_readable_report(self) -> None:+ report = evaluate_knife_review(self.manifest, self.passing_inputs(), self.scene)++ self.assertEqual(report["verdict"], "pass")+ self.assertEqual(report["action"], "continue")+ self.assertEqual(report["family"], "knife")+ self.assertEqual(report["exactnessTier"], "image-only")+ self.assertEqual(report["reviewScene"]["version"], 1)+ self.assertEqual(report["failedGates"], [])+ self.assertEqual(report["approximationNotes"], ["hidden blade side inferred from single view"])++ def test_wrong_family_is_blocking_even_when_visual_metrics_pass(self) -> None:+ manifest = {**self.manifest, "itemFamily": "rifle"}++ report = evaluate_knife_review(manifest, self.passing_inputs(), self.scene)++ self.assertEqual(report["verdict"], "reject")+ self.assertEqual(report["action"], "request-input")+ self.assertIn("unsupported-family:rifle", report["failedGates"])++ def test_projection_coverage_and_identity_detail_are_blocking(self) -> None:+ inputs = self.passing_inputs()+ inputs["projection"] = {"coverage": 0.42, "required": True}+ inputs["criticalFeatures"] = [{"id": "karambit_ring", "score": 0.4, "threshold": 0.8}]++ report = evaluate_knife_review(self.manifest, inputs, self.scene)++ self.assertEqual(report["verdict"], "reject")+ self.assertEqual(report["action"], "refine-code")+ self.assertIn("projection-coverage", report["failedGates"])+ self.assertIn("critical-feature:karambit_ring", report["failedGates"])++ def test_degenerate_orbit_is_blocking_and_missing_scene_metadata_is_error(self) -> None:+ inputs = self.passing_inputs()+ inputs["multiAngle"] = {"degenerate": True, "angles": [{"id": "orbit-a", "degenerate": True}]}+ report = evaluate_knife_review(self.manifest, inputs, self.scene)+ self.assertEqual(report["verdict"], "reject")+ self.assertIn("degenerate-orbit", report["failedGates"])++ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "invalid.json"+ path.write_text(json.dumps({"version": 1}), encoding="utf-8")+ with self.assertRaises(ValueError):+ load_review_scene(path)++ def test_append_review_persists_cs2_report_and_rejects_failed_report(self) -> None:+ report = evaluate_knife_review(self.manifest, self.passing_inputs(), self.scene)+ failed = evaluate_knife_review(+ self.manifest,+ {**self.passing_inputs(), "identityDetail": 0.2},+ self.scene,+ )+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ spec_path = root / "spec.json"+ report_path = root / "report.json"+ failed_path = root / "failed.json"+ spec_path.write_text(json.dumps({"sourceImage": "ref.png"}), encoding="utf-8")+ report_path.write_text(json.dumps(report), encoding="utf-8")+ failed_path.write_text(json.dumps(failed), encoding="utf-8")+ append_review_main([+ str(spec_path), "--pass-id", "optimization-pass", "--fidelity", "0.9",+ "--action", "continue", "--summary", "ok", "--cs2-review-json", str(report_path),+ "--review-scene-json", str(ROOT / "tests" / "fixtures" / "knife_review_scene.json"),+ "--in-place",+ ])+ persisted = json.loads(spec_path.read_text(encoding="utf-8"))+ self.assertEqual(persisted["reviewHistory"][0]["cs2Review"]["verdict"], "pass")+ with self.assertRaises(ValueError):+ append_review_main([+ str(spec_path), "--pass-id", "optimization-pass", "--fidelity", "0.9",+ "--action", "continue", "--summary", "blocked", "--cs2-review-json", str(failed_path),+ ])+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/forge/tests/test_divine_eye.py b/forge/tests/test_divine_eye.pyindex ffb1e5f..e2e84c5 100644--- a/forge/tests/test_divine_eye.py+++ b/forge/tests/test_divine_eye.py@@ -102,11 +102,12 @@ class DivineEyeIntegrationTest(unittest.TestCase):self.assertTrue(r["hardGateFailures"])def test_shifted_same_shape_is_rescued_by_objectness(self):- # subject moved to a corner → low IoU hard gate, BUT it is the same (square)- # shape → objectness (bg/pose/scale-invariant) recognises it → reconstruction-mode- # rescue downgrades the confident reject to a probe (still not a pass).+ # SAME-SIZE square translated to a corner (100x100 → 100x100, area & aspect identical) →+ # only the IoU hard gate trips (scale/aspect pass), and objectness (bg/pose/scale-invariant)+ # recognises the same shape → reconstruction-mode rescue. Soft fidelity is well below target+ # (misaligned pixels tank ssim/edge), so it routes to probe, never an auto-pass.ren = self.dir / "shifted.png"- write_rgb_png(ren, 200, 200, block(0, 0, 60, 60))+ write_rgb_png(ren, 200, 200, block(0, 0, 100, 100))r = evaluate(self.ref, ren)self.assertTrue(r["hardGateFailures"]) # IoU still tripsself.assertTrue(r["reconstructionModeSuspected"])diff --git a/forge/tests/test_pipeline.py b/forge/tests/test_pipeline.pyindex aca52b5..54166ed 100644--- a/forge/tests/test_pipeline.py+++ b/forge/tests/test_pipeline.py@@ -77,6 +77,46 @@ class PipelineTest(unittest.TestCase):self.assertEqual(spec["schemaVersion"], "2.1")self.assertEqual(spec["targetName"], "Oak")+ def test_cs2_assessment_embeds_local_spec_search_results(self):+ r = run(+ "stage2_spec/new_pre_spec_assessment.py",+ "Karambit Fade",+ "--out",+ self.assessment,+ )+ self.assertEqual(r.returncode, 0, r.stderr)+ assessment = json.loads(self.assessment.read_text())+ search = assessment["localSpecSearch"]+ self.assertEqual(search["collection"], "cs2")+ self.assertEqual(search["query"], "Karambit Fade")+ self.assertGreater(len(search["matches"]), 0)+ self.assertTrue(search["matches"][0]["source_refs"])+ self.assertTrue(search["matches"][0]["evidence_refs"])++ r = run(+ "stage2_spec/new_sculpt_spec.py",+ "Karambit Fade",+ "--assessment",+ self.assessment,+ "--out",+ self.spec,+ )+ self.assertEqual(r.returncode, 0, r.stderr)+ spec = json.loads(self.spec.read_text())+ self.assertEqual(spec["localSpecSearch"]["collection"], "cs2")+ self.assertTrue(spec["localSpecSearch"]["matches"])++ def test_generic_assessment_uses_generic_spec_collection(self):+ r = run(+ "stage2_spec/new_pre_spec_assessment.py",+ "wooden chair",+ "--out",+ self.assessment,+ )+ self.assertEqual(r.returncode, 0, r.stderr)+ assessment = json.loads(self.assessment.read_text())+ self.assertEqual(assessment["localSpecSearch"]["collection"], "core_3d")+def test_normal_validate_passes_strict_fails_on_shallow(self):run("stage2_spec/new_pre_spec_assessment.py", "Oak", "--complexity", "complex","--out", self.assessment)@@ -691,6 +731,154 @@ class PipelineTest(unittest.TestCase):self.assertIn("createPersonModel", ts)self.assertIn('meshes["head"]', ts)+ def test_cs2_anodized_finish_and_environment(self):+ # Author a Doppler-style (anodized-multicolored) CS2 skin, image-first.+ run("stage2_spec/new_sculpt_spec.py", "Karambit Doppler", "--cs2",+ "--finish-style", "anodized-multicolored", "--out", self.spec)+ spec = json.loads(self.spec.read_text())+ finish = next(m for m in spec["materials"] if m["id"] == "skin-finish")+ # view-dependent PBR: high metalness, low roughness, strong environment+ self.assertGreaterEqual(finish["metalness"]["base"], 0.9)+ self.assertLessEqual(finish["roughness"]["base"], 0.15)+ self.assertGreaterEqual(spec["envMapIntensity"], 1.5)+ self.assertTrue(finish["needsEnvironment"])+ # authored CS2 seed is no worse than the object baseline: normal validate passes+ self.assertEqual(run("stage2_spec/validate_sculpt_spec.py", self.spec).returncode, 0)+ # factory generates and emits the code-generated environment helper+ out = self.dir / "createCs2Model.ts"+ r = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out)+ self.assertEqual(r.returncode, 0, r.stderr)+ ts = out.read_text()+ self.assertIn("Environment", ts)+ self.assertIn("RoomEnvironment", ts)+ self.assertIn("PMREMGenerator", ts)++ def test_cs2_track_skipped_for_objects(self):+ run("stage2_spec/new_sculpt_spec.py", "Crate", "--out", self.spec)+ spec = json.loads(self.spec.read_text())+ self.assertNotIn("skin-finish", {m["id"] for m in spec["materials"]})++ def test_cs2_intent_autodetected_from_target_name(self):+ r = run("stage2_spec/new_pre_spec_assessment.py", "Karambit | Doppler", "--out", self.assessment)+ self.assertEqual(r.returncode, 0, r.stderr)+ payload = json.loads(self.assessment.read_text())+ self.assertTrue(payload["preSpecAssessment"]["objectClass"]["cs2"])++ def test_cs2_defaults_to_ultra_complex(self):+ # CS2 is held to the top fidelity bar: --cs2 (or autodetected intent) defaults the tier to+ # ultra-complex (targetMinDetails 16) in both the assessment and the authored spec.+ r = run("stage2_spec/new_pre_spec_assessment.py", "Karambit | Doppler", "--out", self.assessment)+ self.assertEqual(r.returncode, 0, r.stderr)+ pre = json.loads(self.assessment.read_text())["preSpecAssessment"]+ self.assertEqual(pre["complexity"]["tier"], "ultra-complex")+ self.assertEqual(pre["detailInventory"]["targetMinDetails"], 16)+ run("stage2_spec/new_sculpt_spec.py", "Karambit Doppler", "--cs2", "--out", self.spec)+ spec_pre = json.loads(self.spec.read_text())["preSpecAssessment"]+ self.assertEqual(spec_pre["complexity"]["tier"], "ultra-complex")+ self.assertEqual(spec_pre["detailInventory"]["targetMinDetails"], 16)+ # an explicit lower --complexity still honors the 9 detail floor+ r2 = run("stage2_spec/new_pre_spec_assessment.py", "Bayonet skin", "--cs2",+ "--complexity", "simple", "--out", self.assessment, "--force")+ self.assertEqual(r2.returncode, 0, r2.stderr)+ low = json.loads(self.assessment.read_text())["preSpecAssessment"]+ self.assertEqual(low["detailInventory"]["targetMinDetails"], 9)++ def test_cs2_identity_precedence_flags_conflict(self):+ # skin name implies anodized-multicolored (Doppler); vision disagrees with patina.+ run("stage2_spec/new_sculpt_spec.py", "Item", "--cs2", "--skin-name", "Karambit Doppler",+ "--vision-finish-style", "patina", "--vision-confidence", "0.9", "--out", self.spec)+ spec = json.loads(self.spec.read_text())+ self.assertEqual(spec["cs2Finish"]["finishStyle"], "anodized-multicolored")+ unknowns = spec["preSpecAssessment"]["unknownsToResolveBeforeImplementation"]+ self.assertTrue(any("conflict" in u.lower() for u in unknowns))++ def test_cs2_float_and_paint_seed_drive_wear_and_placement(self):+ run("stage2_spec/new_sculpt_spec.py", "Karambit", "--cs2", "--finish-style", "patina",+ "--float", "0.7", "--paint-seed", "12345", "--out", self.spec)+ spec = json.loads(self.spec.read_text())+ finish = next(m for m in spec["materials"] if m["id"] == "skin-finish")+ self.assertFalse(finish["wear"]["approximated"])+ self.assertGreater(finish["wear"]["edgeWear"], 0.5)+ self.assertEqual(finish["patternPlacement"]["paintSeed"], 12345)+ self.assertFalse(finish["patternPlacement"]["approximated"])++ def test_cs2_view_dependent_finish_blocked_without_environment(self):+ run("stage2_spec/new_sculpt_spec.py", "Karambit Doppler", "--cs2",+ "--finish-style", "anodized-multicolored", "--no-environment", "--out", self.spec)+ r = run("stage2_spec/validate_sculpt_spec.py", self.spec)+ self.assertNotEqual(r.returncode, 0)+ self.assertIn("environment", r.stdout.lower())++ def test_fetch_cs2_metadata_resolves_and_flags_ambiguity(self):+ index = self.dir / "skins.json"+ index.write_text(json.dumps([+ {"name": "Karambit | Doppler (Phase 1)", "weapon": {"name": "Karambit"}, "paint_index": 415,+ "min_float": 0.0, "max_float": 0.08, "rarity": {"name": "Covert"}, "image": "https://example.test/1.png"},+ {"name": "Karambit | Doppler (Phase 2)", "weapon": {"name": "Karambit"}, "paint_index": 419,+ "min_float": 0.0, "max_float": 0.08, "rarity": {"name": "Covert"}, "image": "https://example.test/2.png"},+ ]))+ # ambiguous without --phase+ r = run("stage1_intake/fetch_cs2_metadata.py", "--weapon", "Karambit", "--skin", "Doppler",+ "--index-file", index)+ self.assertNotEqual(r.returncode, 0)+ self.assertIn("ambiguous", r.stderr.lower())+ # disambiguated with --phase+ out = self.dir / "metadata.json"+ r = run("stage1_intake/fetch_cs2_metadata.py", "--weapon", "Karambit", "--skin", "Doppler",+ "--phase", "Phase 2", "--index-file", index, "--out", out)+ self.assertEqual(r.returncode, 0, r.stderr)+ record = json.loads(out.read_text())+ self.assertEqual(record["paintIndex"], 419)++ def test_fetch_cs2_metadata_paint_index_disambiguates_identical_names(self):+ # The real CSGO-API lists every Doppler phase under the SAME name, differing only by+ # paint_index -- so --phase (a name substring) cannot pick one, but --paint-index can.+ index = self.dir / "skins.json"+ # paint_index is a STRING in the real CSGO-API dataset -- match must handle that+ index.write_text(json.dumps([+ {"name": "★ Karambit | Doppler", "weapon": {"name": "Karambit"}, "paint_index": "418",+ "min_float": 0.0, "max_float": 0.08, "rarity": {"name": "Covert"}, "image": "https://example.test/418.png"},+ {"name": "★ Karambit | Doppler", "weapon": {"name": "Karambit"}, "paint_index": "419",+ "min_float": 0.0, "max_float": 0.08, "rarity": {"name": "Covert"}, "image": "https://example.test/419.png"},+ ]))+ # --phase "Phase 2" is not in these identical names at all -> no match, cannot help here+ no_match = run("stage1_intake/fetch_cs2_metadata.py", "--weapon", "Karambit", "--skin", "Doppler",+ "--phase", "Phase 2", "--index-file", index)+ self.assertNotEqual(no_match.returncode, 0)+ self.assertIn("no match", no_match.stderr.lower())+ # without --phase the two collide -> ambiguous, and the error lists each paint_index to pick from+ amb = run("stage1_intake/fetch_cs2_metadata.py", "--weapon", "Karambit", "--skin", "Doppler",+ "--index-file", index)+ self.assertNotEqual(amb.returncode, 0)+ self.assertIn("paint_index=419", amb.stderr)+ # --paint-index picks exactly one+ out = self.dir / "meta.json"+ r = run("stage1_intake/fetch_cs2_metadata.py", "--weapon", "Karambit", "--skin", "Doppler",+ "--paint-index", "419", "--index-file", index, "--out", out)+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertEqual(str(json.loads(out.read_text())["paintIndex"]), "419")++ def test_locate_cs2_vpk_returns_not_found_when_absent(self):+ r = run("stage1_intake/locate_cs2_vpk.py", "--root", self.dir, "--json")+ self.assertEqual(r.returncode, 1)+ self.assertFalse(json.loads(r.stdout)["found"])++ def test_extract_cs2_textures_falls_back_without_vpk_or_binary(self):+ r = run("stage1_intake/extract_cs2_textures.py", "--out", self.dir / "cs2_textures", "--json")+ self.assertEqual(r.returncode, 1)+ result = json.loads(r.stdout)+ self.assertEqual(result["status"], "fallback")+ self.assertIn("no local CS2 VPK", result["reason"])++ def test_cs2_textures_gitignored_and_never_tracked(self):+ gitignore = (SKILL / ".gitignore").read_text()+ self.assertIn("cs2_textures/", gitignore)+ tracked = subprocess.run(+ ["git", "-C", str(SKILL), "ls-files", "--", "cs2_textures", "**/cs2_textures"],+ capture_output=True, text=True,+ )+ self.assertEqual(tracked.stdout.strip(), "")+if __name__ == "__main__":unittest.main(verbosity=2)diff --git a/forge/tests/test_search_specs.py b/forge/tests/test_search_specs.pynew file mode 100644index 0000000..f3b995a--- /dev/null+++ b/forge/tests/test_search_specs.py@@ -0,0 +1,1107 @@+#!/usr/bin/env python3+"""Spec-search contract and lifecycle tests. # noqa: SIZE_OK"""++from __future__ import annotations++import importlib.util+import json+import os+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parents[2]+SPEC_SEARCH_PATH = ROOT / "forge/_shared/spec_search.py"+SEARCH_SPECS_CLI = ROOT / "forge/stage1_intake/search_specs.py"+SPEC_SEARCH_SPEC = importlib.util.spec_from_file_location("spec_search", SPEC_SEARCH_PATH)+assert SPEC_SEARCH_SPEC is not None and SPEC_SEARCH_SPEC.loader is not None+SPEC_SEARCH_MODULE = importlib.util.module_from_spec(SPEC_SEARCH_SPEC)+sys.modules[SPEC_SEARCH_SPEC.name] = SPEC_SEARCH_MODULE+SPEC_SEARCH_SPEC.loader.exec_module(SPEC_SEARCH_MODULE)+SourceIngestionError = SPEC_SEARCH_MODULE.SourceIngestionError+LoaderRecordValidationError = SPEC_SEARCH_MODULE.SpecRecordValidationError+ProfileValidationError = SPEC_SEARCH_MODULE.ProfileValidationError+UnknownCollectionError = SPEC_SEARCH_MODULE.UnknownCollectionError+Bm25Config = SPEC_SEARCH_MODULE.Bm25Config+CacheWriteError = SPEC_SEARCH_MODULE.CacheWriteError+CacheValidationError = SPEC_SEARCH_MODULE.CacheValidationError+IndexRequest = SPEC_SEARCH_MODULE.IndexRequest+SearchOutputRequest = SPEC_SEARCH_MODULE.SearchOutputRequest+SourceDocument = SPEC_SEARCH_MODULE.SourceDocument+build_index = SPEC_SEARCH_MODULE.build_index+ingest_source_tree = SPEC_SEARCH_MODULE.ingest_source_tree+load_or_build_index = SPEC_SEARCH_MODULE.load_or_build_index+load_jsonl_records = SPEC_SEARCH_MODULE.load_jsonl_records+load_profile = SPEC_SEARCH_MODULE.load_profile+load_profiles = SPEC_SEARCH_MODULE.load_profiles+search_index = SPEC_SEARCH_MODULE.search_index+serialize_search_results = SPEC_SEARCH_MODULE.serialize_search_results+tokenize = SPEC_SEARCH_MODULE.tokenize+++CONTRACT_README = ROOT / "docs/specs/vocabulary/README.md"+REQUIRED_STRING_FIELDS = (+ "record_id",+ "collection",+ "domain",+ "kind",+ "entity",+ "title",+ "content",+ "observation_status",+)+REQUIRED_LIST_FIELDS = ("aliases", "constraints", "measurements", "source_refs", "evidence_refs", "assumptions")+DISTILLED_RECORD_PATHS = (+ ROOT / "docs/specs/vocabulary/core_3d.jsonl",+ ROOT / "docs/specs/vocabulary/cs2.jsonl",+)+DISTILLED_RECORD_FIELDS = frozenset((*REQUIRED_STRING_FIELDS, *REQUIRED_LIST_FIELDS, "confidence"))+++class SpecRecordValidationError(ValueError):+ def __init__(self, path, line_number, reason):+ self.path = path+ self.line_number = line_number+ self.reason = reason+ super().__init__(f"{path}:{line_number}: {reason}")+++def make_record():+ return {+ "record_id": "cs2.karambit.safety-ring",+ "collection": "cs2",+ "domain": "weapon-anatomy",+ "kind": "component",+ "entity": "karambit safety ring",+ "title": "Karambit safety ring / Vòng ngón Karambit",+ "aliases": ["safety ring", "finger ring", "vòng ngón"],+ "content": "A retention ring at the Karambit's pommel.",+ "constraints": ["Preserve the opening as a distinct component."],+ "measurements": [{"name": "opening diameter", "value": "source-dependent", "unit": "mm"}],+ "source_refs": [+ {"path": "docs/cs2/3D_Technical_Mapping.json", "key_path": "karambit.components.safety_ring"},+ {"path": "docs/cs2-anatomy/karambit.md", "heading": "Safety ring"},+ ],+ "evidence_refs": [{"kind": "source", "ref": "docs/cs2/3D_Technical_Mapping.json"}],+ "observation_status": "observed",+ "confidence": 0.9,+ "assumptions": [],+ }+++def write_jsonl(path, records):+ rows = (json.dumps(record, ensure_ascii=False, sort_keys=True) for record in records)+ path.write_text("\n".join(rows) + "\n", encoding="utf-8")+++def make_profile(+ tokenizer_version="1",+ k1=1.5,+ *,+ casefold=True,+ cache=".cache/spec-search/fixture.json",+ aliases_enabled=True,+ term_aliases=None,+):+ return {+ "source_roots": ["specs"],+ "optional_source_roots": [],+ "distilled_records": [],+ "cache": cache,+ "documentation": "README.md",+ "encoding": "utf-8",+ "languages": ["en", "vi"],+ "source_extensions": [".md"],+ "tokenizer": {+ "version": tokenizer_version,+ "unicode_normalization": "NFKC",+ "casefold": casefold,+ "accent_fold": "vi",+ "preserve_identifiers": True,+ "preserve_numbers": True,+ },+ "aliases": {"enabled": aliases_enabled, "max_expansions": 1},+ "bm25": {"k1": k1, "b": 0.75},+ "term_aliases": {} if term_aliases is None else term_aliases,+ }+++def write_fixture_source(root, content="# Safety ring\nKarambit retention component.\n"):+ source_root = root / "specs"+ source_root.mkdir()+ source = source_root / "guide.md"+ source.write_text(content, encoding="utf-8")+ return source+++def write_cli_fixture(+ root,+ *,+ malformed_profile=False,+ include_raw_roots=True,+ cache_path=".cache/spec-search/cs2.json",+):+ shared = root / "forge/_shared"+ intake = root / "forge/stage1_intake"+ shared.mkdir(parents=True, exist_ok=True)+ intake.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(SPEC_SEARCH_PATH, shared / "spec_search.py")+ if SEARCH_SPECS_CLI.is_file():+ shutil.copyfile(SEARCH_SPECS_CLI, intake / "search_specs.py")++ if include_raw_roots:+ raw_docs = root / "docs/raw"+ raw_docs.mkdir(parents=True, exist_ok=True)+ long_section = (+ " ".join(["alpha"] * 20)+ + " earliestneedle "+ + " ".join(["middle"] * 15)+ + " needle "+ + " ".join(["omega"] * 20)+ )+ (raw_docs / "guide.md").write_text(+ "# Knife Guide\n"+ "General geometry.\n\n"+ "## Safety Ring\n"+ f"{long_section}\n\n"+ "## Roughness\n"+ "Roughness and độ nhám control the finish response.\n",+ encoding="utf-8",+ )+ records = root / "docs/specs/vocabulary"+ records.mkdir(parents=True, exist_ok=True)+ duplicate_records = []+ for record_id in ("cs2.fixture.safety-a", "cs2.fixture.safety-b"):+ record = make_record()+ record["record_id"] = record_id+ record["content"] = "earliestneedle needle"+ record["source_refs"] = [{"path": "docs/raw/guide.md", "heading": "Safety Ring"}]+ duplicate_records.append(record)+ write_jsonl(records / "cs2.jsonl", duplicate_records)++ if malformed_profile:+ profile_text = '{"profile_schema_version":1,"defaults":{}}'+ else:+ profile_text = json.dumps(+ {+ "profile_schema_version": 1,+ "defaults": {+ "encoding": "utf-8",+ "languages": ["en", "vi"],+ "source_extensions": [".md", ".json", ".jsonl"],+ "tokenizer": {+ "version": "1",+ "unicode_normalization": "NFKC",+ "casefold": True,+ "accent_fold": "vi",+ "preserve_identifiers": True,+ "preserve_numbers": True,+ },+ "aliases": {"enabled": True, "max_expansions": 1},+ "bm25": {"k1": 1.5, "b": 0.75},+ },+ "collections": {+ "cs2": {+ "source_roots": [],+ "optional_source_roots": ["docs/raw"],+ "distilled_records": ["docs/specs/vocabulary/cs2.jsonl"],+ "documentation": "docs/README.md",+ "cache": cache_path,+ }+ },+ },+ ensure_ascii=False,+ )+ (shared / "spec_search_profiles.json").write_text(profile_text, encoding="utf-8")+ return intake / "search_specs.py"+++def run_cli_fixture(+ root,+ *arguments,+ malformed_profile=False,+ include_raw_roots=True,+ cache_path=".cache/spec-search/cs2.json",+):+ cli = write_cli_fixture(+ root,+ malformed_profile=malformed_profile,+ include_raw_roots=include_raw_roots,+ cache_path=cache_path,+ )+ environment = os.environ.copy()+ environment["PYTHONDONTWRITEBYTECODE"] = "1"+ return subprocess.run(+ [sys.executable, str(cli), *arguments],+ cwd=root,+ env=environment,+ capture_output=True,+ text=True,+ check=False,+ )+++def load_contract_fixture(path):+ records = []+ for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):+ if not line.strip():+ continue+ try:+ record = json.loads(line)+ except json.JSONDecodeError as error:+ raise SpecRecordValidationError(path, line_number, "invalid JSON object") from error+ validate_record(record, path, line_number)+ records.append(record)+ return records+++def validate_record(record, path, line_number):+ if type(record) is not dict:+ raise SpecRecordValidationError(path, line_number, "record must be a JSON object")+ for field in REQUIRED_STRING_FIELDS:+ if type(record.get(field)) is not str or not record[field]:+ raise SpecRecordValidationError(path, line_number, f"{field} must be a non-empty string")+ for field in REQUIRED_LIST_FIELDS:+ if type(record.get(field)) is not list:+ raise SpecRecordValidationError(path, line_number, f"{field} must be an array")+ if record["observation_status"] not in {"observed", "inferred", "unverified"}:+ raise SpecRecordValidationError(path, line_number, "observation_status is invalid")+ confidence = record.get("confidence")+ if type(confidence) is bool or not isinstance(confidence, (int, float)):+ raise SpecRecordValidationError(path, line_number, "confidence must be a number from 0 through 1")+ if not 0 <= confidence <= 1:+ raise SpecRecordValidationError(path, line_number, "confidence must be a number from 0 through 1")+ validate_string_array(record["aliases"], "aliases", path, line_number)+ validate_string_array(record["constraints"], "constraints", path, line_number)+ validate_string_array(record["assumptions"], "assumptions", path, line_number)+ validate_measurements(record["measurements"], path, line_number)+ validate_source_refs(record["source_refs"], path, line_number)+ validate_evidence_refs(record["evidence_refs"], path, line_number)+++def validate_string_array(values, field, path, line_number):+ if not all(type(value) is str for value in values):+ raise SpecRecordValidationError(path, line_number, f"{field} entries must be strings")+++def validate_measurements(measurements, path, line_number):+ for measurement in measurements:+ if type(measurement) is not dict:+ raise SpecRecordValidationError(path, line_number, "measurements entries must be objects")+ for field in ("name", "value"):+ if type(measurement.get(field)) is not str or not measurement[field]:+ raise SpecRecordValidationError(path, line_number, f"measurements.{field} must be a non-empty string")+ for field in ("unit", "context"):+ if field in measurement and type(measurement[field]) is not str:+ raise SpecRecordValidationError(path, line_number, f"measurements.{field} must be a string")+++def validate_source_refs(source_refs, path, line_number):+ if not source_refs:+ raise SpecRecordValidationError(path, line_number, "source_refs must not be empty")+ for source_ref in source_refs:+ if type(source_ref) is not dict or type(source_ref.get("path")) is not str or not source_ref["path"]:+ raise SpecRecordValidationError(path, line_number, "source_refs entries require a non-empty path")+ for field in ("heading", "key_path"):+ if field in source_ref and (type(source_ref[field]) is not str or not source_ref[field]):+ raise SpecRecordValidationError(path, line_number, f"source_refs.{field} must be a non-empty string")+++def validate_evidence_refs(evidence_refs, path, line_number):+ for evidence_ref in evidence_refs:+ if type(evidence_ref) is not dict:+ raise SpecRecordValidationError(path, line_number, "evidence_refs entries must be objects")+ for field in ("kind", "ref"):+ if type(evidence_ref.get(field)) is not str or not evidence_ref[field]:+ raise SpecRecordValidationError(path, line_number, f"evidence_refs.{field} must be a non-empty string")+ if "note" in evidence_ref and type(evidence_ref["note"]) is not str:+ raise SpecRecordValidationError(path, line_number, "evidence_refs.note must be a string")+++class RecordContractTest(unittest.TestCase):+ def test_future_jsonl_loader_api_is_documented(self):+ contract = CONTRACT_README.read_text(encoding="utf-8")++ self.assertIn("load_jsonl_records(path: Path)", contract)+ self.assertIn("SpecRecordValidationError", contract)++ def test_cs2_record_round_trips_with_bilingual_aliases_and_provenance(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ fixture_path = Path(temporary_directory) / "records.jsonl"+ record = make_record()+ write_jsonl(fixture_path, [record])++ parsed_records = load_contract_fixture(fixture_path)++ self.assertEqual(parsed_records, [record])+ self.assertEqual(parsed_records[0]["aliases"], ["safety ring", "finger ring", "vòng ngón"])+ self.assertEqual(parsed_records[0]["source_refs"][0]["key_path"], "karambit.components.safety_ring")+ self.assertEqual(parsed_records[0]["source_refs"][1]["heading"], "Safety ring")++ def test_malformed_jsonl_raises_named_validation_error_instead_of_skipping(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ fixture_path = Path(temporary_directory) / "broken.jsonl"+ write_jsonl(fixture_path, [make_record()])+ fixture_path.write_text(fixture_path.read_text(encoding="utf-8") + '{"record_id":\n', encoding="utf-8")++ with self.assertRaisesRegex(SpecRecordValidationError, r"broken\.jsonl:2: invalid JSON object"):+ load_contract_fixture(fixture_path)+++class DistilledRecordTest(unittest.TestCase):+ def test_reviewed_bilingual_records_are_complete_and_source_backed(self):+ records_by_path = {path: load_contract_fixture(path) for path in DISTILLED_RECORD_PATHS}+ core_records = records_by_path[DISTILLED_RECORD_PATHS[0]]+ cs2_records = records_by_path[DISTILLED_RECORD_PATHS[1]]+ all_records = [record for records in records_by_path.values() for record in records]++ self.assertGreaterEqual(len(core_records), 12)+ self.assertGreaterEqual(len(cs2_records), 8)+ self.assertEqual(len({record["record_id"] for record in all_records}), len(all_records))+ self.assertTrue(all(set(record) <= DISTILLED_RECORD_FIELDS for record in all_records))+ self.assertTrue(all(record["source_refs"] for record in all_records))++ aliases = {alias.casefold() for record in all_records for alias in record["aliases"]}+ self.assertTrue(+ {+ "socket",+ "ổ cắm",+ "pivot",+ "điểm xoay",+ "roughness",+ "độ thô",+ "wear",+ "hao mòn",+ "safety ring",+ "vòng ngón",+ "pommel",+ "chuôi cuối",+ "attachment",+ "gắn kết",+ }.issubset(aliases)+ )++ source_paths = {source_ref["path"] for record in all_records for source_ref in record["source_refs"]}+ self.assertTrue(+ {+ "grimoire/glossary/3d_vocabulary.md",+ "grimoire/readiness/action_rigging.md",+ "grimoire/readiness/joint_attachment.md",+ "grimoire/intake/image_analysis.md",+ "docs/cs2/3D_Technical_Mapping.json",+ "docs/cs2/3D_Vocabulary_CS2.json",+ "docs/cs2/distill.md",+ "docs/cs2-anatomy/knives.md",+ }.issubset(source_paths)+ )+++class TokenizerTest(unittest.TestCase):+ def test_mixed_language_tokens_preserve_identifiers_numbers_and_accents(self):+ text = "Safety ring, vòng ngón, độ nhám/do nham; AK-47 MeshPhysicalMaterial 0.05-0.15 rings"++ tokens = tokenize(text)++ self.assertTrue(+ {+ "safety",+ "ring",+ "vòng",+ "vong",+ "ngón",+ "ngon",+ "độ",+ "do",+ "nhám",+ "nham",+ "ak-47",+ "meshphysicalmaterial",+ "0.05-0.15",+ "rings",+ }.issubset(tokens)+ )+ self.assertEqual(tokens.count("ring"), 1)++ def test_profile_alias_expansion_is_deterministic(self):+ aliases_a = {+ "roughness": ("độ nhám",),+ "safety ring": ("vòng ngón", "finger ring"),+ }+ aliases_b = dict(reversed(tuple(aliases_a.items())))++ tokens_a = tokenize("Safety ring roughness", aliases_a)+ tokens_b = tokenize("Safety ring roughness", aliases_b)++ self.assertEqual(tokens_a, tokens_b)+ self.assertTrue({"vòng", "vong", "ngón", "ngon", "finger", "độ", "do", "nhám", "nham"}.issubset(tokens_a))+++class SourceIngestionTest(unittest.TestCase):+ def test_profile_loader_exposes_cs2_cache_and_documentation(self):+ profile = load_profiles()["cs2"]++ self.assertEqual(profile["cache"], ".cache/spec-search/cs2.json")+ self.assertEqual(profile["documentation"], "docs/specs/vocabulary/README.md")+ self.assertEqual(profile["encoding"], "utf-8")+ self.assertEqual(profile["source_roots"], [])+ self.assertEqual(profile["optional_source_roots"], ["docs/cs2/", "docs/cs2-anatomy/"])++ def test_profile_loader_rejects_malformed_and_unknown_collections(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ malformed_profile = Path(temporary_directory) / "profiles.json"+ malformed_profile.write_text('{"profile_schema_version":1,"defaults":{}}', encoding="utf-8")++ with self.assertRaisesRegex(ProfileValidationError, r"defaults\.tokenizer must be an object"):+ load_profiles(malformed_profile)+ with self.assertRaisesRegex(UnknownCollectionError, r"unknown spec-search collection: missing"):+ load_profile("missing")++ def test_markdown_sections_retain_heading_and_source_path(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ (root / "guide.md").write_text(+ "# Karambit\nCurved blade.\n\n## Safety Ring\nRetains the grip.\n",+ encoding="utf-8",+ )++ documents = ingest_source_tree(root, "fixture", (".md",))++ safety_ring = next(document for document in documents if document.heading == "Safety Ring")+ self.assertEqual(safety_ring.file_path, "guide.md")+ self.assertEqual(safety_ring.content, "Retains the grip.")++ def test_nested_json_values_retain_key_path_and_source_path(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ (root / "mapping.json").write_text(+ '{"karambit":{"components":{"safety_ring":{"diameter_mm":22}}}}',+ encoding="utf-8",+ )++ documents = ingest_source_tree(root, "fixture", (".json",))++ diameter = next(document for document in documents if document.key_path.endswith("diameter_mm"))+ self.assertEqual(diameter.file_path, "mapping.json")+ self.assertEqual(diameter.key_path, "karambit.components.safety_ring.diameter_mm")+ self.assertEqual(diameter.content, "22")++ def test_hidden_directories_and_generated_caches_are_excluded(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ (root / ".hidden").mkdir()+ (root / ".hidden" / "broken.json").write_text("{", encoding="utf-8")+ (root / ".hidden.md").write_text("# Hidden\nMust not be indexed.\n", encoding="utf-8")+ (root / ".cache" / "spec-search").mkdir(parents=True)+ (root / ".cache" / "spec-search" / "broken.json").write_text("{", encoding="utf-8")+ (root / "visible.md").write_text("# Visible\nSearchable.\n", encoding="utf-8")++ documents = ingest_source_tree(root, "fixture", (".md", ".json"))++ self.assertEqual([document.file_path for document in documents], ["visible.md"])++ def test_symlink_source_file_is_rejected_without_indexing_target(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ source_root = root / "specs"+ source_root.mkdir()+ secret = root / "secret.md"+ secret.write_text("# Secret\nmust-not-be-indexed\n", encoding="utf-8")+ (source_root / "linked.md").symlink_to(secret)+ profile = make_profile()++ with self.assertRaisesRegex(SourceIngestionError, r"linked\.md: symbolic links are not allowed"):+ load_or_build_index(IndexRequest(root, "fixture", profile))++ cache_exists = (root / ".cache/spec-search/fixture.json").exists()++ self.assertFalse(cache_exists)++ def test_symlink_source_root_is_rejected_without_indexing_target(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ secret_root = root / "secret"+ secret_root.mkdir()+ (secret_root / "secret.md").write_text(+ "# Secret\nmust-not-be-indexed\n",+ encoding="utf-8",+ )+ (root / "specs").symlink_to(secret_root, target_is_directory=True)++ with self.assertRaisesRegex(+ SourceIngestionError,+ r"specs: symbolic links are not allowed",+ ):+ load_or_build_index(+ IndexRequest(root, "fixture", make_profile())+ )++ cache_exists = (root / ".cache/spec-search/fixture.json").exists()++ self.assertFalse(cache_exists)++ def test_missing_optional_root_is_skipped_but_required_root_is_not(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ records = root / "records"+ records.mkdir()+ write_jsonl(records / "fixture.jsonl", [make_record()])+ optional_profile = make_profile()+ optional_profile["source_roots"] = []+ optional_profile["optional_source_roots"] = ["missing-raw"]+ optional_profile["distilled_records"] = ["records/fixture.jsonl"]++ loaded = load_or_build_index(IndexRequest(root, "fixture", optional_profile))++ required_profile = make_profile(cache=".cache/spec-search/required.json")+ with self.assertRaisesRegex(SourceIngestionError, r"specs: configured source root is not a directory"):+ load_or_build_index(IndexRequest(root, "fixture", required_profile))++ self.assertTrue(loaded.index.records)++ def test_existing_unreadable_optional_root_raises_typed_source_error(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ raw_root = root / "raw"+ raw_root.mkdir()+ profile = make_profile()+ profile["source_roots"] = []+ profile["optional_source_roots"] = ["raw"]++ original_iterdir = Path.iterdir++ def unreadable_iterdir(path):+ if path == raw_root:+ raise PermissionError("denied")+ return original_iterdir(path)++ with mock.patch.object(Path, "iterdir", unreadable_iterdir):+ with self.assertRaisesRegex(SourceIngestionError, r"raw: unable to read configured source root"):+ load_or_build_index(IndexRequest(root, "fixture", profile))++ def test_malformed_configured_json_and_jsonl_raise_named_errors(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ valid_jsonl = root / "records.jsonl"+ write_jsonl(valid_jsonl, [make_record()])+ malformed_json = root / "broken.json"+ malformed_json.write_text('{"blade":', encoding="utf-8")+ malformed_jsonl = root / "broken.jsonl"+ malformed_jsonl.write_text('{"record_id":\n', encoding="utf-8")++ self.assertEqual(load_jsonl_records(valid_jsonl), [make_record()])+ with self.assertRaisesRegex(SourceIngestionError, r"broken\.json: invalid JSON source"):+ ingest_source_tree(root, "fixture", (".json",))+ with self.assertRaisesRegex(LoaderRecordValidationError, r"broken\.jsonl:1: invalid JSON object"):+ load_jsonl_records(malformed_jsonl)+++class BM25Test(unittest.TestCase):+ def test_rare_exact_terms_beat_longer_generic_document(self):+ documents = [+ SourceDocument(+ record_id="fixture.exact",+ collection="fixture",+ title="Karambit safety ring",+ content="Retention opening.",+ file_path="exact.md",+ ),+ SourceDocument(+ record_id="fixture.generic",+ collection="fixture",+ title="Ring overview",+ content=" ".join(["generic component material geometry"] * 30),+ file_path="generic.md",+ ),+ ]++ matches = search_index(build_index(documents, Bm25Config(collection="fixture")), "karambit safety ring")++ self.assertEqual([match.record.record_id for match in matches], ["fixture.exact", "fixture.generic"])+ self.assertGreater(matches[0].score, matches[1].score)++ def test_equal_scores_tie_by_record_id_ascending(self):+ documents = [+ SourceDocument(+ record_id=record_id,+ collection="fixture",+ title="Shared title",+ content="identical searchable terms",+ file_path=f"{record_id}.md",+ )+ for record_id in ("fixture.z", "fixture.a")+ ]++ matches = search_index(build_index(documents, Bm25Config(collection="fixture")), "searchable")++ self.assertEqual([match.record.record_id for match in matches], ["fixture.a", "fixture.z"])+ self.assertEqual(matches[0].score, matches[1].score)++ def test_profile_casefold_setting_changes_index_and_query_tokens(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ write_fixture_source(root, "# MixedCase\nCamelToken\n")++ folded = load_or_build_index(IndexRequest(root, "fixture", make_profile()))+ exact_case = load_or_build_index(+ IndexRequest(+ root,+ "fixture",+ make_profile(casefold=False, cache=".cache/spec-search/exact.json"),+ )+ )++ self.assertTrue(search_index(folded.index, "cameltoken"))+ self.assertEqual(search_index(exact_case.index, "cameltoken"), [])+ self.assertTrue(search_index(exact_case.index, "CamelToken"))++ def test_enabled_term_alias_query_matches_expansion_and_disabled_does_not(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ write_fixture_source(root, "# Hook blade\nhookblade profile\n")+ aliases = {"karambit": ["hookblade"]}++ enabled = load_or_build_index(+ IndexRequest(root, "fixture", make_profile(term_aliases=aliases))+ )+ disabled = load_or_build_index(+ IndexRequest(+ root,+ "fixture",+ make_profile(+ cache=".cache/spec-search/no-alias.json",+ aliases_enabled=False,+ term_aliases=aliases,+ ),+ )+ )++ self.assertTrue(search_index(enabled.index, "karambit"))+ self.assertEqual(search_index(disabled.index, "karambit"), [])+++class CacheLifecycleTest(unittest.TestCase):+ def test_notebooklm_evidence_refs_survive_cache_hit_and_cli_serialization(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ records = root / "records"+ records.mkdir()+ record = make_record()+ record["evidence_refs"] = [+ {+ "kind": "notebooklm",+ "ref": "notebook://cs2/source-7",+ "note": "distilled observation",+ }+ ]+ write_jsonl(records / "fixture.jsonl", [record])+ profile = make_profile()+ profile["source_roots"] = []+ profile["distilled_records"] = ["records/fixture.jsonl"]++ load_or_build_index(IndexRequest(root, "fixture", profile))+ cached = load_or_build_index(IndexRequest(root, "fixture", profile))+ serialized = serialize_search_results(+ cached.index,+ SearchOutputRequest("retention ring", 1, 120),+ )++ self.assertEqual(cached.status, "hit")+ self.assertEqual(+ serialized[0]["evidence_refs"],+ [+ {+ "kind": "notebooklm",+ "ref": "notebook://cs2/source-7",+ "note": "distilled observation",+ }+ ],+ )++ def test_cache_path_rejects_traversal_and_absolute_values_before_write(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ outer = Path(temporary_directory)+ root = outer / "project"+ root.mkdir()+ write_fixture_source(root)+ scenarios = (+ ("../escape.json", outer / "escape.json"),+ (str(outer / "absolute.json"), outer / "absolute.json"),+ )++ for configured_cache, escaped_path in scenarios:+ with self.subTest(configured_cache=configured_cache):+ with self.assertRaisesRegex(+ CacheValidationError,+ r"cache path must be relative and stay within project_root",+ ):+ load_or_build_index(+ IndexRequest(+ root,+ "fixture",+ make_profile(cache=configured_cache),+ )+ )+ self.assertFalse(escaped_path.exists())++ def test_cache_hit_avoids_source_reparse_and_preserves_fingerprint(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ write_fixture_source(root)+ profile = make_profile()++ initial = load_or_build_index(IndexRequest(root, "fixture", profile))+ cache_path = root / ".cache/spec-search/fixture.json"+ initial_cache = json.loads(cache_path.read_text(encoding="utf-8"))+ with mock.patch.object(+ SPEC_SEARCH_MODULE,+ "ingest_markdown",+ side_effect=AssertionError("cache hit reparsed source"),+ ):+ cached = load_or_build_index(IndexRequest(root, "fixture", profile))++ self.assertEqual(initial.status, "rebuilt")+ self.assertEqual(initial.reason, "missing")+ self.assertEqual(cached.status, "hit")+ self.assertEqual(cached.fingerprint, initial.fingerprint)+ self.assertEqual(+ {+ "schema_fingerprint",+ "tokenizer_fingerprint",+ "config_fingerprint",+ "source_fingerprint",+ "document_lengths",+ "avgdl",+ "document_frequencies",+ "postings",+ "records",+ }+ - initial_cache.keys(),+ set(),+ )++ def test_source_mutation_rebuilds_stale_cache(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ source = write_fixture_source(root, "# Safety ring\nalpha beta gamma.\n")+ original_stat = source.stat()+ profile = make_profile()+ initial = load_or_build_index(IndexRequest(root, "fixture", profile))++ source.write_text("# Safety ring\nomega beta gamma.\n", encoding="utf-8")+ os.utime(source, ns=(original_stat.st_atime_ns, original_stat.st_mtime_ns))+ rebuilt = load_or_build_index(IndexRequest(root, "fixture", profile))++ self.assertEqual(rebuilt.status, "rebuilt")+ self.assertEqual(rebuilt.reason, "stale")+ self.assertNotEqual(rebuilt.index.fingerprints.source, initial.index.fingerprints.source)++ def test_config_tokenizer_and_schema_changes_each_rebuild(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ write_fixture_source(root)+ initial = load_or_build_index(IndexRequest(root, "fixture", make_profile()))++ config_changed = load_or_build_index(IndexRequest(root, "fixture", make_profile(k1=1.2)))+ tokenizer_changed = load_or_build_index(+ IndexRequest(root, "fixture", make_profile(tokenizer_version="2", k1=1.2))+ )+ with mock.patch.object(+ SPEC_SEARCH_MODULE,+ "_CACHE_SCHEMA_VERSION",+ SPEC_SEARCH_MODULE._CACHE_SCHEMA_VERSION + 1,+ ):+ schema_changed = load_or_build_index(+ IndexRequest(root, "fixture", make_profile(tokenizer_version="2", k1=1.2))+ )++ self.assertEqual(config_changed.reason, "stale")+ self.assertNotEqual(config_changed.index.fingerprints.config, initial.index.fingerprints.config)+ self.assertEqual(tokenizer_changed.reason, "stale")+ self.assertNotEqual(+ tokenizer_changed.index.fingerprints.tokenizer,+ config_changed.index.fingerprints.tokenizer,+ )+ self.assertEqual(schema_changed.reason, "stale")+ self.assertNotEqual(+ schema_changed.index.fingerprints.schema,+ tokenizer_changed.index.fingerprints.schema,+ )++ def test_force_reindex_rebuilds_unchanged_cache(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ write_fixture_source(root)+ profile = make_profile()+ initial = load_or_build_index(IndexRequest(root, "fixture", profile))++ rebuilt = load_or_build_index(IndexRequest(root, "fixture", profile, force_reindex=True))++ self.assertEqual(rebuilt.status, "rebuilt")+ self.assertEqual(rebuilt.reason, "forced")+ self.assertEqual(rebuilt.fingerprint, initial.fingerprint)++ def test_corrupt_json_rebuilds_when_sources_are_available(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ write_fixture_source(root)+ profile = make_profile()+ load_or_build_index(IndexRequest(root, "fixture", profile))+ cache_path = root / ".cache/spec-search/fixture.json"+ cache_path.write_text('{"schema_version":', encoding="utf-8")++ rebuilt = load_or_build_index(IndexRequest(root, "fixture", profile))+ parsed = json.loads(cache_path.read_text(encoding="utf-8"))++ self.assertEqual(rebuilt.status, "rebuilt")+ self.assertEqual(rebuilt.reason, "corrupt")+ self.assertEqual(parsed["fingerprint"], rebuilt.fingerprint)++ def test_atomic_write_failure_cleans_temp_and_preserves_old_cache(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ source = write_fixture_source(root)+ profile = make_profile()+ load_or_build_index(IndexRequest(root, "fixture", profile))+ cache_path = root / ".cache/spec-search/fixture.json"+ old_cache = cache_path.read_text(encoding="utf-8")+ source.write_text("# Changed\nTrigger atomic replacement.\n", encoding="utf-8")++ with mock.patch.object(SPEC_SEARCH_MODULE.os, "replace", side_effect=OSError("interrupted")):+ with self.assertRaises(CacheWriteError):+ load_or_build_index(IndexRequest(root, "fixture", profile))++ temporary_artifacts = list(cache_path.parent.glob(f".{cache_path.name}.*.tmp"))+ preserved_cache = cache_path.read_text(encoding="utf-8")++ self.assertEqual(preserved_cache, old_cache)+ self.assertEqual(temporary_artifacts, [])+++class CliOutputTest(unittest.TestCase):+ def _assert_unsafe_profile_cache_path(self, configured_cache, outside_name):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ outside = root.parent / f"{root.name}-{outside_name}"+ result = run_cli_fixture(+ root,+ "needle",+ "--json",+ cache_path=configured_cache(root, outside),+ )++ self.assertEqual(result.returncode, 3, result.stderr)+ payload = json.loads(result.stdout)+ self.assertEqual(payload["error"]["code"], "cache_failure")+ self.assertNotIn(str(root), result.stdout + result.stderr)+ self.assertNotIn("Traceback", result.stderr)+ self.assertFalse(outside.exists())++ def test_traversal_profile_cache_path_returns_cache_failure_without_disclosure_or_write(self):+ self._assert_unsafe_profile_cache_path(+ lambda _root, outside: "../" + outside.name,+ "escape.json",+ )++ def test_absolute_profile_cache_path_returns_cache_failure_without_disclosure_or_write(self):+ self._assert_unsafe_profile_cache_path(+ lambda root, _outside: str(root / "absolute.json"),+ "absolute.json",+ )++ def test_symlinked_cache_parent_returns_structured_cache_failure(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ cli = write_cli_fixture(root)+ outside = root.parent / f"{root.name}-outside"+ outside.mkdir()+ (root / ".cache").mkdir()+ (root / ".cache" / "spec-search").symlink_to(outside, target_is_directory=True)++ result = subprocess.run(+ [sys.executable, str(cli), "needle", "--json"],+ cwd=root,+ env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"},+ capture_output=True,+ text=True,+ check=False,+ )++ payload = json.loads(result.stdout)+ self.assertEqual(result.returncode, 3)+ self.assertEqual(payload["error"]["code"], "cache_failure")+ self.assertNotIn("Traceback", result.stderr)+ self.assertFalse((outside / "cs2.json").exists())++ def test_clean_style_project_searches_committed_distilled_records_without_raw_roots(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ result = run_cli_fixture(+ root,+ "retention",+ "ring",+ "--json",+ include_raw_roots=False,+ )+ raw_root_exists = (root / "docs/raw").exists()++ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertFalse(raw_root_exists)+ payload = json.loads(result.stdout)+ self.assertTrue(payload["matches"])+ self.assertEqual(payload["matches"][0]["record_id"], "cs2.fixture.safety-a")++ def test_json_output_has_stable_machine_consumed_shape(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ result = run_cli_fixture(+ Path(temporary_directory),+ "--collection",+ "cs2",+ "safety",+ "ring",+ "vòng",+ "ngón",+ "--limit",+ "2",+ "--json",+ )++ self.assertEqual(result.returncode, 0, result.stderr)+ payload = json.loads(result.stdout)+ self.assertEqual(set(payload), {"query", "collection", "index", "matches"})+ self.assertEqual(payload["query"], "safety ring vòng ngón")+ self.assertEqual(payload["collection"], "cs2")+ self.assertEqual(set(payload["index"]), {"cache_path", "fingerprint", "reason", "status"})+ self.assertLessEqual(len(payload["matches"]), 2)+ self.assertTrue(payload["matches"])+ for match in payload["matches"]:+ self.assertTrue(+ {+ "record_id",+ "file_path",+ "heading",+ "key_path",+ "score",+ "snippets",+ "source_refs",+ "evidence_refs",+ }.issubset(match)+ )+ self.assertIsInstance(match["score"], float)+ self.assertIsInstance(match["snippets"], list)+ self.assertIsInstance(match["source_refs"], list)+ self.assertIsInstance(match["evidence_refs"], list)+ self.assertEqual(result.stderr, "")++ def test_human_output_is_nonempty_and_stable_on_cache_hits(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ run_cli_fixture(root, "roughness", "độ", "nhám")+ cached = run_cli_fixture(root, "roughness", "độ", "nhám")+ repeated = run_cli_fixture(root, "roughness", "độ", "nhám")++ self.assertEqual(cached.returncode, 0, cached.stderr)+ self.assertEqual(repeated.returncode, 0, repeated.stderr)+ self.assertTrue(cached.stdout.strip())+ self.assertEqual(cached.stdout, repeated.stdout)++ def test_validation_and_profile_errors_have_documented_codes(self):+ scenarios = (+ (("--json",), 2, "empty_query", False),+ (("--collection", "missing", "term", "--json"), 2, "unknown_collection", False),+ (("term", "--limit", "0", "--json"), 2, "invalid_limit", False),+ (("term", "--json"), 3, "profile_failure", True),+ )+ for arguments, expected_exit, expected_code, malformed_profile in scenarios:+ with self.subTest(arguments=arguments):+ with tempfile.TemporaryDirectory() as temporary_directory:+ result = run_cli_fixture(+ Path(temporary_directory),+ *arguments,+ malformed_profile=malformed_profile,+ )++ self.assertEqual(result.returncode, expected_exit, result.stderr)+ payload = json.loads(result.stdout)+ self.assertEqual(+ set(payload),+ {"query", "collection", "index", "matches", "error"},+ )+ self.assertEqual(payload["error"]["code"], expected_code)+ self.assertIsInstance(payload["error"]["message"], str)++ def test_no_match_is_success_with_empty_matches(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ result = run_cli_fixture(+ Path(temporary_directory),+ "term-that-cannot-match",+ "--json",+ )++ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertEqual(json.loads(result.stdout)["matches"], [])++ def test_undersized_snippets_are_rejected_before_search(self):+ for snippet_chars in range(1, 5):+ with self.subTest(snippet_chars=snippet_chars):+ with tempfile.TemporaryDirectory() as temporary_directory:+ result = run_cli_fixture(+ Path(temporary_directory),+ "roughness",+ "--snippet-chars",+ str(snippet_chars),+ "--json",+ )++ self.assertEqual(result.returncode, 2, result.stderr)+ payload = json.loads(result.stdout)+ self.assertEqual(payload["error"]["code"], "invalid_snippet_chars")+ self.assertIn("at least 5", payload["error"]["message"])+ self.assertEqual(payload["matches"], [])+++class SnippetTest(unittest.TestCase):+ def test_snippet_is_bounded_centered_and_word_trimmed(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ result = run_cli_fixture(+ Path(temporary_directory),+ "earliestneedle",+ "needle",+ "--limit",+ "5",+ "--snippet-chars",+ "80",+ "--json",+ )++ self.assertEqual(result.returncode, 0, result.stderr)+ matches = json.loads(result.stdout)["matches"]+ self.assertEqual(len(matches), 1)+ snippet = matches[0]["snippets"][0]+ self.assertLessEqual(len(snippet), 80)+ self.assertIn("earliestneedle", snippet)+ self.assertTrue(snippet.startswith("... "))+ self.assertTrue(snippet.endswith(" ..."))+ body_words = snippet.removeprefix("... ").removesuffix(" ...").split()+ self.assertTrue(set(body_words) <= {"alpha", "earliestneedle", "middle", "needle", "omega"})++ def test_untruncated_snippet_has_no_ellipses(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ result = run_cli_fixture(+ Path(temporary_directory),+ "roughness",+ "--snippet-chars",+ "250",+ "--json",+ )++ self.assertEqual(result.returncode, 0, result.stderr)+ snippet = json.loads(result.stdout)["matches"][0]["snippets"][0]+ self.assertNotIn("...", snippet)+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/forge/tests/test_structure_gates.py b/forge/tests/test_structure_gates.pynew file mode 100644index 0000000..09c0b4c--- /dev/null+++ b/forge/tests/test_structure_gates.py@@ -0,0 +1,47 @@+from __future__ import annotations++import json+import tempfile+import unittest+from pathlib import Path+import sys++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "stage4_review"))+sys.path.insert(0, str(ROOT / "stage3_build"))++from geometry_integrity import measure_geometry_integrity, mesh_edge_counts+from append_review import main as append_review_main+from orchestrate_passes import ledger_disagreements, pass_order+++class StructureGateTest(unittest.TestCase):+ def test_coincident_vertices_are_merged_for_edge_counts(self) -> None:+ vertices = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 0], [1, 0, 0], [0, 1, 0]]+ self.assertEqual(mesh_edge_counts(vertices, [0, 1, 2, 3, 5, 4])["boundaryEdges"], 0)++ def test_open_separate_geometry_fails_and_map_only_is_reported(self) -> None:+ result = measure_geometry_integrity({"meshes": [+ {"id": "hardware", "realization": "separate-geometry", "vertices": [[0, 0, 0], [1, 0, 0], [0, 1, 0]], "indices": [0, 1, 2]},+ {"id": "decal", "realization": "map-only"},+ ]})+ self.assertFalse(result["passed"])+ self.assertEqual(result["meshes"][0]["boundaryEdges"], 3)+ self.assertEqual(result["meshes"][1]["realization"], "map-only")++ def test_out_of_order_append_leaves_spec_unchanged(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "spec.json"+ path.write_text(json.dumps({"buildPasses": [{"id": "blockout"}, {"id": "material-pass"}], "reviewHistory": []}) + "\n")+ before = path.read_bytes()+ with self.assertRaises(ValueError):+ append_review_main([str(path), "--pass-id", "material-pass", "--fidelity", "0.9", "--action", "stop", "--summary", "out of order"])+ self.assertEqual(path.read_bytes(), before)++ def test_sync_disagreement_names_uncredited_review(self) -> None:+ spec = {"buildPasses": [{"id": "blockout"}, {"id": "material-pass"}], "reviewHistory": [{"passId": "material-pass", "action": "continue"}]}+ self.assertTrue(any(item.startswith("material-pass:") for item in ledger_disagreements(spec, [])))+++if __name__ == "__main__":+ unittest.main()diff --git a/grimoire/build/cs2_finishes.md b/grimoire/build/cs2_finishes.mdnew file mode 100644index 0000000..41a41d0--- /dev/null+++ b/grimoire/build/cs2_finishes.md@@ -0,0 +1,126 @@+# CS2 / Steam Item Finishes++Rulebook for the supported CS2 **knife** finish track. The reconstruction stays **image-first**: a+reference image is the only required input. A skin name, descriptor (`finishStyle`, `float`,+`paintSeed`), or an extracted Valve texture are optional layers that add exactness when the user+supplies them — they never block the default path.++**Two finish routes, chosen by goal — do NOT default to procedural for a reference-match.**++This rulebook does not authorize pistol, rifle, SMG, sniper, heavy, glove, or unknown knife+subtypes. Intake must return `unsupported-family` or `unsupported-subtype` before finish selection+for those families. The route (`reference-projection`, `authored-texture`, or `procedural-finish`)+and evidence tier (`image-only`, `metadata-assisted`, or `exact-texture`) are separate fields in+`cs2-intake.json`; a route fallback never changes the evidence tier.++- **Projection (default when the goal is matching a specific reference image — e.g. rebuilding a+ named skin from its photo):** author the geometry procedurally, then project the **de-lit**+ reference crop onto the blade/grip as the finish and bake it into UVs — camera-match+ (`solve_camera_pose.py`) → de-light (`delight_albedo.py`) → project + bake+ (`bake_projected_texture.py`). Recipe: `grimoire/character/likeness_maximization.md` (its levers+ generalize from faces to objects). This is what reaches reference fidelity for patterned finishes+ (Doppler / Gamma Doppler / Marble Fade / Fade), and is what the v1.3 baseline demos use. A+ procedural finish for a patterned skin reads visibly wrong beside the reference — that mismatch+ is the #1 CS2 fidelity failure.+- **Procedural per finish style (default ONLY when live view-dependent response matters more than+ matching one reference):** build the finish from independent PBR channels + paint-seed for a real+ environment/anodized response.++**Never** project the raw 2D inventory **icon** as albedo: an icon is a flat render with baked+lighting, no paint-seed, no PBR channels, no environment response; projecting *that* locks in one+wrong, flat-lit pattern. The projection route sidesteps this by **de-lighting first** — the real+distinction is *de-lit reference crop* (the fidelity path) vs *raw flat-lit icon* (banned), NOT+projection vs procedural.++## Identity precedence (who decides the finish style)++`resolve_cs2_finish_style()` (in `forge/stage2_spec/new_sculpt_spec.py`) resolves in order:++1. **explicit descriptor** (`--finish-style`) —+2. **skin name** (`--skin-name`, mapped by `SKIN_NAME_FINISH_HINTS`) —+3. **vision inference** (`--vision-finish-style` + `--vision-confidence`).++A vision read below the confidence threshold (default 0.55) is still used but **flagged**, never+silently dropped. When two sources disagree, the higher-precedence one wins **and the conflict is+written to `preSpecAssessment.unknownsToResolveBeforeImplementation`** — never silently+overwritten. With nothing resolvable, the default is `anodized-multicolored` (the Doppler case the+track exists to fix).++## Finish styles++Eight styles, each with its own PBR recipe and macro/meso/micro `surfaceFrequencyBands`+(`CS2_FINISH_PROFILES`):++| finishStyle | metalness | roughness | view-dependent | note |+|---|---|---|---|---|+| `solid` | low | mid | no | near-uniform lacquer |+| `hydrographic` | low | mid | no | dip-film swirl print |+| `anodized` | high | low | **yes** | dyed metal; colour from reflections |+| `spray-paint` | low | high | no | matte overspray speckle |+| `anodized-multicolored` | high | very low | **yes** | Doppler/Marble-Fade; strong env |+| `custom-paint-job` | low–mid | mid | no | non-tiled illustrative art over dark substrate |+| `patina` | mid | mid | no | oxidation: darkens/hue-shifts with wear |+| `gunsmith` | mid | mid | no | custom-paint ↔ patina mask blend |++**View-dependent** finishes (`anodized`, `anodized-multicolored`) read their colour from+environment reflections. Without an environment map + filmic tonemapping they render muddy — see+*Environment* below.++## Float → wear++`_cs2_wear_mask(float_value)` maps a CS2 float `0.0` (Factory New) … `1.0` (Battle-Scarred) to a+wear mask (albedo-alpha wearness curve + AO bias + curvature-weighted edge scratches/chips), so+scratching concentrates on exposed edges and recesses accumulate grime. Higher float → higher+`edgeWear`, scratches above ~0.15, chips above ~0.55.++With **no float** (image-only default) the mask is an approximated light-moderate condition+estimated from the visible reference and marked `approximated: true` — never presented as an exact+per-item float.++## Paint seed → pattern placement++`_cs2_pattern_affine(paint_seed)` derives a deterministic `A = T2·R·S·T1` affine (rotation ++translation + scale, and the resulting 2×3 matrix) from the seed, so two items sharing a skin but+differing in seed place the pattern differently, and the same seed reproduces identically.++With **no paint seed** (image-only default) a fixed centered placement is used and marked+`approximated: true` — it reproduces the skin's *look*, not a specific item's exact "Max" pattern.+Exact per-item seed matching (community pattern DB / inspect-link) is a deferred follow-up.++## PBR and environment++- **Material**: metallic-roughness `MeshPhysicalMaterial` with independent map channels (never+ alias albedo into roughness/normal/AO). Profiles seed metalness / roughness / clearcoat /+ `envMapIntensity`.+- **Environment (code-generated default)**: `create<Name>Environment(renderer, hdriUrl?)` in the+ generated factory builds a `RoomEnvironment` → `PMREMGenerator` IBL **in code — no bundled image+ asset**, so the image-only path always has one. A user HDRI (`hdriUrl`, via `RGBELoader`) is an+ optional realism upgrade; it falls back to the code-generated default on omission or load+ failure.+- **Renderer**: `configure<Name>Renderer(renderer)` sets `ACESFilmicToneMapping` + `SRGBColorSpace`+ — load-bearing for view-dependent finishes, not cosmetic.+- **Inspect**: `create<Name>InspectControls(camera, domElement)` wraps `OrbitControls` tuned for+ close inspection, because a view-dependent finish only reads correctly in motion.++### The no-environment gate++`validate_cs2_view_dependent_environment()` (in `validate_sculpt_spec.py`) **blocks generation+only** when a `needsEnvironment` material would render with no environment at all — i.e.+`cs2Finish.environmentAvailable` is explicitly `false` (`--no-environment`). Because the+code-generated default always exists otherwise, this is a last-resort guard, **not** the common+path: the flagship image-only Doppler case passes normally.++## Complexity tier & detail floor++A supported CS2 knife skin always carries more identity-defining detail than a generic object+at the same structural tier, so `--cs2` **defaults the complexity tier to `ultra-complex`**+(`targetMinDetails` 16) — the CS2 track is held to the top fidelity bar regardless of how simple+the bare geometry looks. If `--complexity` is set lower by hand, the detail-count floor still+never drops below **9** (see `grimoire/intake/quality_contract.md`).++## Honest ceiling++Image-only reproduces the skin's *look* faithfully but cannot recover a specific item's exact paint+seed / float — the pipeline reports these as approximated rather than implying a byte-exact match.+For exactness, layer in a descriptor or extracted Valve textures+(`grimoire/intake/cs2_texture_acquisition.md`).diff --git a/grimoire/build/geometry_patterns.md b/grimoire/build/geometry_patterns.mdindex b6a9d94..26fe85e 100644--- a/grimoire/build/geometry_patterns.md+++ b/grimoire/build/geometry_patterns.md@@ -136,3 +136,45 @@ A procedural object is usually failing when:**Grip / friction texture = geometric ridge segments.** For a knurled/wrapped/segmented grip, model raised barrel bands: a thin core cylinder + N short attachment-tube segments (radius just *proud* of the core, small groove gaps). Size them barely larger than the core — oversized tori read as a coil/spring, not a grip. Material texture alone (no geometry) reads as smooth/"thô".**`invisibleRoot`/container material is still subject to the material-pass PBR gate.** Give the container a *complete* material (roughness map, frequency bands, textureResolution) — copy a proven one — or it fails "needs usable referencePbr / roughness map" even though it never renders.++---++## Critical Reconstruction Patterns (from Bowie Knife reconstruction failure analysis)++### Failure record: Classic Fade projection passed as structure++The Classic Fade incident exposed open card meshes, constant blade stock, and seams+below the documented overlap. Portable gates now enforce mesh boundaries, seam+overlap, blade grind/distal taper, map-stripped blockout evidence, and ordered pass+credit so each failure is visible at the pass that owns it.++**Blades need a real grind, not constant thickness.** A constant-thickness slab reads as a toy cutout even with perfect silhouette. Model a wedge cross-section tapering to a sharp cutting edge using a grind function:+- For each point on the blade surface, compute height ratio from cutting edge (0) to spine (1)+- Apply a grind curve (smoothstep or power function) to taper thickness: full stock at spine, zero at edge+- For clip-point blades, also thin the false edge near the tip+- Implementation example: Z-warp the projected face plates via a `grindWarp` function that applies `halfThk * grind(height)` per vertex++**Do NOT eyeball proportions — extract 1-to-1 from reference.** Eyeballed shapes (guard, pommel, curves) are consistently wrong. Instead:+- Trace each part's exact outline from the reference image (foreground / colour-masked top & bottom per image column)+- Use a fixed image→world mapping function: `X = (nx - 0.5) * SX`, `Y = (CY - ny) * SY` (adjust SX, SY, CY to your reference dimensions)+- Sample exact colours as RGB medians from reference regions, never guess visually+- Store traced points as coordinate arrays (world space) and use them directly in Shape constructors+- For smooth curves, use `splineThru` through traced points rather than manual control point tuning++**Colours: sample, don't guess.** Visual colour estimation is unreliable. For each material:+- Sample RGB median values from reference regions using image analysis tools+- Convert RGB (0-255) to hex: `0xRRGGBB` where each component is in hex+- Example from Bowie: guard gunmetal (71,74,79) → 0x474a4f, handle gray (140,148,158) → 0x8c949e+- Store these sampled values in comments for traceability and verification++**Parts must physically connect, not just be near each other.** Adjacent components must overlap at their shared seam:+- Check XY overlap between adjacent components (e.g., guard ↔ handle, blade ↔ guard)+- Example bug: guard ended at X=-0.20, handle started at X=-0.42 → gap → "floating" appearance+- Fix: extend one or both shapes so they overlap by at least 0.02-0.05 world units at the seam+- Verify overlap by checking that `partA.end >= partB.start` for each axis where they meet++**Projection core poke-through prevention.** When using photo-projected face plates over a solid core:+- A solid core behind photo-projected face plates bleeds onto the blade face in the grind-transition band+- Keep the core a thin spine rail (top ~18% of blade height) raised well above the red/black boundary+- Translate the core to sit safely inside the plates: `translate(0, 0, -HALF * 0.525)` for ±0.021 plates+- Ensure the core never reaches the red/black boundary or the grind zone so it never shows on the blade facediff --git a/grimoire/feedback/render_capture.md b/grimoire/feedback/render_capture.mdindex 159c254..8b782de 100644--- a/grimoire/feedback/render_capture.md+++ b/grimoire/feedback/render_capture.md@@ -18,6 +18,63 @@ Create a side-by-side review image after capture:The script only aligns and packages evidence. It must not calculate the acceptance score. your agent's vision must inspect `comparison.png`.+---++## Deterministic Viewer for Review (Critical — from Bowie Knife reconstruction)++**The problem:** OrbitControls' per-frame `controls.update()` overrides a scripted `setView`, rendering the object tilted and making screenshots non-deterministic. This breaks comparison integrity.++**Rule:** For review screenshots, the viewer must be deterministic:+- Disable interactive controls before capture: `window.__interactive = false; controls.enabled = false`+- Only enable controls when the user explicitly opts into interaction (e.g., `controls.addEventListener('start', () => { window.__interactive = true; })`)+- In the render loop, only call `controls.update()` when `window.__interactive` is true+- Emulate the exact reference viewport (e.g., 1600×900×1) so the screenshot equals the canvas+- A browser restart resets emulation — be aware of this when comparing across sessions++**Implementation pattern:**+```javascript+const params = new URLSearchParams(location.search);+let spin = params.get('spin') === '1';+window.__interactive = false;+controls.addEventListener('start', () => { window.__interactive = true; });++function loop() {+ requestAnimationFrame(loop);+ if (spin) { model.rotation.y += 0.01; }+ if (window.__interactive) controls.update();+ renderer.render(scene, cam);+ window.__ready = true;+}+```++## Reference Framing Match (Critical — from Bowie Knife reconstruction)++**The problem:** If the render framing (scale/position) doesn't match the reference, Divine Eye scale/aspect hard-gates fail on a framing artifact rather than a real defect. This causes false rejects.++**Rule:** Match framing to the reference, or explicitly account for framing differences:+- Align the model's bounding box to the reference's object extent+- Use a "match" view that scales/positions the camera to approximate the reference framing+- Set the camera position so the object occupies ~98% of the reference width+- If framing cannot match exactly (different aspect ratios, backgrounds), state this in review notes+- Never rely on Divine Eye gates when framing is intentionally different from reference++**Implementation pattern:**+```javascript+const views = {+ front: [0, 0, 14],+ match: [0, 0, 6.5], // framing to match the reference photo extent (~98% width)+ // ...+};+function setView(name) {+ const v = views[name] || views.front;+ cam.up.set(0, 1, 0);+ cam.position.set(v[0], v[1], v[2]);+ cam.lookAt(0, 0, 0);+ controls.target.set(0, 0, 0);+ controls.update();+}+```+Use the same full image pair to score at most five critical semantic features per pass. A feature is a subsystem such as a hull, cabin system, roof system, limb assembly, face, control panel, or sail-and-rigging system. It is not an individual mesh and does not need a separate crop. Score up to three uncertain important features only when adaptive escalation is useful.The starter spec contains generic review targets only as placeholders. Replace them with object-specific systems discovered during pre-spec assessment; otherwise strict quality validation should not pass a moderate or complex object.diff --git a/grimoire/intake/cs2_technical_analysis.md b/grimoire/intake/cs2_technical_analysis.mdnew file mode 100644index 0000000..20a1d38--- /dev/null+++ b/grimoire/intake/cs2_technical_analysis.md@@ -0,0 +1,88 @@+# CS2 Technical Analysis & Reverse-Engineering Protocol++**Role:** You are an Expert 3D Technical Director specialized in CS2 (Counter-Strike 2) weapon and item pipelines.+**Integration:** This protocol operates during Step 1 (Analysis) and Step 3 (Spec Authoring) of the `img2threejs` pipeline.++## Core Mandates (img2threejs Alignment)+1. **No One-Shot Meshes:** Deconstruct the item into logical components. Do not attempt to describe a single blob mesh.+2. **Procedural Geometry + Projected Finish:** For CS2 patterned skins (Doppler, Fade, Crimson Web), the geometry (blade/guard/grip profiles) is procedural, but the *finish* must be planned as a de-lit reference-crop projection. Do not hallucinate procedural noise for complex skins.+3. **Transparent Debugging:** Explicitly name what is visible, what is inferred, and what the single 2D view obscures. If an identity-defining feature cannot be determined, flag it for `request-input`.++## The M.C.M.T Framework for CS2++Analyze the provided orthographic 2D reference images using this exact framework:++* **Macro Shape:** Overall bounding box, primary silhouette taper (e.g., wedge grind of a blade), and axis alignment.+* **Components (CS2 Anatomy):** Strictly divide the item using correct nomenclature: `Blade` (Edge, Spine, Swedge/Clip-point, Ricasso), `Guard/Quillon`, `Handle/Grip` (Scales, Tang), `Pommel`, `Fasteners` (Rivets, Screws).+* **Materials (PBR):** Extract strict Three.js `MeshStandardMaterial` / `MeshPhysicalMaterial` values.+ * Identify if a texture is Solid Paint vs. Anodized Metal vs. Projected Skin.+ * Identify Micro-surface data for Normal maps (e.g., hexagonal grip knurling, spine serrations).+* **Topology:** Define base primitives (Plane, Box, Cylinder) and modifiers (Extrusion profiles, Bevels for edge highlights, Boolean cuts for holes). Do not model micro-details (use normal maps).++## Weathering & Surface Imperfections+CS2 items rely heavily on wear and tear (Float values). Identify:+* **Edge Wear:** Paint chipping on sharp geometry edges exposing base metal.+* **Patina/Rust:** Oxidation changing Base Color, dropping Metalness to `0.0`, and spiking Roughness to `0.8+`.+* **Scratches/Dents:** High-frequency normal map alterations.++## Review hand-off++Use `forge/tests/fixtures/knife_review_scene.json` as the versioned review-scene+contract. It owns the camera, environment hash, exposure, tone mapping, resolution,+background, renderer version, and calibrated knife thresholds. The report from+`forge/stage4_review/cs2_review.py` must preserve family identity, route, exactness+tier, painted-region scores, projection coverage, critical identity-detail scores,+per-region confidence, hidden-region confidence, and approximation notes.++The initial fixture is user-supplied and marked `user-supplied-review-required`+until rights provenance is verified. No extracted Valve texture may be committed or+used to imply an exact-texture result. A single-view result may proceed only when+visible identity features and the two orbit checks pass; hidden regions remain+inferred and confidence-labeled.++---++## Required JSON Output Schema++When instructed to output the CS2 analysis, you MUST return a valid JSON object matching this exact schema. Do not output markdown code blocks wrapping the JSON if writing directly to a file, and do not include conversational text.++{+ "itemClassification": {+ "cs2_type": "Specific weapon/knife type (e.g., Bowie Knife, Karambit)",+ "skin_type": "Identify if Solid, Anodized, or Pattern/Custom Paint (requires projection)",+ "visibility_warnings": "List features obscured by the 2D view (e.g., blade thickness, hidden side symmetry)"+ },+ "threejs_environment": {+ "hdri_required": true,+ "lighting_notes": "Required setup to validate metalness (e.g., strong point light for edge highlights)"+ },+ "featureReviewTargets": [+ "List 3-5 critical identity-defining geometry/material targets for the review gates"+ ],+ "components": [+ {+ "anatomy_part": "e.g., Blade Profile",+ "topology_directives": {+ "primitive": "Base Three.js primitive",+ "construction_rule": "e.g., Extrude 2D shape, apply bevel to cutting edge. Taper Z-thickness towards the tip.",+ "boolean_operations": "e.g., Subtraction for lanyard hole"+ },+ "material_directives": {+ "material_type": "MeshPhysicalMaterial",+ "render_strategy": "procedural | projected_crop",+ "pbr_base": {+ "baseColor": "Hex or descriptor",+ "metalness": 1.0,+ "roughness": 0.15,+ "clearcoat": 0.0+ },+ "normal_map_requirements": "Description of normal map needed (e.g., None, or Hexagonal Grip)"+ },+ "weathering_and_imperfections": {+ "has_wear": true,+ "wear_types": ["Edge Wear", "Scratches"],+ "pbr_overrides": "e.g., Edge wear reveals silver albedo, metalness 1.0, roughness 0.3."+ }+ }+ ]+}diff --git a/grimoire/intake/cs2_texture_acquisition.md b/grimoire/intake/cs2_texture_acquisition.mdnew file mode 100644index 0000000..b7e2ed1--- /dev/null+++ b/grimoire/intake/cs2_texture_acquisition.md@@ -0,0 +1,77 @@+# CS2 Texture Acquisition (optional exactness upgrade)++This is **not** part of the default image-first path. It is an optional Tier-3 upgrade for exact+texture likeness, driven autonomously by the host agent from the **user's own legal CS2 install**.+The user performs no manual step beyond, at most, pointing at the install / VPK path. If nothing is+found the agent falls back to the image-only reconstruction — it never fabricates a wrong render.++**IP boundary (hard rule):** extracted textures are Valve IP. They stay in the local, gitignored+`cs2_textures/` workspace and are **never** committed or redistributed. The MIT repo ships code+only. `.gitignore` excludes `cs2_textures/`; a test asserts nothing under it is+tracked.++## Steps++### 1. Metadata (optional, no install needed) — `forge/stage1_intake/fetch_cs2_metadata.py`++Resolve the skin's paint index, float range, rarity, and CDN image URL from the public CSGO-API+skins index (`--index-file` local, or `--index-url` live). The index is the community-maintained+[`ByMykel/CSGO-API`](https://github.com/ByMykel/CSGO-API) `skins.json` — fetch it straight from+GitHub during a run (metadata only; not Valve's texture files):++```+# live from GitHub (jsDelivr CDN — pin @<tag-or-commit> for reproducible runs, not @main)+fetch_cs2_metadata.py --weapon Karambit --skin Doppler --paint-index 419 \+ --index-url "https://cdn.jsdelivr.net/gh/ByMykel/CSGO-API@main/public/api/en/skins.json" \+ --out metadata.json++# or fully offline from a saved copy+fetch_cs2_metadata.py --weapon Karambit --skin Doppler --phase "Phase 2" \+ --index-file skins.json --out metadata.json+```++A no-match or an ambiguous multi-match is an **error** (nonzero exit), never a silent guess. Add+`--phase` to disambiguate by name — **but** this dataset lists every Doppler phase under the *same*+name (`★ Karambit | Doppler`), differing only by `paint_index`; there, `--phase` can't help and the+ambiguity error lists each candidate's `paint_index` so you can re-run with `--paint-index N`+(e.g. `419` = Phase 2). This gives the precise paint index for a Tier-2 descriptor even without+extracting textures.++> Reproducibility & IP: `@main` is a moving target — pin a commit/tag for deterministic runs. The+> metadata and the `image` preview (Steam CDN) are community data; Valve's actual paint textures are+> **not** distributed via this source (use the local VPK path below, and never commit `cs2_textures/`).++### 2. Locate the VPK — `forge/stage1_intake/locate_cs2_vpk.py`++```+locate_cs2_vpk.py --json # or --root <steam-root> (repeatable) to override+```++Searches the per-OS default Steam roots (override or add more with repeatable `--root`) for+`.../Counter-Strike Global Offensive/game/csgo/pak01_dir.vpk`. Best-effort and non-fatal:+prints `{"found": false, ...}` and exits 1 when nothing is located (never raises). `--root` is+dependency-injectable for offline testing.++### 3. Extract + classify — `forge/stage1_intake/extract_cs2_textures.py`++Requires `Source2Viewer-CLI` on `PATH` (which needs the .NET runtime). Assert availability first,+then extract into the gitignored workspace and bucket the output maps by filename convention+(`color` / `normal` / `roughness_metalness` / `mask` / `other`):++```+extract_cs2_textures.py --out cs2_textures --json # --vpk <path> to skip locating+```++On any failure — no VPK, missing binary, subprocess error, or non-zero exit — it returns+`{"status": "fallback", "reason": ...}` and exits 1, so the pipeline degrades to the image-only+path with an explicit notice that exact texture likeness is unavailable. On `Source2Viewer-CLI`+flag drift, consult its `--help` and adapt the wrapped call in `run_source2viewer()`; if it still+fails, report and fall back rather than guessing.++## Using the result++Feed the classified maps into the finish material's PBR channels (color → albedo, normal → normal,+packed → roughness/metalness, mask → wear/pattern) to raise fidelity above the procedural+image-only recipe. The finish-style machinery (PBR ranges, environment, wear) in+`grimoire/build/cs2_finishes.md` still applies — it drives *realism* independent of whether exact+textures were acquired.diff --git a/grimoire/intake/image_analysis.md b/grimoire/intake/image_analysis.mdnew file mode 100644index 0000000..913e028--- /dev/null+++ b/grimoire/intake/image_analysis.md@@ -0,0 +1,124 @@+# Image Analysis Protocol++Use this reference **first**, before `probe_image.py` and before the pre-spec assessment. It+exists because the agent tends to glance at the whole image once and jump straight to code,+skipping the disciplined observation that every later gate depends on. This is a **generic,+object-agnostic** protocol — it applies to any subject (prop, tool, weapon, vehicle part,+botanical, mechanical, character). Domain tracks (CS2 skins, characters) are specializations+layered *after* this pass, not replacements for it.++## The Rule++Describe what is **there**, in a fixed bottom-up order, using controlled 3D vocabulary — not+what it *means* or how it *feels*. Three disciplines carry the whole protocol:++1. **Observation before inference.** State the observable fact ("a low-roughness band along the+ spine") separately from what you infer from it ("probably a polished bevel"). Mark every+ inference as inference.+2. **Controlled vocabulary over adjectives.** Use the terms below and in+ `grimoire/glossary/3d_vocabulary.md`. Never "nice / sleek / aggressive / high-quality".+3. **3D object-space, not 2D image-space.** Describe parts by front/back/lateral/proximal, not+ left/right-of-the-photo. A single photo is a projection — say what perspective hides.++Run the layers in order; each feeds a real assessment field (mapping at the end). The output of+this protocol IS the raw material for `new_pre_spec_assessment.py` and `build_detail_inventory.py`.++## Layer 1 — Identification & classification++- **Observe:** what the object *is*, its category, and your confidence. Complete a physical+ inventory before any claim about value/purpose.+- **Vocabulary:** work type (a specific noun — *statuette, karambit, socket wrench, rhyton*),+ broad classification (*bladed tool, furnishing, mechanical part*), `primaryDomain`+ (`object` | `character` | `hybrid`), confidence 0–1.+- **Avoid:** using the object's *title/name* as the description; asserting meaning before the+ inventory; indexing beyond the visible evidence.++## Layer 2 — Overall form & silhouette++- **Observe:** the bounding volume and footprint as a small set of primitives; symmetry.+- **Vocabulary:** primitives (*cuboid, cylinder, sphere, cone, extruded profile, lofted curve*);+ symmetry (*bilateral, radial, asymmetric*); shape language (*geometric* vs *organic*);+ aspect/proportion relative to a named reference dimension.+- **Avoid:** emotive shape words; "large/small" with no reference; forcing an organic form into+ one primitive when it is a blend.++## Layer 3 — Macro → meso → micro decomposition++- **Observe:** the whole broken into major assemblies, then sub-parts, then surface-level+ feature groups — a `parent-child` hierarchy for component-based modelling.+- **Vocabulary:** macro (independent major parts — *blade, grip, guard*), meso (sub-assemblies —+ *rivet row, finger choil, pommel*), micro (feature groups — *fastener cluster, engraving band*).+- **Avoid:** treating the object as one monolithic mesh; over-nesting a simple structure; skipping+ a level (jumping macro → micro with no meso).++## Layer 4 — Spatial relationships (scene-graph)++- **Observe:** how parts connect and sit relative to each other, in 3D.+- **Vocabulary:** visual triplets `<subject, predicate, object>` (`<guard, separates, blade+grip>`);+ spatial predicates *attached-to, above, below, inside, behind, flush-with, embedded-in*; each+ connection notes a contact type (*butt, overlap, socket, embed*).+- **Avoid:** 2D image-space placement (left/right of frame); describing adjacency without stating+ how the parts actually join (mid-air parts break the attachment gate later).++## Layer 5 — Materials & surface (PBR)++- **Observe:** the substance of each part and how it responds to light. One material claim per+ distinct surface, tied to a component.+- **Vocabulary:** *albedo/base color* (surface color with lighting removed), *metalness*+ (0 dielectric / 1 raw metal), *roughness* (0 polished → 1 matte), *specular F0* (~4% for+ dielectrics), *normal/relief* (*pitting, grain, pores, brushing*), *translucency*+ (*opaque / semi-translucent / transparent*).+- **Avoid:** reading baked-in highlights/shadows as albedo; calling shiny plastic "metal";+ aliasing one channel into another (see `grimoire/feedback/shading_realism.md`).++## Layer 6 — Color & finish++- **Observe:** hue, value, saturation per region; the surface finish.+- **Vocabulary:** *hue / value / saturation*; finish *matte, satin, gloss, metallic, anodized*;+ gradients as ordered stops with positions, not "fades to".+- **Avoid:** subjective/brand color names ("royal blue") instead of standard descriptors+ ("vivid blue, mid value"); one flat color where a gradient or multi-tone finish exists.++## Layer 7 — Identity-defining features++- **Observe:** the marks that make *this* item recognizable, not a generic member of its class.+- **Vocabulary:** inscriptions/marks (signatures, dates, logos, serials), wear patterns+ (*scratch, dent, oxidation/patina, stain, edge-wear*), recurring motifs.+- **Avoid:** overlooking small but critical identifiers (a maker's mark, a unique gouge that+ changes topology). Each identity feature should become a `detailInventory` entry and, if it+ can be wrong, a `featureReviewTarget`.++## Layer 8 — Uncertainty & single-image limits++- **Observe:** what the one view does not show; what is blurry or ambiguous.+- **Vocabulary:** *occluded* (blocked by another part), *hidden* (back-face / interior, not in+ this view), *uncertain* (blurry/ambiguous), *needs another view*, *undetermined*.+- **Avoid:** hallucinating occluded/hidden detail without flagging it speculative; ignoring+ perspective distortion. Every unknown here becomes a+ `preSpecAssessment.unknownsToResolveBeforeImplementation` entry and may justify `request-input`.++## Output → where each layer lands++| Layer | Feeds |+|---|---|+| 1 identification | `objectClass.primaryType` / `primaryDomain`, complexity classification |+| 2 form & silhouette | complexity tier, geometry strategy, `referenceCamera` framing |+| 3 macro/meso/micro | `componentTree` levels + `minimumSpecDepth` |+| 4 spatial relationships | `attachment` (parentSocket, contactType, embed/overlap) |+| 5 materials & surface | `materials` PBR channels + `material.localOverrides` |+| 6 color & finish | `colorMaterialRecipe`, gradient stops, `finishStyle` |+| 7 identity features | `detailInventory` details + `featureReviewTargets` |+| 8 uncertainty | `unknownsToResolveBeforeImplementation`, `request-input` decision |++## Domain specializations (apply after this pass)++This generic pass runs for every subject. When Layer 1 identifies a specialized domain, layer its+extra rules on top **without** skipping any generic layer:++- **CS2 weapon/knife/glove skins** → `grimoire/build/cs2_finishes.md` (finish style, float, paint+ seed, view-dependent environment) and `grimoire/intake/cs2_texture_acquisition.md`.+- **Characters / hybrids** → `grimoire/character/reconstruction.md` (head-units, landmarks,+ proportion lock).++The generic protocol decides *what is there*; the domain doc decides *how that class is+conventionally parameterized*.diff --git a/grimoire/intake/quality_contract.md b/grimoire/intake/quality_contract.mdindex 22e9951..c0a4932 100644--- a/grimoire/intake/quality_contract.md+++ b/grimoire/intake/quality_contract.md@@ -35,6 +35,17 @@ Map total judgment to:- `complex`: many parts, repeated systems, multiple materials, several hierarchy levels- `ultra-complex`: dense organic/mechanical/architectural structure where fidelity depends on deep hierarchy and repeated microstructure+### CS2 items: ultra-complex by default++A CS2 weapon/knife/glove skin always carries more identity-defining detail (finish/gradient+pattern, wear layer, hardware, stitching, fasteners, engraving) than a generic object at the+same structural complexity tier — the skin *is* the point of the item. So `--cs2` **defaults+the complexity tier to `ultra-complex`** (`targetMinDetails` 16): the CS2 track is held to the+top fidelity bar regardless of how simple the bare geometry looks, and `--strict-quality` then+blocks code generation until those details are enumerated. If `--complexity` is set lower by+hand, `targetMinDetails` still never drops below the **9** floor. Pass `--cs2` to+`forge/stage2_spec/new_pre_spec_assessment.py` to apply this automatically.+## Quality ContractBefore generating code, define exactly what makes the model good enough:diff --git a/grimoire/intake/validation_rubric.md b/grimoire/intake/validation_rubric.mdindex 64292a1..a66fc16 100644--- a/grimoire/intake/validation_rubric.md+++ b/grimoire/intake/validation_rubric.md@@ -64,3 +64,24 @@ For objects with many details, require:- evidence refs to image regionsIf these cannot be inferred from the image, mark the spec `conditional` and list missing views or close-ups.++---++## CS2 Item Identity and References (Critical — from Bowie Knife reconstruction)++**The problem:** `--cs2` only sets the difficulty tier; it does NOT fetch metadata or official references. Assuming stock features from skin names leads to wrong geometry (e.g., assuming "no stock Bowie has sawback" when the vanilla render proves it does).++**Rule:** Get the item's real market name/identity EARLY, and pull official references FIRST before authoring geometry:++1. **Ask the user for the exact market name** up front (e.g., "Autotronic" not just "Bowie Knife with red/black finish")+2. **Use `fetch_cs2_metadata.py`** to resolve paint index + official CDN render + confirm the skin exists+3. **Fetch official + vanilla renders** before authoring geometry — these show the base model features (sawback, clip point, tang, guard style) that skin names don't reveal+4. **Never infer stock features from skin names alone** — the vanilla render is the source of truth for base model geometry++**Reference sources:** Official CS2 CDN renders, vanilla (factory new) renders, and any official artwork provided by the user. Side-view orthographic reference images are ideal for profile extraction; 3/4 angle renders help verify form and materials.++**Verification:** Before writing geometry, confirm you have:+- Exact item name (market name, not description)+- Official vanilla render (to see base model features)+- Official skin render (to see finish/pattern)+- Any orthographic side views if availablediff --git a/grimoire/review/self_correction.md b/grimoire/review/self_correction.mdindex c3f9e2d..6b9a582 100644--- a/grimoire/review/self_correction.md+++ b/grimoire/review/self_correction.md@@ -85,3 +85,23 @@ The proper fix is a Divine-Eye **reconstruction mode** (reference==photo ⇒ drowhen a photo-vs-procedural render fails *only* the IoU hard gate but objectness says "same object"(≥0.48), it downgrades the confident reject to `probe` and sets `reconstructionModeSuspected:true`. So theEye no longer hard-rejects a faithful reconstruction on framing alone — but still never auto-passes it.++---++## 2D Gates Are Blind to 3D Realism (Critical — from Bowie Knife reconstruction)++**The problem:** 2D visual gates (Divine Eye, diagnose_render) only measure silhouette + colour + tone. They cannot see:+- Edge sharpness (a constant-thickness slab reads as a toy cutout even with perfect silhouette)+- Cross-section thickness (blade grind, taper, bevel quality)+- Material realism (metal vs plastic reflection, surface texture response)+- True 3D form beyond the silhouette plane++**Consequence:** A strict-PASS at fidelity 0.83 can still read as a flat toy in a three-quarter render.++**Rule:** NEVER report a 2D-gate PASS as "done". Always judge 3D realism on a three-quarter render, and explicitly state what the gate does/doesn't measure in your review notes. When a gate passes but the 3D render looks wrong, the gate measurement was insufficient — not the reconstruction.++**Verification cues:** A procedural object is failing 3D realism when:+- The silhouette matches but edges are perfectly sharp/flat (no grind, taper, or bevel)+- Material has correct color but wrong surface response (plastic when should be metal, etc.)+- Reference depth cues (grind transitions, material thickness, edge bevels) are missing or flat+- The gate score is high but the object reads as "toy-like" or "cardboard" in angled viewsdiff --git a/skills/cs2-knife.md b/skills/cs2-knife.mdnew file mode 100644index 0000000..df63494--- /dev/null+++ b/skills/cs2-knife.md@@ -0,0 +1,174 @@+Create a high-fidelity procedural Three.js 3D reconstruction of:++ ★ Classic Knife | Fade+ Wear condition: Minimal Wear+ Item family: knife+ Subtype: classic-knife++ The goal is maximum observable agreement with the supplied reference images,+ including:++ - blade silhouette and proportions;+ - spine, cutting edge, tip and bevel profile;+ - guard, handle, pommel and hardware placement;+ - metal base colour and exposed metal;+ - Fade colour gradient, transition zones and pattern placement;+ - roughness, metallic response, clearcoat and edge wear;+ - front/back consistency;+ - camera framing and object orientation.++ The FRONT and BACK images below are the only visual ground truth. Treat them as+ two views of the same physical item, not as separate objects.++ Workflow:++ 1. Validate both images before reconstruction.+ - Check that both images contain the same knife.+ - Check for duplicate views, unreadable regions, cropping, empty background+ and inconsistent scale.+ - Record the role of each image as `front` or `back`.++ 2. Analyze the images before authoring geometry.+ - Separate observation from inference.+ - Identify visible geometry, material regions, wear, lighting artifacts and+ hidden areas.+ - Do not use the filename, skin name or prior model as a substitute for image+ evidence.++ 3. Build one geometry contract from both views.+ - Reconcile front and back silhouette, proportions and orientation.+ - Use a dedicated Classic Knife adapter.+ - Do not substitute a Bayonet, Karambit, Navaja, Flip Knife or generic knife+ model.+ - Do not use a generic knife tree when a Classic Knife-specific detail is+ visible.++ 4. Build the surface/material contract.+ - Separate blade coating, exposed metal, handle, guard, hardware and wear+ regions.+ - Preserve the actual Fade colour placement from the images.+ - Use de-lit reference projection for the visible pattern whenever+ technically possible.+ - Do not replace the observed Fade pattern with a generic procedural gradient+ unless projection is unavailable.+ - Keep albedo, roughness, metalness, normal/height, AO, mask and wear as+ independent channels.+ - Never reuse albedo as roughness, normal, AO or metalness.++ 5. Handle missing evidence honestly.+ - Do not invent paint seed, float value, UV layout or unseen-side details.+ - Mark hidden or inferred geometry with per-region confidence.+ - If the two views are insufficient to resolve an important feature, return+ `request-input`.+ - Do not claim exact geometry or exact texture where the images do not+ provide evidence.++ 6. Exactness policy:+ - If only the two images are available, use `exactnessTier: image-only`.+ - If the skin name is verified with reliable metadata but exact paint seed/+ float/texture maps are unavailable, use `exactnessTier: metadata-assisted`.+ - Use `exactnessTier: exact-texture` only when exact texture maps and valid+ provenance are available.+ - Knowing the skin name alone is not enough for `exact-texture`.+ - Keep `route` and `exactnessTier` independent.+ - If projection falls back to procedural-finish, preserve the original+ evidence tier and record the approximation warning.++ 7. Existing project context:+ - You may inspect `builds/` and `runtime/cs2-preview/` to understand+ available implementation layers.+ - Treat those directories as implementation context only.+ - Do not copy their geometry, materials, colours, proportions or fixture data+ when they conflict with the uploaded images.+ - Do not treat an existing preview fixture as evidence that the+ reconstruction is correct.+ - The uploaded FRONT and BACK images always have priority.++ 8. Review requirements:+ - Render a fixed view aligned to the primary reference view.+ - Render at least two meaningful orbit views.+ - Reject degenerate views where the model is only a flat plane.+ - Review silhouette, proportions, material response, Fade placement, wear and+ hardware separately.+ - A good global score must not override a failed critical feature.++ 9. Final report must include:+ - geometry features matched;+ - material and colour features matched;+ - front/back consistency;+ - inferred or hidden regions;+ - approximation notes;+ - selected route;+ - exactness tier;+ - unresolved differences;+ - recommended next action: `continue`, `refine-spec`, `refine-code`,+ `request-input`, or `stop`.++ Do not claim that the model is exact unless the evidence supports that claim.++ FRONT IMAGE:+ FRONT IMAGE: [Image #2]++ BACK IMAGE: [Image #3]+[Image #2]+[Image #3]++I'll start by loading the img2threejs skill, which is purpose-built for this task.++ technically possible.+ - Do not replace the observed Fade pattern with a generic procedural gradient+ unless projection is unavailable.+ - Keep albedo, roughness, metalness, normal/height, AO, mask and wear as+ independent channels.+ - Never reuse albedo as roughness, normal, AO or metalness.++ 5. Handle missing evidence honestly.+ - Do not invent paint seed, float value, UV layout or unseen-side details.+ - Mark hidden or inferred geometry with per-region confidence.+ - If the two views are insufficient to resolve an important feature, return+ `request-input`.+ - Do not claim exact geometry or exact texture where the images do not+ provide evidence.++ 6. Exactness policy:+ - If only the two images are available, use `exactnessTier: image-only`.+ - If the skin name is verified with reliable metadata but exact paint seed/+ float/texture maps are unavailable, use `exactnessTier: metadata-assisted`.+ - Use `exactnessTier: exact-texture` only when exact texture maps and valid+ provenance are available.+ - Knowing the skin name alone is not enough for `exact-texture`.+ - Keep `route` and `exactnessTier` independent.+ - If projection falls back to procedural-finish, preserve the original+ evidence tier and record the approximation warning.++ 7. Existing project context:+ - You may inspect `builds/` and `runtime/cs2-preview/` to understand+ available implementation layers.+ - Treat those directories as implementation context only.+ - Do not copy their geometry, materials, colours, proportions or fixture data+ when they conflict with the uploaded images.+ - Do not treat an existing preview fixture as evidence that the+ reconstruction is correct.+ - The uploaded FRONT and BACK images always have priority.++ 8. Review requirements:+ - Render a fixed view aligned to the primary reference view.+ - Render at least two meaningful orbit views.+ - Reject degenerate views where the model is only a flat plane.+ - Review silhouette, proportions, material response, Fade placement, wear and+ hardware separately.+ - A good global score must not override a failed critical feature.++ 9. Final report must include:+ - geometry features matched;+ - material and colour features matched;+ - front/back consistency;+ - inferred or hidden regions;+ - approximation notes;+ - selected route;+ - exactness tier;+ - unresolved differences;+ - recommended next action: `continue`, `refine-spec`, `refine-code`,+ `request-input`, or `stop`.++ Do not claim that the model is exact unless the evidence supports that claim.\ No newline at end of filediff --git a/skills/cs2-pistol.md b/skills/cs2-pistol.mdnew file mode 100644index 0000000..3da67be--- /dev/null+++ b/skills/cs2-pistol.md@@ -0,0 +1,35 @@+reate a high-fidelity procedural Three.js 3D reconstruction of:++ ★ Glock-18 | Ghost Protocol+ Wear condition: Well-Worn+ Item family: weapon+ Subtype: glock-18++ The goal is maximum observable agreement with the supplied FRONT and BACK reference images, covering:+ - Slide silhouette, frame/grip ergonomics, ejection port, trigger guard, and internal barrel/breech geometry.+ - Sights, trigger shoe, safety blade, magazine extension, and pin placement.+ - Translucent red polymer PBR parameters (transmission, IOR, thickness, internal occlusion), metallic breech block response, and surface abrasions.+ - Ghost Protocol cybernetic circuit linework, decal positioning ("GHOST (*)", "PROTOCOL", ">_"), and refraction placement.+ - Front/back consistency, camera framing, and 3D orientation.++ Treat the provided FRONT and BACK images as two views of the same physical item.++ ### Workflow & Protocol:++ 1. Image Validation: Verify front/back alignment, scale consistency, readable resolution, and reject inconsistent/duplicate inputs.+ 2. Layered Observation: Isolate visible polymer frame, PBR transmission, visible internal sub-meshes, and wear features. Separate observation from inference.+ 3. Geometry Contract: Reconcile front/back silhouettes using a dedicated glock-18 adapter (never substitute generic pistol models).+ 4. Material Contract: Use de-lit reference projection for translucent shell linework and decals. Keep PBR channels (Albedo, Transmission, Roughness, Metalness, Normal, AO) strictly independent.+ 5. Evidence Honesty: Mark hidden internal geometry with per-region confidence scores. Return `request-input` if crucial features are ambiguous.+ 6. Exactness Tiers:+ - `image-only`: Derived strictly from the 2D reference images.+ - `metadata-assisted`: Verified skin/float metadata without raw texture maps.+ - `exact-texture`: Full raw texture maps and provenance available.+ 7. Context Priority: The uploaded FRONT and BACK images strictly override any existing preview fixtures or legacy code in `builds/`.+ 8. Review Gates: Render fixed reference view + ≥2 orbit views. Reject degenerate flat planes. A high global score cannot bypass a failed critical feature.+ 9. Output Report: Provide matched geometry/material features, front/back consistency, exactness tier, and recommended action (`continue` | `refine-spec` | `refine-code` | `request-input` | `stop`).++ FRONT: [Image #9]+ BACK: [Image #10]++ Do not claim that the model is exact unless the evidence supports that claim.\ No newline at end of filediff --git a/skills/cs2_technical_analysis.md b/skills/cs2_technical_analysis.mdnew file mode 100644index 0000000..59afe6e--- /dev/null+++ b/skills/cs2_technical_analysis.md@@ -0,0 +1,36 @@+You are an Expert 3D Technical Director specialized in CS2 (Counter-Strike 2) weapon and item pipelines. Your task is to analyze orthographic 2D reference images of an item and reverse-engineer it into a strict technical blueprint for rendering in Three.js.++Analyze the image using the M.C.M.T (Macro, Components, Materials, Topology) framework and identify Surface Imperfections (Wear and Tear).++Output ONLY a valid JSON object. Do not include markdown formatting like ```json or any conversational text.++The JSON MUST follow this exact schema:+{+ "item_id": "Classify the item (e.g., Bowie Knife, Karambit, AK-47)",+ "threejs_environment": {+ "hdri_required": true/false,+ "lighting_notes": "Specific lighting setup required to showcase the materials"+ },+ "components": [+ {+ "anatomy_part": "Precise name of the part (e.g., Blade Edge, Spine, Pommel, Handle Scales)",+ "geometry_directives": {+ "primitive_shape": "Base shape (Plane, Box, Cylinder)",+ "topology_rules": "Instructions for extrusions, bevels, or boolean cuts",+ "thickness_estimation": "Relative thickness description"+ },+ "threejs_material": {+ "material_type": "MeshStandardMaterial or MeshPhysicalMaterial",+ "baseColor": "Hex code or precise color description",+ "metalness": Float (0.0 to 1.0),+ "roughness": Float (0.0 to 1.0),+ "normal_map_details": "Describe micro-surface details like serrations or grips to be baked into normals"+ },+ "weathering_and_imperfections": {+ "has_wear": true/false,+ "wear_type": "e.g., Edge Wear, Rust, Scratches, Blood Stains",+ "pbr_overrides": "How the wear alters PBR (e.g., Rust drops metalness to 0.0 and raises roughness to 0.9)"+ }+ }+ ]+}diff --git a/skills/generic-extract-skill.md b/skills/generic-extract-skill.mdnew file mode 100644index 0000000..470ea58--- /dev/null+++ b/skills/generic-extract-skill.md@@ -0,0 +1,14 @@+You are an Autonomous 3D Technical Artist Agent. Your core skill is Reverse-Engineering 2D images into a strict 3D production blueprint.++Regardless of what object is in the reference images, you must autonomously analyze it using the M.C.M.T framework (Macro, Components, Materials, Topology) and output a precise JSON structure.++Do not describe the object creatively. Act as a sensory node extracting physical and lighting properties.++Follow these generic rules for your analysis:+1. Identify all logically separate sub-meshes (Components).+2. For every component, estimate its PBR values (Base Color Hex, Metalness 0.0-1.0, Roughness 0.0-1.0).+3. Identify micro-surface details (scratches, patterns, text) and assign them to the Normal/Bump map category, strictly advising against modeling them as geometry.+4. Define the primitive shapes (Cube, Cylinder, Sphere, Plane) that form the base of each component.+5. Identify areas requiring specific Boolean operations (holes, cutouts) or Hard-Edge normals (sharp corners).++Return ONLY the JSON.