vibedgames 0.10.0 → 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 (175) 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-FXXVXDTW.js → chunk-24TITAFS.js} +1 -1
  125. package/dist/{chunk-OGX4DKIS.js → chunk-2C5PG2QO.js} +1 -1
  126. package/dist/{chunk-HYOXGNWS.js → chunk-2DEVOKI7.js} +1 -1
  127. package/dist/{chunk-RRI23NK2.js → chunk-2GHPYT2P.js} +1 -1
  128. package/dist/{chunk-S7HYWITX.js → chunk-2HXGMXGC.js} +1 -1
  129. package/dist/{chunk-N2UHAQXC.js → chunk-36FORP7T.js} +0 -1
  130. package/dist/{chunk-VB4WLJR2.js → chunk-3IXRQTRF.js} +1 -1
  131. package/dist/{chunk-2KVQJKIZ.js → chunk-4ENHS32B.js} +23 -36
  132. package/dist/{chunk-SXYQL4GK.js → chunk-4YHA32OE.js} +1 -1
  133. package/dist/{chunk-4FJXCS3K.js → chunk-4ZGQKPK5.js} +1 -1
  134. package/dist/{chunk-SBXCK2I2.js → chunk-6CLUPFQA.js} +2 -2
  135. package/dist/{chunk-TXOE5UY5.js → chunk-7WTF2BA4.js} +1 -1
  136. package/dist/{chunk-R2WVORGD.js → chunk-AAXZNK4Z.js} +1 -1
  137. package/dist/{chunk-DOOQUFPG.js → chunk-ALLBT4FB.js} +1 -1
  138. package/dist/{chunk-HRKVAXNN.js → chunk-BAZDPPIG.js} +5 -5
  139. package/dist/{chunk-RPJR3S5S.js → chunk-CYDENLZ4.js} +5 -8
  140. package/dist/{chunk-I5LELJSK.js → chunk-DKSUD44G.js} +1 -1
  141. package/dist/{chunk-43P4U7CB.js → chunk-DWWSJKTE.js} +1 -1
  142. package/dist/{chunk-SUSX3QIA.js → chunk-E72TFJZP.js} +1 -1
  143. package/dist/{chunk-E3FJUPLT.js → chunk-EUAAQMUA.js} +2 -0
  144. package/dist/{chunk-U6DTE5IX.js → chunk-F7LYJSZE.js} +1 -1
  145. package/dist/{chunk-MEAO33XW.js → chunk-FMON3C74.js} +8 -8
  146. package/dist/{chunk-GLEW7VJQ.js → chunk-FPILHRLZ.js} +1 -1
  147. package/dist/{chunk-OPUCUUID.js → chunk-G63MXDX2.js} +4 -0
  148. package/dist/{chunk-4UU622RK.js → chunk-GGO6ZYYI.js} +1 -3
  149. package/dist/{chunk-2ZKS7V72.js → chunk-GZCRYYS6.js} +5 -5
  150. package/dist/{chunk-E7NDOZ27.js → chunk-LE4GVTYI.js} +8 -8
  151. package/dist/{chunk-RKS7SI5L.js → chunk-NO6KPV64.js} +1 -1
  152. package/dist/{chunk-KJK5CB6E.js → chunk-NXW3Z4Y4.js} +1 -1
  153. package/dist/{chunk-7RPLQWR2.js → chunk-OHOAZGO4.js} +1 -1
  154. package/dist/chunk-PYJNI5WD.js +83 -0
  155. package/dist/{chunk-NCX6LYNJ.js → chunk-Q4XAGTFX.js} +1 -1
  156. package/dist/{chunk-3UGGMFJJ.js → chunk-QMZBSVKF.js} +1 -1
  157. package/dist/{chunk-ABTUEIRC.js → chunk-QO66UBOS.js} +2 -2
  158. package/dist/{chunk-LONQWRTR.js → chunk-S4KVGQQO.js} +8 -8
  159. package/dist/{chunk-HX5Q63UA.js → chunk-T777EXAO.js} +1 -1
  160. package/dist/{chunk-UQ7VO6B3.js → chunk-TZZNRA3S.js} +1 -1
  161. package/dist/{chunk-CTY2WZQK.js → chunk-UC3QLWMQ.js} +1 -1
  162. package/dist/{chunk-MR5KIFI7.js → chunk-UDJH2RED.js} +3 -3
  163. package/dist/{chunk-ZHLPE6LI.js → chunk-UIKYK7KI.js} +1 -1
  164. package/dist/{chunk-KAGVI3CE.js → chunk-UJRSQO2B.js} +1 -1
  165. package/dist/{chunk-Q2QC6KAZ.js → chunk-V7LEYVXB.js} +29 -25
  166. package/dist/{chunk-DB7WVFS7.js → chunk-WRMQEXUC.js} +1 -1
  167. package/dist/{chunk-HSMG6U7J.js → chunk-WXSBNC67.js} +3 -9
  168. package/dist/{chunk-QLCVLCPM.js → chunk-X4QIOXNQ.js} +1 -1
  169. package/dist/{chunk-5YPLKGY3.js → chunk-Y6WHUK2O.js} +1 -1
  170. package/dist/{chunk-VZEJ2ZHE.js → chunk-Z3E7ORGQ.js} +5 -5
  171. package/dist/index.js +20 -20
  172. package/package.json +32 -22
  173. package/dist/{chunk-Q3XQPNF6.js → chunk-BN7TR6OR.js} +3 -3
  174. package/dist/{chunk-LORGE2NB.js → chunk-U2NCN5RO.js} +3 -3
  175. package/dist/{chunk-UPHB5HWO.js → chunk-VQTTSPA3.js} +3 -3
