vibedgames 0.10.1 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/assets/rebuild-object/.cache/spec-search/core_3d.json +1 -0
  2. package/assets/rebuild-object/.cache/spec-search/cs2.json +1 -0
  3. package/assets/rebuild-object/LICENSE +201 -0
  4. package/assets/rebuild-object/NOTICE +7 -0
  5. package/assets/rebuild-object/docs/materials/material-reference.json +2324 -0
  6. package/assets/rebuild-object/docs/specs/render-profile.v2.example.json +63 -0
  7. package/assets/rebuild-object/docs/specs/render-profile.v2.schema.json +56 -0
  8. package/assets/rebuild-object/docs/specs/vocabulary/README.md +86 -0
  9. package/assets/rebuild-object/docs/specs/vocabulary/core_3d.jsonl +12 -0
  10. package/assets/rebuild-object/docs/specs/vocabulary/core_3d_reconstruction.jsonl +37 -0
  11. package/assets/rebuild-object/docs/specs/vocabulary/cs2.jsonl +8 -0
  12. package/assets/rebuild-object/docs/specs/vocabulary/cs2_reconstruction.jsonl +62 -0
  13. package/assets/rebuild-object/forge/_shared/artifact_cache.py +54 -0
  14. package/assets/rebuild-object/forge/_shared/chirality.py +272 -0
  15. package/assets/rebuild-object/forge/_shared/color_metrics.py +107 -0
  16. package/assets/rebuild-object/forge/_shared/feature_acceptance_policy.py +113 -0
  17. package/assets/rebuild-object/forge/_shared/image_hash.py +113 -0
  18. package/assets/rebuild-object/forge/_shared/jpeg.py +448 -0
  19. package/assets/rebuild-object/forge/_shared/material_physics.py +253 -0
  20. package/assets/rebuild-object/forge/_shared/pipeline_routing.py +177 -0
  21. package/assets/rebuild-object/forge/_shared/scalp_field.py +302 -0
  22. package/assets/rebuild-object/forge/_shared/sdf_primitives.py +172 -0
  23. package/assets/rebuild-object/forge/_shared/spec_search.py +1792 -0
  24. package/assets/rebuild-object/forge/_shared/spec_search_profiles.json +58 -0
  25. package/assets/rebuild-object/forge/_shared/status_banner.py +35 -0
  26. package/assets/rebuild-object/forge/_shared/subdivision.py +232 -0
  27. package/assets/rebuild-object/forge/_shared/vertex_paint.py +236 -0
  28. package/assets/rebuild-object/forge/_shared/workflow_state.py +406 -0
  29. package/assets/rebuild-object/forge/materials/__init__.py +17 -0
  30. package/assets/rebuild-object/forge/materials/compatibility.py +106 -0
  31. package/assets/rebuild-object/forge/materials/reference.py +240 -0
  32. package/assets/rebuild-object/forge/next.py +116 -0
  33. package/assets/rebuild-object/forge/report.py +38 -0
  34. package/assets/rebuild-object/forge/requirements.txt +6 -0
  35. package/assets/rebuild-object/forge/stage1_intake/analyze_texture.py +255 -0
  36. package/assets/rebuild-object/forge/stage1_intake/bind_detail_properties.py +99 -0
  37. package/assets/rebuild-object/forge/stage1_intake/build_detail_inventory.py +349 -0
  38. package/assets/rebuild-object/forge/stage1_intake/camera_fitting_math.py +133 -0
  39. package/assets/rebuild-object/forge/stage1_intake/camera_fitting_solver.py +197 -0
  40. package/assets/rebuild-object/forge/stage1_intake/camera_fitting_types.py +291 -0
  41. package/assets/rebuild-object/forge/stage1_intake/camera_image_helpers.py +133 -0
  42. package/assets/rebuild-object/forge/stage1_intake/check_intake_correctness.py +116 -0
  43. package/assets/rebuild-object/forge/stage1_intake/check_reference_admission.py +203 -0
  44. package/assets/rebuild-object/forge/stage1_intake/cs2_foundation.py +139 -0
  45. package/assets/rebuild-object/forge/stage1_intake/cs2_manifest.py +230 -0
  46. package/assets/rebuild-object/forge/stage1_intake/cs2_review_contract.py +42 -0
  47. package/assets/rebuild-object/forge/stage1_intake/delight_albedo.py +352 -0
  48. package/assets/rebuild-object/forge/stage1_intake/detect_cs2.py +276 -0
  49. package/assets/rebuild-object/forge/stage1_intake/detect_reference_effects.py +275 -0
  50. package/assets/rebuild-object/forge/stage1_intake/extract_cs2_textures.py +126 -0
  51. package/assets/rebuild-object/forge/stage1_intake/extract_gradient_stops.py +149 -0
  52. package/assets/rebuild-object/forge/stage1_intake/extract_hair_evidence.py +385 -0
  53. package/assets/rebuild-object/forge/stage1_intake/extract_landmarks.py +456 -0
  54. package/assets/rebuild-object/forge/stage1_intake/extract_part_color_recipe.py +496 -0
  55. package/assets/rebuild-object/forge/stage1_intake/extract_pbr_evidence.py +843 -0
  56. package/assets/rebuild-object/forge/stage1_intake/fetch_cs2_metadata.py +147 -0
  57. package/assets/rebuild-object/forge/stage1_intake/label_glb_nodes.py +318 -0
  58. package/assets/rebuild-object/forge/stage1_intake/locate_cs2_vpk.py +73 -0
  59. package/assets/rebuild-object/forge/stage1_intake/material_region_analysis.py +227 -0
  60. package/assets/rebuild-object/forge/stage1_intake/probe_glb.py +357 -0
  61. package/assets/rebuild-object/forge/stage1_intake/probe_image.py +168 -0
  62. package/assets/rebuild-object/forge/stage1_intake/run_vision_adapter.py +45 -0
  63. package/assets/rebuild-object/forge/stage1_intake/search_specs.py +258 -0
  64. package/assets/rebuild-object/forge/stage1_intake/semantic_decomposition.py +119 -0
  65. package/assets/rebuild-object/forge/stage1_intake/solve_camera_pose.py +254 -0
  66. package/assets/rebuild-object/forge/stage2_spec/apply_material_analysis.py +192 -0
  67. package/assets/rebuild-object/forge/stage2_spec/cs2_adapters.py +62 -0
  68. package/assets/rebuild-object/forge/stage2_spec/derive_geometry.py +118 -0
  69. package/assets/rebuild-object/forge/stage2_spec/hair_profile.py +306 -0
  70. package/assets/rebuild-object/forge/stage2_spec/humanoid_proportions.py +214 -0
  71. package/assets/rebuild-object/forge/stage2_spec/new_pre_spec_assessment.py +343 -0
  72. package/assets/rebuild-object/forge/stage2_spec/new_sculpt_spec.py +2396 -0
  73. package/assets/rebuild-object/forge/stage2_spec/validate_sculpt_spec.py +2871 -0
  74. package/assets/rebuild-object/forge/stage3_build/bake_projected_texture.py +181 -0
  75. package/assets/rebuild-object/forge/stage3_build/decimate.py +272 -0
  76. package/assets/rebuild-object/forge/stage3_build/generate_threejs_factory.py +4099 -0
  77. package/assets/rebuild-object/forge/stage3_build/module_cache.py +155 -0
  78. package/assets/rebuild-object/forge/stage3_build/morph_targets.py +178 -0
  79. package/assets/rebuild-object/forge/stage3_build/orchestrate_passes.py +653 -0
  80. package/assets/rebuild-object/forge/stage3_build/uv_unwrap.py +622 -0
  81. package/assets/rebuild-object/forge/stage3_build/visual_hull.py +357 -0
  82. package/assets/rebuild-object/forge/stage4_review/_fit_divine_eye.py +64 -0
  83. package/assets/rebuild-object/forge/stage4_review/append_review.py +453 -0
  84. package/assets/rebuild-object/forge/stage4_review/attachment_anchor.py +349 -0
  85. package/assets/rebuild-object/forge/stage4_review/calibrate_eye.py +131 -0
  86. package/assets/rebuild-object/forge/stage4_review/check_part_coverage.py +298 -0
  87. package/assets/rebuild-object/forge/stage4_review/compare_region_passes.py +169 -0
  88. package/assets/rebuild-object/forge/stage4_review/correction_loop.py +258 -0
  89. package/assets/rebuild-object/forge/stage4_review/cs2_review.py +224 -0
  90. package/assets/rebuild-object/forge/stage4_review/diagnose_render.py +356 -0
  91. package/assets/rebuild-object/forge/stage4_review/diagnose_render_multi_angle.py +143 -0
  92. package/assets/rebuild-object/forge/stage4_review/divine_eye.py +461 -0
  93. package/assets/rebuild-object/forge/stage4_review/fit_params.py +381 -0
  94. package/assets/rebuild-object/forge/stage4_review/geometry_integrity.py +294 -0
  95. package/assets/rebuild-object/forge/stage4_review/hair_gate.py +216 -0
  96. package/assets/rebuild-object/forge/stage4_review/interior_difference.py +188 -0
  97. package/assets/rebuild-object/forge/stage4_review/joint_loops.py +209 -0
  98. package/assets/rebuild-object/forge/stage4_review/make_comparison_sheet.py +292 -0
  99. package/assets/rebuild-object/forge/stage4_review/material_comparator.py +181 -0
  100. package/assets/rebuild-object/forge/stage4_review/material_feedback.py +143 -0
  101. package/assets/rebuild-object/forge/stage4_review/material_gate.py +126 -0
  102. package/assets/rebuild-object/forge/stage4_review/material_views.py +184 -0
  103. package/assets/rebuild-object/forge/stage4_review/mesh_reference_compare.py +362 -0
  104. package/assets/rebuild-object/forge/stage4_review/multi_pass.py +102 -0
  105. package/assets/rebuild-object/forge/stage4_review/objectness.py +143 -0
  106. package/assets/rebuild-object/forge/stage4_review/pairwise_penetration.py +376 -0
  107. package/assets/rebuild-object/forge/stage4_review/per_feature.py +215 -0
  108. package/assets/rebuild-object/forge/stage4_review/render_bridge.py +556 -0
  109. package/assets/rebuild-object/forge/stage4_review/scalp_exposure.py +257 -0
  110. package/assets/rebuild-object/forge/stage4_review/self_intersection.py +592 -0
  111. package/assets/rebuild-object/forge/stage4_review/swept_arc_gate.py +336 -0
  112. package/assets/rebuild-object/forge/stage4_review/turntable_gate.py +415 -0
  113. package/assets/rebuild-object/forge/stage4_review/validate_render_profile.py +182 -0
  114. package/assets/rebuild-object/forge/stage4_review/vertex_region_gate.py +456 -0
  115. package/assets/rebuild-object/forge/stage4_review/vlm_gate.py +196 -0
  116. package/assets/rebuild-object/forge/stage5_rig/NOTES.md +149 -0
  117. package/assets/rebuild-object/forge/stage5_rig/__init__.py +6 -0
  118. package/assets/rebuild-object/forge/stage5_rig/emit_rig.py +420 -0
  119. package/assets/rebuild-object/forge/stage5_rig/geodesic_skinning.py +508 -0
  120. package/assets/rebuild-object/forge/stage5_rig/rig_spec.py +174 -0
  121. package/assets/rebuild-object/forge/stage5_rig/validate_rig_payload.py +195 -0
  122. package/assets/rebuild-object/forge/state.py +98 -0
  123. package/assets/rebuild-object/steps.json +381 -0
  124. package/dist/{chunk-FB3UDZAV.js → chunk-24TITAFS.js} +1 -1
  125. package/dist/{chunk-QNWCBPVO.js → chunk-2C5PG2QO.js} +1 -1
  126. package/dist/{chunk-4RYTTD4D.js → chunk-2DEVOKI7.js} +1 -1
  127. package/dist/{chunk-RRI23NK2.js → chunk-2GHPYT2P.js} +1 -1
  128. package/dist/{chunk-QEKVZ7BX.js → chunk-2HXGMXGC.js} +1 -1
  129. package/dist/{chunk-N2UHAQXC.js → chunk-36FORP7T.js} +0 -1
  130. package/dist/{chunk-DH6WPL3X.js → chunk-3IXRQTRF.js} +1 -1
  131. package/dist/{chunk-SXYQL4GK.js → chunk-4YHA32OE.js} +1 -1
  132. package/dist/{chunk-V5ADM3WC.js → chunk-4ZGQKPK5.js} +1 -1
  133. package/dist/{chunk-BJAN3RMY.js → chunk-6CLUPFQA.js} +1 -1
  134. package/dist/{chunk-52E6EKZV.js → chunk-7WTF2BA4.js} +1 -1
  135. package/dist/{chunk-P74GTK23.js → chunk-AAXZNK4Z.js} +1 -1
  136. package/dist/{chunk-F4J6XCHT.js → chunk-ALLBT4FB.js} +1 -1
  137. package/dist/{chunk-HRKVAXNN.js → chunk-BAZDPPIG.js} +5 -5
  138. package/dist/{chunk-RPJR3S5S.js → chunk-CYDENLZ4.js} +5 -8
  139. package/dist/{chunk-I5LELJSK.js → chunk-DKSUD44G.js} +1 -1
  140. package/dist/{chunk-43P4U7CB.js → chunk-DWWSJKTE.js} +1 -1
  141. package/dist/{chunk-6IUFHPMV.js → chunk-E72TFJZP.js} +1 -1
  142. package/dist/{chunk-E3FJUPLT.js → chunk-EUAAQMUA.js} +2 -0
  143. package/dist/{chunk-37LLKM73.js → chunk-F7LYJSZE.js} +1 -1
  144. package/dist/{chunk-MEAO33XW.js → chunk-FMON3C74.js} +8 -8
  145. package/dist/{chunk-YLUB6252.js → chunk-FPILHRLZ.js} +1 -1
  146. package/dist/{chunk-4UU622RK.js → chunk-GGO6ZYYI.js} +1 -3
  147. package/dist/{chunk-2ZKS7V72.js → chunk-GZCRYYS6.js} +5 -5
  148. package/dist/{chunk-E7NDOZ27.js → chunk-LE4GVTYI.js} +8 -8
  149. package/dist/{chunk-UTSSDFQL.js → chunk-NO6KPV64.js} +1 -1
  150. package/dist/{chunk-W2QPNAZ3.js → chunk-NXW3Z4Y4.js} +1 -1
  151. package/dist/{chunk-NG2X3SMF.js → chunk-OHOAZGO4.js} +1 -1
  152. package/dist/chunk-PYJNI5WD.js +83 -0
  153. package/dist/{chunk-VUV5U4J5.js → chunk-Q4XAGTFX.js} +1 -1
  154. package/dist/{chunk-3UGGMFJJ.js → chunk-QMZBSVKF.js} +1 -1
  155. package/dist/{chunk-ABTUEIRC.js → chunk-QO66UBOS.js} +2 -2
  156. package/dist/{chunk-LONQWRTR.js → chunk-S4KVGQQO.js} +8 -8
  157. package/dist/{chunk-FJXPMA63.js → chunk-T777EXAO.js} +1 -1
  158. package/dist/{chunk-YXOGRERG.js → chunk-TZZNRA3S.js} +1 -1
  159. package/dist/{chunk-CTY2WZQK.js → chunk-UC3QLWMQ.js} +1 -1
  160. package/dist/{chunk-MR5KIFI7.js → chunk-UDJH2RED.js} +3 -3
  161. package/dist/{chunk-FNJL6Z5C.js → chunk-UIKYK7KI.js} +1 -1
  162. package/dist/{chunk-PKM3JOKQ.js → chunk-UJRSQO2B.js} +1 -1
  163. package/dist/{chunk-ALPTHSUT.js → chunk-V7LEYVXB.js} +28 -24
  164. package/dist/{chunk-DPLFCKXP.js → chunk-WRMQEXUC.js} +1 -1
  165. package/dist/{chunk-HSMG6U7J.js → chunk-WXSBNC67.js} +3 -9
  166. package/dist/{chunk-HSCTPDEU.js → chunk-X4QIOXNQ.js} +1 -1
  167. package/dist/{chunk-72KHWZMN.js → chunk-Y6WHUK2O.js} +1 -1
  168. package/dist/{chunk-VZEJ2ZHE.js → chunk-Z3E7ORGQ.js} +5 -5
  169. package/dist/index.js +20 -20
  170. package/package.json +32 -22
  171. package/dist/{chunk-OFJIG4K3.js → chunk-4ENHS32B.js} +0 -0
  172. package/dist/{chunk-Q3XQPNF6.js → chunk-BN7TR6OR.js} +3 -3
  173. package/dist/{chunk-LORGE2NB.js → chunk-U2NCN5RO.js} +3 -3
  174. package/dist/{chunk-UPHB5HWO.js → chunk-VQTTSPA3.js} +3 -3