@@ -0,0 +1,240 @@
1
+ #!/usr/bin/env python3
2
+ """Load and resolve the canonical Three.js material reference library.
3
+
4
+ This is the runtime bridge for ``docs/materials/material-reference.json``. The
5
+ registry is intentionally data-driven: profile numbers seed a candidate, while
6
+ image evidence and user metadata decide whether that candidate may proceed.
7
+ The module is stdlib-only so it can be used by every forge stage and in CI.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import copy
13
+ import json
14
+ import re
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+
19
+ ROOT = Path(__file__).resolve().parents[2]
20
+ DEFAULT_REFERENCE = ROOT / "docs" / "materials" / "material-reference.json"
21
+
22
+
23
+ class MaterialReferenceError(ValueError):
24
+ """Raised when the canonical registry cannot safely be consumed."""
25
+
26
+
27
+ def _token(value: Any) -> str:
28
+ return re.sub(r"[^a-z0-9]+", " ", str(value or "").strip().lower()).strip()
29
+
30
+
31
+ def _tokens(value: Any) -> set[str]:
32
+ token = _token(value)
33
+ return {token, token.replace(" ", "-")} if token else set()
34
+
35
+
36
+ def validate_reference(payload: dict[str, Any]) -> list[str]:
37
+ """Return structural errors; an empty list means the registry is usable."""
38
+ errors: list[str] = []
39
+ if not isinstance(payload, dict):
40
+ return ["reference must be a JSON object"]
41
+ if payload.get("schemaVersion") != 1:
42
+ errors.append("schemaVersion must be 1")
43
+ renderer = payload.get("renderer")
44
+ if not isinstance(renderer, dict) or renderer.get("engine") != "three.js":
45
+ errors.append("renderer.engine must be three.js")
46
+ sources = payload.get("sources")
47
+ if not isinstance(sources, list) or not sources:
48
+ errors.append("sources must be a non-empty array")
49
+ source_ids: set[str] = set()
50
+ else:
51
+ source_ids = set()
52
+ for index, source in enumerate(sources):
53
+ if not isinstance(source, dict):
54
+ errors.append(f"sources[{index}] must be an object")
55
+ continue
56
+ source_id = source.get("id")
57
+ if not isinstance(source_id, str) or not source_id:
58
+ errors.append(f"sources[{index}].id is required")
59
+ elif source_id in source_ids:
60
+ errors.append(f"duplicate source id {source_id!r}")
61
+ source_ids.add(str(source_id))
62
+ if not isinstance(source.get("url"), str) or not source["url"].startswith("https://"):
63
+ errors.append(f"source {source_id!r} must have an https URL")
64
+ materials = payload.get("materials")
65
+ if not isinstance(materials, list) or not materials:
66
+ errors.append("materials must be a non-empty array")
67
+ materials = []
68
+ ids: set[str] = set()
69
+ legal = payload.get("legalRanges", {})
70
+ if not isinstance(legal, dict):
71
+ errors.append("legalRanges must be an object")
72
+ legal = {}
73
+ for index, material in enumerate(materials):
74
+ if not isinstance(material, dict):
75
+ errors.append(f"materials[{index}] must be an object")
76
+ continue
77
+ material_id = material.get("id")
78
+ if not isinstance(material_id, str) or not material_id:
79
+ errors.append(f"materials[{index}].id is required")
80
+ continue
81
+ if material_id in ids:
82
+ errors.append(f"duplicate material id {material_id!r}")
83
+ ids.add(material_id)
84
+ if material.get("recipeBasis") != "inferred-starting-prior":
85
+ errors.append(f"material {material_id!r} must label its recipeBasis as a prior")
86
+ for source_ref in material.get("sourceRefs", []):
87
+ if source_ref not in source_ids:
88
+ errors.append(f"material {material_id!r} has unresolved sourceRef {source_ref!r}")
89
+ render_prior = material.get("renderPrior", {})
90
+ if not isinstance(render_prior, dict):
91
+ errors.append(f"material {material_id!r}.renderPrior must be an object")
92
+ continue
93
+ for property_name, prior in render_prior.items():
94
+ if property_name not in legal:
95
+ errors.append(f"material {material_id!r} uses undocumented property {property_name!r}")
96
+ continue
97
+ if not isinstance(prior, dict) or not isinstance(prior.get("default"), (int, float)):
98
+ errors.append(f"material {material_id!r}.{property_name} prior is malformed")
99
+ continue
100
+ bounds = prior.get("range")
101
+ allowed = legal[property_name]
102
+ if not isinstance(bounds, list) or len(bounds) != 2 or not isinstance(allowed, list) or len(allowed) != 2:
103
+ errors.append(f"material {material_id!r}.{property_name} prior range is malformed")
104
+ continue
105
+ if bounds[0] > prior["default"] or prior["default"] > bounds[1] or bounds[0] < allowed[0] or bounds[1] > allowed[1]:
106
+ errors.append(f"material {material_id!r}.{property_name} prior escapes legal range")
107
+ return errors
108
+
109
+
110
+ def load_reference(path: Path | str = DEFAULT_REFERENCE) -> dict[str, Any]:
111
+ reference_path = Path(path)
112
+ try:
113
+ payload = json.loads(reference_path.read_text(encoding="utf-8"))
114
+ except (OSError, json.JSONDecodeError) as exc:
115
+ raise MaterialReferenceError(f"cannot load material reference {reference_path}: {exc}") from exc
116
+ errors = validate_reference(payload)
117
+ if errors:
118
+ raise MaterialReferenceError("invalid material reference: " + "; ".join(errors))
119
+ return payload
120
+
121
+
122
+ def _material_index(payload: dict[str, Any]) -> list[dict[str, Any]]:
123
+ return [item for item in payload.get("materials", []) if isinstance(item, dict)]
124
+
125
+
126
+ def _candidate(profile: dict[str, Any], method: str, confidence: float, reason: str) -> dict[str, Any]:
127
+ return {
128
+ "materialId": profile.get("id"),
129
+ "profile": profile,
130
+ "method": method,
131
+ "confidence": max(0.0, min(1.0, float(confidence))),
132
+ "reason": reason,
133
+ }
134
+
135
+
136
+ def resolve_material(hypothesis: dict[str, Any], payload: dict[str, Any] | None = None) -> dict[str, Any]:
137
+ """Resolve one hypothesis while retaining alternatives and uncertainty.
138
+
139
+ Explicit user/metadata identity wins. Alias and family matching never
140
+ silently chooses between materially different candidates.
141
+ """
142
+ registry = payload or load_reference()
143
+ materials = _material_index(registry)
144
+ by_id = {str(item.get("id")): item for item in materials}
145
+ explicit = hypothesis.get("materialId")
146
+ if isinstance(explicit, str) and explicit in by_id:
147
+ result = _candidate(by_id[explicit], "explicit-material-id", 1.0, "authoritative material id")
148
+ result["status"] = "proceed"
149
+ result["alternatives"] = []
150
+ return result
151
+
152
+ family = _token(hypothesis.get("family"))
153
+ subtype = _token(hypothesis.get("subtype"))
154
+ finish = _token(hypothesis.get("finish"))
155
+ exact = [
156
+ item for item in materials
157
+ if _token(item.get("family")) == family
158
+ and (not subtype or _token(item.get("subtype")) == subtype)
159
+ and (not finish or _token(item.get("finish")) == finish)
160
+ ]
161
+ if len(exact) == 1:
162
+ result = _candidate(exact[0], "family-subtype-finish", float(hypothesis.get("confidence", 0.7)), "exact semantic match")
163
+ result["status"] = "proceed" if result["confidence"] >= 0.7 else "probe"
164
+ result["alternatives"] = []
165
+ return result
166
+
167
+ aliases = set()
168
+ for field in ("aliases", "alternatives"):
169
+ value = hypothesis.get(field, [])
170
+ if isinstance(value, list):
171
+ for item in value:
172
+ aliases.update(_tokens(item.get("materialId") if isinstance(item, dict) else item))
173
+ alias_matches = [item for item in materials if aliases & set().union(*(_tokens(alias) for alias in item.get("aliases", [])))]
174
+ if len(alias_matches) == 1:
175
+ result = _candidate(alias_matches[0], "alias", float(hypothesis.get("confidence", 0.5)), "unique alias match")
176
+ result["status"] = "proceed" if result["confidence"] >= 0.7 else "probe"
177
+ result["alternatives"] = []
178
+ return result
179
+
180
+ family_matches = [item for item in materials if family and _token(item.get("family")) == family]
181
+ family_matches.sort(key=lambda item: str(item.get("id")))
182
+ alternatives = [
183
+ _candidate(item, "family-fallback", max(0.1, float(hypothesis.get("confidence", 0.3)) * 0.65), "family fallback")
184
+ for item in family_matches
185
+ ]
186
+ if len(family_matches) == 1:
187
+ result = alternatives[0]
188
+ result["status"] = "probe"
189
+ result["alternatives"] = []
190
+ return result
191
+ return {
192
+ "materialId": None,
193
+ "profile": None,
194
+ "method": "unresolved",
195
+ "confidence": 0.0,
196
+ "reason": "ambiguous or unknown material; request more evidence",
197
+ "status": "request-input" if family_matches else "unknown",
198
+ "alternatives": alternatives,
199
+ }
200
+
201
+
202
+ def _prior_values(profile: dict[str, Any]) -> dict[str, float]:
203
+ return {
204
+ name: float(value["default"])
205
+ for name, value in profile.get("renderPrior", {}).items()
206
+ if isinstance(value, dict) and isinstance(value.get("default"), (int, float))
207
+ }
208
+
209
+
210
+ def build_assignment(
211
+ hypothesis: dict[str, Any],
212
+ evidence: dict[str, Any] | None = None,
213
+ payload: dict[str, Any] | None = None,
214
+ ) -> dict[str, Any]:
215
+ """Return the spec-ready assignment without mutating the input hypothesis."""
216
+ result = resolve_material(hypothesis, payload)
217
+ profile = result.get("profile")
218
+ assignment: dict[str, Any] = {
219
+ "materialId": result.get("materialId"),
220
+ "status": result["status"],
221
+ "source": hypothesis.get("source", "vision"),
222
+ "confidence": result["confidence"],
223
+ "method": result["method"],
224
+ "alternatives": [item["materialId"] for item in result.get("alternatives", [])],
225
+ "evidence": copy.deepcopy(evidence or {}),
226
+ }
227
+ if profile:
228
+ assignment.update({
229
+ "profileId": profile["id"],
230
+ "family": profile.get("family"),
231
+ "subtype": profile.get("subtype"),
232
+ "finish": profile.get("finish"),
233
+ "renderPrior": _prior_values(profile),
234
+ "requiredMaps": list(profile.get("requiredMaps", [])),
235
+ "optionalMaps": list(profile.get("optionalMaps", [])),
236
+ "validationViews": list(profile.get("validationViews", [])),
237
+ "sourceRefs": list(profile.get("sourceRefs", [])),
238
+ "visualCues": list(profile.get("visualCues", [])),
239
+ })
240
+ return assignment
@@ -0,0 +1,116 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ ROOT = Path(__file__).resolve().parent
9
+ sys.path.insert(0, str(ROOT / "_shared"))
10
+ sys.path.insert(0, str(ROOT / "stage3_build"))
11
+ from status_banner import emit_status
12
+ from orchestrate_passes import current_pass, pass_acceptance, pass_order, completed_passes
13
+ from workflow_state import (
14
+ WorkflowStateError,
15
+ load_state,
16
+ save_state,
17
+ status_payload,
18
+ sync_from_spec,
19
+ )
20
+
21
+
22
+ def emit_local_state(payload: dict) -> None:
23
+ loop = payload["loop"]
24
+ print(
25
+ f"LOCAL_STATE status={payload['status']} step={payload['currentStep']} "
26
+ f"pass={payload['currentPass'] or 'none'} "
27
+ f"loop={loop['passCount']}/{loop['maxPerPass']} "
28
+ f"total={loop['totalCount']}/{loop['maxTotal']}"
29
+ )
30
+ if payload["stopReason"]:
31
+ print(f"STOP: {payload['stopReason']}")
32
+ elif payload["nextCommand"]:
33
+ print(f"next command: {payload['nextCommand']}")
34
+ print("pending mandatory steps:")
35
+ for step_id in payload["pending"]:
36
+ print(f"- {step_id}")
37
+
38
+
39
+ def main(argv: list[str]) -> int:
40
+ parser = argparse.ArgumentParser(description="Report the exact next sculpt pipeline command")
41
+ parser.add_argument("spec", type=Path, nargs="?")
42
+ parser.add_argument("--state", type=Path, help="local checklist state created by vg asset rebuild-object state init")
43
+ args = parser.parse_args(argv)
44
+ local_state = None
45
+ spec_path = args.spec
46
+ if args.state:
47
+ try:
48
+ local_state = load_state(args.state)
49
+ except WorkflowStateError as error:
50
+ print(f"state error: {error}", file=sys.stderr)
51
+ return 2
52
+ if spec_path is None:
53
+ stored_spec = local_state.get("artifacts", {}).get("spec")
54
+ spec_path = Path(stored_spec) if isinstance(stored_spec, str) and stored_spec else None
55
+ else:
56
+ stored_spec = local_state.get("artifacts", {}).get("spec")
57
+ if isinstance(stored_spec, str) and stored_spec:
58
+ if Path(stored_spec).expanduser().resolve() != spec_path.expanduser().resolve():
59
+ print(
60
+ f"state error: positional spec {spec_path} does not match stored spec {stored_spec}",
61
+ file=sys.stderr,
62
+ )
63
+ return 2
64
+ else:
65
+ local_state["artifacts"]["spec"] = str(spec_path)
66
+
67
+ if spec_path is not None and local_state is not None and not spec_path.expanduser().is_file():
68
+ # `state.py init --spec <path>` records where the spec WILL be written, so between init
69
+ # and spec-authoring that path does not exist yet. That is the normal pre-spec state, not
70
+ # an error: fall back to the local checklist report so the mandatory gate stays runnable
71
+ # for the whole pre-spec phase instead of hard-failing on its own documented first step.
72
+ spec_path = None
73
+
74
+ if spec_path is None:
75
+ if local_state is None:
76
+ parser.error("spec is required unless --state points to an initialized pre-spec workflow")
77
+ payload = status_payload(local_state)
78
+ emit_local_state(payload)
79
+ return 3 if payload["status"] == "stopped" else 0
80
+
81
+ try:
82
+ spec = json.loads(spec_path.expanduser().read_text(encoding="utf-8"))
83
+ except (OSError, json.JSONDecodeError) as error:
84
+ print(f"spec error: {error}", file=sys.stderr)
85
+ return 2
86
+ if not isinstance(spec, dict):
87
+ raise ValueError("spec must be an object")
88
+ ids = pass_order(spec)
89
+ completed = completed_passes(spec, ids)
90
+ current = current_pass(ids, completed)
91
+
92
+ if local_state is not None:
93
+ sync_from_spec(local_state, spec, current)
94
+ save_state(args.state, local_state)
95
+ payload = status_payload(local_state)
96
+ emit_local_state(payload)
97
+ if payload["status"] == "stopped":
98
+ return 3
99
+ return 0
100
+
101
+ emit_status(spec)
102
+ if current == "complete":
103
+ print("pipeline: complete")
104
+ return 0
105
+ acceptance = pass_acceptance(spec, current)
106
+ command = f"vg asset rebuild-object orchestrate-passes check {spec_path} --pass-id {current}"
107
+ print(f"current pass: {current}")
108
+ print(f"next command: {command}")
109
+ print("unmet acceptance criteria:")
110
+ for item in acceptance or ["pass-specific evidence and a reviewHistory entry with action=continue"]:
111
+ print(f"- {item}")
112
+ return 0
113
+
114
+
115
+ if __name__ == "__main__":
116
+ raise SystemExit(main(sys.argv[1:]))
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ ROOT = Path(__file__).resolve().parent
9
+ sys.path.insert(0, str(ROOT / "_shared"))
10
+ sys.path.insert(0, str(ROOT / "stage3_build"))
11
+ from status_banner import emit_status
12
+ from orchestrate_passes import completed_passes, current_pass, pass_order
13
+
14
+
15
+ def main(argv: list[str]) -> int:
16
+ parser = argparse.ArgumentParser(description="Generate a reconstruction report from the pass ledger")
17
+ parser.add_argument("spec", type=Path)
18
+ parser.add_argument("--out", type=Path)
19
+ args = parser.parse_args(argv)
20
+ spec = json.loads(args.spec.expanduser().read_text(encoding="utf-8"))
21
+ if not isinstance(spec, dict):
22
+ raise ValueError("spec must be an object")
23
+ ids = pass_order(spec)
24
+ completed = completed_passes(spec, ids)
25
+ current = current_pass(ids, completed)
26
+ missing = ids[len(completed):]
27
+ opening = "PIPELINE COMPLETE through optimization-pass." if not missing else "INCOMPLETE: uncleared passes: " + ", ".join(missing) + "."
28
+ emit_status(spec)
29
+ report = "\n".join([opening, f"Target: {spec.get('targetName', '(unnamed)')}", f"Completed passes: {', '.join(completed) or '(none)'}", f"Current pass: {current}", "Review history entries: " + str(len(spec.get("reviewHistory", [])))]) + "\n"
30
+ if args.out:
31
+ args.out.expanduser().write_text(report, encoding="utf-8")
32
+ else:
33
+ print(report, end="")
34
+ return 0
35
+
36
+
37
+ if __name__ == "__main__":
38
+ raise SystemExit(main(sys.argv[1:]))
@@ -0,0 +1,6 @@
1
+ # Three.js Object Sculptor scripts have NO third-party dependencies.
2
+ # Everything uses the Python 3.10+ standard library only (json, argparse, struct,
3
+ # zlib, pathlib, math, subprocess). PNG maps and comparison sheets are written with
4
+ # struct/zlib directly — no Pillow/numpy/OpenCV/Playwright required.
5
+ #
6
+ # Requires: python >= 3.10
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env python3
2
+ """Reference texture analysis → finishClass + PBR recipe (Plan 1.3 texture upgrade).
3
+
4
+ Pure stdlib. Classifies a reference crop's *finish* from image statistics and emits a
5
+ material recipe (MeshPhysicalMaterial scalars + palette + procedural hints) that
6
+ `generate_threejs_factory.py`'s procedural texture generator consumes. This replaces the
7
+ per-object hand-crafting of albedo/roughness maps with a repeatable analysis→recipe step.
8
+
9
+ finishClass ∈ { gem-metal, gemstone, painted-metal, worn-composite, brushed-steel, plastic }
10
+ Recipe scalars grounded in grimoire/build/threejs_texture_reference.md (notebooklm/three.js docs).
11
+
12
+ CLI: analyze_texture.py <crop.png> [--json]
13
+ API: analyze(path) -> dict
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import colorsys
19
+ import json
20
+ import sys
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
25
+ from extract_pbr_evidence import build_foreground_mask, load_image # noqa: E402
26
+
27
+ # MeshPhysicalMaterial scalar presets per finish (see grimoire threejs_texture_reference.md)
28
+ RECIPES: dict[str, dict[str, Any]] = {
29
+ "gem-metal": {"metalness": 0.75, "roughness": 0.14, "clearcoat": 0.60, "clearcoatRoughness": 0.06, "transmission": 0.0, "ior": 1.5, "envMapIntensity": 1.3, "anisotropy": 0.0, "procedural": "gradient-smoke"},
30
+ # candy-coat: anodized / PVD / pigment-dominant doppler coat. Dielectric-led (low metalness) +
31
+ # clearcoat + trimmed envMapIntensity so the environment reflection can't steal the hue — the
32
+ # exact counter-recipe that fixed the M9 Doppler blue-wash (grimoire/feedback/shading_realism.md).
33
+ "candy-coat": {"metalness": 0.35, "roughness": 0.18, "clearcoat": 0.60, "clearcoatRoughness": 0.15, "transmission": 0.0, "ior": 1.5, "envMapIntensity": 0.7, "anisotropy": 0.0, "procedural": "gradient-smoke"},
34
+ "gemstone": {"metalness": 0.0, "roughness": 0.05, "clearcoat": 1.00, "clearcoatRoughness": 0.0, "transmission": 0.9, "ior": 1.54, "envMapIntensity": 1.0, "anisotropy": 0.0, "procedural": "gradient-smoke"},
35
+ "painted-metal": {"metalness": 0.0, "roughness": 0.5, "clearcoat": 1.00, "clearcoatRoughness": 0.05, "transmission": 0.0, "ior": 1.5, "envMapIntensity": 1.0, "anisotropy": 0.0, "procedural": "flat-clearcoat"},
36
+ "worn-composite": {"metalness": 0.0, "roughness": 0.9, "clearcoat": 0.0, "clearcoatRoughness": 0.0, "transmission": 0.0, "ior": 1.5, "envMapIntensity": 0.5, "anisotropy": 0.0, "procedural": "mottle"},
37
+ "brushed-steel": {"metalness": 1.0, "roughness": 0.35, "clearcoat": 0.0, "clearcoatRoughness": 0.0, "transmission": 0.0, "ior": 1.5, "envMapIntensity": 1.0, "anisotropy": 1.0, "procedural": "brushed"},
38
+ "plastic": {"metalness": 0.05, "roughness": 0.6, "clearcoat": 0.2, "clearcoatRoughness": 0.3, "transmission": 0.0, "ior": 1.5, "envMapIntensity": 0.7, "anisotropy": 0.0, "procedural": "flat-clearcoat"},
39
+ }
40
+
41
+ N = 64 # downsample grid for stats
42
+
43
+
44
+ def _sample(pixels, w, h, mask):
45
+ minx = miny = 1 << 30
46
+ maxx = maxy = -1
47
+ for y in range(h):
48
+ r = y * w
49
+ for x in range(w):
50
+ if mask[r + x]:
51
+ minx = min(minx, x); maxx = max(maxx, x)
52
+ miny = min(miny, y); maxy = max(maxy, y)
53
+ if maxx < 0:
54
+ minx, miny, maxx, maxy = 0, 0, w - 1, h - 1
55
+ bw = max(1, maxx - minx + 1); bh = max(1, maxy - miny + 1)
56
+ grid = []
57
+ for j in range(N):
58
+ sy = min(h - 1, miny + j * bh // N)
59
+ for i in range(N):
60
+ sx = min(w - 1, minx + i * bw // N)
61
+ p = pixels[sy * w + sx]
62
+ grid.append((p[0], p[1], p[2]))
63
+ return grid
64
+
65
+
66
+ def _lum(p):
67
+ return (p[0] * 30 + p[1] * 59 + p[2] * 11) / 100.0
68
+
69
+
70
+ def analyze(path: str | Path) -> dict[str, Any]:
71
+ w, h, pixels, _ = load_image(Path(path))
72
+ mask, _diag, _warn = build_foreground_mask(w, h, pixels)
73
+ g = _sample(pixels, w, h, mask)
74
+ n = len(g)
75
+ lums = [_lum(p) for p in g]
76
+ mean_lum = sum(lums) / n
77
+
78
+ # saturation + hue (HSV) — chromatic vs neutral, and hue SPREAD (gem shifts hue, paint doesn't)
79
+ hsv = [colorsys.rgb_to_hsv(p[0] / 255, p[1] / 255, p[2] / 255) for p in g]
80
+ sats = [s for _h, s, _v in hsv]
81
+ mean_sat = sum(sats) / n
82
+ # circular hue spread (robust to wraparound + outliers): 1 - mean resultant length,
83
+ # saturation-weighted. ~0 for a single paint hue, larger for a blue→purple gem shift.
84
+ import math as _m
85
+ sc = ss = wsum = 0.0
86
+ for _h, s, _v in hsv:
87
+ if s > 0.2:
88
+ sc += s * _m.cos(2 * _m.pi * _h)
89
+ ss += s * _m.sin(2 * _m.pi * _h)
90
+ wsum += s
91
+ hue_spread = (1.0 - _m.hypot(sc, ss) / wsum) if wsum > 2.0 else 0.0
92
+
93
+ # luminance gradient along rows vs cols (a strong axis gradient = doppler-like finish)
94
+ row_means = [sum(lums[j * N:(j + 1) * N]) / N for j in range(N)]
95
+ col_means = [sum(lums[i + j * N] for j in range(N)) / N for i in range(N)]
96
+ horiz_grad = (max(col_means) - min(col_means)) / 255.0
97
+ vert_grad = (max(row_means) - min(row_means)) / 255.0
98
+ gradient_strength = max(horiz_grad, vert_grad)
99
+ gradient_axis = "horizontal" if horiz_grad >= vert_grad else "vertical"
100
+
101
+ # local mottle: mean abs difference to 4-neighbours (worn/patchy surfaces are high)
102
+ diffs = 0.0
103
+ cnt = 0
104
+ for j in range(1, N - 1):
105
+ for i in range(1, N - 1):
106
+ c = lums[j * N + i]
107
+ diffs += abs(c - lums[j * N + i - 1]) + abs(c - lums[j * N + i + 1])
108
+ cnt += 2
109
+ mottle = (diffs / cnt) / 255.0 if cnt else 0.0
110
+
111
+ # directional streaks: horizontal high-freq >> vertical high-freq ⇒ brushed metal
112
+ hf_h = sum(abs(lums[j * N + i] - lums[j * N + i - 1]) for j in range(N) for i in range(1, N)) / (N * (N - 1))
113
+ hf_v = sum(abs(lums[j * N + i] - lums[(j - 1) * N + i]) for j in range(1, N) for i in range(N)) / (N * (N - 1))
114
+ streak_ratio = hf_h / (hf_v + 1e-6)
115
+ anisotropy = max(streak_ratio, 1.0 / (streak_ratio + 1e-6)) # directional either axis
116
+
117
+ # specular fraction → metalness proxy
118
+ spec_frac = sum(1 for lv in lums if lv > 235) / n
119
+
120
+ # ---- classify ----
121
+ if mean_sat < 0.18: # near-neutral / grey → metal or worn
122
+ if anisotropy > 1.9 and (mean_lum > 95 or spec_frac > 0.03): # bright directional = brushed metal
123
+ finish = "brushed-steel"
124
+ elif spec_frac > 0.05 and mean_lum > 140: # bright smooth specular = polished steel
125
+ finish = "brushed-steel"
126
+ elif mottle > 0.02 or mean_lum < 120: # dark / textured neutral = worn composite/rubber grip
127
+ finish = "worn-composite"
128
+ else: # mid-bright smooth neutral = plastic
129
+ finish = "plastic"
130
+ else: # chromatic
131
+ # gem/candy/doppler family = a chromatic surface with a strong gradient AND smoky internal
132
+ # variance (the swirl); flat paint has the gradient from lighting only, so low mottle.
133
+ if gradient_strength > 0.18 and mottle > 0.038:
134
+ if spec_frac > 0.05:
135
+ # bright chrome-like specular hotspots → genuinely metallic doppler (high metalness)
136
+ finish = "gem-metal"
137
+ elif mean_lum > 150 and spec_frac < 0.005:
138
+ # bright + clean, no specular blowout → transmissive gemstone (quartz/glass)
139
+ finish = "gemstone"
140
+ else:
141
+ # saturated PIGMENT-DOMINANT coat (colour survives into mid-tones, little chrome)
142
+ # → anodized/PVD/doppler candy-coat, rendered as a dielectric so the env can't
143
+ # steal the hue. This is the M9-Doppler case (was mis-classed high-metalness).
144
+ finish = "candy-coat"
145
+ else:
146
+ finish = "painted-metal"
147
+
148
+ # ---- palette stops along the dominant gradient axis (ordered low→high lum) ----
149
+ stops = []
150
+ for k in range(5):
151
+ idx = int(k / 4 * (N - 1))
152
+ if gradient_axis == "horizontal":
153
+ col = [g[j * N + idx] for j in range(N)]
154
+ else:
155
+ col = g[idx * N:(idx + 1) * N]
156
+ r = sum(c[0] for c in col) // len(col)
157
+ gg = sum(c[1] for c in col) // len(col)
158
+ b = sum(c[2] for c in col) // len(col)
159
+ stops.append(f"#{r:02X}{gg:02X}{b:02X}")
160
+
161
+ # Hue-survival annotation: flag any saturated blue-leaning violet/blue
162
+ # palette stop (B > R) that would collapse to flat blue under ACES/Reinhard tone-mapping, and
163
+ # suggest a magenta-lean correction (R >= B + a little green). Same rule as extract_gradient_stops.
164
+ palette_risk = []
165
+ for hexs in stops:
166
+ r_ = int(hexs[1:3], 16)
167
+ g_ = int(hexs[3:5], 16)
168
+ b_ = int(hexs[5:7], 16)
169
+ hh, ss, _vv = colorsys.rgb_to_hsv(r_ / 255, g_ / 255, b_ / 255)
170
+ if b_ > r_ and ss > 0.15 and 0.54 <= hh <= 0.83: # violet/blue hue band on the HSV circle
171
+ palette_risk.append({
172
+ "stop": hexs,
173
+ "hueRisk": "blue-collapse",
174
+ "suggestedRgb": [min(255, b_), max(g_, int(b_ * 0.25)), r_],
175
+ })
176
+
177
+ recipe = dict(RECIPES[finish])
178
+ return {
179
+ "finishClass": finish,
180
+ "recipe": recipe,
181
+ "palette": stops,
182
+ "paletteHueRisk": palette_risk,
183
+ "gradientAxis": gradient_axis,
184
+ "stats": {
185
+ "meanLum": round(mean_lum, 1),
186
+ "meanSaturation": round(mean_sat, 3),
187
+ "gradientStrength": round(gradient_strength, 3),
188
+ "mottle": round(mottle, 3),
189
+ "streakRatio": round(streak_ratio, 2),
190
+ "hueSpread": round(hue_spread, 3),
191
+ "specularFraction": round(spec_frac, 3),
192
+ },
193
+ }
194
+
195
+
196
+ def apply_to_material(material: dict[str, Any], result: dict[str, Any]) -> dict[str, Any]:
197
+ """Write the analysed recipe onto a spec material (doc-grounded MeshPhysicalMaterial scalars).
198
+ Layer-shaped fields ({'base': v}) are preserved so validators stay happy."""
199
+ r = result["recipe"]
200
+ material["finishClass"] = result["finishClass"]
201
+ material["texturePalette"] = result["palette"]
202
+ material["proceduralTexture"] = r["procedural"]
203
+ for key in ("metalness", "roughness", "clearcoat", "clearcoatRoughness", "transmission"):
204
+ existing = material.get(key)
205
+ if isinstance(existing, dict):
206
+ existing["base"] = r[key]
207
+ else:
208
+ material[key] = {"base": r[key], "variation": 0.0}
209
+ material["ior"] = {"base": r["ior"], "value": r["ior"]}
210
+ material["envMapIntensity"] = r["envMapIntensity"]
211
+ if r["anisotropy"] > 0:
212
+ material["anisotropy"] = {"base": r["anisotropy"]}
213
+ return material
214
+
215
+
216
+ def main(argv=None) -> int:
217
+ ap = argparse.ArgumentParser(description="Analyze a reference crop → finishClass + PBR recipe")
218
+ ap.add_argument("image")
219
+ ap.add_argument("--json", action="store_true")
220
+ ap.add_argument("--spec", type=Path, help="ObjectSculptSpec to patch a material in")
221
+ ap.add_argument("--material-id", help="material id to apply the recipe to (with --spec)")
222
+ ap.add_argument("--in-place", action="store_true", help="write the spec back")
223
+ args = ap.parse_args(argv)
224
+ has_patch_target = args.spec is not None and args.material_id is not None
225
+ if (args.spec is None) != (args.material_id is None):
226
+ ap.error("--spec and --material-id must be used together")
227
+ if args.in_place and not has_patch_target:
228
+ ap.error("--in-place requires --spec and --material-id")
229
+ result = analyze(args.image)
230
+
231
+ if has_patch_target:
232
+ spec = json.loads(args.spec.read_text(encoding="utf-8"))
233
+ mats = [m for m in spec.get("materials", []) if m.get("id") == args.material_id]
234
+ if not mats:
235
+ print(f"material {args.material_id!r} not found in spec", file=sys.stderr)
236
+ return 2
237
+ apply_to_material(mats[0], result)
238
+ if args.in_place:
239
+ args.spec.write_text(json.dumps(spec, indent=2), encoding="utf-8")
240
+ print(f"applied {result['finishClass']} recipe to material {args.material_id!r} in {args.spec.name}")
241
+ else:
242
+ print(json.dumps(mats[0], indent=2))
243
+ return 0
244
+
245
+ if args.json:
246
+ print(json.dumps(result, indent=2))
247
+ else:
248
+ print(f"finishClass: {result['finishClass']}")
249
+ print(f"palette: {result['palette']}")
250
+ print(f"stats: {result['stats']}")
251
+ return 0
252
+
253
+
254
+ if __name__ == "__main__":
255
+ raise SystemExit(main())