@@ -0,0 +1,2396 @@
1
+ #!/usr/bin/env python3
2
+ """Create a starter ObjectSculptSpec JSON file."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import math
9
+ import re
10
+ import sys
11
+ from pathlib import Path
12
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
13
+ from pipeline_routing import resolve_pipeline_routing
14
+ from status_banner import emit_status
15
+
16
+
17
+ def slugify(value: str) -> str:
18
+ slug = re.sub(r"[^A-Za-z0-9]+", "-", value.strip().lower()).strip("-")
19
+ return slug or "object"
20
+
21
+
22
+ def make_pre_spec_assessment(target_name: str) -> dict:
23
+ return {
24
+ "objectClass": {
25
+ "primaryType": "unassessed",
26
+ "primaryDomain": "unassessed",
27
+ "formLanguage": [],
28
+ "structureKind": [],
29
+ "motionPotential": [],
30
+ "materialFamilies": [],
31
+ "notes": "Fill from direct visual inspection before writing the final spec. Do not use fixed domain profiles. Set primaryDomain to object, character, or hybrid.",
32
+ },
33
+ "complexity": {
34
+ "tier": "unassessed",
35
+ "scores": {
36
+ "silhouetteComplexity": 0,
37
+ "componentCount": 0,
38
+ "hierarchyDepth": 0,
39
+ "repetitionDensity": 0,
40
+ "materialLayerCount": 0,
41
+ "localDetailDensity": 0,
42
+ "occlusionRisk": 0,
43
+ "actionReadinessNeed": 0,
44
+ },
45
+ "estimatedCounts": {
46
+ "macroComponents": 1,
47
+ "mesoComponents": 0,
48
+ "microFeatureGroups": 0,
49
+ "materialLayers": 1,
50
+ "repetitionSystems": 0,
51
+ },
52
+ "reasoning": [
53
+ f"Assess {target_name!r} from the image before finalizing componentTree/materials.",
54
+ ],
55
+ },
56
+ "specDepthDecision": {
57
+ "requiredDepth": "unassessed",
58
+ "minimumComponentLevels": ["macro"],
59
+ "needsRepetitionSystems": False,
60
+ "needsMaterialLocalOverrides": False,
61
+ "needsMultipleReviewViews": True,
62
+ "needsActionReadyHierarchy": True,
63
+ "rationale": "Choose simple/moderate/complex/ultra-complex from observed structure, not from a hardcoded domain.",
64
+ },
65
+ "unknownsToResolveBeforeImplementation": [],
66
+ "detailInventory": {
67
+ "scanMethod": "component-zones",
68
+ "targetMinDetails": 0,
69
+ "note": (
70
+ "Enumerate every identity-defining small detail before authoring the spec. "
71
+ "Each detail must map to a component.localFeatures entry or material.localOverrides entry, "
72
+ "never prose only. Use vg asset rebuild-object build-detail-inventory to scan zones."
73
+ ),
74
+ "details": [],
75
+ },
76
+ "anatomy": {
77
+ "applies": False,
78
+ "styleHeads": 0.0,
79
+ "proportions": {
80
+ "headUnit": 0.0,
81
+ "torso": 0.0,
82
+ "legs": 0.0,
83
+ "shoulderWidth": 0.0,
84
+ "hipWidth": 0.0,
85
+ },
86
+ "pose": {"type": "unassessed", "jointAngles": {}},
87
+ "faceLandmarks": {
88
+ "eyeLine": 0.0,
89
+ "eyeSpacing": 0.0,
90
+ "noseBase": 0.0,
91
+ "mouthLine": 0.0,
92
+ "hairline": 0.0,
93
+ },
94
+ "features": [],
95
+ "confidence": 0.0,
96
+ "note": (
97
+ "Only meaningful when objectClass.primaryDomain is character or hybrid. "
98
+ "Set applies=true and fill from vg asset rebuild-object extract-landmarks. "
99
+ "See grimoire/character/reconstruction.md and grimoire/character/likeness_maximization.md."
100
+ ),
101
+ },
102
+ }
103
+
104
+
105
+ def make_quality_contract() -> dict:
106
+ return {
107
+ "qualityBar": "unassessed",
108
+ "definitionOfDone": [
109
+ "The rendered model matches the reference silhouette, primary proportions, visible component hierarchy, material response, and most recognizable local features for the selected fidelity tier.",
110
+ ],
111
+ "minimumSpecDepth": {
112
+ "macroComponents": 1,
113
+ "mesoComponents": 0,
114
+ "microFeatureGroups": 0,
115
+ "materialLayers": 1,
116
+ "repetitionSystems": 0,
117
+ "reviewViewpoints": 3,
118
+ },
119
+ "featureGroups": [
120
+ {
121
+ "id": "overall-silhouette",
122
+ "name": "Overall silhouette and proportions",
123
+ "required": True,
124
+ "qualityCriteria": [
125
+ "Bounding shape, dominant curves, negative spaces, and scale relationships are explicitly described.",
126
+ ],
127
+ "evidenceRefs": ["full-object"],
128
+ "failureModes": [
129
+ "model reads as a generic placeholder instead of the reference object",
130
+ "major proportions are guessed without evidence",
131
+ ],
132
+ },
133
+ {
134
+ "id": "primary-structure",
135
+ "name": "Primary structure and hierarchy",
136
+ "required": True,
137
+ "qualityCriteria": [
138
+ "Major parts, joints, seams, contact points, and parent-child relationships are named before code generation.",
139
+ ],
140
+ "evidenceRefs": ["full-object"],
141
+ "failureModes": [
142
+ "large visible parts are merged into one mesh",
143
+ "component hierarchy is too shallow for the observed complexity",
144
+ ],
145
+ },
146
+ {
147
+ "id": "attachment-joint-correctness",
148
+ "name": "Attachment and joint correctness",
149
+ "required": True,
150
+ "qualityCriteria": [
151
+ "Every visible child appendage, branch, limb, handle, connector, tube, cable, horn, wing, leg, or hinged part has an attachment contract with parent socket, localStart/localEnd, contact type, embed/overlap, and gap tolerance.",
152
+ ],
153
+ "evidenceRefs": ["full-object"],
154
+ "failureModes": [
155
+ "child part root floats away from the parent",
156
+ "branch/limb/tube is centered in space instead of pivoting from its root",
157
+ "parent-child transform mixes world and local coordinates",
158
+ ],
159
+ },
160
+ {
161
+ "id": "surface-material-response",
162
+ "name": "Surface material response",
163
+ "required": True,
164
+ "qualityCriteria": [
165
+ "Albedo zones, roughness, normal/bump/displacement intent, cavity dirt, edge wear, and local overrides are specified where visible.",
166
+ "Important materials define independent albedo, roughness, height/normal, and AO responses instead of reusing one texture for unrelated PBR channels.",
167
+ "Surface response is decomposed into macro, meso, and micro frequency bands with scale and amplitude tied to object scale.",
168
+ ],
169
+ "evidenceRefs": ["full-object"],
170
+ "failureModes": [
171
+ "surface looks like flat plastic",
172
+ "local material variation is missing or not tied to image evidence",
173
+ ],
174
+ },
175
+ {
176
+ "id": "reference-lookdev",
177
+ "name": "Reference color, material, and lighting response",
178
+ "required": True,
179
+ "qualityCriteria": [
180
+ "Material-pass names the reference-derived albedo palette, roughness variation, tactile normal/bump/displacement response, and local masks.",
181
+ "When a source image is available, run reference PBR extraction and require confidence >= 0.7 before treating maps as implementation-ready.",
182
+ "Lighting-pass names key/fill/rim or environment light, exposure, tone mapping, background, and contact shadow behavior.",
183
+ "Neutral, grazing-angle, and reference-matched renders prove that surface relief survives relighting and is not painted into albedo.",
184
+ ],
185
+ "evidenceRefs": ["full-object"],
186
+ "failureModes": [
187
+ "model has acceptable shape but reads as flat shaded or plastic",
188
+ "colors are a generic average instead of reference-observed local color zones",
189
+ "lighting is evenly ambient and cannot reproduce the source value range",
190
+ ],
191
+ },
192
+ ],
193
+ "visualDeltaChecks": [
194
+ "silhouette and negative-space delta",
195
+ "component hierarchy depth delta",
196
+ "repetition density and distribution delta",
197
+ "material albedo/roughness/normal response delta",
198
+ "local feature placement and scale delta",
199
+ ],
200
+ "antiShallowSpecRules": [
201
+ "Do not proceed to code if qualityContract.qualityBar is unassessed.",
202
+ "Do not proceed to code if the spec only contains a root component for a moderate or complex object.",
203
+ "Do not proceed to code if required featureGroups are not represented by componentTree, materials, or repetitionSystems.",
204
+ "Do not proceed to code if visible local features are described only in prose and not attached to components/materials/evidenceRefs.",
205
+ "Do not proceed past structural-pass if attached child parts lack attachment.parentSocket, localStart, localEnd, embedDepth/overlap, and gapTolerance.",
206
+ "Do not pass material look-dev when albedo is reused as roughness, height, normal, or AO.",
207
+ "Do not pass material look-dev without macro, meso, and micro surface frequency bands for close-up materials.",
208
+ "Do not pass reference-fidelity material look-dev from a source image without usable referencePbr maps or an explicit documented limitation.",
209
+ "Do not patch a spec with extracted PBR maps when extraction confidence is below the target threshold unless the user explicitly accepts lower fidelity.",
210
+ "Do not place adjacent separate-geometry parts below 0.02 world-unit seam overlap (source: grimoire/build/geometry_patterns.md).",
211
+ "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).",
212
+ ],
213
+ }
214
+
215
+
216
+ def load_assessment(path: Path | None) -> dict | None:
217
+ if path is None:
218
+ return None
219
+ payload = json.loads(path.expanduser().read_text(encoding="utf-8"))
220
+ if not isinstance(payload, dict):
221
+ raise ValueError("assessment must be a JSON object")
222
+ return payload
223
+
224
+
225
+ def inject_geometry_rules(spec: dict, target_name: str) -> None:
226
+ contract = spec.setdefault("qualityContract", {})
227
+ prohibitions = contract.setdefault("mustNotDo", contract.get("antiShallowSpecRules", []))
228
+ if not isinstance(prohibitions, list):
229
+ prohibitions = []
230
+ source = "source: grimoire/build/geometry_patterns.md"
231
+ rules = [
232
+ f"Adjacent components must overlap by at least 0.02 world units at shared seams ({source}).",
233
+ f"Raised or recessed relief and fasteners must be geometry, instanced micro-parts, or displacement; a map alone is an approximation ({source}).",
234
+ ]
235
+ object_tokens = set(re.findall(r"[a-z0-9]+", target_name.lower()))
236
+ if object_tokens & {"blade", "knife", "sword", "dagger", "spear", "bowie"}:
237
+ rules.append(f"Blade components must vary in thickness from spine to edge and taper from ricasso toward the tip ({source}).")
238
+ for rule in rules:
239
+ if rule not in prohibitions:
240
+ prohibitions.append(rule)
241
+ contract["mustNotDo"] = prohibitions
242
+ spec["qualityContract"] = contract
243
+ inventory = spec.get("preSpecAssessment", {}).get("detailInventory", {})
244
+ details = inventory.get("details", []) if isinstance(inventory, dict) else []
245
+ if isinstance(details, list):
246
+ for detail in details:
247
+ if not isinstance(detail, dict):
248
+ continue
249
+ mapping = detail.get("mapsTo")
250
+ detail["realization"] = detail.get("realization") or ("map-only" if isinstance(mapping, dict) and mapping.get("type") == "map" else "unreported")
251
+ if detail["realization"] == "map-only" and detail.get("kind") in {"fastener", "relief", "linework"}:
252
+ detail["approximation"] = f"Map-only detail; geometry guidance requires physical relief ({source})."
253
+
254
+
255
+ def _cnode(cid, name, primitive, parent, position, scale,
256
+ material="skin", role="body", level="meso", rotation=(0, 0, 0),
257
+ importance=0.7, sockets=None, local_features=None, anim_role="static",
258
+ pivot_mode="center", evidence=None, topology_class="assembled-solid",
259
+ topology_rationale=None, attachment=None, sdf=None, transform_scale=None):
260
+ """Build a full schema-valid componentTree node with humanoid-friendly defaults.
261
+
262
+ `attachment` (optional) supplies a validate_sculpt_spec.py-complete attachment contract
263
+ (parentSocket, localStart/localEnd, contactType, baseRadius/endRadius, embedDepth,
264
+ gapTolerance). When localStart/localEnd form a non-degenerate segment, the factory's
265
+ makeAttachmentEndpoint() auto-builds a tapered cylinder spanning them and IGNORES this
266
+ node's own transform/scale for geometry -- so `position`/`scale` above still populate the
267
+ schema's transform/dimensions fields (informational + a render fallback) but the actual
268
+ mesh is driven by the attachment endpoints. `sdf` (optional) supplies a
269
+ geometryDescriptor.sdf block for an implicit/concave part (e.g. a recessed eye socket via
270
+ `subtract`); when given, topologyClass is forced to 'implicit' and transform.scale is
271
+ forced to identity since the SDF primitives already encode real world-unit sizes.
272
+ """
273
+ if topology_rationale is None:
274
+ topology_rationale = (
275
+ f"{name} is a discrete primitive body part assembled onto the humanoid rig, "
276
+ f"not a continuous sculpt or shell."
277
+ )
278
+ if sdf is not None:
279
+ topology_class = "implicit"
280
+ transform_scale = (1.0, 1.0, 1.0)
281
+ node = {
282
+ "id": cid, "name": name, "level": level, "role": role,
283
+ "importance": importance, "confidence": 0.8, "primitive": primitive,
284
+ "topologyClass": topology_class,
285
+ "topologyRationale": topology_rationale,
286
+ "geometryDescriptor": {
287
+ "topologyIntent": "stylized character part",
288
+ "edgeTreatment": {"type": "none", "bevelRadius": 0.0, "segments": 1},
289
+ "deformationStack": [], "uvStrategy": "generated procedural coordinates",
290
+ "normalStrategy": "smooth vertex normals",
291
+ },
292
+ "parent": parent, "attachment": attachment,
293
+ "dimensions": {"width": float(scale[0]), "height": float(scale[1]),
294
+ "depth": float(scale[2]), "units": "relative", "confidence": 0.8},
295
+ "transform": {"position": list(position), "rotation": list(rotation),
296
+ "scale": list(transform_scale if transform_scale is not None else scale)},
297
+ "actionProfile": {
298
+ "animationRole": anim_role,
299
+ "pivot": {"mode": pivot_mode, "localPosition": [0, 0, 0], "axis": [0, 1, 0], "confidence": 0.7},
300
+ "transformChannels": {"translate": True, "rotate": True, "scale": True,
301
+ "bend": False, "twist": False, "detach": False,
302
+ "visibility": True, "materialState": False},
303
+ "sockets": sockets or [],
304
+ "collider": {"type": "box", "offset": [0, 0, 0], "scale": [1, 1, 1],
305
+ "isTrigger": False, "notes": "box proxy"},
306
+ "constraints": [],
307
+ "destruction": {"breakable": False, "fractureGroup": cid, "seamRefs": [],
308
+ "detachableFragments": [], "breakImpulse": 0.0, "debrisMaterial": material},
309
+ },
310
+ "material": material, "materialLayers": [material], "deformations": [], "joints": [],
311
+ "seams": [], "localFeatures": local_features or [],
312
+ "surfaceDetail": {"macroRoughness": 0.0, "microRoughness": 0.0, "bumpAmplitude": 0.0,
313
+ "normalPattern": "", "displacementPattern": "", "occlusionPattern": "",
314
+ "edgeWearPattern": "", "notes": ""},
315
+ "evidenceRefs": evidence or ["full-object"], "details": [], "fidelityTier": "blockout",
316
+ }
317
+ if sdf is not None:
318
+ node["geometryDescriptor"]["sdf"] = sdf
319
+ return node
320
+
321
+
322
+ def _hu_ratio(anatomy: dict | None, key: str, default: float) -> float:
323
+ """A head-unit proportion ratio (torso/legs/shoulderWidth/hipWidth) sourced from
324
+ preSpecAssessment.anatomy.proportions when present and positive, else a stylized default.
325
+ This is what lets a real reference's measured proportions drive the template instead of a
326
+ fixed bust-shaped guess."""
327
+ if isinstance(anatomy, dict):
328
+ proportions = anatomy.get("proportions")
329
+ if isinstance(proportions, dict):
330
+ value = proportions.get(key)
331
+ if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0:
332
+ return float(value)
333
+ return default
334
+
335
+
336
+ def _limb_attachment(start, end, base_radius, end_radius, socket,
337
+ contact_type="socket-joint", embed_depth=0.03, gap_tolerance=0.01,
338
+ evidence=None) -> dict:
339
+ """A validate_sculpt_spec.py-complete attachment contract for a linear body segment
340
+ (torso spine, neck, or a limb bone). `socket` fills attachment.parentSocket, a free-text
341
+ joint-name label -- used instead of parentId because a bare parentId would just restate
342
+ the component's own `parent` field with no more information, and validate_sculpt_spec.py's
343
+ strict-quality mode errors if a supplied parentId ever drifts out of sync with `parent`.
344
+ localStart/localEnd are points in the OWNING COMPONENT'S PARENT's local space (this
345
+ template now authors a real parent chain -- see make_character_component_tree), and drive
346
+ generate_threejs_factory.py's makeAttachmentEndpoint() to auto-build a tapered cylinder
347
+ spanning them -- so the owning component's own primitive/scale/rotation become a
348
+ schema-metadata fallback only."""
349
+ return {
350
+ "parentSocket": socket,
351
+ "localStart": [round(float(v), 5) for v in start],
352
+ "localEnd": [round(float(v), 5) for v in end],
353
+ "contactType": contact_type,
354
+ "baseRadius": round(float(base_radius), 5),
355
+ "endRadius": round(float(end_radius), 5),
356
+ "embedDepth": embed_depth,
357
+ "gapTolerance": gap_tolerance,
358
+ "evidenceRefs": evidence or ["full-object"],
359
+ }
360
+
361
+
362
+ def _eye_socket_sdf(hu: float) -> dict:
363
+ """A concave eye socket: a spherical shell with a smaller, forward-offset sphere carved out
364
+ of it via a boolean subtraction -- a real cavity, not a shaded/decal patch (the recorded
365
+ defect US-004: 'the eye reads as a patch, not a recessed socket'). See
366
+ forge/_shared/sdf_primitives.py VALID_SDF_OPERATIONS for 'subtract'."""
367
+ outer_radius = 0.09 * hu
368
+ carve_radius = 0.075 * hu
369
+ carve_offset = 0.055 * hu
370
+
371
+ # `bounds` is REQUIRED here, not optional. polygonizeSdf falls back to a [-2,-2,-2]..[2,2,2]
372
+ # box, and at resolution 20 that makes each sample cell 0.2 across while this shell's radius is
373
+ # 0.0252 -- the whole sphere falls between samples and marching cubes emits NOTHING. The eye
374
+ # sockets have therefore been EMPTY GEOMETRY in every render so far: the spec said `subtract`,
375
+ # the validator's recessed-feature gate was satisfied by that, and 457 tests passed, while the
376
+ # cavity did not exist in the model. Nothing checked that the emitted geometry was non-empty.
377
+ #
378
+ # Fit the box to the primitives instead of defaulting: the carve sphere reaches furthest, at
379
+ # its offset plus its radius, and 1.25x leaves room for the surface without wasting samples.
380
+ extent = max(outer_radius, carve_offset + carve_radius) * 1.25
381
+ return {
382
+ "primitives": [
383
+ {"id": "shell", "type": "sphere", "center": [0.0, 0.0, 0.0], "radius": round(outer_radius, 5)},
384
+ {"id": "carve", "type": "sphere", "center": [0.0, 0.0, round(carve_offset, 5)], "radius": round(carve_radius, 5)},
385
+ ],
386
+ # id only -- validate_sculpt_spec rejects setting both id and output; they are alternatives.
387
+ "operations": [{"id": "socket", "type": "subtract", "left": "shell", "right": "carve"}],
388
+ "bounds": {"min": [round(-extent, 5)] * 3, "max": [round(extent, 5)] * 3},
389
+ "resolution": 24,
390
+ }
391
+
392
+
393
+ def make_character_component_tree(
394
+ anatomy: dict | None = None,
395
+ include_accessories: bool = False,
396
+ ) -> list:
397
+ """A stylized GENERAL HUMANOID template: head/neck/torso/pelvis, full arms (upper arm ->
398
+ forearm -> hand) and full legs (thigh -> shin -> foot), face features including recessed
399
+ eye sockets, and hair. Head-unit driven; HU ~= 0.28 world units. Reads
400
+ preSpecAssessment.anatomy.proportions (torso/legs/shoulderWidth/hipWidth, in head units)
401
+ when supplied, else falls back to stylized full-body defaults (~7.5 heads tall).
402
+
403
+ Glasses, headphones, and a chest decal are NOT part of the baseline -- they were traits of
404
+ one specific reference person, not general humanoid anatomy. Pass include_accessories=True
405
+ to restore them. Digits ARE baseline (US-003): five per hand, three phalanges each.
406
+
407
+ REAL NESTED HIERARCHY (worker-flatten's WS-E fix has landed: a pivot Group always carries
408
+ identity scale and a part's dimensions are baked into its own geometry, so a non-uniformly
409
+ scaled parent can no longer distort a nested child -- see generate_threejs_factory.py). So,
410
+ unlike the earlier revision of this function, every part below is parented on its real
411
+ anatomical parent (neck -> torso, head -> neck, upper-arm -> torso, forearm -> upper-arm,
412
+ hand -> forearm, thigh -> pelvis, shin -> thigh, foot -> shin, face features -> head, ...),
413
+ not flattened onto a single hidden root.
414
+
415
+ Layout math below is still computed as absolute joint coordinates in one shared coordinate
416
+ space (torso_top_pt, shoulder_pt, hip_pt, ...) because that keeps the trig/anatomy formulas
417
+ simple and easy to check by eye. Each point is then converted to the LOCAL space of the
418
+ component's real parent with `_rel(point, parent_id)` immediately before it is authored onto
419
+ a component -- Three.js interprets a child's position/attachment endpoints relative to its
420
+ own parent Group, not the world, so this conversion is required once nesting is real.
421
+ `world_anchor[parent_id]` tracks, for every already-built component, the point that becomes
422
+ its own pivot Group's world position (its attachment localStart for limb/spine segments, or
423
+ its own authored position for a plain part) so `_rel()` can look it up.
424
+ """
425
+ hu = 0.28
426
+ torso_h = _hu_ratio(anatomy, "torso", 2.2) * hu
427
+ legs_h = _hu_ratio(anatomy, "legs", 3.6) * hu
428
+ shoulder_w = _hu_ratio(anatomy, "shoulderWidth", 2.3) * hu
429
+ hip_w = _hu_ratio(anatomy, "hipWidth", 1.7) * hu
430
+
431
+ # ---- core body-mass landmarks (world Y, root-relative -- see class docstring on _rel()) ----
432
+ torso_center_y = 0.55 * hu
433
+ torso_top_y = torso_center_y + torso_h * 0.5
434
+ torso_bottom_y = torso_center_y - torso_h * 0.5
435
+
436
+ # The head is DERIVED from the spine, bottom-up, not pinned to an absolute height.
437
+ #
438
+ # It used to be `head_y = 2.5 * hu`, fixed. Because `torso_h` comes from anatomy and the head
439
+ # did not, shortening the torso did not lower the head -- it STRETCHED THE NECK to fill the
440
+ # gap. Measured: at the default torso ratio 2.2 the neck is 15% of torso height; at the
441
+ # regret reference's measured 1.584 it became 40%, and the torso-top-to-head-bottom gap
442
+ # doubled from 0.081 to 0.167. That is the giraffe neck visible in the first render, and no
443
+ # per-part check could see it because every part was individually correct.
444
+ #
445
+ # A skeleton has to be built in the order the bones actually stack.
446
+ NECK_LENGTH_HU = 0.33 # a neck is about a third of a head unit
447
+ HEAD_HEIGHT_HU = 1.12 # matches the head ellipsoid's own y scale below
448
+ neck_bottom_y = torso_top_y - 0.08 * hu
449
+ neck_top_y = neck_bottom_y + NECK_LENGTH_HU * hu
450
+ head_y = neck_top_y + HEAD_HEIGHT_HU * hu * 0.5 - 0.04 * hu
451
+
452
+ pelvis_center_y = torso_bottom_y - 0.1 * hu
453
+ # The pelvis height co-varies with its width. It used to be a fixed 0.22 hu while the width
454
+ # scaled with `hip_w`, so a wide-hipped anatomy produced a SLAB: at the regret reference's
455
+ # measured hipWidth the box came out 0.455 wide x 0.123 tall x 0.360 deep, which renders as a
456
+ # tabletop the figure appears to be sitting on. A front-on human pelvis is roughly as tall as
457
+ # it is wide, so tie the two together and keep the old value as the floor for narrow hips.
458
+ pelvis_half_h = max(0.22 * hu, hip_w * 0.30)
459
+ hip_joint_y = pelvis_center_y - pelvis_half_h + 0.05 * hu
460
+
461
+ thigh_len = legs_h * 0.53
462
+ shin_len = legs_h * 0.47
463
+ knee_joint_y = hip_joint_y - thigh_len
464
+ ankle_joint_y = knee_joint_y - shin_len
465
+ foot_y = ankle_joint_y - 0.05 * hu
466
+
467
+ hip_x = hip_w * 0.30
468
+ shoulder_x = shoulder_w * 0.5
469
+
470
+ # The abdomen/chest division. A single torso cannot bend at the waist, so the spine is two
471
+ # segments: below this line is abdomen, above it is chest. 0.42 puts the joint slightly below
472
+ # mid-torso, which is where a human actually flexes.
473
+ waist_y = torso_bottom_y + torso_h * 0.42
474
+
475
+ torso_top_pt = (0.0, torso_top_y, 0.02 * hu)
476
+ torso_bottom_pt = (0.0, torso_bottom_y, 0.0)
477
+ waist_pt = (0.0, waist_y, 0.01 * hu)
478
+ neck_bottom_pt = (0.0, neck_bottom_y, 0.02 * hu)
479
+ neck_top_pt = (0.0, neck_top_y, 0.02 * hu)
480
+ head_world = (0.0, head_y, 0.02 * hu)
481
+ pelvis_world = (0.0, pelvis_center_y, 0.0)
482
+
483
+ world_anchor = {"root": (0.0, 0.0, 0.0)}
484
+
485
+ def _rel(point, parent_id):
486
+ anchor = world_anchor[parent_id]
487
+ return (point[0] - anchor[0], point[1] - anchor[1], point[2] - anchor[2])
488
+
489
+ tree = [_cnode("root", "Character (root)", "box", None, (0, 0, 0), (1, 1, 1),
490
+ material="hidden", role="body", level="macro", importance=1.0, anim_role="root")]
491
+
492
+ # ---- pelvis FIRST: the spine hangs off it, so it has to exist before the abdomen can be
493
+ # parented to it. Previously the torso and pelvis were siblings under "root", which forced
494
+ # derive_character_rig() to pick one as the bone root by hand; a real pelvis->abdomen edge
495
+ # removes that special case entirely.
496
+ tree.append(_cnode(
497
+ # An ellipsoid, not a box. A box gave three consecutive profile bands at exactly the same
498
+ # width (measured: 0.4554, 0.4554, 0.4554) because its sides are flat and vertical -- the
499
+ # signature of a slab in a silhouette. Hip mass is rounded, so an ellipsoid both reads
500
+ # correctly and lets the profile taper into the thighs.
501
+ "pelvis", "Pelvis", "ellipsoid", "root", _rel(pelvis_world, "root"),
502
+ (hip_w * 0.95, pelvis_half_h * 2, hip_w * 0.75), material="pants", role="body",
503
+ level="macro", importance=0.9,
504
+ ))
505
+ world_anchor["pelvis"] = pelvis_world
506
+
507
+ # ---- spine and neck: capsule/cylinder primitives trigger validate_sculpt_spec.py's
508
+ # attachment requirement regardless of role (ATTACHMENT_PRIMITIVES), so each gets a real
509
+ # spine-line attachment segment instead of a bare scale/rotation capsule. That is a genuine
510
+ # improvement rather than a validator workaround: base/end radius gives the waist taper and
511
+ # the neck-to-shoulder taper a uniform capsule could never express.
512
+ #
513
+ # Each segment is anchored at its PROXIMAL (lower) end, exactly like a limb. That is what
514
+ # makes a component's origin its own joint, and it is why derive_character_rig() no longer
515
+ # needs a torso-specific joint exception: summing offsets lands on a real joint every time.
516
+ tree.append(_cnode(
517
+ "abdomen", "Abdomen", "capsule", "pelvis", _rel(torso_bottom_pt, "pelvis"),
518
+ (hip_w * 0.9, waist_y - torso_bottom_y, hip_w * 0.8), material="shirt", role="shell",
519
+ level="macro", importance=0.95,
520
+ attachment=_limb_attachment(_rel(torso_bottom_pt, "pelvis"), _rel(waist_pt, "pelvis"),
521
+ hip_w * 0.40, shoulder_w * 0.34,
522
+ socket="pelvis-waist", contact_type="rigid-weld"),
523
+ ))
524
+ world_anchor["abdomen"] = torso_bottom_pt
525
+
526
+ tree.append(_cnode(
527
+ "chest", "Chest", "capsule", "abdomen", _rel(waist_pt, "abdomen"),
528
+ (shoulder_w * 0.95, torso_top_y - waist_y, hip_w * 0.85), material="shirt", role="shell",
529
+ level="macro", importance=1.0,
530
+ # The chest now tapers INWARD toward the neck (end radius < base) instead of being widest
531
+ # at its flat top. Previously the chest's top radius WAS the shoulder width, so the
532
+ # silhouette jumped from the neck straight to full torso width in a single profile band --
533
+ # measured 0.091 -> 0.262 with no intermediate value, where the reference slopes
534
+ # 0.116 -> 0.229 over ~8% of its height. The shoulder mass belongs to the clavicles.
535
+ attachment=_limb_attachment(_rel(waist_pt, "abdomen"), _rel(torso_top_pt, "abdomen"),
536
+ shoulder_w * 0.38, shoulder_w * 0.26,
537
+ socket="abdomen-chest", contact_type="rigid-weld"),
538
+ ))
539
+ world_anchor["chest"] = waist_pt
540
+
541
+ tree.append(_cnode(
542
+ "neck", "Neck", "cylinder", "chest", _rel(neck_bottom_pt, "chest"),
543
+ (0.55 * hu, neck_top_y - neck_bottom_y, 0.55 * hu), material="skin", role="support",
544
+ level="meso", importance=0.6,
545
+ attachment=_limb_attachment(_rel(neck_bottom_pt, "chest"), _rel(neck_top_pt, "chest"),
546
+ 0.26 * hu, 0.2 * hu,
547
+ socket="chest-neck-base", contact_type="rigid-weld"),
548
+ ))
549
+ world_anchor["neck"] = neck_bottom_pt
550
+
551
+ tree.append(_cnode(
552
+ "head", "Head", "ellipsoid", "neck", _rel(head_world, "neck"),
553
+ (0.92 * hu, 1.12 * hu, 0.98 * hu), material="skin", role="body", level="macro",
554
+ importance=1.0,
555
+ ))
556
+ world_anchor["head"] = head_world
557
+
558
+ # ---- face features and hair: parented to "head". Offsets are already authored local to
559
+ # head (never went through world_pos/flattening even before the un-flatten), so they need
560
+ # no _rel() conversion. ----
561
+ # (id, name, primitive, offset, scale, material, role, level, rotation, importance, features)
562
+ face_parts = [
563
+ ("hair", "Hair", "ellipsoid", (0, 0.3 * hu, -0.02 * hu),
564
+ (1.0 * hu, 0.78 * hu, 1.02 * hu), "hair", "hair", "meso", (0, 0, 0), 0.8,
565
+ ["short, neutral stylized hairstyle"]),
566
+ ("brow-l", "Eyebrow L", "box", (0.2 * hu, 0.12 * hu, 0.46 * hu),
567
+ (0.22 * hu, 0.04 * hu, 0.06 * hu), "hair", "detail", "micro", (0, 0, 0), 0.4, []),
568
+ ("brow-r", "Eyebrow R", "box", (-0.2 * hu, 0.12 * hu, 0.46 * hu),
569
+ (0.22 * hu, 0.04 * hu, 0.06 * hu), "hair", "detail", "micro", (0, 0, 0), 0.4, []),
570
+ # Ears. Offsets are head-unit multiples like every other feature here, so they scale with
571
+ # the anatomy ratios instead of being pinned to one figure's dimensions. x = 0.43 hu puts
572
+ # them on the skull surface (the head's own half-width is 0.46 hu), y at eye level, z
573
+ # slightly aft of centre. They are detail, not bones: an ear does not articulate.
574
+ ("ear-l", "Ear L", "ellipsoid", (0.43 * hu, 0.02 * hu, -0.02 * hu),
575
+ (0.09 * hu, 0.26 * hu, 0.17 * hu), "skin", "detail", "micro", (0, 0, 0), 0.45,
576
+ ["outer helix reads as a flattened shell against the skull, not a disc"]),
577
+ ("ear-r", "Ear R", "ellipsoid", (-0.43 * hu, 0.02 * hu, -0.02 * hu),
578
+ (0.09 * hu, 0.26 * hu, 0.17 * hu), "skin", "detail", "micro", (0, 0, 0), 0.45,
579
+ ["outer helix reads as a flattened shell against the skull, not a disc"]),
580
+ ("nose", "Nose", "ellipsoid", (0, -0.04 * hu, 0.5 * hu),
581
+ (0.14 * hu, 0.28 * hu, 0.18 * hu), "skin", "detail", "micro", (1.4, 0, 0), 0.4, []),
582
+ ("mouth", "Mouth", "box", (0, -0.34 * hu, 0.46 * hu),
583
+ (0.24 * hu, 0.04 * hu, 0.05 * hu), "lips", "detail", "micro", (0, 0, 0), 0.4, []),
584
+ ]
585
+ if include_accessories:
586
+ face_parts.extend([
587
+ ("glasses-frame-l", "Glasses frame L", "torus", (0.21 * hu, 0.02 * hu, 0.48 * hu),
588
+ (0.26 * hu, 0.22 * hu, 0.08 * hu), "glasses-frame", "rim", "meso", (0, 0, 0), 0.85, []),
589
+ ("glasses-frame-r", "Glasses frame R", "torus", (-0.21 * hu, 0.02 * hu, 0.48 * hu),
590
+ (0.26 * hu, 0.22 * hu, 0.08 * hu), "glasses-frame", "rim", "meso", (0, 0, 0), 0.85, []),
591
+ ("glasses-bridge", "Glasses bridge", "box", (0, 0.04 * hu, 0.5 * hu),
592
+ (0.12 * hu, 0.04 * hu, 0.04 * hu), "glasses-frame", "trim", "micro", (0, 0, 0), 0.5, []),
593
+ ("lens-l", "Lens L", "plane-card", (0.21 * hu, 0.02 * hu, 0.485 * hu),
594
+ (0.22 * hu, 0.18 * hu, 1.0), "glasses-lens", "panel", "micro", (0, 0, 0), 0.5, []),
595
+ ("lens-r", "Lens R", "plane-card", (-0.21 * hu, 0.02 * hu, 0.485 * hu),
596
+ (0.22 * hu, 0.18 * hu, 1.0), "glasses-lens", "panel", "micro", (0, 0, 0), 0.5, []),
597
+ ("hp-band", "Headphone band", "torus", (0, -0.72 * hu, 0.05 * hu),
598
+ (0.95 * hu, 0.62 * hu, 0.7 * hu), "headphone", "ring", "meso", (1.2, 0, 0), 0.85, []),
599
+ ("hp-cup-l", "Ear cup L", "sphere", (0.5 * hu, -0.98 * hu, 0.35 * hu),
600
+ (0.4 * hu, 0.4 * hu, 0.22 * hu), "headphone", "detail", "meso", (0, 0, 0), 0.7, []),
601
+ ("hp-cup-r", "Ear cup R", "sphere", (-0.5 * hu, -0.98 * hu, 0.35 * hu),
602
+ (0.4 * hu, 0.4 * hu, 0.22 * hu), "headphone", "detail", "meso", (0, 0, 0), 0.7, []),
603
+ ])
604
+ for pid, name, prim, off, scale, mat, role, level, rot, imp, feats in face_parts:
605
+ tree.append(_cnode(pid, name, prim, "head", off, scale,
606
+ material=mat, role=role, level=level, rotation=rot, importance=imp,
607
+ local_features=feats))
608
+
609
+ if include_accessories:
610
+ # Chest decal is parented to torso; its offset was authored relative to torso's OLD
611
+ # seed position (torso_center_y) back when this template flattened everything, so
612
+ # convert it into torso's real local frame (anchored at torso_top_pt) here.
613
+ decal_old_world = (0.0, torso_center_y + 0.1 * hu, 0.78 * hu)
614
+ decal_local = _rel(decal_old_world, "chest")
615
+ tree.append(_cnode(
616
+ "shirt-decal", "Chest graphic", "plane-card", "chest", decal_local,
617
+ (1.5 * hu, 0.9 * hu, 1.0), material="shirt-decal", role="decal", level="micro",
618
+ importance=0.7,
619
+ ))
620
+
621
+ # ---- eyes: a visible eyeball sphere plus a recessed cavity carved via SDF subtract, not a
622
+ # flat patch (US-004). Naming/roles deliberately avoid the token "socket": that token is
623
+ # also in validate_sculpt_spec.py's ATTACHMENT_ROLES (ball-and-socket limb joints), so
624
+ # reusing it here would additionally force an unrelated attachment contract onto a part
625
+ # that has no start/end line to attach -- "cavity" trips the recessed-feature gate just as
626
+ # well without that collision. Offsets are already local to head. ----
627
+ for side, eye_x in (("l", 0.19 * hu), ("r", -0.19 * hu)):
628
+ eye_local = (eye_x, 0.03 * hu, 0.40 * hu)
629
+ cavity_local = (eye_x, 0.03 * hu, 0.43 * hu)
630
+ tree.append(_cnode(
631
+ f"eye-{side}", f"Eye {side.upper()}", "sphere", "head", eye_local,
632
+ (0.11 * hu, 0.11 * hu, 0.11 * hu), material="eye", role="detail", level="micro",
633
+ importance=0.5,
634
+ ))
635
+ tree.append(_cnode(
636
+ f"eye-cavity-{side}", f"Eye cavity {side.upper()}", "sphere", "head", cavity_local,
637
+ (0.18 * hu, 0.18 * hu, 0.18 * hu), material="skin", role="cavity", level="micro",
638
+ importance=0.4, sdf=_eye_socket_sdf(hu),
639
+ topology_rationale=(
640
+ "The eye reads as a recessed concave cavity carved out of the head volume with a "
641
+ "boolean subtraction (US-004), not a flat decal or shaded patch."
642
+ ),
643
+ ))
644
+
645
+ # ---- arms: shoulder -> elbow -> wrist -> hand, laid out as absolute joint coordinates,
646
+ # then each segment is parented on the PREVIOUS segment (torso -> upper-arm -> forearm ->
647
+ # hand) and its attachment endpoints are converted into that parent's local space. ----
648
+ arm_lean = 0.20
649
+ arm_total = torso_h * 0.95
650
+ upper_arm_len = arm_total * 0.55
651
+ forearm_len = arm_total * 0.45
652
+ shoulder_y = torso_top_y - 0.08 * hu
653
+ for side, sign in (("l", 1), ("r", -1)):
654
+ sx = shoulder_x * sign
655
+ lean = arm_lean * sign
656
+ shoulder_pt = (sx, shoulder_y, 0.05 * hu)
657
+ elbow_pt = (
658
+ shoulder_pt[0] + math.sin(lean) * upper_arm_len,
659
+ shoulder_pt[1] - math.cos(lean) * upper_arm_len,
660
+ shoulder_pt[2],
661
+ )
662
+ wrist_pt = (
663
+ elbow_pt[0] + math.sin(lean * 0.6) * forearm_len,
664
+ elbow_pt[1] - math.cos(lean * 0.6) * forearm_len,
665
+ elbow_pt[2],
666
+ )
667
+ hand_len = 0.32 * hu
668
+ hand_center = (
669
+ wrist_pt[0] + math.sin(lean * 0.6) * hand_len * 0.5,
670
+ wrist_pt[1] - math.cos(lean * 0.6) * hand_len * 0.5,
671
+ wrist_pt[2],
672
+ )
673
+ clavicle_id = f"clavicle-{side}"
674
+ upper_arm_id = f"upper-arm-{side}"
675
+ forearm_id = f"forearm-{side}"
676
+ hand_id = f"hand-{side}"
677
+
678
+ # ---- clavicle: sternum -> shoulder joint. Without it the upper arm parents straight to
679
+ # the chest, so a shoulder cannot shrug or roll forward and the arm's rotation origin
680
+ # sits inside the chest volume rather than on the joint. It also gives the arm chain a
681
+ # real root that moves with the ribcage, which is what a shoulder does.
682
+ clavicle_root_pt = (sign * shoulder_x * 0.16, shoulder_y + 0.02 * hu, 0.03 * hu)
683
+ tree.append(_cnode(
684
+ clavicle_id, f"Clavicle {side.upper()}", "capsule", "chest",
685
+ _rel(clavicle_root_pt, "chest"),
686
+ (shoulder_x * 0.84, 0.34 * hu, 0.34 * hu), material="skin", role="support",
687
+ level="meso", importance=0.6,
688
+ # Thick, and tapering OUTWARD to the shoulder joint. This is the trapezius/deltoid
689
+ # mass, and it is what produces the neck-to-shoulder slope: it starts narrow beside
690
+ # the neck and ends wide at the joint. At the old 0.09 hu radius the clavicle was a
691
+ # 0.05-wide stick, invisible inside the chest, and the chest's flat top had to be the
692
+ # shoulder instead -- which is exactly what made the silhouette a cliff.
693
+ attachment=_limb_attachment(_rel(clavicle_root_pt, "chest"), _rel(shoulder_pt, "chest"),
694
+ 0.11 * hu, 0.17 * hu, socket=f"chest-clavicle-{side}",
695
+ contact_type="rigid-weld"),
696
+ ))
697
+ world_anchor[clavicle_id] = clavicle_root_pt
698
+
699
+ tree.append(_cnode(
700
+ upper_arm_id, f"Upper arm {side.upper()}", "capsule", clavicle_id,
701
+ _rel(shoulder_pt, clavicle_id),
702
+ (0.32 * hu, upper_arm_len, 0.32 * hu), material="shirt", role="arm", level="meso",
703
+ importance=0.7,
704
+ attachment=_limb_attachment(_rel(shoulder_pt, clavicle_id), _rel(elbow_pt, clavicle_id),
705
+ 0.16 * hu, 0.13 * hu, socket=f"clavicle-shoulder-{side}"),
706
+ ))
707
+ world_anchor[upper_arm_id] = shoulder_pt
708
+ tree.append(_cnode(
709
+ forearm_id, f"Forearm {side.upper()}", "capsule", upper_arm_id, _rel(elbow_pt, upper_arm_id),
710
+ (0.26 * hu, forearm_len, 0.26 * hu), material="skin", role="arm", level="meso",
711
+ importance=0.65,
712
+ attachment=_limb_attachment(_rel(elbow_pt, upper_arm_id), _rel(wrist_pt, upper_arm_id),
713
+ 0.12 * hu, 0.09 * hu, socket=f"upper-arm-elbow-{side}",
714
+ contact_type="hinge-joint"),
715
+ ))
716
+ world_anchor[forearm_id] = elbow_pt
717
+ tree.append(_cnode(
718
+ hand_id, f"Hand {side.upper()}", "box", forearm_id, _rel(hand_center, forearm_id),
719
+ (0.22 * hu, hand_len, 0.13 * hu), material="skin", role="hand", level="meso",
720
+ importance=0.55,
721
+ ))
722
+ world_anchor[hand_id] = hand_center
723
+ # ---- digits: five per hand, three phalanges each, chained proximal -> middle -> distal.
724
+ # This replaces the old `--fingers` flag, which added ONE box labelled "fingers" plus one
725
+ # box labelled "thumb" -- a mitten, not a hand, and opt-in at that. A humanoid that cannot
726
+ # curl a finger is not finished, so digits are now baseline with no flag.
727
+ #
728
+ # Four fingers march down off the distal palm edge; the thumb branches from near the wrist
729
+ # and travels MEDIALLY (toward the body) rather than down, which is what opposes it. The
730
+ # medial direction is -sign: for the left hand (sign=+1, +x side of the body) the inside
731
+ # is -x. Getting that backwards puts both thumbs on the outside.
732
+ knuckle_row_y = hand_center[1] - hand_len * 0.42
733
+ digit_layout = (
734
+ # name, x offset (hu), phalanx lengths (hu), radius (hu), medial thumb?
735
+ ("thumb", -0.10 * sign, (0.075, 0.055, 0.040), 0.032, True),
736
+ ("index", -0.075 * sign, (0.105, 0.072, 0.048), 0.028, False),
737
+ ("middle", -0.025 * sign, (0.115, 0.080, 0.050), 0.029, False),
738
+ ("ring", 0.025 * sign, (0.105, 0.072, 0.046), 0.027, False),
739
+ ("little", 0.070 * sign, (0.080, 0.058, 0.038), 0.024, False),
740
+ )
741
+ for digit_name, x_offset, lengths, radius, is_thumb in digit_layout:
742
+ # The thumb starts near the wrist and runs inward; the fingers start at the knuckle
743
+ # row and run down the same lean the forearm already has.
744
+ if is_thumb:
745
+ joint = (hand_center[0] + x_offset * hu,
746
+ hand_center[1] - hand_len * 0.06,
747
+ hand_center[2] + 0.02 * hu)
748
+ step = (-0.72 * sign, -0.62, 0.30) # medial, down, forward
749
+ else:
750
+ joint = (hand_center[0] + x_offset * hu, knuckle_row_y, hand_center[2] + 0.01 * hu)
751
+ step = (math.sin(lean * 0.6), -math.cos(lean * 0.6), 0.0)
752
+
753
+ parent_id = hand_id
754
+ for index, length in enumerate(lengths):
755
+ phalanx_id = f"{digit_name}-{side}-{index + 1}"
756
+ tip = (joint[0] + step[0] * length * hu,
757
+ joint[1] + step[1] * length * hu,
758
+ joint[2] + step[2] * length * hu)
759
+ tree.append(_cnode(
760
+ phalanx_id,
761
+ f"{digit_name.capitalize()} {side.upper()} phalanx {index + 1}",
762
+ "capsule", parent_id, _rel(joint, parent_id),
763
+ (radius * 2 * hu, length * hu, radius * 2 * hu),
764
+ material="skin", role="finger", level="micro",
765
+ importance=0.3 if index == 0 else 0.2,
766
+ attachment=_limb_attachment(
767
+ _rel(joint, parent_id), _rel(tip, parent_id),
768
+ radius * hu, radius * 0.82 * hu,
769
+ socket=f"{parent_id}-{digit_name}-{index + 1}",
770
+ contact_type="hinge-joint" if index else "rigid-weld",
771
+ ),
772
+ ))
773
+ world_anchor[phalanx_id] = joint
774
+ parent_id = phalanx_id
775
+ joint = tip
776
+
777
+ # ---- legs: hip -> knee -> ankle -> foot, same pattern (pelvis -> thigh -> shin -> foot). ----
778
+ for side, sign in (("l", 1), ("r", -1)):
779
+ lx = hip_x * sign
780
+ hip_pt = (lx, hip_joint_y, 0.02 * hu)
781
+ knee_pt = (lx, knee_joint_y, 0.02 * hu)
782
+ ankle_pt = (lx, ankle_joint_y, 0.0)
783
+ foot_center = (lx, foot_y, 0.16 * hu)
784
+ thigh_id = f"thigh-{side}"
785
+ shin_id = f"shin-{side}"
786
+ tree.append(_cnode(
787
+ thigh_id, f"Thigh {side.upper()}", "capsule", "pelvis", _rel(hip_pt, "pelvis"),
788
+ (0.38 * hu, thigh_len, 0.38 * hu), material="pants", role="leg", level="meso",
789
+ importance=0.75,
790
+ attachment=_limb_attachment(_rel(hip_pt, "pelvis"), _rel(knee_pt, "pelvis"),
791
+ 0.2 * hu, 0.16 * hu, socket=f"pelvis-hip-{side}"),
792
+ ))
793
+ world_anchor[thigh_id] = hip_pt
794
+ tree.append(_cnode(
795
+ shin_id, f"Shin {side.upper()}", "capsule", thigh_id, _rel(knee_pt, thigh_id),
796
+ (0.28 * hu, shin_len, 0.28 * hu), material="pants", role="leg", level="meso",
797
+ importance=0.7,
798
+ attachment=_limb_attachment(_rel(knee_pt, thigh_id), _rel(ankle_pt, thigh_id),
799
+ 0.14 * hu, 0.1 * hu, socket=f"thigh-knee-{side}",
800
+ contact_type="hinge-joint"),
801
+ ))
802
+ world_anchor[shin_id] = knee_pt
803
+ tree.append(_cnode(
804
+ f"foot-{side}", f"Foot {side.upper()}", "box", shin_id, _rel(foot_center, shin_id),
805
+ (0.24 * hu, 0.16 * hu, 0.44 * hu), material="shoes", role="foot", level="meso",
806
+ importance=0.5,
807
+ ))
808
+ return tree
809
+
810
+
811
+ def _shade_hex(hex_color: str, factor: float) -> str:
812
+ """Return a slightly darker/lighter shade of a #RRGGBB color (factor<1 darker)."""
813
+ h = hex_color.lstrip("#")
814
+ if len(h) != 6:
815
+ return hex_color
816
+ r, g, b = (int(h[i:i + 2], 16) for i in (0, 2, 4))
817
+ r, g, b = (max(0, min(255, round(c * factor))) for c in (r, g, b))
818
+ return f"#{r:02x}{g:02x}{b:02x}"
819
+
820
+
821
+ CHARACTER_BASE_MATERIALS = [
822
+ {"id": "hidden", "baseColor": "#000000", "roughness": {"base": 1.0, "variation": 0.0}, "opacity": {"base": 0.0}},
823
+ {"id": "skin", "baseColor": "#e8b98f", "roughness": {"base": 0.55, "variation": 0.08}},
824
+ {"id": "hair", "baseColor": "#171310", "roughness": {"base": 0.42, "variation": 0.1}},
825
+ {"id": "shirt", "baseColor": "#20202a", "roughness": {"base": 0.85, "variation": 0.12}},
826
+ {"id": "pants", "baseColor": "#2b2d33", "roughness": {"base": 0.75, "variation": 0.1}},
827
+ {"id": "shoes", "baseColor": "#171512", "roughness": {"base": 0.55, "variation": 0.08}},
828
+ {"id": "eye", "baseColor": "#f2eee4", "roughness": {"base": 0.2, "variation": 0.03}},
829
+ {"id": "lips", "baseColor": "#c98070", "roughness": {"base": 0.5, "variation": 0.05}},
830
+ ]
831
+ # Accessories are opt-in (apply_character_template's include_accessories) -- a chest decal,
832
+ # glasses, and headphones are one reference person's traits, not general humanoid anatomy.
833
+ CHARACTER_ACCESSORY_MATERIALS = [
834
+ {"id": "shirt-decal", "baseColor": "#d24a20", "roughness": {"base": 0.7, "variation": 0.05}},
835
+ {"id": "glasses-frame", "baseColor": "#111114", "roughness": {"base": 0.35, "variation": 0.05}},
836
+ {"id": "glasses-lens", "baseColor": "#a9c6d8", "roughness": {"base": 0.08, "variation": 0.02}},
837
+ {"id": "headphone", "baseColor": "#0e0e10", "roughness": {"base": 0.5, "variation": 0.08}},
838
+ ]
839
+
840
+
841
+ def make_character_build_passes() -> list:
842
+ base = make_pre_spec_assessment # noqa: reference to keep import graph obvious
843
+ passes = [
844
+ {"id": "blockout", "goal": "Match head-unit proportions and pose silhouette.",
845
+ "componentRefs": ["root"], "acceptance": ["Humanoid proportions and pose read correctly without materials."]},
846
+ {"id": "proportion-lock", "goal": "Lock head/torso/limb head-unit ratios and pose angles.",
847
+ "componentRefs": ["root", "head", "chest"], "acceptance": ["Head-unit ratios match anatomy; silhouette matches reference."]},
848
+ {"id": "feature-placement", "goal": "Place facial features, hair, and any enabled accessories to landmarks.",
849
+ "componentRefs": ["head", "hair", "eye-l", "eye-r"],
850
+ "acceptance": ["Eyeline/nose/mouth on landmark lines; eyes read as recessed, not flat patches; enabled accessories placed as in reference."]},
851
+ {"id": "material-pass", "goal": "Match skin/hair/cloth/metal color and roughness.",
852
+ "componentRefs": ["root"], "acceptance": ["Skin, hair, shirt, pants, shoe, and any enabled accessory materials match reference palette."]},
853
+ {"id": "lighting-pass", "goal": "Soft key from reference direction plus rim.",
854
+ "componentRefs": ["root"], "acceptance": ["Readable under neutral light; reference-matched lighting added."]},
855
+ {"id": "interaction-pass", "goal": "Rig-ready pivots and sockets.",
856
+ "componentRefs": ["root"], "acceptance": ["Head/neck/shoulder/elbow/hip/knee pivots and sockets exposed."]},
857
+ {"id": "optimization-pass", "goal": "Protect runtime performance.",
858
+ "componentRefs": ["root"], "acceptance": ["Triangle/draw-call budget documented."]},
859
+ ]
860
+ del base
861
+ return passes
862
+
863
+
864
+ def make_character_feature_targets(include_accessories: bool = False) -> list:
865
+ outfit_refs = ["shirt-decal", "headphone", "glasses-frame-l"] if include_accessories else ["chest", "pants", "shoes"]
866
+ return [
867
+ {"id": "anatomy-proportion", "name": "Head-unit proportions and pose", "tier": "critical",
868
+ "passIds": ["blockout", "proportion-lock"], "minimumScore": 0.78, "mustPass": True,
869
+ "componentRefs": ["root", "head", "chest"], "evidenceRefs": ["full-object"]},
870
+ {"id": "face-landmark-placement", "name": "Face landmarks incl. recessed eye sockets", "tier": "critical",
871
+ "passIds": ["feature-placement"], "minimumScore": 0.75, "mustPass": True,
872
+ "componentRefs": ["head", "eye-l", "eye-cavity-l", "nose"], "evidenceRefs": ["full-object"]},
873
+ {"id": "pose-silhouette", "name": "Pose and full-body silhouette", "tier": "critical",
874
+ "passIds": ["blockout", "proportion-lock"], "minimumScore": 0.75, "mustPass": True,
875
+ "componentRefs": ["root", "upper-arm-l", "thigh-l"], "evidenceRefs": ["full-object"]},
876
+ {"id": "outfit-and-palette", "name": "Outfit + accessories + palette", "tier": "important",
877
+ "passIds": ["material-pass"], "minimumScore": 0.7, "mustPass": False,
878
+ "componentRefs": outfit_refs, "evidenceRefs": ["full-object"]},
879
+ ]
880
+
881
+
882
+ # Components that are body SEGMENTS and therefore become bones, but carry no
883
+ # `attachment` block to derive a segment from (they are not capsules/cylinders).
884
+ # Everything else without an attachment block -- brows, nose, mouth, hair, eyes,
885
+ # eye cavities, lenses, decals -- rides its parent bone and is deliberately NOT a
886
+ # bone: a brow does not articulate.
887
+ _RIG_STRUCTURAL_LEAVES = {"pelvis", "head", "hand-l", "hand-r", "foot-l", "foot-r"}
888
+
889
+ _RIG_CHAINS = (
890
+ # Digits are checked BEFORE the arm prefixes. They do not collide today, but a future
891
+ # "hand-thumb-*" id would match "hand-" first and land in the wrong chain.
892
+ (("thumb-", "index-", "middle-", "ring-", "little-"), "digit"),
893
+ (("clavicle-", "upper-arm-", "forearm-", "hand-"), "arm"),
894
+ (("thigh-", "shin-", "foot-"), "leg"),
895
+ (("neck", "head"), "head"),
896
+ (("chest", "abdomen", "pelvis"), "spine"),
897
+ )
898
+
899
+
900
+ def _rig_chain_of(component_id: str) -> str:
901
+ for prefixes, chain in _RIG_CHAINS:
902
+ for prefix in prefixes:
903
+ if component_id == prefix or component_id.startswith(prefix):
904
+ return chain
905
+ return "prop"
906
+
907
+
908
+ def derive_character_rig(component_tree: list) -> dict:
909
+ """Derive a PLAN_1.5 §6 `RigSpec` from the component tree instead of authoring one.
910
+
911
+ Deriving rather than authoring is the point: a hand-written skeleton and a
912
+ hand-written component tree drift the moment either is edited, and nothing
913
+ detects the drift. Everything below comes from data the tree already carries.
914
+
915
+ Three decisions that are choices rather than facts, recorded here because the
916
+ next person cannot re-derive them from the code alone:
917
+
918
+ 1. **Every position is MODEL space, and a bone's tip is its child's joint.**
919
+ `attachment.localEnd` looks like the obvious tip and is NOT used, because it
920
+ is right for limbs and wrong for the spine: a limb component's origin IS its
921
+ proximal joint, but the torso's origin is its centre, so reading localEnd
922
+ there produced a spine bone running from the chest DOWN past the pelvis --
923
+ which would have pulled leg vertices onto the torso's weight. PLAN_1.5 §6's
924
+ "tipPos defaults to the child's jointPos" is the right rule but is
925
+ meaningless parent-local (a parent's tip and its child's joint sit in
926
+ different frames), so everything is accumulated into one space first.
927
+
928
+ 2. **`pelvis` is the single bone root, with `torso` parented to it.** A
929
+ `RigSpec` requires exactly one root, and the component tree parents BOTH
930
+ `torso` and `pelvis` to `"root"` (they are siblings there). Hips-as-root is
931
+ the standard humanoid convention and it is the one that makes rotating the
932
+ pelvis bend the whole figure. This makes the bone hierarchy deliberately
933
+ differ from the pivot hierarchy at exactly one edge, which PLAN_1.5 §8
934
+ ("bones and pivots coexist") explicitly permits.
935
+
936
+ 3. **A leaf bone continues its parent's direction** for its own `scale.y`,
937
+ rather than being given an invented orientation. Known simplification: a
938
+ foot therefore points down the shin rather than forward. That is wrong
939
+ anatomically and right for weighting, and it is derived rather than
940
+ guessed -- flagged so a real foot orientation can replace it deliberately.
941
+ """
942
+ by_id = {c["id"]: c for c in component_tree if isinstance(c, dict) and c.get("id")}
943
+
944
+ def is_bone(component: dict) -> bool:
945
+ return bool(component.get("attachment")) or component["id"] in _RIG_STRUCTURAL_LEAVES
946
+
947
+ bone_ids = [cid for cid, c in by_id.items() if is_bone(c)]
948
+
949
+ def bone_parent(component_id: str) -> str | None:
950
+ # Walk up the component tree until a component that is itself a bone is
951
+ # found, so a bone parented through a non-bone (a detail) still attaches
952
+ # to the nearest real segment rather than falling out of the hierarchy.
953
+ parent = by_id.get(component_id, {}).get("parent")
954
+ while parent and parent != "root":
955
+ if parent in bone_ids:
956
+ return parent
957
+ parent = by_id.get(parent, {}).get("parent")
958
+ if component_id == "pelvis":
959
+ return None # the single root
960
+ return None
961
+
962
+ children = {cid: [] for cid in bone_ids}
963
+ for _cid in bone_ids:
964
+ _parent = bone_parent(_cid)
965
+ if _parent in children:
966
+ children[_parent].append(_cid)
967
+
968
+ # A branching bone's tip is its SPINE-WARD child's joint. `pelvis` has three bone children
969
+ # (abdomen + both thighs) and `chest` has three (neck + both arms), so §6's single-child
970
+ # default does not apply and rig_spec.resolve_tip_positions() would reject them; naming the
971
+ # spine-ward child is an explicit choice rather than picking an arbitrary one.
972
+ _SPINE_WARD = {
973
+ "chest": "neck", "abdomen": "chest", "pelvis": "abdomen",
974
+ # A hand has five bone children since US-003, so it needs a named tip too. The hand's
975
+ # axis runs to the middle finger, so that digit's proximal phalanx is the anatomical
976
+ # choice rather than whichever digit happens to sort first.
977
+ "hand-l": "middle-l-1", "hand-r": "middle-r-1",
978
+ }
979
+
980
+ # No joint override is needed any more. It used to be, because the single `torso` component
981
+ # was anchored at its CENTRE, so reading its own position as a joint produced a spine bone
982
+ # running from the chest DOWN past the pelvis. Splitting the spine into abdomen + chest and
983
+ # anchoring each at its PROXIMAL end -- exactly how limbs were already authored -- makes a
984
+ # component's origin its own joint everywhere, so `hip_top()` and the torso exception are
985
+ # gone. Getting the anatomy right removed the special case rather than adding one.
986
+ def joint_of(component_id: str) -> list:
987
+ return model_pos(component_id)
988
+
989
+ def explicit_tip(component_id: str) -> list | None:
990
+ return None
991
+
992
+ def model_pos(component_id: str) -> list:
993
+ """Accumulate parent-local offsets into MODEL space.
994
+
995
+ Summing offsets instead of composing matrices is exact under TWO preconditions, and
996
+ both are checked rather than assumed, because a silent violation would move every
997
+ descendant joint without anything failing:
998
+
999
+ 1. **No cascading non-uniform scale.** Holds because pivot Groups always carry identity
1000
+ scale now (WS-E); the component's dimensions live in its geometry.
1001
+ 2. **No rotation on any ancestor.** A rotated ancestor rotates its children's offsets,
1002
+ which a sum cannot represent. This holds at BIND POSE and is exactly what applying
1003
+ `anatomy.pose.jointAngles` would break — hence the fail-closed check below, and
1004
+ hence `apply_character_pose()` must run AFTER this function, never before.
1005
+ """
1006
+ total = [0.0, 0.0, 0.0]
1007
+ cursor = component_id
1008
+ while cursor and cursor != "root":
1009
+ component = by_id.get(cursor)
1010
+ if not component:
1011
+ break
1012
+ transform = component.get("transform") or {}
1013
+ rotation = transform.get("rotation") or [0.0, 0.0, 0.0]
1014
+ if any(abs(float(v)) > 1e-9 for v in rotation):
1015
+ raise ValueError(
1016
+ f"cannot derive a rig through rotated component {cursor!r} "
1017
+ f"(rotation={rotation}): a bone's joint is accumulated by summing "
1018
+ f"parent-local offsets, which is only valid at bind pose. Derive the rig "
1019
+ f"BEFORE applying pose rotations."
1020
+ )
1021
+ position = transform.get("position") or [0.0, 0.0, 0.0]
1022
+ for i in range(3):
1023
+ total[i] += float(position[i])
1024
+ cursor = component.get("parent")
1025
+ return total
1026
+
1027
+ def segment(component_id: str) -> tuple[list, list]:
1028
+ component = by_id[component_id]
1029
+ joint = joint_of(component_id)
1030
+ override = explicit_tip(component_id)
1031
+ if override is not None:
1032
+ return joint, override
1033
+ kids = children.get(component_id, [])
1034
+ preferred = _SPINE_WARD.get(component_id)
1035
+ if preferred and preferred in kids:
1036
+ return joint, joint_of(preferred)
1037
+ if len(kids) == 1:
1038
+ return joint, joint_of(kids[0]) # the §6 default, now well-defined
1039
+ transform = component.get("transform") or {}
1040
+ position = joint
1041
+ length = float((transform.get("scale") or [0.0, 0.0, 0.0])[1])
1042
+ parent = bone_parent(component_id)
1043
+ direction = [0.0, -1.0, 0.0]
1044
+ if parent: # decision 3
1045
+ p_start, p_end = segment(parent)
1046
+ delta = [p_end[i] - p_start[i] for i in range(3)]
1047
+ norm = sum(d * d for d in delta) ** 0.5
1048
+ if norm > 1e-9:
1049
+ direction = [d / norm for d in delta]
1050
+ return position, [round(position[i] + direction[i] * length, 5) for i in range(3)]
1051
+
1052
+ bones = []
1053
+ for cid in bone_ids:
1054
+ joint, tip = segment(cid)
1055
+ bones.append({
1056
+ "id": cid,
1057
+ "parent": bone_parent(cid),
1058
+ "jointPos": [round(v, 5) for v in joint],
1059
+ "tipPos": [round(v, 5) for v in tip],
1060
+ "component": cid,
1061
+ "role": "skinned",
1062
+ "chain": _rig_chain_of(cid),
1063
+ })
1064
+ bones.sort(key=lambda b: (b["parent"] is not None, b["id"]))
1065
+ return {"version": "1.0", "bindPose": "A", "forward": "+Z", "bones": bones}
1066
+
1067
+
1068
+ # `anatomy.pose.jointAngles` uses anatomical sides: "left" is the CHARACTER's left, which the
1069
+ # component tree spells `-l`. On a front-facing reference that is the viewer's right.
1070
+ _POSE_JOINT_TO_COMPONENT = {
1071
+ "neck": "neck",
1072
+ "leftShoulder": "upper-arm-l", "rightShoulder": "upper-arm-r",
1073
+ "leftElbow": "forearm-l", "rightElbow": "forearm-r",
1074
+ "leftWrist": "hand-l", "rightWrist": "hand-r",
1075
+ "leftHip": "thigh-l", "rightHip": "thigh-r",
1076
+ "leftKnee": "shin-l", "rightKnee": "shin-r",
1077
+ "leftAnkle": "foot-l", "rightAnkle": "foot-r",
1078
+ }
1079
+
1080
+
1081
+ def apply_character_pose(component_tree: list, anatomy: dict | None) -> list[str]:
1082
+ """Apply `anatomy.pose.jointAngles` as component rotations. Returns the joints applied.
1083
+
1084
+ Why this is worth having even though skinning (WS-C) is unfinished: posing a hierarchy of
1085
+ RIGID segments needs no skeleton at all. It needs a real parent chain that propagates
1086
+ rotation, which the template now has and which has been measured on executed geometry.
1087
+ Skinning buys smooth deformation ACROSS a joint; it is not what makes a limb move. So a
1088
+ reference pose (a contrapposto, an arm resting on a sword) is reachable now, and treating
1089
+ pose as blocked on skinning was wrong.
1090
+
1091
+ Before this, `pose.jointAngles` was declared in two places and consumed in none -- the same
1092
+ "accepted but silently unused" state `anatomy.proportions` was in before `_hu_ratio()`.
1093
+
1094
+ MUST run AFTER `derive_character_rig()`. That function accumulates joints by summing
1095
+ parent-local offsets, which is only valid while every ancestor rotation is identity -- i.e.
1096
+ at bind pose. It now raises rather than silently mis-deriving if called on a posed tree, so
1097
+ the ordering is enforced, not merely documented. The rig stays bind-pose data, which is what
1098
+ a skeleton is.
1099
+ """
1100
+ pose = ((anatomy or {}).get("pose") or {})
1101
+ angles = pose.get("jointAngles") or {}
1102
+ if not angles:
1103
+ return []
1104
+ by_id = {c["id"]: c for c in component_tree if isinstance(c, dict) and c.get("id")}
1105
+ applied: list[str] = []
1106
+ for joint, component_id in _POSE_JOINT_TO_COMPONENT.items():
1107
+ value = angles.get(joint)
1108
+ if not (isinstance(value, list) and len(value) == 3):
1109
+ continue
1110
+ if not any(abs(float(v)) > 1e-9 for v in value):
1111
+ continue
1112
+ component = by_id.get(component_id)
1113
+ if component is None:
1114
+ continue
1115
+ transform = component.setdefault("transform", {})
1116
+ transform["rotation"] = [float(v) for v in value]
1117
+ applied.append(f"{joint}->{component_id}")
1118
+ return applied
1119
+
1120
+
1121
+ def apply_character_template(
1122
+ spec: dict,
1123
+ anatomy: dict | None = None,
1124
+ include_accessories: bool = False,
1125
+ ) -> dict:
1126
+ """Swap in the humanoid componentTree, character materials, build passes, and feature
1127
+ targets. Object specs are untouched; only called when primaryDomain is character/hybrid."""
1128
+ spec["componentTree"] = make_character_component_tree(anatomy, include_accessories)
1129
+ # Derived, never authored -- see derive_character_rig()'s docstring. Kept in step with
1130
+ # the component tree by construction, so the skeleton cannot drift away from the parts.
1131
+ spec["rig"] = derive_character_rig(spec["componentTree"])
1132
+ # Strictly after the rig: a skeleton is bind-pose data, and derive_character_rig() now
1133
+ # raises if handed a posed tree rather than mis-deriving it quietly.
1134
+ posed = apply_character_pose(spec["componentTree"], anatomy)
1135
+ if posed:
1136
+ spec["rig"]["posedJoints"] = posed
1137
+ object_class = spec.setdefault("preSpecAssessment", {}).setdefault("objectClass", {})
1138
+ object_class["primaryDomain"] = "character"
1139
+ existing = {m.get("id"): m for m in spec.get("materials", []) if isinstance(m, dict)}
1140
+ character_materials = CHARACTER_BASE_MATERIALS + (CHARACTER_ACCESSORY_MATERIALS if include_accessories else [])
1141
+ for mat in character_materials:
1142
+ merged = dict(existing.get("base", {}))
1143
+ merged.update(mat)
1144
+ merged.setdefault("name", mat["id"])
1145
+ merged.setdefault("type", "standard")
1146
+ # the generator colours meshes from `color`/`albedo`, so keep them in sync with baseColor
1147
+ base_color = mat.get("baseColor")
1148
+ if base_color:
1149
+ shade = _shade_hex(base_color, 0.82)
1150
+ merged["color"] = base_color
1151
+ # the generator only honours a palette with >= 2 entries (else it blends in beige
1152
+ # fallback tones), so provide two near-identical shades of the intended colour.
1153
+ merged["albedo"] = {"dominant": base_color, "secondary": [shade]}
1154
+ merged["colorVariation"] = {"palette": [base_color, shade], "pattern": "flat",
1155
+ "amplitude": 0.05, "heightCorrelation": 0.0}
1156
+ existing[mat["id"]] = merged
1157
+ spec["materials"] = list(existing.values())
1158
+ spec["buildPasses"] = make_character_build_passes()
1159
+ # A humanoid is reviewed as a whole each pass, so every pass renders all parts
1160
+ # (unlike the object pipeline where passes add parts incrementally).
1161
+ all_ids = [c["id"] for c in spec["componentTree"] if isinstance(c, dict) and c.get("id")]
1162
+ for build_pass in spec["buildPasses"]:
1163
+ build_pass["componentRefs"] = all_ids
1164
+ spec["featureReviewTargets"] = make_character_feature_targets(include_accessories)
1165
+ pipeline = spec.setdefault("sculptPipeline", {})
1166
+ pipeline["passOrder"] = [p["id"] for p in spec["buildPasses"]]
1167
+ pipeline["currentPass"] = "blockout"
1168
+ return spec
1169
+
1170
+
1171
+ # --- CS2 weapon-skin finish profile (image-first Tier 1) ---------------------
1172
+ # Each finish style maps to a PBR recipe. View-dependent finishes (anodized /
1173
+ # anodized-multicolored, e.g. Doppler) need a low roughness + high metalness +
1174
+ # strong environment reflection or they render muddy; see
1175
+ # grimoire/build/cs2_finishes.md and grimoire/intake/cs2_texture_acquisition.md.
1176
+ CS2_FINISH_STYLES = [
1177
+ "solid", "hydrographic", "anodized", "spray-paint",
1178
+ "anodized-multicolored", "custom-paint-job", "patina", "gunsmith",
1179
+ ]
1180
+
1181
+ CS2_FINISH_PROFILES = {
1182
+ "solid": {"baseColor": "#7a4b2b", "metalness": 0.15, "roughness": 0.55, "clearcoat": 0.0, "env": 0.9, "viewDependent": False,
1183
+ "pattern": "flat", "bands": [
1184
+ {"id": "macro", "frequency": 1.0, "amplitude": 0.05, "role": "near-uniform lacquer color"},
1185
+ {"id": "meso", "frequency": 8.0, "amplitude": 0.03, "role": "faint brush-out streaks"},
1186
+ {"id": "micro", "frequency": 40.0, "amplitude": 0.02, "role": "edge-wear scratches under grazing light"},
1187
+ ]},
1188
+ "hydrographic": {"baseColor": "#5b6357", "metalness": 0.20, "roughness": 0.50, "clearcoat": 0.10, "env": 1.0, "viewDependent": False,
1189
+ "pattern": "swirl", "bands": [
1190
+ {"id": "macro", "frequency": 3.0, "amplitude": 0.5, "role": "dip-film swirl distortion"},
1191
+ {"id": "meso", "frequency": 10.0, "amplitude": 0.15, "role": "print-pattern fine detail"},
1192
+ {"id": "micro", "frequency": 50.0, "amplitude": 0.05, "role": "edge-wear scratches under grazing light"},
1193
+ ]},
1194
+ "anodized": {"baseColor": "#3a4a9a", "metalness": 0.92, "roughness": 0.12, "clearcoat": 0.30, "env": 1.8, "viewDependent": True,
1195
+ "pattern": "brushed", "bands": [
1196
+ {"id": "macro", "frequency": 1.5, "amplitude": 0.1, "role": "dyed-metal color breakup"},
1197
+ {"id": "meso", "frequency": 20.0, "amplitude": 0.1, "role": "directional brushed-metal streaks"},
1198
+ {"id": "micro", "frequency": 70.0, "amplitude": 0.05, "role": "edge-wear scratches under grazing light"},
1199
+ ]},
1200
+ "spray-paint": {"baseColor": "#6a6a6a", "metalness": 0.10, "roughness": 0.60, "clearcoat": 0.0, "env": 0.9, "viewDependent": False,
1201
+ "pattern": "speckle", "bands": [
1202
+ {"id": "macro", "frequency": 1.0, "amplitude": 0.05, "role": "matte overspray base"},
1203
+ {"id": "meso", "frequency": 30.0, "amplitude": 0.25, "role": "overspray speckle clusters"},
1204
+ {"id": "micro", "frequency": 90.0, "amplitude": 0.1, "role": "edge-wear scratches under grazing light"},
1205
+ ]},
1206
+ "anodized-multicolored": {"baseColor": "#b0417a", "metalness": 0.95, "roughness": 0.08, "clearcoat": 0.60, "env": 2.0, "viewDependent": True,
1207
+ "pattern": "marble", "bands": [
1208
+ {"id": "macro", "frequency": 2.0, "amplitude": 0.4, "role": "broad pattern/color breakup"},
1209
+ {"id": "meso", "frequency": 14.0, "amplitude": 0.2, "role": "brushed grain / marble swirl relief"},
1210
+ {"id": "micro", "frequency": 60.0, "amplitude": 0.07, "role": "edge-wear scratches under grazing light"},
1211
+ ]},
1212
+ "custom-paint-job": {"baseColor": "#9a2b2b", "metalness": 0.20, "roughness": 0.45, "clearcoat": 0.20, "env": 1.1, "viewDependent": False,
1213
+ "pattern": "illustrative", "bands": [
1214
+ {"id": "macro", "frequency": 0.8, "amplitude": 0.6, "role": "large non-tiled artwork blocks"},
1215
+ {"id": "meso", "frequency": 6.0, "amplitude": 0.1, "role": "artwork edge detail"},
1216
+ {"id": "micro", "frequency": 40.0, "amplitude": 0.04, "role": "peel-wear scratches under grazing light"},
1217
+ ]},
1218
+ "patina": {"baseColor": "#7a6a3a", "metalness": 0.60, "roughness": 0.40, "clearcoat": 0.0, "env": 1.2, "viewDependent": False,
1219
+ "pattern": "blotch", "bands": [
1220
+ {"id": "macro", "frequency": 1.2, "amplitude": 0.35, "role": "oxidation blotch breakup"},
1221
+ {"id": "meso", "frequency": 9.0, "amplitude": 0.25, "role": "hue-shift oxidation detail"},
1222
+ {"id": "micro", "frequency": 45.0, "amplitude": 0.1, "role": "darkened edge wear under grazing light"},
1223
+ ]},
1224
+ "gunsmith": {"baseColor": "#8a7a5a", "metalness": 0.70, "roughness": 0.35, "clearcoat": 0.10, "env": 1.3, "viewDependent": False,
1225
+ "pattern": "mask-blend", "bands": [
1226
+ {"id": "macro", "frequency": 1.5, "amplitude": 0.3, "role": "custom-paint/patina mask blend"},
1227
+ {"id": "meso", "frequency": 12.0, "amplitude": 0.2, "role": "peel + oxidize transition detail"},
1228
+ {"id": "micro", "frequency": 55.0, "amplitude": 0.09, "role": "edge-wear scratches under grazing light"},
1229
+ ]},
1230
+ }
1231
+
1232
+
1233
+ def _cs2_wear_mask(float_value: float | None) -> dict:
1234
+ """Map a CS2 float (0.0 Factory New .. 1.0 Battle-Scarred) to wear-mask parameters. With no
1235
+ float (image-only default) approximate a light-moderate condition from the visible reference
1236
+ instead of silently guessing -- see grimoire/build/cs2_finishes.md ('Float -> wear')."""
1237
+ if float_value is None:
1238
+ return {
1239
+ "edgeWear": 0.35, "scratches": ["approximated-light-edge-scratch"], "chips": [],
1240
+ "alphaCurve": "curvature-weighted", "aoBias": 0.3, "approximated": True,
1241
+ "notes": "No float supplied: estimated apparent condition from the reference image.",
1242
+ }
1243
+ clamped = max(0.0, min(1.0, float_value))
1244
+ return {
1245
+ "edgeWear": round(0.1 + clamped * 0.8, 3),
1246
+ "scratches": ["edge-scratch"] if clamped > 0.15 else [],
1247
+ "chips": ["edge-chip"] if clamped > 0.55 else [],
1248
+ "alphaCurve": "curvature-weighted",
1249
+ "aoBias": round(0.15 + clamped * 0.25, 3),
1250
+ "approximated": False,
1251
+ "notes": f"Wear mask derived from float={clamped}.",
1252
+ }
1253
+
1254
+
1255
+ def _cs2_pattern_affine(paint_seed: int | None) -> dict:
1256
+ """Deterministic T2*R*S*T1 affine placement for the pattern layer, seeded by paintSeed. With
1257
+ no paintSeed (image-only default) use a fixed centered placement and report it approximated --
1258
+ never claim it matches a specific item's actual pattern (see grimoire/build/cs2_finishes.md)."""
1259
+ if paint_seed is None:
1260
+ return {
1261
+ "paintSeed": None, "affine": "T2*R*S*T1",
1262
+ "translation": [0.5, 0.5], "rotation": 0.0, "scale": [1.0, 1.0],
1263
+ "matrix": [1.0, 0.0, 0.0, 1.0, 0.5, 0.5],
1264
+ "approximated": True,
1265
+ "notes": "No paintSeed in image-first mode: deterministic default placement, reported approximated.",
1266
+ }
1267
+ rng = paint_seed & 0xFFFFFFFF
1268
+ angle = ((rng % 360) / 360.0) * 2 * math.pi
1269
+ tx = ((rng >> 8) % 1000) / 1000.0
1270
+ ty = ((rng >> 16) % 1000) / 1000.0
1271
+ scale = 0.85 + ((rng >> 24) % 30) / 100.0
1272
+ cos_a, sin_a = math.cos(angle), math.sin(angle)
1273
+ return {
1274
+ "paintSeed": paint_seed, "affine": "T2*R*S*T1",
1275
+ "translation": [round(tx, 4), round(ty, 4)], "rotation": round(angle, 4),
1276
+ "scale": [round(scale, 4), round(scale, 4)],
1277
+ "matrix": [round(cos_a * scale, 4), round(sin_a * scale, 4),
1278
+ round(-sin_a * scale, 4), round(cos_a * scale, 4),
1279
+ round(tx, 4), round(ty, 4)],
1280
+ "approximated": False,
1281
+ "notes": f"Deterministic placement from paintSeed={paint_seed}.",
1282
+ }
1283
+
1284
+
1285
+ # Minimal skin-name -> finish-style hints for the identity precedence resolver. Not exhaustive
1286
+ # (thousands of CS2 skins exist); a name that doesn't match falls through to vision/default.
1287
+ SKIN_NAME_FINISH_HINTS = {
1288
+ "doppler": "anodized-multicolored", "gamma doppler": "anodized-multicolored",
1289
+ "marble fade": "anodized-multicolored", "fade": "anodized",
1290
+ "damascus": "patina", "case hardened": "patina",
1291
+ "hydrographic": "hydrographic", "hydro dip": "hydrographic",
1292
+ "urban": "spray-paint", "spray": "spray-paint",
1293
+ "custom": "custom-paint-job", "gunsmith": "gunsmith",
1294
+ }
1295
+
1296
+
1297
+ def infer_finish_style_from_skin_name(skin_name: str) -> str | None:
1298
+ lowered = skin_name.lower()
1299
+ for keyword, style in SKIN_NAME_FINISH_HINTS.items():
1300
+ if keyword in lowered:
1301
+ return style
1302
+ return None
1303
+
1304
+
1305
+ def resolve_cs2_finish_style(
1306
+ descriptor_finish_style: str | None,
1307
+ skin_name: str | None,
1308
+ vision_finish_style: str | None,
1309
+ vision_confidence: float | None = None,
1310
+ vision_confidence_threshold: float = 0.55,
1311
+ ) -> tuple[str, list[str]]:
1312
+ """Identity precedence: explicit descriptor > skin name (parsed) > vision inference > default.
1313
+ A low-confidence vision read is still used (never silently dropped) but flagged. Disagreements
1314
+ between sources are reported, never silently overwritten -- see design.md 'Vision inference'."""
1315
+ conflicts: list[str] = []
1316
+ skin_inferred = infer_finish_style_from_skin_name(skin_name) if skin_name else None
1317
+ candidates: list[tuple[str, str]] = []
1318
+ if descriptor_finish_style:
1319
+ candidates.append(("descriptor", descriptor_finish_style))
1320
+ if skin_inferred:
1321
+ candidates.append(("skin name", skin_inferred))
1322
+ if vision_finish_style and (vision_confidence is None or vision_confidence >= vision_confidence_threshold):
1323
+ candidates.append(("vision", vision_finish_style))
1324
+ if len(candidates) >= 2 and len({style for _, style in candidates}) > 1:
1325
+ sources = ", ".join(f"{source}={style}" for source, style in candidates)
1326
+ conflicts.append(
1327
+ f"CS2 finish style conflict: {sources} disagree; using {candidates[0][1]!r} "
1328
+ f"({candidates[0][0]} takes precedence). Confirm before implementation."
1329
+ )
1330
+ if candidates:
1331
+ return candidates[0][1], conflicts
1332
+ if vision_finish_style:
1333
+ conflicts.append(
1334
+ f"CS2 finish style {vision_finish_style!r} inferred by vision below confidence "
1335
+ f"threshold ({vision_confidence}); confirm before implementation."
1336
+ )
1337
+ return vision_finish_style, conflicts
1338
+ return "anodized-multicolored", conflicts
1339
+
1340
+
1341
+ def _cs2_finish_material(finish_style: str, float_value: float | None = None, paint_seed: int | None = None) -> dict:
1342
+ profile = CS2_FINISH_PROFILES[finish_style]
1343
+ base = profile["baseColor"]
1344
+ shade = _shade_hex(base, 0.8)
1345
+ bands = profile["bands"]
1346
+ return {
1347
+ "id": "skin-finish", "name": f"CS2 {finish_style} finish", "type": "standard",
1348
+ "shaderModel": "MeshPhysicalMaterial / metallic-roughness PBR",
1349
+ "baseColor": base, "color": base,
1350
+ "albedo": {"dominant": base, "secondary": [shade],
1351
+ "samplingNotes": "Image-first: estimate from the reference; report as approximated (not the exact Valve paint texture)."},
1352
+ "colorVariation": {"palette": [base, shade], "pattern": profile["pattern"], "amplitude": bands[0]["amplitude"], "heightCorrelation": 0.25},
1353
+ "textureResolution": 1024,
1354
+ "textureProjection": {"mode": "uv", "repeat": [1.0, 1.0], "anisotropy": 8,
1355
+ "texelDensityIntent": "Preserve stable blade-scale detail; do not stretch pattern with component scale."},
1356
+ "surfaceFrequencyBands": bands,
1357
+ "roughness": {"base": profile["roughness"], "variation": 0.06, "map": "independent-procedural-field",
1358
+ "localResponse": "lower roughness on worn edges, higher in recesses"},
1359
+ "metalness": {"base": profile["metalness"], "variation": 0.03},
1360
+ "clearcoat": {"base": profile["clearcoat"]},
1361
+ "clearcoatRoughness": {"base": 0.12},
1362
+ "normal": {"pattern": "derived-from-independent-height-field", "strength": 0.3, "scale": 28.0, "space": "tangent"},
1363
+ "ambientOcclusion": {"cavityStrength": 0.3, "contactShadowBias": 0.35,
1364
+ "notes": "Darken guard/pommel seams and engraving recesses."},
1365
+ "wear": _cs2_wear_mask(float_value),
1366
+ "envMapIntensity": profile["env"],
1367
+ "finishStyle": finish_style,
1368
+ "viewDependent": profile["viewDependent"],
1369
+ "needsEnvironment": profile["viewDependent"],
1370
+ "patternPlacement": _cs2_pattern_affine(paint_seed),
1371
+ "shaderNotes": [
1372
+ "Use MeshPhysicalMaterial: metallic-roughness with independent map channels.",
1373
+ "View-dependent finishes require scene.environment (code-generated default is fine) + ACESFilmic tonemapping in sRGB.",
1374
+ "Never bake lighting/pattern into a single flat albedo.",
1375
+ ],
1376
+ "notes": f"{finish_style} finish recipe; see grimoire/build/cs2_finishes.md.",
1377
+ }
1378
+
1379
+
1380
+ _CS2_SUBSTRATE_BANDS = [
1381
+ {"id": "macro", "frequency": 2.0, "amplitude": 0.4, "role": "broad pattern/color breakup"},
1382
+ {"id": "meso", "frequency": 14.0, "amplitude": 0.2, "role": "brushed grain relief"},
1383
+ {"id": "micro", "frequency": 60.0, "amplitude": 0.07, "role": "edge-wear scratches under grazing light"},
1384
+ ]
1385
+
1386
+
1387
+ def _cs2_substrate_material() -> dict:
1388
+ return {
1389
+ "id": "substrate", "name": "Bare metal substrate", "type": "standard",
1390
+ "shaderModel": "MeshPhysicalMaterial / metallic-roughness PBR",
1391
+ "baseColor": "#3b3b40", "color": "#3b3b40",
1392
+ "colorVariation": {"palette": ["#3b3b40", "#2b2b30"], "pattern": "flat", "amplitude": 0.05, "heightCorrelation": 0.0},
1393
+ "textureResolution": 1024,
1394
+ "textureProjection": {"mode": "uv", "repeat": [2.0, 2.0], "anisotropy": 8,
1395
+ "texelDensityIntent": "Preserve stable metal-scale detail on exposed substrate."},
1396
+ "surfaceFrequencyBands": _CS2_SUBSTRATE_BANDS,
1397
+ "roughness": {"base": 0.34, "variation": 0.08, "map": "independent-procedural-field"},
1398
+ "metalness": {"base": 1.0, "variation": 0.0},
1399
+ "ambientOcclusion": {"cavityStrength": 0.3, "contactShadowBias": 0.35},
1400
+ "envMapIntensity": 1.4,
1401
+ "notes": "Exposed metal revealed by wear on painted/anodized finishes.",
1402
+ }
1403
+
1404
+
1405
+ def _cs2_hidden_material() -> dict:
1406
+ """Invisible material (opacity 0) for the organizing root group -- same trick as the
1407
+ character template's 'hidden' material, so the root component's mesh never renders."""
1408
+ return {
1409
+ "id": "hidden", "name": "Hidden (root group)", "type": "standard",
1410
+ "baseColor": "#000000", "color": "#000000",
1411
+ "colorVariation": {"palette": ["#000000", "#000000"], "pattern": "flat", "amplitude": 0.0, "heightCorrelation": 0.0},
1412
+ "albedo": {"dominant": "#000000", "secondary": ["#000000"]},
1413
+ "roughness": {"base": 1.0, "variation": 0.0},
1414
+ "opacity": {"base": 0.0},
1415
+ "notes": "Root organizing group only; not a visible surface.",
1416
+ }
1417
+
1418
+
1419
+ def _cs2node(cid, name, primitive, position, scale, material, role, level,
1420
+ importance=0.7, local_features=None):
1421
+ """Weapon-part node. All parts parent to root with safe (non-attachment) primitives
1422
+ and names so strict-quality does not demand attachment contracts."""
1423
+ return _cnode(cid, name, primitive, "root", position, scale, material=material,
1424
+ role=role, level=level, importance=importance,
1425
+ local_features=local_features or [], evidence=["full-object"])
1426
+
1427
+
1428
+ CS2_KNIFE_SUBTYPES = frozenset(
1429
+ {"karambit", "butterfly", "bayonet", "m9", "flip", "gut", "falchion", "bowie", "navaja",
1430
+ "talon", "classic"}
1431
+ )
1432
+
1433
+
1434
+ def make_cs2_component_tree(item_family: str = "knife", subtype: str | None = None) -> list:
1435
+ if item_family != "knife":
1436
+ raise ValueError(f"unsupported CS2 family {item_family!r}; only knife is implemented")
1437
+ if subtype and subtype not in CS2_KNIFE_SUBTYPES:
1438
+ raise ValueError(f"unsupported CS2 knife subtype {subtype!r}")
1439
+ # Root is an organizing group only: use the invisible 'hidden' material (opacity 0) exactly
1440
+ # like the character template, so the generator's per-component mesh for root never renders as
1441
+ # a stray box over the weapon -- no generic generator change needed.
1442
+ root = _cnode("root", "Weapon (root)", "box", None, (0, 0, 0), (1, 1, 1),
1443
+ material="hidden", role="body", level="macro", importance=1.0, anim_role="root")
1444
+ parts = [
1445
+ _cs2node("blade", "Blade", "ground-blade", (0, 0.55, 0), (1.0, 1.0, 1.0), "skin-finish", "blade", "macro", 1.0,
1446
+ ["edge bevel highlight", "engraved pattern swirl"]),
1447
+ _cs2node("grip", "Grip", "curve-sweep", (0, -0.55, 0), (1.0, 1.0, 1.0), "skin-finish", "grip", "macro", 0.9,
1448
+ ["checkered grip relief"]),
1449
+ _cs2node("guard", "Guard", "extrude", (0, 0.0, 0), (1.0, 1.0, 1.0), "substrate", "guard", "meso", 0.7),
1450
+ _cs2node("pommel", "Pommel", "sphere", (0, -0.95, 0), (0.2, 0.2, 0.2), "substrate", "pommel", "meso", 0.6),
1451
+ _cs2node("bolster", "Bolster", "box", (0, 0.02, 0), (0.2, 0.18, 0.26), "substrate", "bolster", "meso", 0.6),
1452
+ ]
1453
+ return [root, *parts]
1454
+
1455
+
1456
+ def make_cs2_feature_targets() -> list:
1457
+ return [
1458
+ {"id": "cs2-silhouette", "name": "Weapon silhouette and proportions", "tier": "critical",
1459
+ "passIds": ["blockout"], "minimumScore": 0.8, "mustPass": True,
1460
+ "componentRefs": ["root", "blade", "grip"], "evidenceRefs": ["full-object"]},
1461
+ {"id": "cs2-finish-style-read", "name": "Finish style reads correctly", "tier": "critical",
1462
+ "passIds": ["material-pass"], "minimumScore": 0.75, "mustPass": True,
1463
+ "componentRefs": ["blade"], "evidenceRefs": ["full-object"]},
1464
+ {"id": "cs2-metal-response", "name": "Metal / anodized environment response", "tier": "critical",
1465
+ "passIds": ["lighting-pass"], "minimumScore": 0.75, "mustPass": True,
1466
+ "componentRefs": ["blade", "guard"], "evidenceRefs": ["full-object"]},
1467
+ {"id": "cs2-pattern-placement", "name": "Pattern placement (approximated)", "tier": "important",
1468
+ "passIds": ["material-pass"], "minimumScore": 0.65, "mustPass": False,
1469
+ "componentRefs": ["blade"], "evidenceRefs": ["full-object"]},
1470
+ {"id": "cs2-wear-read", "name": "Wear / float reads plausibly", "tier": "important",
1471
+ "passIds": ["surface-pass"], "minimumScore": 0.65, "mustPass": False,
1472
+ "componentRefs": ["blade", "grip"], "evidenceRefs": ["full-object"]},
1473
+ ]
1474
+
1475
+
1476
+ def apply_cs2_template(
1477
+ spec: dict,
1478
+ finish_style: str | None = None,
1479
+ *,
1480
+ skin_name: str | None = None,
1481
+ vision_finish_style: str | None = None,
1482
+ vision_confidence: float | None = None,
1483
+ float_value: float | None = None,
1484
+ paint_seed: int | None = None,
1485
+ environment_available: bool = True,
1486
+ item_family: str = "knife",
1487
+ subtype: str | None = None,
1488
+ ) -> dict:
1489
+ """Seed a self-consistent image-first CS2 weapon-skin spec. Object geometry reuses the
1490
+ hard-surface path (primaryDomain=object); only the finish/material recipe is CS2-specific.
1491
+ Leaves object specs untouched unless invoked. `finish_style` is treated as the explicit
1492
+ descriptor tier; resolve_cs2_finish_style() applies identity precedence against skin_name /
1493
+ vision when finish_style is not itself given."""
1494
+ resolved_style, conflicts = resolve_cs2_finish_style(
1495
+ finish_style, skin_name, vision_finish_style, vision_confidence
1496
+ )
1497
+ if resolved_style not in CS2_FINISH_PROFILES:
1498
+ raise ValueError(f"unknown finish style {resolved_style!r}; expected one of: {', '.join(CS2_FINISH_STYLES)}")
1499
+ profile = CS2_FINISH_PROFILES[resolved_style]
1500
+ spec["componentTree"] = make_cs2_component_tree(item_family, subtype)
1501
+ spec["materials"] = [_cs2_finish_material(resolved_style, float_value, paint_seed), _cs2_substrate_material(), _cs2_hidden_material()]
1502
+ spec["featureReviewTargets"] = make_cs2_feature_targets()
1503
+ # top-level signal for the pre-render environment gate (mirrors the material value)
1504
+ spec["envMapIntensity"] = profile["env"]
1505
+ spec["cs2Finish"] = {"finishStyle": resolved_style, "viewDependent": profile["viewDependent"],
1506
+ "environment": "code-generated-default (RoomEnvironment->PMREM); user HDRI optional",
1507
+ "environmentAvailable": environment_available,
1508
+ "tier": "image-first"}
1509
+ # fill the assessment/contract so a normal validate passes; CS2 is held to the ultra-complex
1510
+ # bar, so strict-quality still requires the agent to enumerate the CS2 detail inventory first.
1511
+ pre = spec.setdefault("preSpecAssessment", {})
1512
+ if conflicts:
1513
+ unknowns = pre.setdefault("unknownsToResolveBeforeImplementation", [])
1514
+ unknowns.extend(conflict for conflict in conflicts if conflict not in unknowns)
1515
+ oc = pre.setdefault("objectClass", {})
1516
+ oc["primaryType"] = "weapon-skin"
1517
+ oc["primaryDomain"] = "object"
1518
+ oc["formLanguage"] = ["hard-surface", "bladed"]
1519
+ oc["structureKind"] = ["blade", "grip", "guard"]
1520
+ oc["motionPotential"] = ["static", "inspect-orbit"]
1521
+ oc["materialFamilies"] = ["metal", "anodized-coat" if profile["viewDependent"] else "painted-coat"]
1522
+ oc["cs2"] = True
1523
+ complexity = pre.setdefault("complexity", {})
1524
+ complexity["tier"] = "ultra-complex"
1525
+ decision = pre.setdefault("specDepthDecision", {})
1526
+ decision["requiredDepth"] = "ultra-complex"
1527
+ decision["needsRepetitionSystems"] = True
1528
+ decision["needsMaterialLocalOverrides"] = True
1529
+ decision["minimumComponentLevels"] = ["macro", "meso", "micro"]
1530
+ inv = pre.setdefault("detailInventory", {})
1531
+ # CS2 skins are treated as ultra-complex: the finish/wear/hardware IS the item, so the detail
1532
+ # gate demands the ultra count (16). strict-quality then blocks code-gen until the agent
1533
+ # enumerates the identity-defining details -- it does not pass on the bare seed.
1534
+ inv["targetMinDetails"] = 16
1535
+ contract = spec.setdefault("qualityContract", {})
1536
+ contract["qualityBar"] = "ultra-complex"
1537
+ contract.setdefault("minimumSpecDepth", {}).update(
1538
+ {"macroComponents": 5, "mesoComponents": 16, "microFeatureGroups": 8,
1539
+ "materialLayers": 4, "repetitionSystems": 2, "reviewViewpoints": 5}
1540
+ )
1541
+ return spec
1542
+
1543
+
1544
+ def apply_cs2_manifest_evidence(spec: dict, manifest: dict) -> dict:
1545
+ intake = {
1546
+ "schemaVersion": manifest.get("schemaVersion"),
1547
+ "state": manifest.get("state"),
1548
+ "itemFamily": manifest.get("itemFamily"),
1549
+ "subtype": manifest.get("subtype"),
1550
+ "route": manifest.get("route"),
1551
+ "exactnessTier": manifest.get("exactnessTier"),
1552
+ "identity": manifest.get("identity", {}),
1553
+ "finish": manifest.get("finish", {}),
1554
+ "paintedRegions": manifest.get("paintedRegions", []),
1555
+ "unpaintedRegions": manifest.get("unpaintedRegions", []),
1556
+ "assets": manifest.get("assets", {}),
1557
+ "camera": manifest.get("camera", {}),
1558
+ "assumptions": manifest.get("assumptions", {}),
1559
+ "confidence": manifest.get("confidence", {}),
1560
+ "provenance": manifest.get("provenance", {}),
1561
+ "warnings": manifest.get("warnings", []),
1562
+ }
1563
+ spec["cs2Intake"] = intake
1564
+ spec["exactnessTier"] = manifest.get("exactnessTier")
1565
+ if isinstance(manifest.get("camera"), dict) and manifest["camera"].get("referenceCamera"):
1566
+ spec["referenceCamera"] = manifest["camera"]["referenceCamera"]
1567
+ materials = spec.get("materials", [])
1568
+ skin = next((item for item in materials if isinstance(item, dict) and item.get("id") == "skin-finish"), None)
1569
+ if isinstance(skin, dict):
1570
+ route = manifest.get("route")
1571
+ projection = skin.setdefault("textureProjection", {})
1572
+ if route == "reference-projection":
1573
+ projection["mode"] = "projective"
1574
+ projection["source"] = manifest.get("deLitAlbedo") or manifest.get("sourceImage")
1575
+ elif route == "authored-texture":
1576
+ projection["mode"] = "uv"
1577
+ reference_pbr = manifest.get("referencePbr")
1578
+ if isinstance(reference_pbr, dict):
1579
+ skin["referencePbr"] = reference_pbr
1580
+ elif route == "procedural-finish":
1581
+ projection["mode"] = "procedural"
1582
+ skin["route"] = route
1583
+ skin["exactnessTier"] = manifest.get("exactnessTier")
1584
+ skin["paintedRegions"] = manifest.get("paintedRegions", [])
1585
+ skin["unpaintedRegions"] = manifest.get("unpaintedRegions", [])
1586
+ return spec
1587
+
1588
+
1589
+ def make_spec(target_name: str, image: str | None, assessment_payload: dict | None = None) -> dict:
1590
+ target_id = slugify(target_name)
1591
+ pre_spec_assessment = make_pre_spec_assessment(target_name)
1592
+ quality_contract = make_quality_contract()
1593
+ local_spec_search = None
1594
+ if assessment_payload:
1595
+ incoming_assessment = assessment_payload.get("preSpecAssessment")
1596
+ incoming_contract = assessment_payload.get("qualityContract")
1597
+ incoming_local_spec_search = assessment_payload.get("localSpecSearch")
1598
+ if isinstance(incoming_assessment, dict):
1599
+ pre_spec_assessment = incoming_assessment
1600
+ if isinstance(incoming_contract, dict):
1601
+ quality_contract = incoming_contract
1602
+ if isinstance(incoming_local_spec_search, dict):
1603
+ local_spec_search = incoming_local_spec_search
1604
+ spec = {
1605
+ "targetName": target_name,
1606
+ "targetId": target_id,
1607
+ "schemaVersion": "2.1",
1608
+ "terminologyProfile": {
1609
+ "domain": "real-time procedural Three.js asset",
1610
+ "geometryTerms": [
1611
+ "silhouette",
1612
+ "topology",
1613
+ "primitive",
1614
+ "bevel",
1615
+ "chamfer",
1616
+ "taper",
1617
+ "bend",
1618
+ "boolean cut",
1619
+ "edge loop",
1620
+ "surface normal",
1621
+ "displacement",
1622
+ ],
1623
+ "materialTerms": [
1624
+ "albedo",
1625
+ "baseColor",
1626
+ "roughness",
1627
+ "metalness",
1628
+ "normal map",
1629
+ "bump map",
1630
+ "ambient occlusion",
1631
+ "cavity dirt",
1632
+ "edge wear",
1633
+ "clearcoat",
1634
+ ],
1635
+ "lightingTerms": [
1636
+ "key light",
1637
+ "fill light",
1638
+ "rim light",
1639
+ "HDRI/environment reflection",
1640
+ "contact shadow",
1641
+ ],
1642
+ "descriptionRule": "Use measurable 3D graphics terms. Avoid vague words unless they are paired with concrete geometry/material/shader parameters.",
1643
+ },
1644
+ "sourceImage": image or "",
1645
+ "referenceCamera": {
1646
+ "solved": False,
1647
+ "fovDegrees": 40.0,
1648
+ "aspect": 1.0,
1649
+ "orientation": {"yaw": 0.0, "pitch": 0.0, "roll": 0.0},
1650
+ "positionHint": [0.0, 0.0, 3.0],
1651
+ "note": (
1652
+ "For likeness work, solve the reference camera (vg asset rebuild-object solve-camera-pose) so the "
1653
+ "review render aligns with the photo and the reference can be projected. Confirm by overlay review."
1654
+ ),
1655
+ },
1656
+ "suitability": "conditional",
1657
+ "scores": {
1658
+ "object_isolation": 0,
1659
+ "silhouette_readability": 0,
1660
+ "depth_inference": 0,
1661
+ "primitive_decomposition": 0,
1662
+ "material_procedurality": 0,
1663
+ "occlusion_risk": 0,
1664
+ "interaction_fit": 0,
1665
+ },
1666
+ "preSpecAssessment": pre_spec_assessment,
1667
+ "qualityContract": quality_contract,
1668
+ "qualityTargets": {
1669
+ "targetFidelity": 0.7,
1670
+ "mustMatch": [
1671
+ "macro silhouette and proportions",
1672
+ "primary material albedo/roughness response",
1673
+ "reference-derived PBR material response at or above 0.7 confidence when source pixels are usable",
1674
+ "most recognizable local features",
1675
+ ],
1676
+ "niceToHave": [
1677
+ "micro scratches, stains, chips, and dirt masks",
1678
+ "secondary lighting match",
1679
+ ],
1680
+ "fpsTarget": 60,
1681
+ "reviewViewpoints": ["front", "three-quarter", "side", "thickness-axis", "long-axis"],
1682
+ },
1683
+ "selfCorrectLoop": {
1684
+ "enabled": True,
1685
+ "visualAcceptance": {
1686
+ "reviewer": "ai-vision",
1687
+ "threshold": 0.7,
1688
+ "comparisonArtifactRequired": True,
1689
+ "layerScoresRequired": True,
1690
+ "codePixelDiffIsAcceptanceAuthority": False,
1691
+ "scoringRule": "AI vision must inspect a side-by-side reference/render sheet and score the current pass from 0 to 1. Pixel-diff code may assist diagnostics but cannot approve a pass.",
1692
+ "requiredLayerScores": [
1693
+ "silhouetteProportion",
1694
+ "componentStructure",
1695
+ "formDetail",
1696
+ "materialSurface",
1697
+ "lightingCamera",
1698
+ ],
1699
+ "featureReviewPolicy": {
1700
+ "enabled": True,
1701
+ "reviewUnit": "semantic-subsystem",
1702
+ "maxCriticalFeaturesPerPass": 5,
1703
+ "maxImportantFeaturesPerPass": 3,
1704
+ "criticalDefaultThreshold": 0.8,
1705
+ "importantAverageThreshold": 0.65,
1706
+ "adaptiveEscalation": True,
1707
+ "singleImagePairOnly": True,
1708
+ "selectionRule": "Choose only the most visually salient, identity-defining, user-prioritized, or high-risk semantic systems. Group repeated parts instead of reviewing every mesh. AI vision scores every selected feature from the same full reference/render pair.",
1709
+ },
1710
+ },
1711
+ "reviewAfterPasses": [
1712
+ "blockout",
1713
+ "structural-pass",
1714
+ "form-refinement",
1715
+ "material-pass",
1716
+ "surface-pass",
1717
+ "lighting-pass",
1718
+ "interaction-pass",
1719
+ "optimization-pass",
1720
+ ],
1721
+ "allowedActions": [
1722
+ "continue",
1723
+ "refine-spec",
1724
+ "refine-code",
1725
+ "request-input",
1726
+ "stop",
1727
+ ],
1728
+ "specRefineTriggers": [
1729
+ "missing component",
1730
+ "wrong primitive family",
1731
+ "wrong proportions",
1732
+ "material layer under-specified",
1733
+ "local feature not traceable to viewEvidence",
1734
+ "reference ambiguity discovered during implementation",
1735
+ ],
1736
+ "codeRefineTriggers": [
1737
+ "spec is adequate but generated geometry/material does not match",
1738
+ "browser render differs from reference",
1739
+ "performance budget exceeded",
1740
+ "lighting hides geometry or material response",
1741
+ ],
1742
+ "stopCriteria": [
1743
+ "target fidelity reached or user accepts current approximation",
1744
+ "remaining gaps require new reference images or manual art",
1745
+ ],
1746
+ "screenshotPolicy": {
1747
+ "requiredForPasses": [
1748
+ "blockout",
1749
+ "structural-pass",
1750
+ "form-refinement",
1751
+ "material-pass",
1752
+ "surface-pass",
1753
+ "lighting-pass",
1754
+ "interaction-pass",
1755
+ ],
1756
+ "preferredCapture": "in-app-browser-screenshot",
1757
+ "fallbackCapture": "user-supplied-screenshot-path",
1758
+ "minimumEvidence": "Each visual pass needs a reference image, rendered screenshot, side-by-side comparison sheet, AI vision score, layer scores, and critique before choosing continue.",
1759
+ "reviewPairRule": "Compare the same camera/viewpoint whenever possible; do not judge a front reference against a random render angle.",
1760
+ "acceptanceAuthority": "AI vision review of the comparison sheet. Code-generated pixel similarity is not sufficient evidence.",
1761
+ },
1762
+ },
1763
+ "featureReviewTargets": [
1764
+ {
1765
+ "id": "overall-silhouette",
1766
+ "name": "Overall silhouette and proportion system",
1767
+ "tier": "critical",
1768
+ "passIds": ["blockout"],
1769
+ "minimumScore": 0.8,
1770
+ "mustPass": True,
1771
+ "componentRefs": ["root"],
1772
+ "evidenceRefs": ["full-object"],
1773
+ },
1774
+ {
1775
+ "id": "primary-structure",
1776
+ "name": "Primary identity-defining structure",
1777
+ "tier": "critical",
1778
+ "passIds": ["structural-pass", "form-refinement"],
1779
+ "minimumScore": 0.8,
1780
+ "mustPass": True,
1781
+ "componentRefs": ["root"],
1782
+ "evidenceRefs": ["full-object"],
1783
+ },
1784
+ {
1785
+ "id": "reference-material-system",
1786
+ "name": "Primary reference material and surface response",
1787
+ "tier": "critical",
1788
+ "passIds": ["material-pass", "surface-pass"],
1789
+ "minimumScore": 0.75,
1790
+ "mustPass": True,
1791
+ "componentRefs": ["root"],
1792
+ "evidenceRefs": ["full-object"],
1793
+ },
1794
+ ],
1795
+ "sculptPipeline": {
1796
+ "passGateMode": "locked-sequential",
1797
+ "passOrder": [
1798
+ "blockout",
1799
+ "structural-pass",
1800
+ "form-refinement",
1801
+ "material-pass",
1802
+ "surface-pass",
1803
+ "lighting-pass",
1804
+ "interaction-pass",
1805
+ "optimization-pass",
1806
+ ],
1807
+ "currentPass": "blockout",
1808
+ "completedPasses": [],
1809
+ "lastCompletedPass": "",
1810
+ "blockedReason": "blockout requires a browser screenshot and self-correction review before structural-pass unlocks",
1811
+ "nextRequiredEvidence": [
1812
+ "blockout browser render screenshot from your agent's browser/screenshot tool",
1813
+ "side-by-side reference/render comparison sheet",
1814
+ "AI vision score >= 0.7 with layer scores and mismatch critique",
1815
+ "critical semantic feature scores from the same image pair meeting their individual thresholds",
1816
+ "reviewHistory entry for blockout with action=continue",
1817
+ ],
1818
+ },
1819
+ "lookDevTargets": {
1820
+ "qualityPriority": "reference-fidelity",
1821
+ "materialPass": {
1822
+ "albedoPaletteRequired": True,
1823
+ "roughnessVariationRequired": True,
1824
+ "normalOrBumpRequired": True,
1825
+ "localOverridesRequired": True,
1826
+ "minimumTextureResolution": 1024,
1827
+ "preferredTextureResolution": 2048,
1828
+ "independentMapChannels": [
1829
+ "albedo",
1830
+ "roughness",
1831
+ "height",
1832
+ "normal",
1833
+ "ambient-occlusion",
1834
+ ],
1835
+ "requiredSurfaceFrequencyBands": ["macro", "meso", "micro"],
1836
+ "geometryReliefRequiredWhenSilhouetteAffected": True,
1837
+ "referencePbrExtraction": {
1838
+ "requiredWhenSourceImagePresent": True,
1839
+ "targetThreshold": 0.7,
1840
+ "stopOnLowConfidence": True,
1841
+ "script": "vg asset rebuild-object extract-pbr-evidence",
1842
+ "acceptedLimitation": "single-image extraction is reference-derived inference, not exact photogrammetry",
1843
+ },
1844
+ "mustAvoid": [
1845
+ "single flat albedo per material",
1846
+ "uniform roughness",
1847
+ "albedo texture reused as roughness/height/normal/AO",
1848
+ "single-frequency random noise",
1849
+ "plastic-looking smooth bark, stone, cloth, foliage, or aged material",
1850
+ "local color/detail described only in prose without material masks",
1851
+ "claiming exact PBR recovery when confidence is below the target threshold",
1852
+ ],
1853
+ },
1854
+ "lightingPass": {
1855
+ "requiredTerms": [
1856
+ "key light",
1857
+ "fill light",
1858
+ "rim or environment light",
1859
+ "exposure",
1860
+ "tone mapping",
1861
+ "background",
1862
+ "contact shadow",
1863
+ ],
1864
+ "mustAvoid": [
1865
+ "ambient-only lighting",
1866
+ "flat value range",
1867
+ "missing contact shadow",
1868
+ "reference lighting copied without separating material readability",
1869
+ ],
1870
+ },
1871
+ "screenshotReview": [
1872
+ "Compare albedo palette and local color zones.",
1873
+ "Compare roughness/normal/bump response under light.",
1874
+ "Compare cavity dirt, edge wear, stains, moss, scratches, or other local masks.",
1875
+ "Compare key/fill/rim structure, exposure, tone mapping, background, and contact shadows.",
1876
+ "Capture a neutral-light render to verify material readability without reference lighting.",
1877
+ "Capture a grazing-light close-up to expose flat normals, uniform roughness, tiling, and plastic highlights.",
1878
+ "Capture a reference-matched render from the same camera framing as the source.",
1879
+ ],
1880
+ },
1881
+ "actionReadiness": {
1882
+ "contract": "Every macro/meso component should be generated as a stable named Object3D pivot node with a mesh child, action metadata, optional sockets, collider proxy, and destruction metadata.",
1883
+ "defaultRigType": "action-ready-static-rig",
1884
+ "rootMotionNode": "root",
1885
+ "requiredComponentFields": [
1886
+ "id",
1887
+ "parent",
1888
+ "transform",
1889
+ "attachment for child appendages, connectors, limbs, tubes, handles, legs, horns, wings, branches, or cables",
1890
+ "actionProfile.animationRole",
1891
+ "actionProfile.pivot",
1892
+ "actionProfile.collider",
1893
+ "actionProfile.destruction",
1894
+ ],
1895
+ "transformChannels": [
1896
+ "translate",
1897
+ "rotate",
1898
+ "scale",
1899
+ "bend",
1900
+ "twist",
1901
+ "detach",
1902
+ "visibility",
1903
+ "material-state",
1904
+ ],
1905
+ "authoringRules": [
1906
+ "Do not collapse independently movable parts into one mesh.",
1907
+ "Put transforms on component pivot groups, not only on raw meshes.",
1908
+ "For attached child parts, put the pivot at the semantic root/socket and build visible geometry from localStart to localEnd.",
1909
+ "Represent hinge, socket, detachable, and breakable intent even when no animation is implemented yet.",
1910
+ "Use simplified collider proxies for runtime physics instead of visual mesh colliders by default.",
1911
+ ],
1912
+ "destructionPolicy": {
1913
+ "defaultBreakable": False,
1914
+ "fractureGroupNaming": "Use stable semantic names such as body-shell, left-hinge, glass-panel, branch-segment.",
1915
+ "debrisStrategy": "Prefer detachable component groups and a small number of procedural fragments over random mesh explosion.",
1916
+ },
1917
+ },
1918
+ "assumptions": [],
1919
+ "coordinateFrame": {
1920
+ "front": "camera-facing side in the reference image",
1921
+ "up": "image up direction",
1922
+ "scaleReference": "unit scale; adjust after first browser render",
1923
+ },
1924
+ "silhouette": {
1925
+ "boundingShape": "",
1926
+ "aspectRatios": [],
1927
+ "symmetry": "",
1928
+ "dominantCurves": [],
1929
+ "negativeSpaces": [],
1930
+ "landmarks": [],
1931
+ },
1932
+ "viewEvidence": [
1933
+ {
1934
+ "id": "full-object",
1935
+ "view": "primary",
1936
+ "imageRegion": {
1937
+ "x": 0.0,
1938
+ "y": 0.0,
1939
+ "width": 1.0,
1940
+ "height": 1.0,
1941
+ "units": "normalized",
1942
+ },
1943
+ "observations": [],
1944
+ "confidence": 0.5,
1945
+ }
1946
+ ],
1947
+ "componentTree": [
1948
+ {
1949
+ "id": "root",
1950
+ "name": target_name,
1951
+ "level": "macro",
1952
+ "role": "body",
1953
+ "importance": 1.0,
1954
+ "confidence": 0.5,
1955
+ "primitive": "box",
1956
+ "topologyClass": "assembled-solid",
1957
+ "topologyRationale": (
1958
+ "Placeholder root blockout; reclassify per Workstream A's decision tree "
1959
+ "(grimoire/intake/surface_topology.md) once real geometry is authored."
1960
+ ),
1961
+ "geometryDescriptor": {
1962
+ "topologyIntent": "low-poly blockout with bevel-ready edges",
1963
+ "edgeTreatment": {
1964
+ "type": "none",
1965
+ "bevelRadius": 0.0,
1966
+ "segments": 1,
1967
+ },
1968
+ "deformationStack": [],
1969
+ "uvStrategy": "generated procedural coordinates",
1970
+ "normalStrategy": "vertex normals from generated geometry",
1971
+ },
1972
+ "parent": None,
1973
+ "attachment": None,
1974
+ "dimensions": {
1975
+ "width": 1.0,
1976
+ "height": 1.0,
1977
+ "depth": 1.0,
1978
+ "units": "relative",
1979
+ "confidence": 0.5,
1980
+ },
1981
+ "transform": {
1982
+ "position": [0, 0, 0],
1983
+ "rotation": [0, 0, 0],
1984
+ "scale": [1, 1, 1],
1985
+ },
1986
+ "actionProfile": {
1987
+ "animationRole": "root",
1988
+ "pivot": {
1989
+ "mode": "center",
1990
+ "localPosition": [0, 0, 0],
1991
+ "axis": [0, 1, 0],
1992
+ "confidence": 0.5,
1993
+ },
1994
+ "transformChannels": {
1995
+ "translate": True,
1996
+ "rotate": True,
1997
+ "scale": True,
1998
+ "bend": False,
1999
+ "twist": False,
2000
+ "detach": False,
2001
+ "visibility": True,
2002
+ "materialState": True,
2003
+ },
2004
+ "sockets": [],
2005
+ "collider": {
2006
+ "type": "box",
2007
+ "offset": [0, 0, 0],
2008
+ "scale": [1, 1, 1],
2009
+ "isTrigger": False,
2010
+ "notes": "Replace with sphere/capsule/compound proxy when the object shape demands it.",
2011
+ },
2012
+ "constraints": [],
2013
+ "destruction": {
2014
+ "breakable": False,
2015
+ "fractureGroup": "root",
2016
+ "seamRefs": [],
2017
+ "detachableFragments": [],
2018
+ "breakImpulse": 0.0,
2019
+ "debrisMaterial": "base",
2020
+ },
2021
+ },
2022
+ "material": "base",
2023
+ "materialLayers": ["base"],
2024
+ "deformations": [],
2025
+ "joints": [],
2026
+ "seams": [],
2027
+ "localFeatures": [],
2028
+ "surfaceDetail": {
2029
+ "macroRoughness": 0.0,
2030
+ "microRoughness": 0.0,
2031
+ "bumpAmplitude": 0.0,
2032
+ "normalPattern": "",
2033
+ "displacementPattern": "",
2034
+ "occlusionPattern": "",
2035
+ "edgeWearPattern": "",
2036
+ "notes": "",
2037
+ },
2038
+ "evidenceRefs": ["full-object"],
2039
+ "details": [],
2040
+ "fidelityTier": "blockout",
2041
+ }
2042
+ ],
2043
+ "materials": [
2044
+ {
2045
+ "id": "base",
2046
+ "name": "Base material",
2047
+ "type": "standard",
2048
+ "shaderModel": "MeshStandardMaterial / PBR approximation",
2049
+ "baseColor": "#8A7A5F",
2050
+ "color": "#8A7A5F",
2051
+ "albedo": {
2052
+ "dominant": "#8A7A5F",
2053
+ "secondary": ["#6E614B", "#A08F70"],
2054
+ "samplingNotes": "Use image-observed local color zones, not a single averaged color.",
2055
+ },
2056
+ "colorVariation": {
2057
+ "palette": ["#8A7A5F", "#6E614B", "#A08F70"],
2058
+ "pattern": "mottled",
2059
+ "amplitude": 0.15,
2060
+ "heightCorrelation": 0.3,
2061
+ },
2062
+ "textureResolution": 1024,
2063
+ "textureProjection": {
2064
+ "mode": "uv",
2065
+ "repeat": [2.0, 2.0],
2066
+ "anisotropy": 8,
2067
+ "texelDensityIntent": "Preserve stable world/object-scale detail; do not stretch micro detail with component scale.",
2068
+ },
2069
+ "surfaceFrequencyBands": [
2070
+ {
2071
+ "id": "macro",
2072
+ "frequency": 2.0,
2073
+ "amplitude": 0.42,
2074
+ "role": "broad color and height breakup",
2075
+ },
2076
+ {
2077
+ "id": "meso",
2078
+ "frequency": 12.0,
2079
+ "amplitude": 0.22,
2080
+ "role": "ridges, pores, grain, dents, or equivalent visible relief",
2081
+ },
2082
+ {
2083
+ "id": "micro",
2084
+ "frequency": 56.0,
2085
+ "amplitude": 0.08,
2086
+ "role": "highlight breakup visible under grazing light",
2087
+ },
2088
+ ],
2089
+ "roughness": {
2090
+ "base": 0.75,
2091
+ "variation": 0.15,
2092
+ "map": "independent-procedural-field",
2093
+ "localResponse": "higher roughness in cavities, lower roughness on worn edges",
2094
+ },
2095
+ "metalness": {
2096
+ "base": 0.0,
2097
+ "variation": 0.0,
2098
+ },
2099
+ "normal": {
2100
+ "pattern": "derived-from-independent-height-field",
2101
+ "strength": 0.35,
2102
+ "scale": 24.0,
2103
+ "space": "tangent",
2104
+ },
2105
+ "bump": {
2106
+ "pattern": "none",
2107
+ "amplitude": 0.0,
2108
+ "scale": 1.0,
2109
+ },
2110
+ "displacement": {
2111
+ "pattern": "none",
2112
+ "amplitude": 0.0,
2113
+ "scale": 1.0,
2114
+ "silhouetteAffects": False,
2115
+ },
2116
+ "ambientOcclusion": {
2117
+ "cavityStrength": 0.25,
2118
+ "contactShadowBias": 0.35,
2119
+ "notes": "Darken creases, seams, intersections, and recessed local features.",
2120
+ },
2121
+ "wear": {
2122
+ "edgeWear": 0.0,
2123
+ "scratches": [],
2124
+ "chips": [],
2125
+ },
2126
+ "dirt": {
2127
+ "amount": 0.0,
2128
+ "cavityBias": 0.0,
2129
+ "color": "#2F2A22",
2130
+ },
2131
+ "localOverrides": [],
2132
+ "shaderNotes": [
2133
+ "Prefer MeshPhysicalMaterial when clearcoat, sheen, transmission, or thin-surface response is observed; otherwise use MeshStandardMaterial-compatible PBR channels.",
2134
+ "Generate albedo, roughness, height/normal, and AO independently; never alias albedo into roughness.",
2135
+ "Use normal/bump/displacement only when they map to observed surface relief.",
2136
+ "Use displacement geometry when the observed relief changes the close-up silhouette; texture-only relief is insufficient there.",
2137
+ ],
2138
+ "notes": "Replace with image-derived color, roughness, noise, and edge-wear notes.",
2139
+ }
2140
+ ],
2141
+ "repetitionSystems": [],
2142
+ "buildPasses": [
2143
+ {
2144
+ "id": "blockout",
2145
+ "goal": "Match macro silhouette and proportions.",
2146
+ "componentRefs": ["root"],
2147
+ "acceptance": [
2148
+ "Silhouette reads correctly without materials.",
2149
+ "Quality contract has named all required macro feature groups before code generation.",
2150
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold.",
2151
+ ],
2152
+ },
2153
+ {
2154
+ "id": "structural-pass",
2155
+ "goal": "Build the component hierarchy implied by the pre-spec complexity assessment.",
2156
+ "componentRefs": ["root"],
2157
+ "acceptance": [
2158
+ "Macro, meso, and repeated structures meet qualityContract.minimumSpecDepth.",
2159
+ "Parent-child relations, joints, seams, sockets, and contact points are explicit.",
2160
+ "Every attached child appendage/connector has parentSocket, localStart/localEnd, contactType, embedDepth or overlap, and gapTolerance.",
2161
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold.",
2162
+ ],
2163
+ },
2164
+ {
2165
+ "id": "form-refinement",
2166
+ "goal": "Refine shape, deformation, bevels, tapers, curves, asymmetry, and visible local geometry.",
2167
+ "componentRefs": ["root"],
2168
+ "acceptance": [
2169
+ "Important visible forms are represented in component geometryDescriptor, deformations, localFeatures, or repetitionSystems.",
2170
+ "Endpoint-based child parts are rooted at their attachment sockets and do not visibly float away from parents.",
2171
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold.",
2172
+ ],
2173
+ },
2174
+ {
2175
+ "id": "material-pass",
2176
+ "goal": "Match material color, roughness, bump, and local variation.",
2177
+ "componentRefs": ["root"],
2178
+ "acceptance": [
2179
+ "Reference-derived albedo palette records dominant, secondary, and accent colors per visible material.",
2180
+ "Each important material defines roughness variation and at least one normal/bump/displacement response.",
2181
+ "Local material overrides, dirt/wear/stains/moss/chips/scratches or equivalent masks are tied to evidenceRefs.",
2182
+ "Thin, transparent, reflective, wet, or fibrous materials document alpha/transmission/clearcoat/metalness/fiber response when relevant.",
2183
+ "Generated preview uses procedural albedo/roughness/bump texture or vertex color variation instead of one flat color.",
2184
+ "Generated preview uses independent PBR maps at 1024px or higher for the quality-first tier.",
2185
+ "If source pixels are available, referencePbr extraction passed at confidence >= 0.7 or the pass is stopped/requesting better references.",
2186
+ "Macro, meso, and micro surface frequency bands are visible at the intended review distance without obvious tiling.",
2187
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold.",
2188
+ ],
2189
+ },
2190
+ {
2191
+ "id": "surface-pass",
2192
+ "goal": "Add procedural surface locality such as normal/bump/displacement, AO, dirt, stains, chips, grain, moss, scratches, and wear.",
2193
+ "componentRefs": ["root"],
2194
+ "acceptance": [
2195
+ "Every required material feature group has local overrides or surfaceDetail tied to evidenceRefs.",
2196
+ "A grazing-angle close-up proves that normal/height detail breaks highlights naturally and does not read as smooth plastic.",
2197
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold.",
2198
+ ],
2199
+ },
2200
+ {
2201
+ "id": "lighting-pass",
2202
+ "goal": "Make material and form readable under neutral turntable lighting plus optional reference lighting.",
2203
+ "componentRefs": ["root"],
2204
+ "acceptance": [
2205
+ "lightingFromPhoto identifies key light direction/color/intensity, fill light, rim or environment light, and ambient color.",
2206
+ "Exposure, tone mapping, background color/gradient, shadow softness, and contact shadow behavior are specified.",
2207
+ "Lighting does not hide geometry/material gaps and screenshots can be compared fairly to the reference.",
2208
+ "Neutral, grazing, and reference-matched lighting checks distinguish material errors from lighting errors.",
2209
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold.",
2210
+ ],
2211
+ },
2212
+ {
2213
+ "id": "interaction-pass",
2214
+ "goal": "Make the model ready for future animation, transformation, physics, or destruction.",
2215
+ "componentRefs": ["root"],
2216
+ "acceptance": [
2217
+ "Macro and movable meso components have stable pivot nodes.",
2218
+ "Sockets, collider proxies, and destruction metadata are present for future runtime actions.",
2219
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold.",
2220
+ ],
2221
+ },
2222
+ {
2223
+ "id": "optimization-pass",
2224
+ "goal": "Protect runtime performance after visual fidelity is accepted.",
2225
+ "componentRefs": ["root"],
2226
+ "acceptance": [
2227
+ "Triangle count, draw calls, instancing, LOD strategy, and FPS target are documented or verified.",
2228
+ "Repeated detail is instanced or simplified where possible without breaking silhouette/material believability.",
2229
+ ],
2230
+ },
2231
+ ],
2232
+ "visualEvidence": [],
2233
+ "reviewHistory": [],
2234
+ "lodPlan": [
2235
+ {
2236
+ "tier": "near",
2237
+ "distance": 0,
2238
+ "strategy": "full component tree and material layers",
2239
+ },
2240
+ {
2241
+ "tier": "far",
2242
+ "distance": 30,
2243
+ "strategy": "merge static components and reduce local feature geometry",
2244
+ },
2245
+ ],
2246
+ "performanceBudget": {
2247
+ "qualityPriority": "reference-fidelity",
2248
+ "targetTriangles": 250000,
2249
+ "maxDrawCalls": 160,
2250
+ "textureSize": 2048,
2251
+ "fpsTarget": 30,
2252
+ "optimizationPolicy": "Reach accepted visual fidelity first, then optimize without removing reference-critical geometry or surface layers.",
2253
+ },
2254
+ "lightingFromPhoto": [],
2255
+ "proceduralStrategy": [
2256
+ "Block out macro silhouette first.",
2257
+ "Add component hierarchy and joints.",
2258
+ "Create stable pivot groups, sockets, collider proxies, and destruction metadata before visual polish.",
2259
+ "Refine forms with bevels, tapers, bends, and procedural noise.",
2260
+ "Run reference PBR extraction for important source-image materials and stop when confidence is below the target threshold.",
2261
+ "Add material variation before adding expensive micro-geometry.",
2262
+ ],
2263
+ "animationAnchors": [
2264
+ "root pivot node supports whole-object translation, rotation, scale, and visibility changes",
2265
+ "component pivot groups support later local transforms without rebuilding geometry",
2266
+ ],
2267
+ "destructionAnchors": [
2268
+ "actionProfile.destruction.fractureGroup marks detachable or breakable component sets",
2269
+ "component seams and sockets define plausible break points instead of random explosions",
2270
+ ],
2271
+ "risks": [],
2272
+ }
2273
+ if local_spec_search is not None:
2274
+ spec["localSpecSearch"] = local_spec_search
2275
+ if assessment_payload and isinstance(assessment_payload.get("pipelineRouting"), dict):
2276
+ spec["pipelineRouting"] = assessment_payload["pipelineRouting"]
2277
+ inject_geometry_rules(spec, target_name)
2278
+ return spec
2279
+
2280
+
2281
+ def main(argv: list[str]) -> int:
2282
+ parser = argparse.ArgumentParser(description=__doc__)
2283
+ parser.add_argument("target_name", help="Human-readable object name")
2284
+ parser.add_argument("--image", help="Reference image path or URL")
2285
+ parser.add_argument("--assessment", type=Path, help="Pre-spec assessment JSON from stage2_spec/new_pre_spec_assessment.py")
2286
+ parser.add_argument("--manifest", type=Path, help="Validated cs2-intake.json produced by stage1 intake")
2287
+ parser.add_argument("--out", type=Path, help="Output JSON path")
2288
+ parser.add_argument("--force", action="store_true", help="Overwrite output file")
2289
+ parser.add_argument("--character", action="store_true",
2290
+ help="Use the humanoid character template (auto-enabled when the assessment primaryDomain is character/hybrid)")
2291
+ parser.add_argument("--accessories", action="store_true",
2292
+ help="Character template only: add the opt-in accessory set (glasses, headphones, chest "
2293
+ "decal). Off by default so the baseline humanoid carries no reference-person traits.")
2294
+ parser.add_argument("--cs2", action="store_true",
2295
+ help="Use the CS2 weapon-skin finish profile (image-first; auto-enabled when the assessment objectClass.cs2 is true)")
2296
+ parser.add_argument("--finish-style", choices=CS2_FINISH_STYLES, default=None,
2297
+ help="CS2 finish style descriptor (explicit; takes precedence over --skin-name/--vision-finish-style). "
2298
+ "Falls back to anodized-multicolored if nothing else resolves it.")
2299
+ parser.add_argument("--skin-name", help="CS2 skin name, e.g. 'Karambit | Doppler' (used to infer finish style)")
2300
+ parser.add_argument("--vision-finish-style", choices=CS2_FINISH_STYLES,
2301
+ help="Finish style inferred by vision from the reference image (image-only mode)")
2302
+ parser.add_argument("--vision-confidence", type=float,
2303
+ help="Confidence (0-1) of --vision-finish-style; below threshold it is still used but flagged")
2304
+ parser.add_argument("--float", dest="cs2_float", type=float,
2305
+ help="CS2 item float (0.0 Factory New .. 1.0 Battle-Scarred); approximated from the image if omitted")
2306
+ parser.add_argument("--paint-seed", type=int, help="CS2 paint seed; deterministic default placement if omitted")
2307
+ parser.add_argument("--no-environment", action="store_true",
2308
+ help="Mark the code-generated default environment as unavailable (testing/last-resort only) "
2309
+ "-- validate_sculpt_spec.py blocks view-dependent finishes when set")
2310
+ args = parser.parse_args(argv)
2311
+ emit_status(None, next_command="vg asset rebuild-object new-sculpt-spec")
2312
+
2313
+ assessment = load_assessment(args.assessment)
2314
+ manifest = None
2315
+ if args.manifest:
2316
+ manifest = json.loads(args.manifest.read_text(encoding="utf-8"))
2317
+ if not isinstance(manifest, dict):
2318
+ parser.error("CS2 intake manifest must be a JSON object")
2319
+ if manifest.get("state") != "proceed":
2320
+ parser.error(f"CS2 intake is not ready for spec authoring: {manifest.get('state', 'unknown')}")
2321
+ if manifest.get("itemFamily") != "knife":
2322
+ parser.error("CS2 spec authoring currently supports only the knife family")
2323
+ spec = make_spec(args.target_name, args.image, assessment)
2324
+ domain = None
2325
+ cs2_marker = False
2326
+ if isinstance(assessment, dict):
2327
+ pre = assessment.get("preSpecAssessment", {})
2328
+ oc = pre.get("objectClass", {}) if isinstance(pre, dict) else {}
2329
+ domain = oc.get("primaryDomain") if isinstance(oc, dict) else None
2330
+ cs2_marker = bool(oc.get("cs2")) if isinstance(oc, dict) else False
2331
+ incoming_routing = assessment.get("pipelineRouting") if isinstance(assessment, dict) else None
2332
+ incoming_classification = incoming_routing.get("classification") if isinstance(incoming_routing, dict) else None
2333
+ explicit_track = "character-v1.5" if args.character or domain in {"character", "hybrid"} else None
2334
+ if explicit_track is None and (args.cs2 or cs2_marker):
2335
+ explicit_track = "weapon-v1.4"
2336
+ legacy_cs2 = manifest is not None and not isinstance(manifest.get("pipelineRouting"), dict)
2337
+ if manifest is not None and isinstance(manifest.get("pipelineRouting"), dict):
2338
+ incoming_classification = manifest["pipelineRouting"].get("classification")
2339
+ if args.character and (args.cs2 or manifest is not None) and incoming_classification is None:
2340
+ incoming_classification = {
2341
+ "kind": "weapon",
2342
+ "confidence": 1.0,
2343
+ "evidenceRefs": ["pipeline-routing:explicit:weapon-v1.4"],
2344
+ "provider": "pipeline-routing-cli",
2345
+ "version": "1",
2346
+ }
2347
+ routing = None
2348
+ if explicit_track is not None or incoming_classification is not None or legacy_cs2:
2349
+ routing = resolve_pipeline_routing(
2350
+ explicit_track=explicit_track,
2351
+ classification=incoming_classification,
2352
+ legacy_cs2=legacy_cs2,
2353
+ )
2354
+ spec["pipelineRouting"] = routing
2355
+ if routing["status"] != "resolved":
2356
+ parser.error("pipeline routing requires input: " + "; ".join(routing["conflicts"]))
2357
+ if routing is not None and routing["track"] == "weapon-v1.4":
2358
+ finish_style = args.finish_style
2359
+ if finish_style is None and isinstance(assessment, dict):
2360
+ oc = assessment.get("preSpecAssessment", {}).get("objectClass", {})
2361
+ if isinstance(oc, dict) and oc.get("finishStyle") in CS2_FINISH_PROFILES:
2362
+ finish_style = oc["finishStyle"]
2363
+ apply_cs2_template(
2364
+ spec, finish_style,
2365
+ skin_name=args.skin_name,
2366
+ vision_finish_style=args.vision_finish_style,
2367
+ vision_confidence=args.vision_confidence,
2368
+ float_value=args.cs2_float,
2369
+ paint_seed=args.paint_seed,
2370
+ environment_available=not args.no_environment,
2371
+ item_family=str(manifest.get("itemFamily", "knife")) if manifest else "knife",
2372
+ subtype=str(manifest["subtype"]) if manifest and manifest.get("subtype") else None,
2373
+ )
2374
+ if manifest:
2375
+ apply_cs2_manifest_evidence(spec, manifest)
2376
+ elif routing is not None and routing["track"] == "character-v1.5":
2377
+ anatomy = None
2378
+ if isinstance(assessment, dict) and isinstance(assessment.get("preSpecAssessment"), dict):
2379
+ anatomy = assessment["preSpecAssessment"].get("anatomy")
2380
+ apply_character_template(spec, anatomy, include_accessories=args.accessories)
2381
+ payload = json.dumps(spec, indent=2, ensure_ascii=False) + "\n"
2382
+
2383
+ if args.out:
2384
+ output = args.out.expanduser().resolve()
2385
+ if output.exists() and not args.force:
2386
+ parser.error(f"{output} already exists; use --force to overwrite")
2387
+ output.parent.mkdir(parents=True, exist_ok=True)
2388
+ output.write_text(payload, encoding="utf-8")
2389
+ print(output)
2390
+ else:
2391
+ print(payload, end="")
2392
+ return 0
2393
+
2394
+
2395
+ if __name__ == "__main__":
2396
+ raise SystemExit(main(sys.argv[1:]))