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,4099 @@
1
+ #!/usr/bin/env python3
2
+ """Generate a TypeScript Three.js factory skeleton from an ObjectSculptSpec."""
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
+ from typing import Any
13
+
14
+ _FORGE_ROOT = Path(__file__).resolve().parent.parent
15
+ sys.path[:0] = [str(_FORGE_ROOT), str(_FORGE_ROOT / "_shared"), str(_FORGE_ROOT / "stage2_spec")]
16
+ from orchestrate_passes import pass_specific_gaps
17
+ from subdivision import (
18
+ ATTACHMENT_CYLINDER_HEIGHT_SEGMENTS,
19
+ ATTACHMENT_CYLINDER_RADIAL_SEGMENTS,
20
+ CAPSULE_CAP_SEGMENTS,
21
+ CAPSULE_RADIAL_SEGMENTS,
22
+ CONE_HEIGHT_SEGMENTS,
23
+ CONE_SUBDIVISION_TOP_RADIUS,
24
+ CYLINDER_HEIGHT_SEGMENTS,
25
+ CYLINDER_RADIAL_SEGMENTS,
26
+ DEFAULT_TESSELLATION_TIER,
27
+ MAX_SUBDIVISION_ITERATIONS,
28
+ MAX_SUBDIVISION_QUAD_FACES,
29
+ PLANE_HEIGHT_SEGMENTS,
30
+ PLANE_WIDTH_SEGMENTS,
31
+ SPHERE_HEIGHT_SEGMENTS,
32
+ SPHERE_WIDTH_SEGMENTS,
33
+ resolve_instanced_cluster_base,
34
+ segments_for_spec,
35
+ TESSELLATION_TIERS,
36
+ TORUS_RADIAL_SEGMENTS,
37
+ TORUS_TUBULAR_SEGMENTS,
38
+ )
39
+ from validate_sculpt_spec import ATTACHMENT_PRIMITIVES, VALID_PRIMITIVES, validate_spec
40
+ from vertex_paint import VertexPaintError, normalize_vertex_paint
41
+ from visual_hull import MAX_VISUAL_HULL_TRIANGLES
42
+
43
+ # VALID_PRIMITIVES is re-exported rather than redefined. This module used to keep its own copy,
44
+ # and the two stayed identical only because someone edited both every time. A primitive present
45
+ # in one list and absent from the other does not error: line ~2873 silently rewrites it to "box",
46
+ # so the spec validates, the factory builds, and the wrong shape ships. Importing the validator's
47
+ # set makes that class of drift impossible instead of merely unlikely.
48
+ DEFAULT_PASS_ORDER = [
49
+ "blockout",
50
+ "structural-pass",
51
+ "form-refinement",
52
+ "material-pass",
53
+ "surface-pass",
54
+ "lighting-pass",
55
+ "interaction-pass",
56
+ "optimization-pass",
57
+ ]
58
+ VISUAL_PASS_IDS = set(DEFAULT_PASS_ORDER) - {"optimization-pass"}
59
+ PASS_LEVELS = {
60
+ "blockout": {"macro"},
61
+ "structural-pass": {"macro", "meso"},
62
+ "form-refinement": {"macro", "meso", "micro"},
63
+ "material-pass": {"macro", "meso", "micro"},
64
+ "surface-pass": {"macro", "meso", "micro"},
65
+ "lighting-pass": {"macro", "meso", "micro"},
66
+ "interaction-pass": {"macro", "meso", "micro"},
67
+ "optimization-pass": {"macro", "meso", "micro"},
68
+ }
69
+
70
+
71
+ def load_spec(path: Path) -> dict[str, Any]:
72
+ payload = json.loads(path.read_text(encoding="utf-8"))
73
+ if not isinstance(payload, dict):
74
+ raise ValueError("spec must be a JSON object")
75
+ return payload
76
+
77
+
78
+ def strict_quality_failures(spec: dict[str, Any]) -> tuple[list[str], list[str], list[str]]:
79
+ """Return normal validation output plus the failures that block production codegen."""
80
+ errors, warnings = validate_spec(spec)
81
+ failures = list(errors)
82
+ failures.extend(
83
+ f"strict quality failure: {warning.removeprefix('quality: ').strip()}"
84
+ for warning in warnings
85
+ if warning.startswith("quality:")
86
+ )
87
+ return errors, warnings, failures
88
+
89
+
90
+ def blocked_report(
91
+ spec_path: Path,
92
+ failures: list[str],
93
+ warnings: list[str],
94
+ pass_id: str | None,
95
+ ) -> dict[str, Any]:
96
+ """Build a machine-readable fail-closed report without touching the factory output."""
97
+ return {
98
+ "status": "BLOCKED",
99
+ "phase": "strict-quality",
100
+ "gate": "strict-quality",
101
+ "artifact": str(spec_path),
102
+ "metric": {
103
+ "failureCount": len(failures),
104
+ "qualityWarningCount": sum(1 for warning in warnings if warning.startswith("quality:")),
105
+ },
106
+ "cause": failures,
107
+ "warnings": warnings,
108
+ "requestedPass": pass_id,
109
+ "nextAction": "refine-spec: author a subject-specific ObjectSculptSpec, then rerun strict-quality",
110
+ }
111
+
112
+
113
+ def emit_blocked(report: dict[str, Any], report_path: Path | None) -> None:
114
+ payload = json.dumps(report, indent=2, ensure_ascii=False)
115
+ if report_path is not None:
116
+ report_path = report_path.expanduser().resolve()
117
+ report_path.parent.mkdir(parents=True, exist_ok=True)
118
+ report_path.write_text(payload + "\n", encoding="utf-8")
119
+ print(payload, file=sys.stderr)
120
+
121
+
122
+ def pass_order(spec: dict[str, Any]) -> list[str]:
123
+ ids: list[str] = []
124
+ for item in spec.get("buildPasses", []):
125
+ if isinstance(item, dict) and isinstance(item.get("id"), str) and item["id"].strip():
126
+ ids.append(item["id"])
127
+ return ids or DEFAULT_PASS_ORDER.copy()
128
+
129
+
130
+ def review_visual_evidence(entry: dict[str, Any]) -> dict[str, Any]:
131
+ visual = entry.get("visualEvidence")
132
+ return visual if isinstance(visual, dict) else {}
133
+
134
+
135
+ def review_completes_pass(entry: dict[str, Any], pass_id: str) -> bool:
136
+ if entry.get("passId") != pass_id or entry.get("action") != "continue":
137
+ return False
138
+ if pass_id in VISUAL_PASS_IDS and not review_visual_evidence(entry).get("renderScreenshot"):
139
+ return False
140
+ return True
141
+
142
+
143
+ def completed_passes(spec: dict[str, Any], ids: list[str]) -> list[str]:
144
+ history = spec.get("reviewHistory", [])
145
+ if not isinstance(history, list):
146
+ return []
147
+ completed: list[str] = []
148
+ for pass_id in ids:
149
+ if any(isinstance(entry, dict) and review_completes_pass(entry, pass_id) for entry in history):
150
+ completed.append(pass_id)
151
+ else:
152
+ break
153
+ return completed
154
+
155
+
156
+ def unlocked_pass(spec: dict[str, Any]) -> str:
157
+ ids = pass_order(spec)
158
+ completed = completed_passes(spec, ids)
159
+ if len(completed) >= len(ids):
160
+ return ids[-1]
161
+ return ids[len(completed)]
162
+
163
+
164
+ def assert_pass_unlocked(spec: dict[str, Any], requested_pass: str) -> None:
165
+ ids = pass_order(spec)
166
+ if requested_pass not in ids:
167
+ raise ValueError(f"unknown build pass {requested_pass!r}; expected one of: {', '.join(ids)}")
168
+ completed = completed_passes(spec, ids)
169
+ current = ids[-1] if len(completed) >= len(ids) else ids[len(completed)]
170
+ if requested_pass in completed or requested_pass == current:
171
+ return
172
+ previous_index = ids.index(requested_pass) - 1
173
+ previous = ids[previous_index] if previous_index >= 0 else ""
174
+ raise ValueError(
175
+ f"build pass {requested_pass!r} is locked; complete {previous!r} first with "
176
+ "stage4_review/append_review.py action=continue and browser screenshot evidence"
177
+ )
178
+
179
+
180
+ def component_refs_for_pass(spec: dict[str, Any], pass_id: str) -> set[str]:
181
+ ids = pass_order(spec)
182
+ if pass_id not in ids:
183
+ return set()
184
+ allowed_ids = set(ids[: ids.index(pass_id) + 1])
185
+ refs: set[str] = set()
186
+ for item in spec.get("buildPasses", []):
187
+ if not isinstance(item, dict) or item.get("id") not in allowed_ids:
188
+ continue
189
+ component_refs = item.get("componentRefs", [])
190
+ if isinstance(component_refs, list):
191
+ refs.update(str(value) for value in component_refs if str(value).strip())
192
+ return refs
193
+
194
+
195
+ def filter_components_for_pass(spec: dict[str, Any], components: list[dict[str, Any]], pass_id: str) -> list[dict[str, Any]]:
196
+ allowed_levels = PASS_LEVELS.get(pass_id, {"macro"})
197
+ explicit_refs = component_refs_for_pass(spec, pass_id)
198
+ included: list[dict[str, Any]] = []
199
+ included_ids: set[str] = set()
200
+ component_by_id = {str(item.get("id")): item for item in components if item.get("id") is not None}
201
+
202
+ def include_component(component: dict[str, Any]) -> None:
203
+ component_id = str(component.get("id") or "")
204
+ if not component_id or component_id in included_ids:
205
+ return
206
+ parent_id = component.get("parent")
207
+ if parent_id is not None and str(parent_id) in component_by_id:
208
+ include_component(component_by_id[str(parent_id)])
209
+ included.append(component)
210
+ included_ids.add(component_id)
211
+
212
+ for component in components:
213
+ component_id = str(component.get("id") or "")
214
+ level = str(component.get("level") or "macro")
215
+ tier = str(component.get("fidelityTier") or "")
216
+ if component_id in explicit_refs or level in allowed_levels or tier == pass_id:
217
+ include_component(component)
218
+ if not included and components:
219
+ included.append(components[0])
220
+ return included
221
+
222
+
223
+ def pascal_case(value: str) -> str:
224
+ parts = re.findall(r"[A-Za-z0-9]+", value)
225
+ return "".join(part[:1].upper() + part[1:] for part in parts) or "Object"
226
+
227
+
228
+ def const_name(value: str) -> str:
229
+ name = re.sub(r"[^A-Za-z0-9_]", "_", value.strip())
230
+ if not name:
231
+ return "component"
232
+ if name[0].isdigit():
233
+ name = "_" + name
234
+ return name
235
+
236
+
237
+ def local_var(prefix: str, value: str, index: int) -> str:
238
+ return f"{prefix}_{const_name(value)}_{index}"
239
+
240
+
241
+ def hex_to_number(value: Any, fallback: str = "#8A7A5F") -> str:
242
+ color = value if isinstance(value, str) else fallback
243
+ if re.fullmatch(r"#[0-9A-Fa-f]{6}", color):
244
+ return "0x" + color[1:]
245
+ if re.fullmatch(r"#[0-9A-Fa-f]{3}", color):
246
+ return "0x" + "".join(ch * 2 for ch in color[1:])
247
+ return "0x" + fallback[1:]
248
+
249
+
250
+ def material_base_value(value: Any, fallback: float) -> float:
251
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
252
+ return float(value)
253
+ if isinstance(value, dict) and isinstance(value.get("base"), (int, float)):
254
+ return float(value["base"])
255
+ return fallback
256
+
257
+
258
+ def json_literal(value: Any) -> str:
259
+ return json.dumps(value, ensure_ascii=False)
260
+
261
+
262
+ def vector(values: Any, fallback: list[float]) -> str:
263
+ if (
264
+ isinstance(values, list)
265
+ and len(values) == 3
266
+ and all(isinstance(item, (int, float)) for item in values)
267
+ ):
268
+ return ", ".join(str(float(item)) for item in values)
269
+ return ", ".join(str(item) for item in fallback)
270
+
271
+
272
+ def scale_triple(component: dict[str, Any], transform: dict[str, Any]) -> tuple[float, float, float]:
273
+ """The numeric factors `scale_vector` renders, for callers that must do arithmetic with them.
274
+
275
+ This exists because `geometry.scale(...)` bakes the factors into the VERTEX DATA and leaves the
276
+ pivot at scale 1. Anything that describes a component's surface analytically -- a ring stack to
277
+ stand proud of, say -- therefore has to apply the same factors itself, because no matrix in the
278
+ scene graph carries them. Reading the surface from the unit form instead put the skull's radius
279
+ at 0.5 where the geometry actually sits at 0.2.
280
+ """
281
+ if "scale" in transform:
282
+ values = transform.get("scale")
283
+ if isinstance(values, list) and len(values) == 3 and all(
284
+ isinstance(item, (int, float)) for item in values
285
+ ):
286
+ return (float(values[0]), float(values[1]), float(values[2]))
287
+ return (1.0, 1.0, 1.0)
288
+ dimensions = component.get("dimensions")
289
+ if isinstance(dimensions, dict):
290
+ radius = dimensions.get("radius")
291
+ fallback = radius * 2 if isinstance(radius, (int, float)) else 1
292
+ width = dimensions.get("width", fallback)
293
+ height = dimensions.get("height", dimensions.get("length", 1))
294
+ depth = dimensions.get("depth", fallback)
295
+ if all(isinstance(item, (int, float)) for item in (width, height, depth)):
296
+ return (float(width), float(height), float(depth))
297
+ return (1.0, 1.0, 1.0)
298
+
299
+
300
+ def scale_vector(component: dict[str, Any], transform: dict[str, Any]) -> str:
301
+ if "scale" in transform:
302
+ return vector(transform.get("scale"), [1, 1, 1])
303
+ dimensions = component.get("dimensions")
304
+ if isinstance(dimensions, dict):
305
+ width = dimensions.get("width", dimensions.get("radius", 0.5) * 2 if isinstance(dimensions.get("radius"), (int, float)) else 1)
306
+ height = dimensions.get("height", dimensions.get("length", 1))
307
+ depth = dimensions.get("depth", dimensions.get("radius", 0.5) * 2 if isinstance(dimensions.get("radius"), (int, float)) else 1)
308
+ if all(isinstance(item, (int, float)) for item in (width, height, depth)):
309
+ return vector([width, height, depth], [1, 1, 1])
310
+ return vector(None, [1, 1, 1])
311
+
312
+
313
+ class GeometryNotImplementedError(Exception):
314
+ """A component's primitive is a valid VALID_PRIMITIVES member but geometry_for()
315
+ has no codegen branch for it yet. Never silently substitute a box for this case —
316
+ that produced structurally-wrong renders (e.g. blade/knife primitives collapsing to
317
+ a generic box) with no signal that anything was wrong. See Plan 1.3 Workstream F."""
318
+
319
+
320
+ _DEFAULT_EXTRUDE_PROFILE = {"points": [[-0.3, -0.3], [0.3, -0.3], [0.3, 0.3], [-0.3, 0.3]], "depth": 0.1}
321
+ # Plan 1.3 — ground blade: a real knife solid with a PRIMARY BEVEL (lower body grinds from
322
+ # full thickness at a mid grind-line down to a sharp cutting edge) and a SWEDGE / false edge
323
+ # (near the tip the spine also grinds to a false edge). Lofted from stations [x, spineY, edgeY].
324
+ _DEFAULT_BLADE_SPEC = {
325
+ "stations": [
326
+ [0.00, 0.080, -0.090], [0.12, 0.086, -0.100], [0.30, 0.086, -0.110],
327
+ [0.50, 0.084, -0.108], [0.63, 0.078, -0.095], [0.74, 0.055, -0.055],
328
+ [0.82, 0.028, -0.020], [0.88, 0.000, 0.000],
329
+ ],
330
+ "thickness": 0.05, "grindFrac": 0.55, "swedgeFromTipFrac": 0.34,
331
+ }
332
+ _DEFAULT_LATHE_PROFILE = {"points": [[0.3, -0.5], [0.15, 0.0], [0.3, 0.5]], "segments": 24}
333
+ _DEFAULT_TUBE_PATH = {"points": [[0.0, -0.5, 0.0], [0.0, 0.5, 0.0]], "radius": 0.05, "closed": False}
334
+ # Plan 1.3 F.6 — curve-sweep: a thin 2D cross-section swept along a measured 3D spine.
335
+ # The FIX for curved forms (hooked blades, handles) that a flat extrude only renders
336
+ # correctly from the reference camera angle. Default is a gentle S-curve so a missing
337
+ # spine still produces a real swept solid, not a straight bar.
338
+ _DEFAULT_CURVE_SWEEP = {
339
+ "spine": [[-0.5, -0.4, 0.0], [-0.1, 0.1, 0.0], [0.3, 0.2, 0.0], [0.6, -0.1, 0.0]],
340
+ "crossSection": {"points": [[-0.04, -0.02], [0.04, -0.02], [0.04, 0.02], [-0.04, 0.02]]},
341
+ "closed": False,
342
+ }
343
+
344
+ # A sweep whose cross-section CHANGES along the spine. Every other sweep this factory emits --
345
+ # tube, curve-sweep, extrude -- carries one constant section from root to tip, so nothing that
346
+ # comes to a point (a hair lock, a horn, a tail, a blade tip, a finger) can be expressed by them.
347
+ # The default tapers to 8% of its root, which is the profile the grimoire prescribes; the
348
+ # validator warns when a spec's stations do not actually taper, because a barely-tapering sweep
349
+ # is a `tube` written the long way and reads as a noodle.
350
+ _DEFAULT_TAPERED_SWEEP = {
351
+ "stations": [
352
+ {"position": [0.0, -0.5, 0.0], "rx": 0.060, "rz": 0.040, "twist": 0.0},
353
+ {"position": [0.0, -0.1, 0.0], "rx": 0.048, "rz": 0.030, "twist": 0.0},
354
+ {"position": [0.0, 0.25, 0.0], "rx": 0.024, "rz": 0.014, "twist": 0.0},
355
+ # A true point, not a small ring: the tip is where a lock, a horn or a blade has to close.
356
+ {"position": [0.0, 0.5, 0.0], "rx": 0.0, "rz": 0.0, "twist": 0.0},
357
+ ],
358
+ "radialSegments": 10,
359
+ "capEnds": True,
360
+ }
361
+
362
+
363
+ _VISUAL_HULL_HELPER_SOURCE = """type VisualHullVector = readonly [number, number, number];
364
+ type VisualHullAxis = 'front' | 'side' | 'top';
365
+ type VisualHullView = {
366
+ readonly axis: VisualHullAxis;
367
+ readonly confidence: number;
368
+ readonly mask: readonly string[];
369
+ };
370
+ type VisualHullDescriptor = {
371
+ readonly projection: 'orthographic';
372
+ readonly boundsSpace: 'component-local';
373
+ readonly bounds: { readonly min: VisualHullVector; readonly max: VisualHullVector };
374
+ readonly resolution: number;
375
+ readonly triangleBudget: number;
376
+ readonly views: readonly VisualHullView[];
377
+ readonly hiddenRegions?: readonly string[];
378
+ };
379
+ const MAX_VISUAL_HULL_TRIANGLES = __MAX_VISUAL_HULL_TRIANGLES__;
380
+
381
+ class VisualHullGeometryBudgetError extends Error {
382
+ readonly triangleBudget: number;
383
+ readonly emittedTriangles: number;
384
+
385
+ constructor(triangleBudget: number, emittedTriangles: number) {
386
+ super(`visual hull emitted ${emittedTriangles} triangles, exceeding budget ${triangleBudget}`);
387
+ this.name = 'VisualHullGeometryBudgetError';
388
+ this.triangleBudget = triangleBudget;
389
+ this.emittedTriangles = emittedTriangles;
390
+ }
391
+ }
392
+
393
+ class VisualHullOccupancyError extends Error {
394
+ readonly occupiedVoxelCount: number;
395
+ readonly emittedTriangles: number;
396
+
397
+ constructor(occupiedVoxelCount: number, emittedTriangles: number) {
398
+ super('visual hull silhouettes produced no bounded occupied surface');
399
+ this.name = 'VisualHullOccupancyError';
400
+ this.occupiedVoxelCount = occupiedVoxelCount;
401
+ this.emittedTriangles = emittedTriangles;
402
+ }
403
+ }
404
+
405
+ function visualHullMaskContains(view: VisualHullView, horizontal: number, vertical: number): boolean {
406
+ const height = view.mask.length;
407
+ const width = view.mask[0].length;
408
+ const column = Math.max(0, Math.min(width - 1, Math.floor(horizontal * width)));
409
+ const row = Math.max(0, Math.min(height - 1, Math.floor((1 - vertical) * height)));
410
+ return view.mask[row][column] === '1';
411
+ }
412
+
413
+ function buildVisualHullGeometry(descriptor: VisualHullDescriptor): THREE.BufferGeometry {
414
+ const resolution = descriptor.resolution;
415
+ const min = new THREE.Vector3(...descriptor.bounds.min);
416
+ const max = new THREE.Vector3(...descriptor.bounds.max);
417
+ const step = max.clone().sub(min).multiplyScalar(1 / resolution);
418
+ const indexAt = (x: number, y: number, z: number): number => (z * resolution + y) * resolution + x;
419
+ const occupied = new Uint8Array(resolution * resolution * resolution);
420
+ let occupiedVoxelCount = 0;
421
+ const contains = (x: number, y: number, z: number): boolean => (
422
+ x >= 0 && y >= 0 && z >= 0 && x < resolution && y < resolution && z < resolution && occupied[indexAt(x, y, z)] === 1
423
+ );
424
+ for (let z = 0; z < resolution; z += 1) {
425
+ for (let y = 0; y < resolution; y += 1) {
426
+ for (let x = 0; x < resolution; x += 1) {
427
+ const horizontalX = (x + 0.5) / resolution;
428
+ const verticalY = (y + 0.5) / resolution;
429
+ const horizontalZ = (z + 0.5) / resolution;
430
+ let inside = true;
431
+ for (const view of descriptor.views) {
432
+ switch (view.axis) {
433
+ case 'front':
434
+ inside = inside && visualHullMaskContains(view, horizontalX, verticalY);
435
+ break;
436
+ case 'side':
437
+ inside = inside && visualHullMaskContains(view, horizontalZ, verticalY);
438
+ break;
439
+ case 'top':
440
+ inside = inside && visualHullMaskContains(view, horizontalX, horizontalZ);
441
+ break;
442
+ }
443
+ if (!inside) break;
444
+ }
445
+ if (inside) {
446
+ occupied[indexAt(x, y, z)] = 1;
447
+ occupiedVoxelCount += 1;
448
+ }
449
+ }
450
+ }
451
+ }
452
+ if (occupiedVoxelCount === 0) throw new VisualHullOccupancyError(0, 0);
453
+ const positions: number[] = [];
454
+ const indices: number[] = [];
455
+ const vertices = new Map<string, number>();
456
+ const vertexAt = (x: number, y: number, z: number): number => {
457
+ const key = `${x},${y},${z}`;
458
+ const existing = vertices.get(key);
459
+ if (existing !== undefined) return existing;
460
+ const vertex = positions.length / 3;
461
+ positions.push(min.x + x * step.x, min.y + y * step.y, min.z + z * step.z);
462
+ vertices.set(key, vertex);
463
+ return vertex;
464
+ };
465
+ const addFace = (a: number, b: number, c: number, d: number): void => {
466
+ indices.push(a, b, c, a, c, d);
467
+ const emittedTriangles = indices.length / 3;
468
+ if (emittedTriangles > descriptor.triangleBudget || emittedTriangles > MAX_VISUAL_HULL_TRIANGLES) {
469
+ throw new VisualHullGeometryBudgetError(descriptor.triangleBudget, emittedTriangles);
470
+ }
471
+ };
472
+ for (let z = 0; z < resolution; z += 1) {
473
+ for (let y = 0; y < resolution; y += 1) {
474
+ for (let x = 0; x < resolution; x += 1) {
475
+ if (!contains(x, y, z)) continue;
476
+ if (!contains(x - 1, y, z)) addFace(vertexAt(x, y, z), vertexAt(x, y, z + 1), vertexAt(x, y + 1, z + 1), vertexAt(x, y + 1, z));
477
+ if (!contains(x + 1, y, z)) addFace(vertexAt(x + 1, y, z), vertexAt(x + 1, y + 1, z), vertexAt(x + 1, y + 1, z + 1), vertexAt(x + 1, y, z + 1));
478
+ if (!contains(x, y - 1, z)) addFace(vertexAt(x, y, z), vertexAt(x + 1, y, z), vertexAt(x + 1, y, z + 1), vertexAt(x, y, z + 1));
479
+ if (!contains(x, y + 1, z)) addFace(vertexAt(x, y + 1, z), vertexAt(x, y + 1, z + 1), vertexAt(x + 1, y + 1, z + 1), vertexAt(x + 1, y + 1, z));
480
+ if (!contains(x, y, z - 1)) addFace(vertexAt(x, y, z), vertexAt(x, y + 1, z), vertexAt(x + 1, y + 1, z), vertexAt(x + 1, y, z));
481
+ if (!contains(x, y, z + 1)) addFace(vertexAt(x, y, z + 1), vertexAt(x + 1, y, z + 1), vertexAt(x + 1, y + 1, z + 1), vertexAt(x, y + 1, z + 1));
482
+ }
483
+ }
484
+ }
485
+ if (indices.length === 0) throw new VisualHullOccupancyError(occupiedVoxelCount, 0);
486
+ const geometry = new THREE.BufferGeometry();
487
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
488
+ geometry.setIndex(indices);
489
+ const uv: number[] = [];
490
+ for (let index = 0; index < positions.length; index += 3) {
491
+ uv.push((positions[index] - min.x) / (max.x - min.x), (positions[index + 1] - min.y) / (max.y - min.y));
492
+ }
493
+ geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));
494
+ geometry.computeVertexNormals();
495
+ geometry.userData.visualHull = {
496
+ method: 'orthographic-silhouette-intersection',
497
+ observedAxes: descriptor.views.map((view) => view.axis),
498
+ viewConfidence: descriptor.views.map((view) => ({ axis: view.axis, confidence: view.confidence })),
499
+ hiddenRegions: descriptor.hiddenRegions ?? ['Unobserved depth detail remains underconstrained by silhouette intersection.'],
500
+ lowConfidence: {
501
+ hiddenRegions: true,
502
+ reason: 'Silhouette intersection constrains the exterior envelope, not unseen surface detail.',
503
+ },
504
+ };
505
+ return geometry;
506
+ }"""
507
+
508
+
509
+ _DECIMATE_HELPER_SOURCE = '''// Quadric-error decimation (Garland & Heckbert 1997), ported from
510
+ // forge/stage3_build/decimate.py so it can run on geometry that only exists at runtime.
511
+ //
512
+ // WHY IT RUNS HERE RATHER THAN OFFLINE: the Python version reads a mesh file, and this
513
+ // factory does not produce one -- an implicit surface is polygonised in the browser from
514
+ // its descriptor, so there is no mesh to decimate until the page is running. Baking a
515
+ // vertex array into this file instead would contradict the whole point of a code-only
516
+ // procedural model.
517
+ //
518
+ // WHY IT RUNS BEFORE BINDING: a quadric collapse merges two vertices into one, and
519
+ // skinIndex/skinWeight would have to be interpolated across that merge to stay correct.
520
+ // The generated bind pass recomputes weights from `position` afterwards, so decimating
521
+ // first means the weights are simply computed on the surviving vertices and no
522
+ // interpolation of skinning data ever has to happen.
523
+ //
524
+ // LIMITATION, stated rather than discovered later: only `position` survives. UVs are
525
+ // dropped and normals are recomputed, so this must not be applied to geometry carrying
526
+ // authored UVs. Its intended input is polygonizeSdf output, which is position + index
527
+ // + computed normals and therefore loses nothing.
528
+ //
529
+ // Two collapses are refused, exactly as in the Python original, because both produce a
530
+ // mesh that passes a triangle count while no longer being a surface:
531
+ // * one that would FLIP a face -- the neighbouring normal reversing means the surface
532
+ // folded through itself, which is the defect self_intersection.py exists to catch;
533
+ // * one on a BOUNDARY edge -- an open border erodes inward and the silhouette visibly
534
+ // retreats, the classic "the LOD is smaller than the original" artefact.
535
+ function decimateGeometry(source: THREE.BufferGeometry, targetRatio: number): THREE.BufferGeometry {
536
+ const MIN_TRIANGLES = 4;
537
+ const position = source.getAttribute('position');
538
+ if (!position || !(targetRatio > 0) || targetRatio >= 1) return source;
539
+
540
+ const vertices: number[][] = [];
541
+ for (let i = 0; i < position.count; i++) {
542
+ vertices.push([position.getX(i), position.getY(i), position.getZ(i)]);
543
+ }
544
+ const index = source.getIndex();
545
+ const faces: number[][] = [];
546
+ if (index) {
547
+ for (let i = 0; i + 2 < index.count; i += 3) {
548
+ faces.push([index.getX(i), index.getX(i + 1), index.getX(i + 2)]);
549
+ }
550
+ } else {
551
+ for (let i = 0; i + 2 < position.count; i += 3) faces.push([i, i + 1, i + 2]);
552
+ }
553
+ if (!faces.length) return source;
554
+
555
+ const originalCount = faces.length;
556
+ const targetCount = Math.max(MIN_TRIANGLES, Math.floor(originalCount * targetRatio));
557
+ if (originalCount <= targetCount) return source;
558
+
559
+ const planeOf = (a: number[], b: number[], c: number[]): number[] | null => {
560
+ const e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
561
+ const e2 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
562
+ const n = [
563
+ e1[1] * e2[2] - e1[2] * e2[1],
564
+ e1[2] * e2[0] - e1[0] * e2[2],
565
+ e1[0] * e2[1] - e1[1] * e2[0],
566
+ ];
567
+ const len = Math.sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]);
568
+ if (len <= 1e-12) return null;
569
+ const u = [n[0] / len, n[1] / len, n[2] / len];
570
+ return [u[0], u[1], u[2], -(u[0] * a[0] + u[1] * a[1] + u[2] * a[2])];
571
+ };
572
+ // Upper triangle of the symmetric 4x4, row-major -- same 10-element layout as the Python side.
573
+ const quadricOf = (p: number[]): number[] => {
574
+ const [a, b, c, d] = p;
575
+ return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
576
+ };
577
+ const addQuadric = (q1: number[], q2: number[]): number[] => q1.map((x, i) => x + q2[i]);
578
+ const quadricError = (q: number[], v: number[]): number => {
579
+ const [x, y, z] = v;
580
+ return (
581
+ q[0] * x * x + 2 * q[1] * x * y + 2 * q[2] * x * z + 2 * q[3] * x +
582
+ q[4] * y * y + 2 * q[5] * y * z + 2 * q[6] * y +
583
+ q[7] * z * z + 2 * q[8] * z + q[9]
584
+ );
585
+ };
586
+
587
+ const alive = faces.map(() => true);
588
+ const vertexFaces: Set<number>[] = vertices.map(() => new Set<number>());
589
+ faces.forEach((face, i) => face.forEach((v) => vertexFaces[v].add(i)));
590
+
591
+ const quadrics: number[][] = vertices.map(() => new Array(10).fill(0));
592
+ faces.forEach((face, i) => {
593
+ const p = planeOf(vertices[face[0]], vertices[face[1]], vertices[face[2]]);
594
+ if (!p) { alive[i] = false; return; }
595
+ const q = quadricOf(p);
596
+ face.forEach((v) => { quadrics[v] = addQuadric(quadrics[v], q); });
597
+ });
598
+
599
+ const edgeFaces = new Map<string, number>();
600
+ const edgeKey = (u: number, v: number) => (u < v ? u + ':' + v : v + ':' + u);
601
+ faces.forEach((face) => {
602
+ const [a, b, c] = face;
603
+ for (const [u, v] of [[a, b], [b, c], [c, a]]) {
604
+ const k = edgeKey(u, v);
605
+ edgeFaces.set(k, (edgeFaces.get(k) ?? 0) + 1);
606
+ }
607
+ });
608
+ const boundary = new Set<string>();
609
+ edgeFaces.forEach((count, k) => { if (count === 1) boundary.add(k); });
610
+
611
+ const midpointOf = (u: number, v: number): number[] =>
612
+ [0, 1, 2].map((i) => (vertices[u][i] + vertices[v][i]) / 2);
613
+ // Midpoint rather than the quadric-optimal position: solving the 3x3 needs an inverse that
614
+ // is singular on flat regions, and the midpoint keeps the collapse on the original surface.
615
+ const costOf = (u: number, v: number): number =>
616
+ quadricError(addQuadric(quadrics[u], quadrics[v]), midpointOf(u, v));
617
+
618
+ // Binary heap keyed on collapse cost; entries are stale-checked on pop rather than updated
619
+ // in place, the same lazy-deletion approach heapq gets in the Python original.
620
+ const heap: { cost: number; u: number; v: number }[] = [];
621
+ const heapPush = (entry: { cost: number; u: number; v: number }) => {
622
+ heap.push(entry);
623
+ let i = heap.length - 1;
624
+ while (i > 0) {
625
+ const parent = (i - 1) >> 1;
626
+ if (heap[parent].cost <= heap[i].cost) break;
627
+ [heap[parent], heap[i]] = [heap[i], heap[parent]];
628
+ i = parent;
629
+ }
630
+ };
631
+ const heapPop = () => {
632
+ const top = heap[0];
633
+ const last = heap.pop()!;
634
+ if (heap.length) {
635
+ heap[0] = last;
636
+ let i = 0;
637
+ for (;;) {
638
+ const l = 2 * i + 1, r = 2 * i + 2;
639
+ let small = i;
640
+ if (l < heap.length && heap[l].cost < heap[small].cost) small = l;
641
+ if (r < heap.length && heap[r].cost < heap[small].cost) small = r;
642
+ if (small === i) break;
643
+ [heap[small], heap[i]] = [heap[i], heap[small]];
644
+ i = small;
645
+ }
646
+ }
647
+ return top;
648
+ };
649
+
650
+ edgeFaces.forEach((_count, k) => {
651
+ if (boundary.has(k)) return;
652
+ const [u, v] = k.split(':').map(Number);
653
+ heapPush({ cost: costOf(u, v), u, v });
654
+ });
655
+
656
+ let liveFaces = alive.reduce((n, flag) => n + (flag ? 1 : 0), 0);
657
+ while (heap.length && liveFaces > targetCount) {
658
+ const { u, v } = heapPop();
659
+ if (u === v || !vertexFaces[u].size || !vertexFaces[v].size) continue;
660
+ const shared = new Set<number>();
661
+ vertexFaces[u].forEach((i) => { if (vertexFaces[v].has(i)) shared.add(i); });
662
+ let anyAlive = false;
663
+ shared.forEach((i) => { if (alive[i]) anyAlive = true; });
664
+ if (!anyAlive) continue;
665
+ const merged = midpointOf(u, v);
666
+
667
+ let flips = false;
668
+ const affected = new Set<number>();
669
+ vertexFaces[u].forEach((i) => { if (!shared.has(i)) affected.add(i); });
670
+ vertexFaces[v].forEach((i) => { if (!shared.has(i)) affected.add(i); });
671
+ for (const i of affected) {
672
+ if (!alive[i] || flips) continue;
673
+ const face = faces[i];
674
+ const before = planeOf(vertices[face[0]], vertices[face[1]], vertices[face[2]]);
675
+ const pts = face.map((w) => (w === u || w === v ? merged : vertices[w]));
676
+ const after = planeOf(pts[0], pts[1], pts[2]);
677
+ if (!before || !after) { flips = true; break; }
678
+ if (before[0] * after[0] + before[1] * after[1] + before[2] * after[2] < 0) { flips = true; break; }
679
+ }
680
+ if (flips) continue;
681
+
682
+ vertices[u] = merged;
683
+ quadrics[u] = addQuadric(quadrics[u], quadrics[v]);
684
+ shared.forEach((i) => { if (alive[i]) { alive[i] = false; liveFaces -= 1; } });
685
+ Array.from(vertexFaces[v]).forEach((i) => {
686
+ if (!alive[i]) return;
687
+ faces[i] = faces[i].map((w) => (w === v ? u : w));
688
+ vertexFaces[u].add(i);
689
+ });
690
+ vertexFaces[v] = new Set<number>();
691
+ Array.from(vertexFaces[u]).forEach((i) => {
692
+ if (!alive[i]) return;
693
+ faces[i].forEach((w) => { if (w !== u) heapPush({ cost: costOf(u, w), u, v: w }); });
694
+ });
695
+ }
696
+
697
+ const kept = faces.filter((_face, i) => alive[i]);
698
+ const used = Array.from(new Set(kept.flat())).sort((a, b) => a - b);
699
+ const remap = new Map<number, number>();
700
+ used.forEach((old, next) => remap.set(old, next));
701
+ const outPositions: number[] = [];
702
+ used.forEach((old) => outPositions.push(vertices[old][0], vertices[old][1], vertices[old][2]));
703
+ const outIndices: number[] = [];
704
+ kept.forEach((face) => face.forEach((w) => outIndices.push(remap.get(w)!)));
705
+
706
+ const geometry = new THREE.BufferGeometry();
707
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(outPositions, 3));
708
+ geometry.setIndex(outIndices);
709
+ geometry.computeVertexNormals();
710
+ geometry.userData.decimation = {
711
+ originalTriangleCount: originalCount,
712
+ triangleCount: kept.length,
713
+ targetTriangleCount: targetCount,
714
+ // Reported because stopping short is not a failure but IS something the caller must know:
715
+ // on a mesh whose remaining collapses would all flip a face, the honest outcome is fewer
716
+ // triangles removed, not a folded mesh that hits the number.
717
+ reachedTarget: kept.length <= targetCount,
718
+ };
719
+ return geometry;
720
+ }'''
721
+
722
+
723
+ _SDF_HELPER_SOURCE = """type SdfVector = readonly [number, number, number];
724
+ type SdfTransform = { position?: SdfVector; translation?: SdfVector; rotation?: SdfVector; scale?: SdfVector };
725
+ type SdfPrimitive = {
726
+ readonly id: string;
727
+ readonly type: 'sphere' | 'capsule' | 'box' | 'cone' | 'ellipsoid';
728
+ readonly center?: SdfVector;
729
+ readonly radius?: number | SdfVector;
730
+ readonly height?: number;
731
+ readonly size?: SdfVector;
732
+ readonly dimensions?: SdfVector;
733
+ readonly radii?: SdfVector;
734
+ readonly transform?: SdfTransform;
735
+ };
736
+ type SdfOperation = {
737
+ readonly id?: string;
738
+ readonly output?: string;
739
+ readonly type: 'smooth-union' | 'subtract' | 'intersect';
740
+ readonly left: string;
741
+ readonly right: string;
742
+ readonly radius?: number;
743
+ };
744
+ type SdfDescriptor = {
745
+ readonly primitives: readonly SdfPrimitive[];
746
+ readonly operations?: readonly SdfOperation[];
747
+ readonly resolution: number;
748
+ readonly bounds?: { readonly min: SdfVector; readonly max: SdfVector };
749
+ };
750
+ type SdfFunction = (point: THREE.Vector3) => number;
751
+
752
+ function sdfSphere(point: THREE.Vector3, radius: number): number {
753
+ return point.length() - radius;
754
+ }
755
+
756
+ function sdfCapsule(point: THREE.Vector3, radius: number, height: number): number {
757
+ const halfHeight = height * 0.5;
758
+ const y = Math.max(-halfHeight, Math.min(halfHeight, point.y));
759
+ return point.distanceTo(new THREE.Vector3(0, y, 0)) - radius;
760
+ }
761
+
762
+ function sdfBox(point: THREE.Vector3, size: SdfVector): number {
763
+ const q = new THREE.Vector3(Math.abs(point.x), Math.abs(point.y), Math.abs(point.z))
764
+ .sub(new THREE.Vector3(size[0] * 0.5, size[1] * 0.5, size[2] * 0.5));
765
+ return q.clone().max(new THREE.Vector3()).length() + Math.min(Math.max(q.x, q.y, q.z), 0);
766
+ }
767
+
768
+ function sdfCone(point: THREE.Vector3, radius: number, height: number): number {
769
+ const halfHeight = height * 0.5;
770
+ const taper = radius * (1 - (point.y + halfHeight) / height);
771
+ return Math.max(Math.hypot(point.x, point.z) - Math.max(0, taper), Math.abs(point.y) - halfHeight);
772
+ }
773
+
774
+ function sdfEllipsoid(point: THREE.Vector3, radii: SdfVector): number {
775
+ const scaled = new THREE.Vector3(point.x / radii[0], point.y / radii[1], point.z / radii[2]);
776
+ return (scaled.length() - 1) * Math.min(radii[0], radii[1], radii[2]);
777
+ }
778
+
779
+ function sdfRadii(primitive: SdfPrimitive): SdfVector {
780
+ const radius = primitive.radius;
781
+ if (primitive.radii) return primitive.radii;
782
+ if (typeof radius === 'number') return [radius, radius, radius];
783
+ return radius ?? [0.5, 0.5, 0.5];
784
+ }
785
+
786
+ function smin(left: number, right: number, radius: number): number {
787
+ const blend = Math.max(radius - Math.abs(left - right), 0) / radius;
788
+ return Math.min(left, right) - blend * blend * radius * 0.25;
789
+ }
790
+
791
+ function sdfLocalPoint(point: THREE.Vector3, primitive: SdfPrimitive): { point: THREE.Vector3; scale: number } {
792
+ const transform = primitive.transform;
793
+ const translation = transform?.position ?? transform?.translation ?? primitive.center ?? [0, 0, 0];
794
+ const rotation = transform?.rotation ?? [0, 0, 0];
795
+ const scale = transform?.scale ?? [1, 1, 1];
796
+ const local = point.clone().sub(new THREE.Vector3(translation[0], translation[1], translation[2]));
797
+ const inverseRotation = new THREE.Quaternion()
798
+ .setFromEuler(new THREE.Euler(rotation[0], rotation[1], rotation[2]))
799
+ .invert();
800
+ local.applyQuaternion(inverseRotation);
801
+ local.set(local.x / scale[0], local.y / scale[1], local.z / scale[2]);
802
+ return { point: local, scale: Math.min(scale[0], scale[1], scale[2]) };
803
+ }
804
+
805
+ function sdfPrimitive(point: THREE.Vector3, primitive: SdfPrimitive): number {
806
+ const local = sdfLocalPoint(point, primitive);
807
+ let distance: number;
808
+ switch (primitive.type) {
809
+ case 'sphere':
810
+ distance = sdfSphere(local.point, typeof primitive.radius === 'number' ? primitive.radius : 0.5);
811
+ break;
812
+ case 'capsule':
813
+ distance = sdfCapsule(local.point, typeof primitive.radius === 'number' ? primitive.radius : 0.25, primitive.height ?? 1);
814
+ break;
815
+ case 'box':
816
+ distance = sdfBox(local.point, primitive.size ?? primitive.dimensions ?? [1, 1, 1]);
817
+ break;
818
+ case 'cone':
819
+ distance = sdfCone(local.point, typeof primitive.radius === 'number' ? primitive.radius : 0.5, primitive.height ?? 1);
820
+ break;
821
+ case 'ellipsoid':
822
+ distance = sdfEllipsoid(local.point, sdfRadii(primitive));
823
+ break;
824
+ }
825
+ return distance * local.scale;
826
+ }
827
+
828
+ function sdfSample(descriptor: SdfDescriptor): SdfFunction {
829
+ const nodes = new Map<string, SdfFunction>();
830
+ for (const primitive of descriptor.primitives) nodes.set(primitive.id, (point) => sdfPrimitive(point, primitive));
831
+ let result = descriptor.primitives.length > 0 ? nodes.get(descriptor.primitives[0].id) : undefined;
832
+ for (let index = 0; index < (descriptor.operations?.length ?? 0); index += 1) {
833
+ const operation = descriptor.operations?.[index];
834
+ if (!operation) continue;
835
+ const left = nodes.get(operation.left);
836
+ const right = nodes.get(operation.right);
837
+ if (!left || !right) continue;
838
+ let combined: SdfFunction;
839
+ switch (operation.type) {
840
+ case 'smooth-union':
841
+ combined = (point) => smin(left(point), right(point), operation.radius ?? 0.1);
842
+ break;
843
+ case 'subtract':
844
+ combined = (point) => Math.max(left(point), -right(point));
845
+ break;
846
+ case 'intersect':
847
+ combined = (point) => Math.max(left(point), right(point));
848
+ break;
849
+ }
850
+ nodes.set(operation.id ?? operation.output ?? `operation-${index}`, combined);
851
+ result = combined;
852
+ }
853
+ return result ?? (() => Infinity);
854
+ }
855
+
856
+ function polygonizeSdf(descriptor: SdfDescriptor): THREE.BufferGeometry {
857
+ // SURFACE NETS, not a voxel shell.
858
+ //
859
+ // This used to emit one axis-aligned quad per exposed voxel face, which is a Minecraft surface:
860
+ // every face is axis-aligned, every edge is a 90-degree step, and the result is stair-stepped at
861
+ // exactly the scale of the sampling grid. For a subject whose whole identity is smooth blended
862
+ // organic form -- which is the only kind of subject anyone reaches for an implicit surface to
863
+ // build -- that is worse than the assembled primitives it was meant to replace.
864
+ //
865
+ // Naive surface nets places ONE vertex per sign-changing cell, at the average of the linearly
866
+ // interpolated crossings on that cell's edges, and joins the four cells around each crossing
867
+ // edge into a quad. It is compact, manifold, and smooth, and it is a natural fit for a field
868
+ // that can be sampled anywhere rather than only at corners.
869
+ //
870
+ // Normals come from the field GRADIENT, not from face averaging: the gradient is the exact
871
+ // surface normal of the implicit surface, so shading no longer carries the grid's imprint.
872
+ const resolution = Math.max(4, Math.min(64, Math.floor(descriptor.resolution)));
873
+ const defaultBounds: { readonly min: SdfVector; readonly max: SdfVector } = { min: [-2, -2, -2], max: [2, 2, 2] };
874
+ const bounds = descriptor.bounds ?? defaultBounds;
875
+ const min = new THREE.Vector3(bounds.min[0], bounds.min[1], bounds.min[2]);
876
+ const step = new THREE.Vector3(
877
+ (bounds.max[0] - bounds.min[0]) / resolution,
878
+ (bounds.max[1] - bounds.min[1]) / resolution,
879
+ (bounds.max[2] - bounds.min[2]) / resolution,
880
+ );
881
+ const sample = sdfSample(descriptor);
882
+ const scratch = new THREE.Vector3();
883
+
884
+ // Corner grid: one more corner than cells on each axis.
885
+ const side = resolution + 1;
886
+ const field = new Float32Array(side * side * side);
887
+ const cornerAt = (x: number, y: number, z: number): number => (z * side + y) * side + x;
888
+ for (let z = 0; z < side; z += 1) {
889
+ for (let y = 0; y < side; y += 1) {
890
+ for (let x = 0; x < side; x += 1) {
891
+ scratch.set(min.x + x * step.x, min.y + y * step.y, min.z + z * step.z);
892
+ field[cornerAt(x, y, z)] = sample(scratch);
893
+ }
894
+ }
895
+ }
896
+
897
+ // The 12 cell edges as corner-offset pairs.
898
+ const CUBE_EDGES: readonly (readonly [number, number, number, number, number, number])[] = [
899
+ [0, 0, 0, 1, 0, 0], [1, 0, 0, 1, 1, 0], [0, 1, 0, 1, 1, 0], [0, 0, 0, 0, 1, 0],
900
+ [0, 0, 1, 1, 0, 1], [1, 0, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 1, 0, 1, 1],
901
+ [0, 0, 0, 0, 0, 1], [1, 0, 0, 1, 0, 1], [1, 1, 0, 1, 1, 1], [0, 1, 0, 0, 1, 1],
902
+ ];
903
+
904
+ const positions: number[] = [];
905
+ const normals: number[] = [];
906
+ const indices: number[] = [];
907
+ const cellVertex = new Int32Array(resolution * resolution * resolution).fill(-1);
908
+ const cellAt = (x: number, y: number, z: number): number => (z * resolution + y) * resolution + x;
909
+
910
+ // Central-difference gradient, stepped at a fraction of a cell so it follows the field rather
911
+ // than the grid.
912
+ const epsilon = Math.min(step.x, step.y, step.z) * 0.25;
913
+ const gradient = (point: THREE.Vector3): THREE.Vector3 => {
914
+ const gx = sample(scratch.set(point.x + epsilon, point.y, point.z))
915
+ - sample(scratch.set(point.x - epsilon, point.y, point.z));
916
+ const gy = sample(scratch.set(point.x, point.y + epsilon, point.z))
917
+ - sample(scratch.set(point.x, point.y - epsilon, point.z));
918
+ const gz = sample(scratch.set(point.x, point.y, point.z + epsilon))
919
+ - sample(scratch.set(point.x, point.y, point.z - epsilon));
920
+ const normal = new THREE.Vector3(gx, gy, gz);
921
+ // A point where the field is flat has no defined normal; +Y is arbitrary but finite, and
922
+ // leaving a zero vector would poison every lighting calculation downstream.
923
+ return normal.lengthSq() < 1e-20 ? new THREE.Vector3(0, 1, 0) : normal.normalize();
924
+ };
925
+
926
+ for (let z = 0; z < resolution; z += 1) {
927
+ for (let y = 0; y < resolution; y += 1) {
928
+ for (let x = 0; x < resolution; x += 1) {
929
+ let crossings = 0;
930
+ let sumX = 0;
931
+ let sumY = 0;
932
+ let sumZ = 0;
933
+ for (const [ax, ay, az, bx, by, bz] of CUBE_EDGES) {
934
+ const a = field[cornerAt(x + ax, y + ay, z + az)];
935
+ const b = field[cornerAt(x + bx, y + by, z + bz)];
936
+ if ((a <= 0) === (b <= 0)) continue;
937
+ const t = a / (a - b);
938
+ sumX += (ax + (bx - ax) * t);
939
+ sumY += (ay + (by - ay) * t);
940
+ sumZ += (az + (bz - az) * t);
941
+ crossings += 1;
942
+ }
943
+ if (crossings === 0) continue;
944
+ const px = min.x + (x + sumX / crossings) * step.x;
945
+ const py = min.y + (y + sumY / crossings) * step.y;
946
+ const pz = min.z + (z + sumZ / crossings) * step.z;
947
+ cellVertex[cellAt(x, y, z)] = positions.length / 3;
948
+ positions.push(px, py, pz);
949
+ const normal = gradient(new THREE.Vector3(px, py, pz));
950
+ normals.push(normal.x, normal.y, normal.z);
951
+ }
952
+ }
953
+ }
954
+
955
+ // One quad per sign-changing grid edge, joining the four cells that share it.
956
+ //
957
+ // Winding, worked out rather than guessed. For the +x edge from corner (x,y,z), the four cells
958
+ // around it are (x, y-1, z-1), (x, y, z-1), (x, y, z), (x, y-1, z); in the (y,z) plane that
959
+ // traversal is +y, +z, -y, whose cross product is +x. So when the corner is INSIDE and its
960
+ // neighbour is outside, the unflipped order already faces out, and the flip belongs on the
961
+ // opposite case. Getting this backwards is invisible in the normals -- those come from the
962
+ // gradient and stay correct -- and shows only as back-face culling removing the front surface,
963
+ // i.e. the model rendering as a hollow shell with its interior visible.
964
+ const quad = (a: number, b: number, c: number, d: number, flip: boolean): void => {
965
+ if (a < 0 || b < 0 || c < 0 || d < 0) return;
966
+ if (flip) indices.push(a, c, b, a, d, c);
967
+ else indices.push(a, b, c, a, c, d);
968
+ };
969
+ // Each quad joins the FOUR cells sharing one grid edge, so every one of those cells must exist.
970
+ // Bounding only the edge axis and the lower end of the other two let y/z reach `resolution`, which
971
+ // is a corner index, not a cell index: `cellAt` then strides into an unrelated slot (with
972
+ // resolution 8, `cellAt(3, 8, 1)` is 131 -- the slot for cell (3, 0, 2)) or past the end of the
973
+ // array, where a typed-array read yields `undefined`. `undefined < 0` is false, so the guard in
974
+ // `quad` passed it through to `setIndex`, which coerces it to 0. Measured on a sphere reaching its
975
+ // own bounds at resolution 8: 60 out-of-range reads and 108 aliased reads. A surface that touches
976
+ // the sampling box is therefore left OPEN at that face rather than closed with wrong triangles --
977
+ // pad `bounds` past the surface to get a closed mesh.
978
+ for (let z = 0; z < side; z += 1) {
979
+ for (let y = 0; y < side; y += 1) {
980
+ for (let x = 0; x < side; x += 1) {
981
+ const here = field[cornerAt(x, y, z)] <= 0;
982
+ if (x + 1 < side && y > 0 && z > 0 && y < side - 1 && z < side - 1
983
+ && here !== (field[cornerAt(x + 1, y, z)] <= 0)) {
984
+ quad(
985
+ cellVertex[cellAt(x, y - 1, z - 1)], cellVertex[cellAt(x, y, z - 1)],
986
+ cellVertex[cellAt(x, y, z)], cellVertex[cellAt(x, y - 1, z)], !here,
987
+ );
988
+ }
989
+ if (y + 1 < side && x > 0 && z > 0 && x < side - 1 && z < side - 1
990
+ && here !== (field[cornerAt(x, y + 1, z)] <= 0)) {
991
+ quad(
992
+ cellVertex[cellAt(x - 1, y, z - 1)], cellVertex[cellAt(x - 1, y, z)],
993
+ cellVertex[cellAt(x, y, z)], cellVertex[cellAt(x, y, z - 1)], !here,
994
+ );
995
+ }
996
+ if (z + 1 < side && x > 0 && y > 0 && x < side - 1 && y < side - 1
997
+ && here !== (field[cornerAt(x, y, z + 1)] <= 0)) {
998
+ quad(
999
+ cellVertex[cellAt(x - 1, y - 1, z)], cellVertex[cellAt(x, y - 1, z)],
1000
+ cellVertex[cellAt(x, y, z)], cellVertex[cellAt(x - 1, y, z)], !here,
1001
+ );
1002
+ }
1003
+ }
1004
+ }
1005
+ }
1006
+
1007
+ const geometry = new THREE.BufferGeometry();
1008
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
1009
+ geometry.setAttribute('normal', new THREE.Float32BufferAttribute(normals, 3));
1010
+ geometry.setIndex(indices);
1011
+ geometry.computeBoundingSphere();
1012
+ return geometry;
1013
+ }"""
1014
+
1015
+
1016
+ _SUBDIVISION_HELPER_SOURCE = """type SubdivisionFace = number[];
1017
+ type SubdivisionEdge = {
1018
+ a: number;
1019
+ b: number;
1020
+ faces: number[];
1021
+ };
1022
+ type SubdivisionUvChannel = {
1023
+ name: string;
1024
+ faces: THREE.Vector2[][];
1025
+ };
1026
+ const MAX_SUBDIVISION_QUAD_FACES = __MAX_SUBDIVISION_QUAD_FACES__;
1027
+ const MAX_SUBDIVISION_ITERATIONS = __MAX_SUBDIVISION_ITERATIONS__;
1028
+
1029
+ class SubdivisionInputError extends Error {
1030
+ readonly iterations: unknown;
1031
+
1032
+ constructor(iterations: unknown) {
1033
+ super(`subdivision iterations must be an integer from 0 to ${MAX_SUBDIVISION_ITERATIONS}`);
1034
+ this.name = 'SubdivisionInputError';
1035
+ this.iterations = iterations;
1036
+ }
1037
+ }
1038
+
1039
+ class SubdivisionGeometryBudgetError extends Error {
1040
+ readonly sourceFaceCount: number;
1041
+ readonly projectedQuadFaceCount: number;
1042
+
1043
+ constructor(sourceFaceCount: number, projectedQuadFaceCount: number) {
1044
+ super(`subdivision would produce ${projectedQuadFaceCount} quad faces from ${sourceFaceCount} source faces`);
1045
+ this.name = 'SubdivisionGeometryBudgetError';
1046
+ this.sourceFaceCount = sourceFaceCount;
1047
+ this.projectedQuadFaceCount = projectedQuadFaceCount;
1048
+ }
1049
+ }
1050
+
1051
+ class SubdivisionTopologyError extends Error {
1052
+ readonly reason: string;
1053
+
1054
+ constructor(reason: string) {
1055
+ super(reason);
1056
+ this.name = 'SubdivisionTopologyError';
1057
+ this.reason = reason;
1058
+ }
1059
+ }
1060
+
1061
+ function subdivideCatmullClark(source: THREE.BufferGeometry, iterations: number): THREE.BufferGeometry {
1062
+ if (!Number.isInteger(iterations) || iterations < 0 || iterations > MAX_SUBDIVISION_ITERATIONS) {
1063
+ throw new SubdivisionInputError(iterations);
1064
+ }
1065
+ if (iterations === 0) return source;
1066
+ const position = source.getAttribute('position');
1067
+ if (!position) {
1068
+ source.computeVertexNormals();
1069
+ return source;
1070
+ }
1071
+
1072
+ const sourcePositions: THREE.Vector3[] = [];
1073
+ const sourceVertexByKey = new Map<string, number>();
1074
+ const sourceUvChannels: SubdivisionUvChannel[] = [];
1075
+ for (const name of ['uv', 'uv2']) {
1076
+ const attribute = source.getAttribute(name);
1077
+ if (attribute && attribute.itemSize >= 2) sourceUvChannels.push({ name, faces: [] });
1078
+ }
1079
+ const vertexIndexAt = (attributeIndex: number): number => {
1080
+ const x = position.getX(attributeIndex);
1081
+ const y = position.getY(attributeIndex);
1082
+ const z = position.getZ(attributeIndex);
1083
+ const key = `${Math.round(x * 1000000)},${Math.round(y * 1000000)},${Math.round(z * 1000000)}`;
1084
+ const existing = sourceVertexByKey.get(key);
1085
+ if (existing !== undefined) return existing;
1086
+ const vertexIndex = sourcePositions.length;
1087
+ sourcePositions.push(new THREE.Vector3(x, y, z));
1088
+ sourceVertexByKey.set(key, vertexIndex);
1089
+ return vertexIndex;
1090
+ };
1091
+ const sourceIndex = source.getIndex();
1092
+ const sourceVertexCount = sourceIndex?.count ?? position.count;
1093
+ const sourceTriangles: SubdivisionFace[] = [];
1094
+ const sourceTriangleAttributeIndices: number[][] = [];
1095
+ for (let index = 0; index + 2 < sourceVertexCount; index += 3) {
1096
+ const attributeA = sourceIndex ? sourceIndex.getX(index) : index;
1097
+ const attributeB = sourceIndex ? sourceIndex.getX(index + 1) : index + 1;
1098
+ const attributeC = sourceIndex ? sourceIndex.getX(index + 2) : index + 2;
1099
+ const a = vertexIndexAt(attributeA);
1100
+ const b = vertexIndexAt(attributeB);
1101
+ const c = vertexIndexAt(attributeC);
1102
+ if (a !== b && b !== c && c !== a) {
1103
+ sourceTriangles.push([a, b, c]);
1104
+ sourceTriangleAttributeIndices.push([attributeA, attributeB, attributeC]);
1105
+ }
1106
+ }
1107
+
1108
+ const triangleNormal = (face: SubdivisionFace): THREE.Vector3 => {
1109
+ const a = sourcePositions[face[0]];
1110
+ const b = sourcePositions[face[1]];
1111
+ const c = sourcePositions[face[2]];
1112
+ return new THREE.Vector3().subVectors(b, a).cross(new THREE.Vector3().subVectors(c, a)).normalize();
1113
+ };
1114
+ const edgeKey = (a: number, b: number): string => (a < b ? `${a}:${b}` : `${b}:${a}`);
1115
+ const triangleEdges = new Map<string, number[]>();
1116
+ for (let triangleIndex = 0; triangleIndex < sourceTriangles.length; triangleIndex += 1) {
1117
+ const triangle = sourceTriangles[triangleIndex];
1118
+ for (let vertexIndex = 0; vertexIndex < triangle.length; vertexIndex += 1) {
1119
+ const a = triangle[vertexIndex];
1120
+ const b = triangle[(vertexIndex + 1) % triangle.length];
1121
+ const key = edgeKey(a, b);
1122
+ const entries = triangleEdges.get(key) ?? [];
1123
+ entries.push(triangleIndex);
1124
+ triangleEdges.set(key, entries);
1125
+ }
1126
+ }
1127
+
1128
+ const pairedTriangles = new Set<number>();
1129
+ let faces: SubdivisionFace[] = [];
1130
+ let faceAttributeIndices: number[][] = [];
1131
+ for (const triangleIndices of triangleEdges.values()) {
1132
+ if (triangleIndices.length !== 2) continue;
1133
+ const leftIndex = triangleIndices[0];
1134
+ const rightIndex = triangleIndices[1];
1135
+ if (pairedTriangles.has(leftIndex) || pairedTriangles.has(rightIndex)) continue;
1136
+ const left = sourceTriangles[leftIndex];
1137
+ const right = sourceTriangles[rightIndex];
1138
+ if (triangleNormal(left).dot(triangleNormal(right)) < 0.999999) continue;
1139
+ const leftAttributes = sourceTriangleAttributeIndices[leftIndex];
1140
+ const rightAttributes = sourceTriangleAttributeIndices[rightIndex];
1141
+ const directedEdges: Array<{ start: number; end: number; attributeIndex: number }> = [
1142
+ { start: left[0], end: left[1], attributeIndex: leftAttributes[0] },
1143
+ { start: left[1], end: left[2], attributeIndex: leftAttributes[1] },
1144
+ { start: left[2], end: left[0], attributeIndex: leftAttributes[2] },
1145
+ { start: right[0], end: right[1], attributeIndex: rightAttributes[0] },
1146
+ { start: right[1], end: right[2], attributeIndex: rightAttributes[1] },
1147
+ { start: right[2], end: right[0], attributeIndex: rightAttributes[2] },
1148
+ ];
1149
+ const boundaryEdges = directedEdges.filter(
1150
+ (edge, edgeIndex) => !directedEdges.some(
1151
+ (candidate, candidateIndex) => (
1152
+ candidateIndex !== edgeIndex && candidate.start === edge.end && candidate.end === edge.start
1153
+ ),
1154
+ ),
1155
+ );
1156
+ if (boundaryEdges.length !== 4) continue;
1157
+ const face: number[] = [];
1158
+ const attributeIndices: number[] = [];
1159
+ let edge = boundaryEdges[0];
1160
+ let closesFace = false;
1161
+ while (face.length < 4) {
1162
+ face.push(edge.start);
1163
+ attributeIndices.push(edge.attributeIndex);
1164
+ if (face.length === 4) {
1165
+ closesFace = edge.end === face[0];
1166
+ break;
1167
+ }
1168
+ const nextEdge = boundaryEdges.find((candidate) => candidate.start === edge.end);
1169
+ if (!nextEdge) break;
1170
+ edge = nextEdge;
1171
+ }
1172
+ if (face.length === 4 && closesFace) {
1173
+ faces.push(face);
1174
+ faceAttributeIndices.push(attributeIndices);
1175
+ pairedTriangles.add(leftIndex);
1176
+ pairedTriangles.add(rightIndex);
1177
+ }
1178
+ }
1179
+ for (let triangleIndex = 0; triangleIndex < sourceTriangles.length; triangleIndex += 1) {
1180
+ if (!pairedTriangles.has(triangleIndex)) {
1181
+ faces.push(sourceTriangles[triangleIndex]);
1182
+ faceAttributeIndices.push(sourceTriangleAttributeIndices[triangleIndex]);
1183
+ }
1184
+ }
1185
+ if (faces.length === 0) {
1186
+ source.computeVertexNormals();
1187
+ return source;
1188
+ }
1189
+
1190
+ for (const channel of sourceUvChannels) {
1191
+ const attribute = source.getAttribute(channel.name);
1192
+ if (!attribute) continue;
1193
+ channel.faces = faceAttributeIndices.map((indices) => (
1194
+ indices.map((attributeIndex) => new THREE.Vector2(attribute.getX(attributeIndex), attribute.getY(attributeIndex)))
1195
+ ));
1196
+ }
1197
+
1198
+ const sourceFaceCount = faces.length;
1199
+ const projectedQuadFaceCount = sourceFaceCount * 4 ** iterations;
1200
+ if (projectedQuadFaceCount > MAX_SUBDIVISION_QUAD_FACES) {
1201
+ throw new SubdivisionGeometryBudgetError(sourceFaceCount, projectedQuadFaceCount);
1202
+ }
1203
+ let vertices = sourcePositions;
1204
+ let uvChannels = sourceUvChannels;
1205
+ for (let iteration = 0; iteration < iterations; iteration += 1) {
1206
+ const facePoints = faces.map((face) => {
1207
+ const point = new THREE.Vector3();
1208
+ for (const vertexIndex of face) point.add(vertices[vertexIndex]);
1209
+ return point.multiplyScalar(1 / face.length);
1210
+ });
1211
+ const vertexFaces: number[][] = Array.from({ length: vertices.length }, () => []);
1212
+ const vertexEdges: number[][] = Array.from({ length: vertices.length }, () => []);
1213
+ const faceEdges: number[][] = faces.map(() => []);
1214
+ const edges: SubdivisionEdge[] = [];
1215
+ const edgeIndices = new Map<string, number>();
1216
+ for (let faceIndex = 0; faceIndex < faces.length; faceIndex += 1) {
1217
+ const face = faces[faceIndex];
1218
+ for (const vertexIndex of face) vertexFaces[vertexIndex].push(faceIndex);
1219
+ for (let vertexIndex = 0; vertexIndex < face.length; vertexIndex += 1) {
1220
+ const a = face[vertexIndex];
1221
+ const b = face[(vertexIndex + 1) % face.length];
1222
+ const key = edgeKey(a, b);
1223
+ let edgeIndex = edgeIndices.get(key);
1224
+ if (edgeIndex === undefined) {
1225
+ edgeIndex = edges.length;
1226
+ edges.push({ a: Math.min(a, b), b: Math.max(a, b), faces: [] });
1227
+ edgeIndices.set(key, edgeIndex);
1228
+ }
1229
+ edges[edgeIndex].faces.push(faceIndex);
1230
+ vertexEdges[a].push(edgeIndex);
1231
+ vertexEdges[b].push(edgeIndex);
1232
+ faceEdges[faceIndex].push(edgeIndex);
1233
+ }
1234
+ }
1235
+ for (const edge of edges) {
1236
+ if (edge.faces.length > 2) {
1237
+ throw new SubdivisionTopologyError(`non-manifold edge ${edge.a}:${edge.b} has ${edge.faces.length} incident faces`);
1238
+ }
1239
+ if (edge.faces.length === 1) {
1240
+ throw new SubdivisionTopologyError(`open boundary edge ${edge.a}:${edge.b} has 1 incident face`);
1241
+ }
1242
+ }
1243
+ for (let vertexIndex = 0; vertexIndex < vertices.length; vertexIndex += 1) {
1244
+ const incidentFaces = vertexFaces[vertexIndex];
1245
+ if (incidentFaces.length < 2) continue;
1246
+ const connectedFaces = new Set<number>();
1247
+ const pendingFaces = [incidentFaces[0]];
1248
+ while (pendingFaces.length > 0) {
1249
+ const faceIndex = pendingFaces.pop();
1250
+ if (faceIndex === undefined || connectedFaces.has(faceIndex)) continue;
1251
+ connectedFaces.add(faceIndex);
1252
+ for (const edgeIndex of vertexEdges[vertexIndex]) {
1253
+ const edge = edges[edgeIndex];
1254
+ if (edge.faces.length !== 2 || !edge.faces.includes(faceIndex)) continue;
1255
+ const adjacentFace = edge.faces[0] === faceIndex ? edge.faces[1] : edge.faces[0];
1256
+ if (!connectedFaces.has(adjacentFace)) pendingFaces.push(adjacentFace);
1257
+ }
1258
+ }
1259
+ if (connectedFaces.size !== incidentFaces.length) {
1260
+ throw new SubdivisionTopologyError(`vertex ${vertexIndex} has a disconnected incident face fan`);
1261
+ }
1262
+ }
1263
+
1264
+ const nextVertices: THREE.Vector3[] = [];
1265
+ for (let vertexIndex = 0; vertexIndex < vertices.length; vertexIndex += 1) {
1266
+ const vertex = vertices[vertexIndex];
1267
+ const incidentFaces = vertexFaces[vertexIndex];
1268
+ const incidentEdges = vertexEdges[vertexIndex];
1269
+ if (incidentFaces.length === 0 || incidentEdges.length === 0) {
1270
+ nextVertices.push(vertex.clone());
1271
+ continue;
1272
+ }
1273
+ const faceAverage = new THREE.Vector3();
1274
+ for (const faceIndex of incidentFaces) faceAverage.add(facePoints[faceIndex]);
1275
+ faceAverage.multiplyScalar(1 / incidentFaces.length);
1276
+ const edgeAverage = new THREE.Vector3();
1277
+ for (const edgeIndex of incidentEdges) {
1278
+ const edge = edges[edgeIndex];
1279
+ edgeAverage.add(vertices[edge.a].clone().add(vertices[edge.b]).multiplyScalar(0.5));
1280
+ }
1281
+ edgeAverage.multiplyScalar(1 / incidentEdges.length);
1282
+ nextVertices.push(
1283
+ vertex.clone()
1284
+ .multiplyScalar(incidentFaces.length - 3)
1285
+ .add(faceAverage)
1286
+ .addScaledVector(edgeAverage, 2)
1287
+ .multiplyScalar(1 / incidentFaces.length),
1288
+ );
1289
+ }
1290
+
1291
+ const nextUvChannels = uvChannels.map((channel) => {
1292
+ const nextFaces: THREE.Vector2[][] = [];
1293
+ for (const faceValues of channel.faces) {
1294
+ const faceValue = new THREE.Vector2();
1295
+ for (const value of faceValues) faceValue.add(value);
1296
+ faceValue.multiplyScalar(1 / faceValues.length);
1297
+ for (let vertexIndex = 0; vertexIndex < faceValues.length; vertexIndex += 1) {
1298
+ const value = faceValues[vertexIndex];
1299
+ const nextValue = faceValues[(vertexIndex + 1) % faceValues.length];
1300
+ const previousValue = faceValues[(vertexIndex + faceValues.length - 1) % faceValues.length];
1301
+ nextFaces.push([
1302
+ value.clone(),
1303
+ value.clone().add(nextValue).multiplyScalar(0.5),
1304
+ faceValue.clone(),
1305
+ previousValue.clone().add(value).multiplyScalar(0.5),
1306
+ ]);
1307
+ }
1308
+ }
1309
+ return { name: channel.name, faces: nextFaces };
1310
+ });
1311
+
1312
+ const edgePointIndices: number[] = [];
1313
+ for (const edge of edges) {
1314
+ const point = vertices[edge.a].clone().add(vertices[edge.b]);
1315
+ if (edge.faces.length >= 2) {
1316
+ point.add(facePoints[edge.faces[0]]).add(facePoints[edge.faces[1]]).multiplyScalar(0.25);
1317
+ } else {
1318
+ point.multiplyScalar(0.5);
1319
+ }
1320
+ edgePointIndices.push(nextVertices.length);
1321
+ nextVertices.push(point);
1322
+ }
1323
+ const facePointIndices: number[] = [];
1324
+ for (const point of facePoints) {
1325
+ facePointIndices.push(nextVertices.length);
1326
+ nextVertices.push(point);
1327
+ }
1328
+ const nextFaces: number[][] = [];
1329
+ for (let faceIndex = 0; faceIndex < faces.length; faceIndex += 1) {
1330
+ const face = faces[faceIndex];
1331
+ const faceEdgeIndices = faceEdges[faceIndex];
1332
+ for (let vertexIndex = 0; vertexIndex < face.length; vertexIndex += 1) {
1333
+ const previousEdgeIndex = (vertexIndex + faceEdgeIndices.length - 1) % faceEdgeIndices.length;
1334
+ nextFaces.push([
1335
+ face[vertexIndex],
1336
+ edgePointIndices[faceEdgeIndices[vertexIndex]],
1337
+ facePointIndices[faceIndex],
1338
+ edgePointIndices[faceEdgeIndices[previousEdgeIndex]],
1339
+ ]);
1340
+ }
1341
+ }
1342
+ vertices = nextVertices;
1343
+ uvChannels = nextUvChannels;
1344
+ faces = nextFaces;
1345
+ }
1346
+
1347
+ const topologyPositions: number[] = [];
1348
+ for (const vertex of vertices) topologyPositions.push(vertex.x, vertex.y, vertex.z);
1349
+ const topologyIndices: number[] = [];
1350
+ for (const face of faces) {
1351
+ for (let vertexIndex = 1; vertexIndex + 1 < face.length; vertexIndex += 1) {
1352
+ topologyIndices.push(face[0], face[vertexIndex], face[vertexIndex + 1]);
1353
+ }
1354
+ }
1355
+ const topologyGeometry = new THREE.BufferGeometry();
1356
+ topologyGeometry.setAttribute('position', new THREE.Float32BufferAttribute(topologyPositions, 3));
1357
+ topologyGeometry.setIndex(topologyIndices);
1358
+ topologyGeometry.computeVertexNormals();
1359
+
1360
+ let geometry = topologyGeometry;
1361
+ if (uvChannels.length > 0) {
1362
+ const normals = topologyGeometry.getAttribute('normal');
1363
+ const positions: number[] = [];
1364
+ const normalValues: number[] = [];
1365
+ const indices: number[] = [];
1366
+ const seamUvValues: Array<{ name: string; values: number[] }> = uvChannels.map((channel) => ({ name: channel.name, values: [] }));
1367
+ for (let faceIndex = 0; faceIndex < faces.length; faceIndex += 1) {
1368
+ const face = faces[faceIndex];
1369
+ const cornerIndices: number[] = [];
1370
+ const faceStart = positions.length / 3;
1371
+ for (let vertexIndex = 0; vertexIndex < face.length; vertexIndex += 1) {
1372
+ const topologyIndex = face[vertexIndex];
1373
+ const vertex = vertices[topologyIndex];
1374
+ positions.push(vertex.x, vertex.y, vertex.z);
1375
+ normalValues.push(normals.getX(topologyIndex), normals.getY(topologyIndex), normals.getZ(topologyIndex));
1376
+ for (let channelIndex = 0; channelIndex < uvChannels.length; channelIndex += 1) {
1377
+ const value = uvChannels[channelIndex].faces[faceIndex][vertexIndex];
1378
+ seamUvValues[channelIndex].values.push(value.x, value.y);
1379
+ }
1380
+ cornerIndices.push(faceStart + vertexIndex);
1381
+ }
1382
+ for (let vertexIndex = 1; vertexIndex + 1 < cornerIndices.length; vertexIndex += 1) {
1383
+ indices.push(cornerIndices[0], cornerIndices[vertexIndex], cornerIndices[vertexIndex + 1]);
1384
+ }
1385
+ }
1386
+ geometry = new THREE.BufferGeometry();
1387
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
1388
+ geometry.setAttribute('normal', new THREE.Float32BufferAttribute(normalValues, 3));
1389
+ geometry.setIndex(indices);
1390
+ for (const channel of seamUvValues) {
1391
+ geometry.setAttribute(channel.name, new THREE.Float32BufferAttribute(channel.values, 2));
1392
+ }
1393
+ }
1394
+ geometry.userData.subdivision = {
1395
+ method: 'catmull-clark-style',
1396
+ sourceFaceCount,
1397
+ quadFaceCount: faces.length,
1398
+ iterations,
1399
+ };
1400
+ return geometry;
1401
+ }"""
1402
+
1403
+
1404
+ def capped_sdf(sdf: dict[str, Any], segments: dict[str, int]) -> dict[str, Any]:
1405
+ """Clamp an SDF descriptor's sampling grid to the tessellation tier's ceiling.
1406
+
1407
+ Lowering the grid is the only lever an implicit surface has: it has no segment counts.
1408
+ The author's value is kept when it is already at or below the ceiling, so a deliberately
1409
+ coarse field is never made denser by the tier.
1410
+ """
1411
+ ceiling = segments.get("SDF_MAX_RESOLUTION")
1412
+ resolution = sdf.get("resolution")
1413
+ if not isinstance(ceiling, int) or not isinstance(resolution, int) or isinstance(resolution, bool):
1414
+ return sdf
1415
+ if resolution <= ceiling:
1416
+ return sdf
1417
+ return {**sdf, "resolution": ceiling}
1418
+
1419
+
1420
+ _STAND_PROUD_HELPER_SOURCE = '''\
1421
+ type ProudRingStack = { rings: [number, number, number, number][] };
1422
+
1423
+ // Signed distance to a stack of ellipse rings. Negative inside, positive outside.
1424
+ //
1425
+ // The sign is exact; the magnitude is the first-order estimate f / |grad f|, which UNDERSTATES how
1426
+ // clear an outside point is and OVERSTATES how deep an inside point is. Both errors make the march
1427
+ // below push slightly further than strictly necessary, which is the safe direction: the failure
1428
+ // being prevented is a component sinking into the one beneath it and rendering as a bare patch.
1429
+ function ringStackDistance(stack: ProudRingStack, x: number, y: number, z: number): number {
1430
+ const rings = stack.rings;
1431
+ const yMin = rings[0][0];
1432
+ const yMax = rings[rings.length - 1][0];
1433
+ let rx = rings[0][1];
1434
+ let rz = rings[0][2];
1435
+ let zc = rings[0][3];
1436
+ if (y >= yMax) {
1437
+ const last = rings[rings.length - 1];
1438
+ rx = last[1]; rz = last[2]; zc = last[3];
1439
+ } else if (y > yMin) {
1440
+ for (let i = 0; i + 1 < rings.length; i += 1) {
1441
+ const lo = rings[i];
1442
+ const hi = rings[i + 1];
1443
+ if (y >= lo[0] && y <= hi[0]) {
1444
+ const span = hi[0] - lo[0];
1445
+ const t = span > 1e-9 ? (y - lo[0]) / span : 0;
1446
+ rx = lo[1] + (hi[1] - lo[1]) * t;
1447
+ rz = lo[2] + (hi[2] - lo[2]) * t;
1448
+ zc = lo[3] + (hi[3] - lo[3]) * t;
1449
+ break;
1450
+ }
1451
+ }
1452
+ }
1453
+ const dx = x / rx;
1454
+ const dz = (z - zc) / rz;
1455
+ const f = dx * dx + dz * dz - 1;
1456
+ const gx = (2 * x) / (rx * rx);
1457
+ const gz = (2 * (z - zc)) / (rz * rz);
1458
+ const grad = Math.hypot(gx, gz);
1459
+ const radial = grad < 1e-12 ? -Math.min(rx, rz) : f / grad;
1460
+ const axial = Math.max(yMin - y, y - yMax);
1461
+ return Math.hypot(Math.max(radial, 0), Math.max(axial, 0)) + Math.min(Math.max(radial, axial), 0);
1462
+ }
1463
+
1464
+ // Push every vertex outward until it stands `clearance` clear of the target's surface.
1465
+ //
1466
+ // WHY THE AUTHORED NUMBERS ARE ONLY A LOWER BOUND. A ring is an ELLIPSE, and the surface it has to
1467
+ // clear generally is not. Any single ellipse that clears the widest point is loose at the narrowest
1468
+ // and vice versa, so hand-widening moves the error rather than shrinking it -- measured on hair,
1469
+ // where widening the side masses took closure from 42.2% to 40.9%, worse on all six views, with
1470
+ // dark coverage DOWN because the widened mass had slid off the skull. Here the authored width is a
1471
+ // floor and the real radius is MEASURED per vertex.
1472
+ //
1473
+ // Each vertex travels along its OWN radial spoke rather than along the field's gradient, so the
1474
+ // ring keeps its vertex order and its seam positions and only its radius changes. `maxPush` is
1475
+ // required, not a safeguard: an uncapped march walks inner vertices straight through the target and
1476
+ // out the far side, closing the very gap the component exists to leave.
1477
+ function applyStandProud(
1478
+ geometry: THREE.BufferGeometry,
1479
+ marcher: THREE.Object3D,
1480
+ target: THREE.Object3D,
1481
+ stack: ProudRingStack,
1482
+ clearance: number,
1483
+ maxPush: number,
1484
+ ): void {
1485
+ const position = geometry.getAttribute('position') as THREE.BufferAttribute;
1486
+ marcher.updateWorldMatrix(true, false);
1487
+ target.updateWorldMatrix(true, false);
1488
+ const toTarget = new THREE.Matrix4().copy(target.matrixWorld).invert().multiply(marcher.matrixWorld);
1489
+ const fromTarget = new THREE.Matrix4().copy(toTarget).invert();
1490
+ const p = new THREE.Vector3();
1491
+ // A vertex can exhaust `maxPush` and still be inside the target. That is the cap doing its job --
1492
+ // an uncapped march walks vertices out the far side -- but it means the clearance this function
1493
+ // promises was NOT achieved, and saying nothing there hides exactly the defect the caller asked
1494
+ // to be protected from. Measured on the shipped fixture: 2 of 8 sampled hair vertices sat 0.059
1495
+ // inside a skull against a 0.04 cap and could never have reached clear.
1496
+ let unresolved = 0;
1497
+
1498
+ for (let i = 0; i < position.count; i += 1) {
1499
+ p.fromBufferAttribute(position, i).applyMatrix4(toTarget);
1500
+ // The spoke is the vertex's own radial direction in the target's frame; marching along it keeps
1501
+ // each ring a ring, since every vertex holds its own angle and only its radius changes.
1502
+ //
1503
+ // A vertex on the axis has no radial direction at all -- and that is precisely the crown, the
1504
+ // one place a bald patch is most visible. Skipping it leaves the exact failure this function
1505
+ // exists to prevent. So a degenerate spoke marches axially instead, out through whichever cap
1506
+ // it is nearer, which is the direction the field itself measures there.
1507
+ const spokeLength = Math.hypot(p.x, p.z);
1508
+ const onAxis = spokeLength < 1e-9;
1509
+ const midHeight = (stack.rings[0][0] + stack.rings[stack.rings.length - 1][0]) / 2;
1510
+ const sx = onAxis ? 0 : p.x / spokeLength;
1511
+ const sz = onAxis ? 0 : p.z / spokeLength;
1512
+ const sy = onAxis ? (p.y >= midHeight ? 1 : -1) : 0;
1513
+
1514
+ let travelled = 0;
1515
+ for (let step = 0; step < 24; step += 1) {
1516
+ const gap = ringStackDistance(stack, p.x, p.y, p.z);
1517
+ if (gap >= clearance) break;
1518
+ const move = Math.min(Math.max(0.002, clearance - gap), maxPush - travelled);
1519
+ if (move <= 0) break;
1520
+ p.x += sx * move;
1521
+ p.y += sy * move;
1522
+ p.z += sz * move;
1523
+ travelled += move;
1524
+ }
1525
+
1526
+ if (ringStackDistance(stack, p.x, p.y, p.z) < clearance) unresolved += 1;
1527
+
1528
+ p.applyMatrix4(fromTarget);
1529
+ position.setXYZ(i, p.x, p.y, p.z);
1530
+ }
1531
+
1532
+ position.needsUpdate = true;
1533
+ geometry.computeVertexNormals();
1534
+
1535
+ geometry.userData.standProud = { clearance, maxPush, unresolved, total: position.count };
1536
+ if (unresolved > 0) {
1537
+ console.warn(
1538
+ `standProud: ${unresolved}/${position.count} vertices could not reach ${clearance} within ` +
1539
+ `maxPush ${maxPush}. They are still inside the target and will render as bare patches. ` +
1540
+ `Raise maxPush, or move the component out so it does not start that deep.`,
1541
+ );
1542
+ }
1543
+ }
1544
+ '''
1545
+
1546
+
1547
+ _ROOT_TIP_GRADIENT_HELPER_SOURCE = '''\
1548
+ // Darken a mass toward its root.
1549
+ //
1550
+ // WHY THIS IS SHADING AND NOT GEOMETRY. Measured on the reference this pipeline is calibrated
1551
+ // against -- a 570,400 vertex merged scan -- the surface roughness over the hair is 0.00338 against
1552
+ // a torso control of 0.00312. Its hair is a SMOOTH SHELL and every strand it appears to have lives
1553
+ // in the diffuse and normal textures. This pipeline emits code and no textures, so the same
1554
+ // impression has to be carried by vertex colour, faceting and sheen. Adding lock geometry does not
1555
+ // substitute for it: four attempts to close the gap geometrically all failed, and the last one made
1556
+ // every view worse.
1557
+ //
1558
+ // The gradient runs along the mass's own local axis rather than world Y, so a fringe sweeping
1559
+ // sideways darkens at its root and not at whatever happens to be lowest.
1560
+ function applyRootTipGradient(
1561
+ geometry: THREE.BufferGeometry,
1562
+ rootColor: THREE.ColorRepresentation,
1563
+ tipColor: THREE.ColorRepresentation,
1564
+ axis: 'x' | 'y' | 'z',
1565
+ ): void {
1566
+ const position = geometry.getAttribute('position') as THREE.BufferAttribute;
1567
+ const root = new THREE.Color(rootColor);
1568
+ const tip = new THREE.Color(tipColor);
1569
+ const values = new Float32Array(position.count * 3);
1570
+
1571
+ let low = Infinity;
1572
+ let high = -Infinity;
1573
+ for (let i = 0; i < position.count; i += 1) {
1574
+ const v = axis === 'x' ? position.getX(i) : axis === 'z' ? position.getZ(i) : position.getY(i);
1575
+ if (v < low) low = v;
1576
+ if (v > high) high = v;
1577
+ }
1578
+ // A mass with no extent along its own axis has no root and no tip; a flat colour is the honest
1579
+ // answer, and dividing by the span would produce NaN on every vertex.
1580
+ const span = high - low;
1581
+
1582
+ const mixed = new THREE.Color();
1583
+ for (let i = 0; i < position.count; i += 1) {
1584
+ const v = axis === 'x' ? position.getX(i) : axis === 'z' ? position.getZ(i) : position.getY(i);
1585
+ const t = span > 1e-9 ? (v - low) / span : 1;
1586
+ mixed.copy(root).lerp(tip, t);
1587
+ values[i * 3] = mixed.r;
1588
+ values[i * 3 + 1] = mixed.g;
1589
+ values[i * 3 + 2] = mixed.b;
1590
+ }
1591
+ geometry.setAttribute('color', new THREE.BufferAttribute(values, 3));
1592
+ }
1593
+ '''
1594
+
1595
+
1596
+ _VERTEX_PAINT_HELPER_SOURCE = '''\
1597
+ // Paint declared colour regions into the vertex-colour attribute.
1598
+ //
1599
+ // WHY VERTEX COLOUR AND NOT A TEXTURE. A subject whose identity is a set of flat colour regions
1600
+ // with hard boundaries -- a blaze, a bib, a sock, a livery stripe -- needs those boundaries placed
1601
+ // to a measured position. This pipeline emits code and no image assets, so a texture is not
1602
+ // available to place them with; a single root-to-tip ramp cannot express a shaped region. Per-
1603
+ // vertex colour driven by a declared shape is the remaining honest representation, and it is the
1604
+ // one the boundary gate can measure BEFORE a browser is involved.
1605
+ //
1606
+ // The maths here is a transcription of forge/_shared/vertex_paint.py, and
1607
+ // forge/tests/test_vertex_paint.py holds the two to the same numbers on a fixture. Editing one
1608
+ // side without the other turns a gated boundary into an ungated one, which is exactly the failure
1609
+ // the shared implementation exists to prevent.
1610
+ //
1611
+ // Regions are evaluated in the component's own local space AFTER its real dimensions have been
1612
+ // applied to the vertex data, so every coordinate below is in the same units as the component's
1613
+ // measured dimensions rather than in a unit cube.
1614
+ type VertexPaintRegion = {
1615
+ id: string;
1616
+ kind: 'axis-band' | 'ellipsoid' | 'tapered-capsule';
1617
+ color: string;
1618
+ softness: number;
1619
+ axis?: 'x' | 'y' | 'z';
1620
+ min?: number;
1621
+ max?: number;
1622
+ center?: [number, number, number];
1623
+ radii?: [number, number, number];
1624
+ start?: [number, number, number];
1625
+ end?: [number, number, number];
1626
+ startRadius?: number;
1627
+ endRadius?: number;
1628
+ };
1629
+
1630
+ function vertexPaintSmoothstep(edge0: number, edge1: number, value: number): number {
1631
+ if (edge1 <= edge0) return value < edge1 ? 0 : 1;
1632
+ let t = (value - edge0) / (edge1 - edge0);
1633
+ t = t < 0 ? 0 : t > 1 ? 1 : t;
1634
+ return t * t * (3 - 2 * t);
1635
+ }
1636
+
1637
+ function vertexPaintSignedDistance(
1638
+ region: VertexPaintRegion,
1639
+ x: number,
1640
+ y: number,
1641
+ z: number,
1642
+ ): number {
1643
+ if (region.kind === 'axis-band') {
1644
+ const value = region.axis === 'x' ? x : region.axis === 'z' ? z : y;
1645
+ const low = region.min as number;
1646
+ const high = region.max as number;
1647
+ if (value < low) return low - value;
1648
+ if (value > high) return value - high;
1649
+ return -Math.min(value - low, high - value);
1650
+ }
1651
+ if (region.kind === 'ellipsoid') {
1652
+ const [cx, cy, cz] = region.center as [number, number, number];
1653
+ const [rx, ry, rz] = region.radii as [number, number, number];
1654
+ const q = Math.sqrt(
1655
+ ((x - cx) / rx) ** 2 + ((y - cy) / ry) ** 2 + ((z - cz) / rz) ** 2,
1656
+ );
1657
+ return (q - 1) * Math.min(rx, ry, rz);
1658
+ }
1659
+ const [ax, ay, az] = region.start as [number, number, number];
1660
+ const [bx, by, bz] = region.end as [number, number, number];
1661
+ const abx = bx - ax;
1662
+ const aby = by - ay;
1663
+ const abz = bz - az;
1664
+ const denominator = abx * abx + aby * aby + abz * abz;
1665
+ let t = denominator > 0
1666
+ ? ((x - ax) * abx + (y - ay) * aby + (z - az) * abz) / denominator
1667
+ : 0;
1668
+ t = t < 0 ? 0 : t > 1 ? 1 : t;
1669
+ const distance = Math.sqrt(
1670
+ (x - (ax + abx * t)) ** 2 + (y - (ay + aby * t)) ** 2 + (z - (az + abz * t)) ** 2,
1671
+ );
1672
+ const startRadius = region.startRadius as number;
1673
+ const endRadius = region.endRadius as number;
1674
+ return distance - (startRadius + (endRadius - startRadius) * t);
1675
+ }
1676
+
1677
+ function vertexPaintWeight(region: VertexPaintRegion, x: number, y: number, z: number): number {
1678
+ const distance = vertexPaintSignedDistance(region, x, y, z);
1679
+ if (region.softness <= 0) return distance <= 0 ? 1 : 0;
1680
+ return 1 - vertexPaintSmoothstep(-region.softness * 0.5, region.softness * 0.5, distance);
1681
+ }
1682
+
1683
+ function applyVertexPaint(
1684
+ geometry: THREE.BufferGeometry,
1685
+ baseColor: string,
1686
+ regions: VertexPaintRegion[],
1687
+ ): void {
1688
+ const position = geometry.getAttribute('position') as THREE.BufferAttribute;
1689
+ const values = new Float32Array(position.count * 3);
1690
+ const base = new THREE.Color(baseColor);
1691
+ const target = new THREE.Color();
1692
+ const mixed = new THREE.Color();
1693
+ const regionColors = regions.map((region) => new THREE.Color(region.color));
1694
+
1695
+ for (let i = 0; i < position.count; i += 1) {
1696
+ const x = position.getX(i);
1697
+ const y = position.getY(i);
1698
+ const z = position.getZ(i);
1699
+ mixed.copy(base);
1700
+ for (let r = 0; r < regions.length; r += 1) {
1701
+ const weight = vertexPaintWeight(regions[r], x, y, z);
1702
+ if (weight <= 0) continue;
1703
+ target.copy(regionColors[r]);
1704
+ mixed.lerp(target, weight);
1705
+ }
1706
+ values[i * 3] = mixed.r;
1707
+ values[i * 3 + 1] = mixed.g;
1708
+ values[i * 3 + 2] = mixed.b;
1709
+ }
1710
+ geometry.setAttribute('color', new THREE.BufferAttribute(values, 3));
1711
+ }
1712
+ '''
1713
+
1714
+
1715
+ def vertex_paint(component: dict[str, Any]) -> dict[str, Any] | None:
1716
+ """A component's declared colour-region paint, or None.
1717
+
1718
+ Raises rather than degrading to flat colour when the declaration is malformed. A boundary that
1719
+ silently vanishes is the failure mode this whole subsystem exists to remove: the render still
1720
+ looks like a cat, the gate still finds a mesh, and the identity feature is simply not there.
1721
+ """
1722
+ paint = component.get("vertexPaint")
1723
+ if paint is None:
1724
+ return None
1725
+ try:
1726
+ return normalize_vertex_paint(paint, f"component {component.get('id')!r} vertexPaint")
1727
+ except VertexPaintError as error:
1728
+ raise ValueError(str(error)) from error
1729
+
1730
+
1731
+ def root_tip_gradient(component: dict[str, Any]) -> dict[str, Any] | None:
1732
+ """A component's root-to-tip colour ramp, or None.
1733
+
1734
+ Rejected rather than defaulted when malformed: a gradient silently falling back to flat colour
1735
+ is the kind of quiet no-op that made hair hard to diagnose in the first place.
1736
+ """
1737
+ gradient = component.get("rootTipGradient")
1738
+ if not isinstance(gradient, dict):
1739
+ return None
1740
+ root = gradient.get("rootColor")
1741
+ tip = gradient.get("tipColor")
1742
+ if not isinstance(root, str) or not isinstance(tip, str):
1743
+ return None
1744
+ axis = gradient.get("axis", "y")
1745
+ if axis not in ("x", "y", "z"):
1746
+ axis = "y"
1747
+ return {"rootColor": root, "tipColor": tip, "axis": axis}
1748
+
1749
+
1750
+ def stand_proud_ring_stack(component: dict[str, Any]) -> list[list[float]] | None:
1751
+ """The ring stack a component presents as a surface to stand proud of, in its own local space.
1752
+
1753
+ Two sources, because two shapes actually occur. A component authored as a ring stack carries one
1754
+ directly. Everything else that is a closed convex blob -- an ellipsoid or a sphere, which is what
1755
+ a generated head is -- gets one synthesised from its unit geometry, since `geometry_for` authors
1756
+ those at radius 0.5 and the real dimensions arrive later via `geometry.scale`. Returning None
1757
+ means the target has no surface this march can describe, and the caller must say so rather than
1758
+ silently skip the clearance.
1759
+ """
1760
+ descriptor = component.get("geometryDescriptor")
1761
+ if isinstance(descriptor, dict):
1762
+ stack = descriptor.get("ringStack")
1763
+ if isinstance(stack, dict) and isinstance(stack.get("rings"), list) and stack["rings"]:
1764
+ offsets = stack.get("zOffsets")
1765
+ rings: list[list[float]] = []
1766
+ for index, ring in enumerate(stack["rings"]):
1767
+ values = [float(v) for v in list(ring)[:4]]
1768
+ if len(values) < 3:
1769
+ return None
1770
+ if len(values) == 3:
1771
+ offset = 0.0
1772
+ if isinstance(offsets, list) and index < len(offsets):
1773
+ offset = float(offsets[index])
1774
+ values.append(offset)
1775
+ rings.append(values)
1776
+ rings.sort(key=lambda r: r[0])
1777
+ return rings
1778
+
1779
+ if component.get("primitive") in {"ellipsoid", "sphere", "capsule"}:
1780
+ # A unit sphere of radius 0.5, sliced into rings. The march runs in the TARGET's local
1781
+ # space, and `geometry.scale` has already been applied to the target's own vertices, so the
1782
+ # stack has to describe the unit form and let the caller's matrix carry the scale.
1783
+ slices = 12
1784
+ rings = []
1785
+ for index in range(slices + 1):
1786
+ t = index / slices
1787
+ y = -0.5 + t
1788
+ radius = math.sqrt(max(0.0, 0.25 - y * y))
1789
+ rings.append([round(y, 6), round(max(radius, 1e-4), 6), round(max(radius, 1e-4), 6), 0.0])
1790
+ return rings
1791
+
1792
+ return None
1793
+
1794
+
1795
+ def geometry_for(
1796
+ primitive: str,
1797
+ component: dict[str, Any] | None = None,
1798
+ subdivision_requested: bool = False,
1799
+ segments: dict[str, int] | None = None,
1800
+ ) -> str:
1801
+ """Emit the geometry construction for one primitive.
1802
+
1803
+ `segments` is the resolved tessellation table (see `_shared/subdivision.py`).
1804
+ It defaults to the `hero` tier, which is the module-level constants, so a
1805
+ caller that does not pass one gets exactly the output it got before tiers
1806
+ existed.
1807
+ """
1808
+ seg = segments if segments is not None else TESSELLATION_TIERS[DEFAULT_TESSELLATION_TIER]
1809
+ if primitive == "box":
1810
+ n = seg["BOX_SEGMENTS"]
1811
+ return f"new THREE.BoxGeometry(1, 1, 1, {n}, {n}, {n})"
1812
+ if primitive in {"sphere", "ellipsoid"}:
1813
+ return f"new THREE.SphereGeometry(0.5, {seg['SPHERE_WIDTH_SEGMENTS']}, {seg['SPHERE_HEIGHT_SEGMENTS']})"
1814
+ if primitive == "cylinder":
1815
+ return f"new THREE.CylinderGeometry(0.5, 0.5, 1, {seg['CYLINDER_RADIAL_SEGMENTS']}, {seg['CYLINDER_HEIGHT_SEGMENTS']})"
1816
+ if primitive == "cone":
1817
+ if subdivision_requested:
1818
+ return f"new THREE.CylinderGeometry(0.5, {CONE_SUBDIVISION_TOP_RADIUS}, 1, {seg['CYLINDER_RADIAL_SEGMENTS']}, {seg['CYLINDER_HEIGHT_SEGMENTS']})"
1819
+ return f"new THREE.ConeGeometry(0.5, 1, {seg['CYLINDER_RADIAL_SEGMENTS']}, {seg['CONE_HEIGHT_SEGMENTS']})"
1820
+ if primitive == "capsule":
1821
+ return f"buildWatertightCapsule(0.35, 0.7, {seg['CAPSULE_CAP_SEGMENTS']}, {seg['CAPSULE_RADIAL_SEGMENTS']}, 1)"
1822
+ if primitive == "torus":
1823
+ # Tube thickness is ring-relative (fraction of the 0.45 base radius) so a
1824
+ # component can be a slim bike tyre or a fat donut without changing scale.
1825
+ desc = component.get("geometryDescriptor") if isinstance(component, dict) and isinstance(component.get("geometryDescriptor"), dict) else {}
1826
+ tube_ratio = desc.get("torusTubeRatio")
1827
+ tube = 0.45 * float(tube_ratio) if isinstance(tube_ratio, (int, float)) and tube_ratio > 0 else 0.08
1828
+ return f"new THREE.TorusGeometry(0.45, {round(tube, 4)}, {seg['TORUS_TUBULAR_SEGMENTS']}, {seg['TORUS_RADIAL_SEGMENTS']})"
1829
+ if primitive == "plane-card":
1830
+ return f"new THREE.PlaneGeometry(1, 1, {seg['PLANE_WIDTH_SEGMENTS']}, {seg['PLANE_HEIGHT_SEGMENTS']})"
1831
+ descriptor = component.get("geometryDescriptor") if isinstance(component, dict) and isinstance(component.get("geometryDescriptor"), dict) else {}
1832
+ if primitive == "extrude":
1833
+ profile = descriptor.get("profile2D") if isinstance(descriptor.get("profile2D"), dict) else _DEFAULT_EXTRUDE_PROFILE
1834
+ return f"buildExtrudeGeometry({json_literal(profile)})"
1835
+ if primitive == "ground-blade":
1836
+ spec = descriptor.get("bladeSpec") if isinstance(descriptor.get("bladeSpec"), dict) else _DEFAULT_BLADE_SPEC
1837
+ return f"buildGroundBladeGeometry({json_literal(spec)})"
1838
+ if primitive == "lathe":
1839
+ profile = descriptor.get("latheProfile") if isinstance(descriptor.get("latheProfile"), dict) else _DEFAULT_LATHE_PROFILE
1840
+ return f"buildLatheGeometry({json_literal(profile)})"
1841
+ if primitive == "tube":
1842
+ path = descriptor.get("tubePath") if isinstance(descriptor.get("tubePath"), dict) else _DEFAULT_TUBE_PATH
1843
+ return f"buildTubeGeometry({json_literal(path)})"
1844
+ if primitive == "curve-sweep":
1845
+ sweep = descriptor.get("curveSweep") if isinstance(descriptor.get("curveSweep"), dict) else _DEFAULT_CURVE_SWEEP
1846
+ return f"buildCurveSweepGeometry({json_literal(sweep)})"
1847
+ if primitive == "tapered-sweep":
1848
+ tapered = (
1849
+ descriptor.get("taperedSweep")
1850
+ if isinstance(descriptor.get("taperedSweep"), dict)
1851
+ else _DEFAULT_TAPERED_SWEEP
1852
+ )
1853
+ return f"buildTaperedSweepGeometry({json_literal(tapered)})"
1854
+ if primitive == "instanced-cluster":
1855
+ # An instanced cluster's *geometry* is its base shape; the instancing itself is applied
1856
+ # by the repetition-system emitter (THREE.InstancedMesh). Resolve the base primitive from
1857
+ # the descriptor (default box); guard against self-reference so we never recurse.
1858
+ base = resolve_instanced_cluster_base(primitive, descriptor, VALID_PRIMITIVES)
1859
+ return geometry_for(base, component, subdivision_requested, seg)
1860
+ raise GeometryNotImplementedError(primitive)
1861
+
1862
+
1863
+ def decimate_ratio(component: dict[str, Any]) -> float | None:
1864
+ """Read `geometryDescriptor.decimate.targetRatio`, or None when decimation is not asked for.
1865
+
1866
+ Opt-in per component rather than derived from the tessellation tier, because the two
1867
+ solve different halves of the same problem: a tier dials the density of primitives that
1868
+ HAVE segment counts, and decimation is the only lever for geometry that does not -- an
1869
+ implicit surface's density comes from its sampling grid, which is quantised, so the tier
1870
+ can only get near a budget while a ratio can land on it. Running it on every mesh instead
1871
+ would put a quadric collapse on the page-load path for shapes whose density is already
1872
+ exactly what was asked for.
1873
+ """
1874
+ descriptor = component.get("geometryDescriptor")
1875
+ if not isinstance(descriptor, dict):
1876
+ return None
1877
+ decimate = descriptor.get("decimate")
1878
+ if not isinstance(decimate, dict):
1879
+ return None
1880
+ ratio = decimate.get("targetRatio")
1881
+ if isinstance(ratio, bool) or not isinstance(ratio, (int, float)):
1882
+ return None
1883
+ if not 0.0 < float(ratio) < 1.0:
1884
+ return None
1885
+ return float(ratio)
1886
+
1887
+
1888
+ def subdivision_iterations(component: dict[str, Any]) -> int:
1889
+ descriptor = component.get("geometryDescriptor")
1890
+ if not isinstance(descriptor, dict):
1891
+ return 0
1892
+ subdivide = descriptor.get("subdivide")
1893
+ if not isinstance(subdivide, dict):
1894
+ return 0
1895
+ iterations = subdivide.get("iterations")
1896
+ if (
1897
+ not isinstance(iterations, int)
1898
+ or isinstance(iterations, bool)
1899
+ or iterations < 1
1900
+ or iterations > MAX_SUBDIVISION_ITERATIONS
1901
+ ):
1902
+ return 0
1903
+ return iterations
1904
+
1905
+
1906
+ def component_uses_dense_height_maps(component: dict[str, Any]) -> bool:
1907
+ return (
1908
+ component.get("denseMesh") is True
1909
+ or component.get("geometryDensity") == "dense"
1910
+ or component.get("topologyClass") in {"dense", "implicit"}
1911
+ or subdivision_iterations(component) > 0
1912
+ )
1913
+
1914
+
1915
+ BONE_TRACK_DOMAINS = {"character", "hybrid"}
1916
+
1917
+
1918
+ def rig_is_bone_track(spec: dict[str, Any]) -> bool:
1919
+ """PLAN_1.5 §8: route on the EXISTING `objectClass.primaryDomain`, no new routing field.
1920
+
1921
+ `object` stays on the pivot track, which §8 says is "not replaced" and stays the default.
1922
+ So this returns False for it and `emit_rig_hierarchy()` emits nothing whatsoever -- an
1923
+ object spec's generated source must remain byte-identical to its pre-plan output.
1924
+ """
1925
+ object_class = (spec.get("preSpecAssessment") or {}).get("objectClass") or {}
1926
+ if object_class.get("primaryDomain") not in BONE_TRACK_DOMAINS:
1927
+ return False
1928
+ rig = spec.get("rig")
1929
+ return isinstance(rig, dict) and bool(rig.get("bones"))
1930
+
1931
+
1932
+ def emit_rig_hierarchy(spec: dict[str, Any]) -> list[str]:
1933
+ """Emit the bone hierarchy from `spec["rig"]` — PLAN_1.5 WS-C.
1934
+
1935
+ Emits the bones, one shared `THREE.Skeleton`, exactly one vertex-weight helper, and binds every
1936
+ skinned component as a `THREE.SkinnedMesh`. `root.userData.rig.bound` is COMPUTED — it is true
1937
+ only when every skinned mesh actually bound — rather than asserted, so a partial bind reports
1938
+ itself instead of reading as success.
1939
+
1940
+ On the pivot track this emits nothing at all, so an object spec's output is byte-identical to
1941
+ what it was before the rig track existed.
1942
+
1943
+ Two things that are easy to get wrong here:
1944
+
1945
+ - `jointPos` in the spec is **model space** (see `derive_character_rig`'s docstring). A
1946
+ `THREE.Bone`'s position is parent-local, so each bone's offset is its own joint minus its
1947
+ parent's joint; the root keeps its model-space joint unchanged.
1948
+ - Bones are emitted **parents first**. The spec's bone list is sorted by `(has-parent, id)`,
1949
+ so `foot-l` precedes `shin-l` alphabetically — emitting in list order would parent a bone
1950
+ to one that does not exist yet. This walks the tree rather than trusting list order.
1951
+ """
1952
+ if not rig_is_bone_track(spec):
1953
+ return []
1954
+
1955
+ bones = [b for b in spec["rig"]["bones"] if isinstance(b, dict) and b.get("id")]
1956
+ by_id = {b["id"]: b for b in bones}
1957
+
1958
+ ordered: list[dict[str, Any]] = []
1959
+ seen: set[str] = set()
1960
+
1961
+ def visit(bone: dict[str, Any]) -> None:
1962
+ parent = bone.get("parent")
1963
+ if parent and parent in by_id and parent not in seen:
1964
+ visit(by_id[parent])
1965
+ if bone["id"] not in seen:
1966
+ seen.add(bone["id"])
1967
+ ordered.append(bone)
1968
+
1969
+ for bone in bones:
1970
+ visit(bone)
1971
+
1972
+ def bone_var(bone_id: str) -> str:
1973
+ return f"bone_{re.sub(r'[^A-Za-z0-9]', '_', bone_id)}"
1974
+
1975
+ lines = [
1976
+ "",
1977
+ " // PLAN_1.5 WS-C slice 1: bone hierarchy from spec.rig. Model-space joints are",
1978
+ " // converted to parent-local offsets here. Nothing is bound yet (rig.bound === false).",
1979
+ " const bones: Record<string, THREE.Bone> = {};",
1980
+ " const boneOrder: string[] = [];",
1981
+ ]
1982
+ for bone in ordered:
1983
+ bone_id = bone["id"]
1984
+ joint = bone.get("jointPos") or [0.0, 0.0, 0.0]
1985
+ parent = bone.get("parent")
1986
+ var = bone_var(bone_id)
1987
+ if parent and parent in by_id:
1988
+ parent_joint = by_id[parent].get("jointPos") or [0.0, 0.0, 0.0]
1989
+ offset = [float(joint[i]) - float(parent_joint[i]) for i in range(3)]
1990
+ else:
1991
+ offset = [float(joint[i]) for i in range(3)]
1992
+ lines.extend([
1993
+ f" const {var} = new THREE.Bone();",
1994
+ f" {var}.name = {json.dumps(bone_id)};",
1995
+ f" {var}.position.set({vector(offset, [0.0, 0.0, 0.0])});",
1996
+ (f" {bone_var(parent)}.add({var});" if parent and parent in by_id
1997
+ else f" root.add({var});"),
1998
+ f" bones[{json.dumps(bone_id)}] = {var};",
1999
+ f" boneOrder.push({json.dumps(bone_id)});",
2000
+ ])
2001
+ lines.extend([
2002
+ " // The bones are now in REST position. updateMatrixWorld() before constructing the",
2003
+ " // Skeleton is load-bearing: calculateInverses() reads each bone's CURRENT world matrix,",
2004
+ " // and those inverses are what cancel the rest pose during skinning. Constructed before",
2005
+ " // this call it captures identity matrices, the rest pose never cancels, and every",
2006
+ " // vertex is displaced by its bone's offset at rest. Measured, not assumed --",
2007
+ " // scratchpad/bind_experiment.mjs read (0, 3, 0) for a vertex authored at (0, 2, 0).",
2008
+ " root.updateMatrixWorld(true);",
2009
+ " const skeleton = new THREE.Skeleton(boneOrder.map((id) => bones[id]));",
2010
+ " const boneIndexOf = new Map<string, number>(boneOrder.map((id, i) => [id, i]));",
2011
+ ])
2012
+ lines.extend(_rig_weight_function_lines(spec, ordered))
2013
+ lines.extend(_rig_pose_lines(spec, ordered, bone_var))
2014
+ lines.append(" root.userData.rig = { bones, skeleton, boneOrder, boneIndexOf, "
2015
+ "skinAttributes: skinnedMeshNames, bound: skinnedMeshNames.length > 0 "
2016
+ "&& boundCount === skinnedMeshNames.length, "
2017
+ "frustumCulled: false, "
2018
+ "cullingNote: 'skinned meshes set frustumCulled = false; bone motion does not "
2019
+ "update a SkinnedMesh boundingSphere, so a consumer that needs culling must "
2020
+ "recompute bounds per frame' };")
2021
+ return lines
2022
+
2023
+
2024
+ def _rig_pose_lines(
2025
+ spec: dict[str, Any],
2026
+ ordered: list[dict[str, Any]],
2027
+ bone_var: Any,
2028
+ ) -> list[str]:
2029
+ """Move the authored pose from the component pivots onto the BONES.
2030
+
2031
+ `apply_character_pose` writes `component.transform.rotation`, which drives the component's
2032
+ pivot `Group`. Once a body segment is a `SkinnedMesh` its geometry has been baked to model
2033
+ space and reparented to `root`, so the pivot no longer reaches it — the pose has to be
2034
+ re-expressed as bone rotations or it disappears from the render.
2035
+
2036
+ That substitution is exact rather than approximate because a bone's origin IS its
2037
+ component's pivot origin: `derive_character_rig` takes each `jointPos` from the component's
2038
+ proximal end, which is what the spine split in `make_character_component_tree` exists to
2039
+ guarantee, and the bone parent chain mirrors the component parent chain. Same origin, same
2040
+ parent frame, same euler order — so the same euler triple produces the same rotation.
2041
+
2042
+ **Applied after `bind()`, never before.** These rotations are the pose, not the bind pose;
2043
+ setting them before the `Skeleton` is constructed would bake the pose in as rest and nothing
2044
+ would deform.
2045
+ """
2046
+ posed = _posed_bone_rotations(spec, ordered)
2047
+ if not posed:
2048
+ return []
2049
+ lines = [
2050
+ "",
2051
+ " // The authored pose, moved from the pivots onto the bones (see _rig_pose_lines). Set",
2052
+ " // AFTER bind() so that the rest pose -- not this one -- is what the skeleton's inverse",
2053
+ " // bind matrices cancel.",
2054
+ ]
2055
+ for bone_id, _component_id, values in posed:
2056
+ lines.append(f" {bone_var(bone_id)}.rotation.set({vector(values, [0.0, 0.0, 0.0])});")
2057
+ lines.extend([
2058
+ " root.updateMatrixWorld(true);",
2059
+ " skeleton.update();",
2060
+ ])
2061
+ return lines
2062
+
2063
+
2064
+ def _posed_bone_rotations(
2065
+ spec: dict[str, Any],
2066
+ ordered: list[dict[str, Any]],
2067
+ ) -> list[tuple[str, str, list[float]]]:
2068
+ """Every bone whose component carries an authored pose, as `(bone id, component id, euler)`.
2069
+
2070
+ One source for the three places that need it: resting the pivots for the bake, restoring them
2071
+ afterwards, and rotating the bones. Deriving it three times is how the pose ends up applied
2072
+ twice in one of them.
2073
+ """
2074
+ by_component = {c.get("id"): c for c in spec.get("componentTree", []) if isinstance(c, dict)}
2075
+ posed: list[tuple[str, str, list[float]]] = []
2076
+ for bone in ordered:
2077
+ component_id = str(bone.get("component") or bone["id"])
2078
+ rotation = ((by_component.get(component_id) or {}).get("transform") or {}).get("rotation")
2079
+ values = [float(v) for v in (rotation or [0.0, 0.0, 0.0])[:3]]
2080
+ if any(abs(v) > 1e-9 for v in values):
2081
+ posed.append((bone["id"], component_id, values))
2082
+ return posed
2083
+
2084
+
2085
+ def _rig_weight_function_lines(spec: dict[str, Any], ordered: list[dict[str, Any]]) -> list[str]:
2086
+ """Emit the PLAN_1.5 §4 weight function ONCE, plus the per-mesh skin attributes it feeds.
2087
+
2088
+ Ported from `forge/stage5_rig/emit_rig.py`, which measured `max |Σw − 1| = 2.98e-8` on real
2089
+ executed geometry. Ported rather than rewritten on purpose: a second implementation of a
2090
+ weight function is exactly what WS-C's "a grep must find no second weight function"
2091
+ acceptance criterion exists to prevent.
2092
+
2093
+ Two things are deliberate:
2094
+
2095
+ - **The envelope radius is computed in Python**, by `derive_envelope_radius` (PLAN_1.5 §4.3),
2096
+ and emitted as a literal. Doing it here reuses the one implementation instead of
2097
+ transcribing the formula into TypeScript, where it could drift.
2098
+ - **The helper is emitted once and IS called.** Both the showcase tsconfig and the test
2099
+ harness compile with `--noUnusedLocals`, so an emitted-but-uncalled helper is a hard tsc
2100
+ error. WS-C.3 consumes these attributes: each skinned component becomes a
2101
+ `THREE.SkinnedMesh` and binds against the one shared `Skeleton`.
2102
+ """
2103
+ # stage5_rig was deliberately standalone "until WS-C integration" per its own docstring.
2104
+ # This is that integration, so importing its derivation is the intended coupling rather than
2105
+ # transcribing the §4.3 formula into a second place where it could drift.
2106
+ from stage5_rig.rig_spec import derive_envelope_radius # noqa: PLC0415
2107
+
2108
+ by_component = {c.get("id"): c for c in spec.get("componentTree", []) if isinstance(c, dict)}
2109
+ envelope: dict[str, float] = {}
2110
+ for bone in ordered:
2111
+ component = by_component.get(bone.get("component") or bone["id"]) or {}
2112
+ scale = (component.get("transform") or {}).get("scale") or [0.0, 0.0, 0.0]
2113
+ width, depth = float(scale[0]), float(scale[2])
2114
+ if width <= 0 or depth <= 0:
2115
+ width = depth = 0.05
2116
+ envelope[bone["id"]] = round(derive_envelope_radius(width, depth), 6)
2117
+
2118
+ joints = {b["id"]: [float(v) for v in b["jointPos"]] for b in ordered}
2119
+ tips = {b["id"]: [float(v) for v in b["tipPos"]] for b in ordered}
2120
+
2121
+ # The bake below reads `mesh.matrixWorld`, and by this point the pivots already carry the
2122
+ # authored pose -- so baking as-is would freeze the POSE into the geometry while the bones sit
2123
+ # at rest, and the two would disagree by exactly the pose. The pivots are therefore returned to
2124
+ # rest for the duration of the bake and restored afterwards, so that what lands in the vertex
2125
+ # data is the rest pose the skeleton's inverse bind matrices were computed from.
2126
+ posed = _posed_bone_rotations(spec, ordered)
2127
+ if posed:
2128
+ rest_pose_comment = (
2129
+ " // Pivots back to REST for the bake: the geometry that lands in the buffer must be\n"
2130
+ " // the same rest pose the skeleton's inverse bind matrices cancel, not the pose."
2131
+ )
2132
+ rest_pose_lines = [
2133
+ f" nodes[{json.dumps(component_id)}]?.rotation.set(0, 0, 0);"
2134
+ for _bone_id, component_id, _values in posed
2135
+ ]
2136
+ restore_pose_lines = [
2137
+ "",
2138
+ " // Pose restored on the pivots. The skinned meshes no longer hang off them -- they",
2139
+ " // were reparented to `root` -- so this drives only the non-skinned descendants",
2140
+ " // (ear shells, eye cavities), which have no bone of their own and would otherwise",
2141
+ " // stay at rest while the head they sit on turns. The bones get the same rotations",
2142
+ " // applied separately, so nothing is posed twice.",
2143
+ *[
2144
+ f" nodes[{json.dumps(component_id)}]?.rotation.set("
2145
+ f"{vector(values, [0.0, 0.0, 0.0])});"
2146
+ for _bone_id, component_id, values in posed
2147
+ ],
2148
+ " root.updateMatrixWorld(true);",
2149
+ ]
2150
+ else:
2151
+ rest_pose_comment = " // No component carries an authored pose, so there is nothing to rest."
2152
+ rest_pose_lines = []
2153
+ restore_pose_lines = []
2154
+
2155
+ return [
2156
+ "",
2157
+ " // ---- PLAN_1.5 §4 weight function: ONE function over the complete bone set. No",
2158
+ " // mesh-id or vertex-index branching -- only positions, segment endpoints and the",
2159
+ " // envelope radius derived per §4.3. Ported from forge/stage5_rig/emit_rig.py, which",
2160
+ " // measured max |sum(w) - 1| = 2.98e-8 on executed geometry.",
2161
+ f" const BONE_JOINT: Record<string, number[]> = {json.dumps(joints)};",
2162
+ f" const BONE_TIP: Record<string, number[]> = {json.dumps(tips)};",
2163
+ f" const BONE_ENVELOPE: Record<string, number> = {json.dumps(envelope)};",
2164
+ " const _closest = new THREE.Vector3();",
2165
+ " const distanceToSegment = (p: THREE.Vector3, s: number[], e: number[]): number => {",
2166
+ " const ab = [e[0] - s[0], e[1] - s[1], e[2] - s[2]];",
2167
+ " const ap = [p.x - s[0], p.y - s[1], p.z - s[2]];",
2168
+ " const abLenSq = ab[0] * ab[0] + ab[1] * ab[1] + ab[2] * ab[2];",
2169
+ " const t = abLenSq > 1e-12",
2170
+ " ? THREE.MathUtils.clamp((ap[0] * ab[0] + ap[1] * ab[1] + ap[2] * ab[2]) / abLenSq, 0, 1)",
2171
+ " : 0;",
2172
+ " _closest.set(s[0] + ab[0] * t, s[1] + ab[1] * t, s[2] + ab[2] * t);",
2173
+ " return p.distanceTo(_closest);",
2174
+ " };",
2175
+ " const computeVertexWeights = (p: THREE.Vector3) => {",
2176
+ " const scored = boneOrder.map((id) => {",
2177
+ " const d = distanceToSegment(p, BONE_JOINT[id], BONE_TIP[id]);",
2178
+ " const u = d / BONE_ENVELOPE[id];",
2179
+ " const falloff = Math.max(0, 1 - u * u);",
2180
+ " return { id, d, w: falloff * falloff };",
2181
+ " });",
2182
+ " scored.sort((a, b) => b.w - a.w);",
2183
+ " const kept = scored.slice(0, 4);",
2184
+ " const total = kept.reduce((sum, c) => sum + c.w, 0);",
2185
+ " const indices = [0, 0, 0, 0];",
2186
+ " const weights = [0, 0, 0, 0];",
2187
+ " if (total > 0) {",
2188
+ " for (let slot = 0; slot < kept.length; slot++) {",
2189
+ " indices[slot] = boneIndexOf.get(kept[slot].id) ?? 0;",
2190
+ " weights[slot] = kept[slot].w / total;",
2191
+ " }",
2192
+ " return { indices, weights, fallback: false };",
2193
+ " }",
2194
+ " // Mandatory zero-sum fallback (PLAN_1.5 §4 / ADR-8). Without it three.js's own",
2195
+ " // normalizeSkinWeights() rewrites an all-zero vertex to (1,0,0,0) against bone 0",
2196
+ " // regardless of distance, which spikes stray vertices toward the hips. Instead:",
2197
+ " // ignore the envelope and pin weight 1.0 to the absolutely nearest bone.",
2198
+ " let nearest = boneOrder[0];",
2199
+ " let nearestDistance = Infinity;",
2200
+ " for (const id of boneOrder) {",
2201
+ " const d = distanceToSegment(p, BONE_JOINT[id], BONE_TIP[id]);",
2202
+ " if (d < nearestDistance) { nearestDistance = d; nearest = id; }",
2203
+ " }",
2204
+ " indices[0] = boneIndexOf.get(nearest) ?? 0;",
2205
+ " weights[0] = 1;",
2206
+ " return { indices, weights, fallback: true };",
2207
+ " };",
2208
+ "",
2209
+ " // ---- Bake to model space, weight, and bind.",
2210
+ " //",
2211
+ " // The arrangement below was chosen by measurement, not derivation, because the same",
2212
+ " // geometry can be skinned four plausible ways and three of them are wrong. With a",
2213
+ " // vertex authored at model-space (0, 2, 0) fully weighted to a bone at (0, 1, 0) and",
2214
+ " // that bone rotated +90 degrees about X (correct answer: (0, 1, 1)):",
2215
+ " //",
2216
+ " // pivot transform kept, bind identity -> rest pose already wrong, no deformation",
2217
+ " // pivot transform kept, bind matrixWorld -> (0, 1.5, 0.5): HALF the correct swing,",
2218
+ " // because the pivot applies on top of skinning",
2219
+ " // geometry baked, pivot bypassed -> (0, 1, 1): correct",
2220
+ " // no pivot at all -> (0, 1, 1): correct, and identical",
2221
+ " //",
2222
+ " // The last two agreeing is the finding: what matters is that the mesh's own world",
2223
+ " // transform is identity and its geometry lives in the skeleton's space. So each skinned",
2224
+ " // mesh gets its world matrix folded into its vertex data and is reparented to `root`",
2225
+ " // with an identity transform. Meshes are leaves -- components are added to their pivot",
2226
+ " // Group, never to another mesh -- so reparenting one moves nothing else.",
2227
+ rest_pose_comment,
2228
+ *rest_pose_lines,
2229
+ " root.updateMatrixWorld(true);",
2230
+ " const skinnedMeshNames: string[] = [];",
2231
+ " let boundCount = 0;",
2232
+ " for (const boneId of boneOrder) {",
2233
+ " const mesh = meshes[boneId];",
2234
+ " if (!mesh) continue;",
2235
+ " const position = mesh.geometry.getAttribute('position');",
2236
+ " if (!position) continue;",
2237
+ " mesh.updateWorldMatrix(true, false);",
2238
+ " mesh.geometry.applyMatrix4(mesh.matrixWorld);",
2239
+ " root.add(mesh);",
2240
+ " mesh.position.set(0, 0, 0);",
2241
+ " mesh.quaternion.identity();",
2242
+ " mesh.scale.set(1, 1, 1);",
2243
+ " mesh.updateMatrixWorld(true);",
2244
+ " // Vertices are model-space now, which is the space the weight function measures in,",
2245
+ " // so no per-vertex matrix multiply is needed any more.",
2246
+ " const count = position.count;",
2247
+ " const skinIndices = new Uint16Array(count * 4);",
2248
+ " const skinWeights = new Float32Array(count * 4);",
2249
+ " const vertex = new THREE.Vector3();",
2250
+ " for (let v = 0; v < count; v++) {",
2251
+ " vertex.fromBufferAttribute(position, v);",
2252
+ " const { indices, weights } = computeVertexWeights(vertex);",
2253
+ " for (let slot = 0; slot < 4; slot++) {",
2254
+ " skinIndices[v * 4 + slot] = indices[slot];",
2255
+ " skinWeights[v * 4 + slot] = weights[slot];",
2256
+ " }",
2257
+ " }",
2258
+ " mesh.geometry.setAttribute('skinIndex', new THREE.Uint16BufferAttribute(skinIndices, 4));",
2259
+ " mesh.geometry.setAttribute('skinWeight', new THREE.Float32BufferAttribute(skinWeights, 4));",
2260
+ " skinnedMeshNames.push(boneId);",
2261
+ " const skinned = mesh as THREE.SkinnedMesh;",
2262
+ " if (!skinned.isSkinnedMesh) continue;",
2263
+ " // bindMode is left at its default (AttachedBindMode). The bones live under `root`",
2264
+ " // rather than under any one mesh because a single Skeleton is shared by every skinned",
2265
+ " // mesh and cannot be parented under all of them; with root and each mesh at identity",
2266
+ " // the bone world matrices are the same either way.",
2267
+ " skinned.bind(skeleton, new THREE.Matrix4());",
2268
+ " // A SkinnedMesh's boundingSphere is computed from its REST vertex data and is not",
2269
+ " // recomputed when bones move, so a posed limb that swings outside its rest bounds gets",
2270
+ " // culled and vanishes -- worse, it vanishes only from certain camera angles, which",
2271
+ " // reads as a geometry bug rather than a culling one. Disabling the test outright is",
2272
+ " // chosen over recomputing bounds every frame because these are small, always-onscreen",
2273
+ " // character parts where the test saves nothing. Recorded in userData.rig so a consumer",
2274
+ " // that DOES need culling knows it has to supply its own bounds.",
2275
+ " skinned.frustumCulled = false;",
2276
+ " boundCount += 1;",
2277
+ " }",
2278
+ *restore_pose_lines,
2279
+ ]
2280
+
2281
+
2282
+ def generate(spec: dict[str, Any], pass_id: str) -> str:
2283
+ errors, _warnings = validate_spec(spec)
2284
+ if errors:
2285
+ raise ValueError(f"spec validation failed: {'; '.join(errors)}")
2286
+ target = str(spec.get("targetName") or "Procedural Object")
2287
+ type_name = pascal_case(target)
2288
+ function_name = f"create{type_name}Model"
2289
+ # Resolved once per generate() so every primitive in one model agrees on density.
2290
+ seg = segments_for_spec(spec)
2291
+ reconstruction_evidence = {
2292
+ "itemFamily": spec.get("itemFamily"),
2293
+ "subtype": spec.get("subtype"),
2294
+ "componentAdapter": spec.get("componentAdapter"),
2295
+ "route": spec.get("route"),
2296
+ "exactnessTier": spec.get("exactnessTier"),
2297
+ "referenceCamera": spec.get("referenceCamera"),
2298
+ "approximationNotes": spec.get("approximationNotes", []),
2299
+ }
2300
+ materials = {
2301
+ str(material.get("id") or f"material{index}"): material
2302
+ for index, material in enumerate(spec.get("materials", []))
2303
+ if isinstance(material, dict)
2304
+ }
2305
+ all_components = [item for item in spec.get("componentTree", []) if isinstance(item, dict)]
2306
+ components = filter_components_for_pass(spec, all_components, pass_id)
2307
+
2308
+ lines: list[str] = [
2309
+ "import * as THREE from 'three';",
2310
+ "import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment.js';",
2311
+ "import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';",
2312
+ "import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js';",
2313
+ "import { BokehPass } from 'three/examples/jsm/postprocessing/BokehPass.js';",
2314
+ "import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js';",
2315
+ "import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';",
2316
+ "",
2317
+ "export type ProceduralModelOptions = {",
2318
+ " wireframe?: boolean;",
2319
+ " castShadow?: boolean;",
2320
+ " receiveShadow?: boolean;",
2321
+ " textureSize?: number;",
2322
+ " textureAnisotropy?: number;",
2323
+ " qualityPriority?: 'reference-fidelity' | 'balanced';",
2324
+ "};",
2325
+ "",
2326
+ "export type ProceduralModelRuntime = {",
2327
+ " nodes: Record<string, THREE.Object3D>;",
2328
+ " meshes: Record<string, THREE.Mesh>;",
2329
+ " sockets: Record<string, THREE.Object3D>;",
2330
+ " colliders: Record<string, unknown>;",
2331
+ " destructionGroups: Record<string, THREE.Object3D[]>;",
2332
+ "};",
2333
+ "",
2334
+ "type SculptMaterialSpec = Record<string, any>;",
2335
+ "",
2336
+ ]
2337
+
2338
+ # Plan 1.3 Workstream F.5: real geometry for the primitives that previously fell
2339
+ # through to a silent BoxGeometry fallback. Only emit the helper functions a
2340
+ # primitive that's actually used in THIS pass's components needs — TypeScript
2341
+ # projects commonly build with noUnusedLocals, and an always-emitted
2342
+ # buildLatheGeometry/buildTubeGeometry fails that build the moment a spec (or a
2343
+ # pass, since blockout only includes macro components) doesn't use them.
2344
+ def _calls_geometry_for(component: dict[str, Any]) -> bool:
2345
+ # A component whose geometry actually comes from polygonizeSdf() (implicit
2346
+ # SDF) or buildVisualHullGeometry() never calls geometry_for() for its OWN
2347
+ # `primitive` field at all -- that field is descriptive metadata only on
2348
+ # those two paths. Exclude them here so a primitive-specific helper (e.g.
2349
+ # buildWatertightCapsule) isn't emitted-but-unused merely because some OTHER
2350
+ # component happens to share that primitive label while actually building via
2351
+ # SDF/visual-hull -- an always-emitted, never-called helper fails a build with
2352
+ # `--noUnusedLocals` (found via implicit_character_torso_limb.json, whose one
2353
+ # component is `primitive: "capsule"` + `topologyClass: "implicit"`).
2354
+ descriptor = component.get("geometryDescriptor")
2355
+ geometry_descriptor = descriptor if isinstance(descriptor, dict) else {}
2356
+ is_implicit = component.get("topologyClass") == "implicit" and isinstance(geometry_descriptor.get("sdf"), dict)
2357
+ is_visual_hull = isinstance(geometry_descriptor.get("visualHull"), dict)
2358
+ return not is_implicit and not is_visual_hull
2359
+
2360
+ used_primitives = {
2361
+ str(component.get("primitive")) for component in components if _calls_geometry_for(component)
2362
+ }
2363
+ implicit_components = [
2364
+ component
2365
+ for component in components
2366
+ if component.get("topologyClass") == "implicit"
2367
+ and isinstance(component.get("geometryDescriptor"), dict)
2368
+ and isinstance(component["geometryDescriptor"].get("sdf"), dict)
2369
+ ]
2370
+ visual_hull_components = [
2371
+ component
2372
+ for component in components
2373
+ if isinstance(component.get("geometryDescriptor"), dict)
2374
+ and isinstance(component["geometryDescriptor"].get("visualHull"), dict)
2375
+ ]
2376
+ # A component may require that it stay outside another's surface. Resolved here rather than at
2377
+ # each emission site so an unresolvable declaration becomes one visible comment in the output
2378
+ # instead of a clearance that silently never ran.
2379
+ components_by_id = {
2380
+ str(component.get("id")): component
2381
+ for component in components
2382
+ if isinstance(component, dict) and component.get("id")
2383
+ }
2384
+ stand_proud_jobs: list[dict[str, Any]] = []
2385
+ stand_proud_skipped: list[str] = []
2386
+ for component in components:
2387
+ proud = component.get("standProud") if isinstance(component, dict) else None
2388
+ if not isinstance(proud, dict):
2389
+ continue
2390
+ component_id = str(component.get("id"))
2391
+ target_id = str(proud.get("againstComponentId") or "")
2392
+ proud_target = components_by_id.get(target_id)
2393
+ if proud_target is None:
2394
+ stand_proud_skipped.append(
2395
+ f"{component_id}: standProud target {target_id!r} is not in this component tree"
2396
+ )
2397
+ continue
2398
+ # In the target's LOCAL frame -- which is what `toTarget` maps into -- the surface sits
2399
+ # where `geometry.scale` put it, and that scale is baked into the vertices rather than into
2400
+ # any matrix. So the analytic stack has to be scaled by hand to match. Measured on the
2401
+ # fixture: the authored rings span rx 0.12..0.20 while the scaled geometry spans
2402
+ # 0.048..0.080, and an ellipsoid target's unit stack claims 0.5 against an actual 0.2. Left
2403
+ # unscaled, the march pushed hair to two and a half times the skull's real radius.
2404
+ target_transform = proud_target.get("transform")
2405
+ sx, sy, sz = scale_triple(
2406
+ proud_target, target_transform if isinstance(target_transform, dict) else {}
2407
+ )
2408
+ rings = stand_proud_ring_stack(proud_target)
2409
+ # A ring stack is a SEPARATE description of a shape the generator also builds another way,
2410
+ # so the two can disagree and nothing else would notice. The case that occurs: a `lathe` is
2411
+ # a revolve and is therefore circular before `geometry.scale`, so its rings must have
2412
+ # rx == rz and let the dimensions supply the ellipticity. A fixture here authored rx != rz
2413
+ # on a lathe and described a surface 10-33% wider in z than the geometry it stood for.
2414
+ if rings and proud_target.get("primitive") == "lathe":
2415
+ for ring in rings:
2416
+ if abs(ring[1] - ring[2]) > 1e-9:
2417
+ stand_proud_skipped.append(
2418
+ f"{component_id}: standProud target {target_id!r} is a lathe, which is "
2419
+ f"circular before scaling, but its ringStack authors rx {ring[1]} != rz "
2420
+ f"{ring[2]}. The stack does not describe the target's geometry."
2421
+ )
2422
+ rings = None
2423
+ break
2424
+ if rings:
2425
+ rings = [
2426
+ [ring[0] * sy, ring[1] * sx, ring[2] * sz, ring[3] * sz] for ring in rings
2427
+ ]
2428
+ if not rings:
2429
+ stand_proud_skipped.append(
2430
+ f"{component_id}: standProud target {target_id!r} "
2431
+ f"(primitive {proud_target.get('primitive')!r}) exposes no ring stack to stand proud of"
2432
+ )
2433
+ continue
2434
+ clearance = proud.get("clearance")
2435
+ max_push = proud.get("maxPush")
2436
+ if not isinstance(clearance, (int, float)) or not isinstance(max_push, (int, float)):
2437
+ stand_proud_skipped.append(f"{component_id}: standProud needs numeric clearance and maxPush")
2438
+ continue
2439
+ stand_proud_jobs.append({
2440
+ "componentId": component_id,
2441
+ "targetId": target_id,
2442
+ "rings": rings,
2443
+ "clearance": float(clearance),
2444
+ "maxPush": float(max_push),
2445
+ })
2446
+ if stand_proud_jobs:
2447
+ lines.extend(_STAND_PROUD_HELPER_SOURCE.splitlines())
2448
+ lines.append("")
2449
+ if any(root_tip_gradient(component) for component in components):
2450
+ lines.extend(_ROOT_TIP_GRADIENT_HELPER_SOURCE.splitlines())
2451
+ lines.append("")
2452
+ if any(vertex_paint(component) for component in components):
2453
+ lines.extend(_VERTEX_PAINT_HELPER_SOURCE.splitlines())
2454
+ lines.append("")
2455
+
2456
+ has_subdivision = any(subdivision_iterations(component) > 0 for component in components)
2457
+ has_decimation = any(decimate_ratio(component) is not None for component in components)
2458
+ if visual_hull_components:
2459
+ lines.extend(
2460
+ _VISUAL_HULL_HELPER_SOURCE.replace(
2461
+ "__MAX_VISUAL_HULL_TRIANGLES__",
2462
+ str(MAX_VISUAL_HULL_TRIANGLES),
2463
+ ).splitlines()
2464
+ )
2465
+ lines.append("")
2466
+ if implicit_components:
2467
+ lines.extend(_SDF_HELPER_SOURCE.splitlines())
2468
+ lines.append("")
2469
+ if has_decimation:
2470
+ lines.extend(_DECIMATE_HELPER_SOURCE.splitlines())
2471
+ lines.append("")
2472
+ if has_subdivision:
2473
+ lines.extend(
2474
+ _SUBDIVISION_HELPER_SOURCE.replace(
2475
+ "__MAX_SUBDIVISION_QUAD_FACES__",
2476
+ str(MAX_SUBDIVISION_QUAD_FACES),
2477
+ ).replace(
2478
+ "__MAX_SUBDIVISION_ITERATIONS__",
2479
+ str(MAX_SUBDIVISION_ITERATIONS),
2480
+ ).splitlines()
2481
+ )
2482
+ lines.append("")
2483
+ if "capsule" in used_primitives:
2484
+ lines.extend(
2485
+ [
2486
+ "// THREE.CapsuleGeometry duplicates every UV-seam vertex (measured: 194 boundary",
2487
+ "// edges on the default radius/segments below) -- same benign pattern as box/",
2488
+ "// cylinder/sphere/torus, all of which weld cleanly to 0 given a CORRECT weld.",
2489
+ "// (A naive vertex-only mergeVertices() reports 64 'non-manifold' edges here, but",
2490
+ "// that is a counting artifact, not a real defect: it double-counts a handful of",
2491
+ "// near-pole triangles that become degenerate once two of their three corners",
2492
+ "// coincide -- confirmed by replicating subdivideCatmullClark's own degenerate-",
2493
+ "// triangle-aware vertex identity, which finds a perfectly ordinary 2-manifold.)",
2494
+ "// A capsule is the primary shape for skinned limbs/torso (PLAN_1.5), and skinning",
2495
+ "// weight computation is O(vertices x bones), so fewer, guaranteed-simple vertices",
2496
+ "// is worth having regardless -- authored as a deterministic, closed-by-",
2497
+ "// construction mesh instead: shared pole vertices, and",
2498
+ "// the radial index taken `% radialSegments` so the seam is never a duplicate",
2499
+ "// vertex in the first place, rather than something to weld away afterward.",
2500
+ "// Adapted from forge/stage5_rig/emit_rig.py's buildWatertightCapsule (verified",
2501
+ "// there: 0 boundary edges, 0 non-manifold edges, deterministic across repeated",
2502
+ "// runs) -- ported here rather than imported because this factory and the rig",
2503
+ "// emitter are separate generated-output surfaces with no shared runtime module;",
2504
+ "// see forge/tests/test_primitive_watertightness.py for the measured proof, and",
2505
+ "// coordinate with the rig owner before changing either copy independently.",
2506
+ "function buildWatertightCapsule(",
2507
+ " radius: number,",
2508
+ " cylLength: number,",
2509
+ " capSegments: number,",
2510
+ " radialSegments: number,",
2511
+ " heightSegments: number,",
2512
+ "): THREE.BufferGeometry {",
2513
+ " const positions: number[] = [];",
2514
+ " const indices: number[] = [];",
2515
+ " const uvs: number[] = [];",
2516
+ " const halfCyl = cylLength / 2;",
2517
+ " const totalSpan = 2 * (Math.PI / 2 * radius) + Math.max(0, cylLength);",
2518
+ " const vOf = (fromBottom: number) => (totalSpan > 0 ? fromBottom / totalSpan : 0);",
2519
+ "",
2520
+ " const bottomPoleIndex = positions.length / 3;",
2521
+ " positions.push(0, -halfCyl - radius, 0);",
2522
+ " uvs.push(0.5, vOf(0));",
2523
+ "",
2524
+ " const ringStarts: number[] = [];",
2525
+ " const ringV: number[] = [];",
2526
+ " for (let ring = 1; ring <= capSegments; ring += 1) {",
2527
+ " const phi = (Math.PI / 2) * (ring / capSegments);",
2528
+ " const y = -halfCyl - radius * Math.cos(phi);",
2529
+ " const r = radius * Math.sin(phi);",
2530
+ " const start = positions.length / 3;",
2531
+ " ringStarts.push(start);",
2532
+ " ringV.push(vOf(radius * phi));",
2533
+ " for (let radial = 0; radial < radialSegments; radial += 1) {",
2534
+ " const theta = (radial / radialSegments) * Math.PI * 2;",
2535
+ " positions.push(r * Math.cos(theta), y, r * Math.sin(theta));",
2536
+ " uvs.push(radial / radialSegments, vOf(radius * phi));",
2537
+ " }",
2538
+ " }",
2539
+ "",
2540
+ " const cylinderRingStarts: number[] = [];",
2541
+ " if (cylLength > 0) {",
2542
+ " for (let step = 1; step <= heightSegments; step += 1) {",
2543
+ " const y = -halfCyl + (cylLength * step) / heightSegments;",
2544
+ " const start = positions.length / 3;",
2545
+ " cylinderRingStarts.push(start);",
2546
+ " const v = vOf(radius * (Math.PI / 2) + halfCyl + y);",
2547
+ " for (let radial = 0; radial < radialSegments; radial += 1) {",
2548
+ " const theta = (radial / radialSegments) * Math.PI * 2;",
2549
+ " positions.push(radius * Math.cos(theta), y, radius * Math.sin(theta));",
2550
+ " uvs.push(radial / radialSegments, v);",
2551
+ " }",
2552
+ " }",
2553
+ " }",
2554
+ "",
2555
+ " const topRingStarts: number[] = [];",
2556
+ " for (let ring = capSegments - 1; ring >= 1; ring -= 1) {",
2557
+ " const phi = (Math.PI / 2) * (ring / capSegments);",
2558
+ " const y = halfCyl + radius * Math.cos(phi);",
2559
+ " const r = radius * Math.sin(phi);",
2560
+ " const start = positions.length / 3;",
2561
+ " topRingStarts.push(start);",
2562
+ " const v = vOf(radius * (Math.PI / 2) + Math.max(0, cylLength) + radius * (Math.PI / 2 - phi));",
2563
+ " for (let radial = 0; radial < radialSegments; radial += 1) {",
2564
+ " const theta = (radial / radialSegments) * Math.PI * 2;",
2565
+ " positions.push(r * Math.cos(theta), y, r * Math.sin(theta));",
2566
+ " uvs.push(radial / radialSegments, v);",
2567
+ " }",
2568
+ " }",
2569
+ "",
2570
+ " const topPoleIndex = positions.length / 3;",
2571
+ " positions.push(0, halfCyl + radius, 0);",
2572
+ " uvs.push(0.5, vOf(totalSpan));",
2573
+ "",
2574
+ " const firstBottomRing = ringStarts[0];",
2575
+ " for (let radial = 0; radial < radialSegments; radial += 1) {",
2576
+ " const next = (radial + 1) % radialSegments;",
2577
+ " indices.push(bottomPoleIndex, firstBottomRing + radial, firstBottomRing + next);",
2578
+ " }",
2579
+ "",
2580
+ " const allRings = [...ringStarts, ...cylinderRingStarts, ...topRingStarts];",
2581
+ " for (let i = 0; i < allRings.length - 1; i += 1) {",
2582
+ " const a = allRings[i];",
2583
+ " const b = allRings[i + 1];",
2584
+ " for (let radial = 0; radial < radialSegments; radial += 1) {",
2585
+ " const next = (radial + 1) % radialSegments;",
2586
+ " indices.push(a + radial, a + next, b + next);",
2587
+ " indices.push(a + radial, b + next, b + radial);",
2588
+ " }",
2589
+ " }",
2590
+ "",
2591
+ " const lastRing = allRings[allRings.length - 1];",
2592
+ " for (let radial = 0; radial < radialSegments; radial += 1) {",
2593
+ " const next = (radial + 1) % radialSegments;",
2594
+ " indices.push(topPoleIndex, lastRing + next, lastRing + radial);",
2595
+ " }",
2596
+ "",
2597
+ " const geometry = new THREE.BufferGeometry();",
2598
+ " geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));",
2599
+ " geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));",
2600
+ " geometry.setIndex(indices);",
2601
+ " geometry.computeVertexNormals();",
2602
+ " return geometry;",
2603
+ "}",
2604
+ "",
2605
+ ]
2606
+ )
2607
+ if "extrude" in used_primitives:
2608
+ lines.extend(
2609
+ [
2610
+ "// bevelEnabled defaults to true on THREE.ExtrudeGeometry and rounds every",
2611
+ "// corner — sharp/pointed profiles (blades, fork tines, spikes) need",
2612
+ "// bevelEnabled: false plus lineTo()-only path segments near the tip, since a",
2613
+ "// curve command cannot produce a true converging point.",
2614
+ "function buildExtrudeShape(points: [number, number][], holes?: [number, number][][]): THREE.Shape {",
2615
+ " const shape = new THREE.Shape();",
2616
+ " if (points.length > 0) {",
2617
+ " shape.moveTo(points[0][0], points[0][1]);",
2618
+ " for (let i = 1; i < points.length; i += 1) {",
2619
+ " shape.lineTo(points[i][0], points[i][1]);",
2620
+ " }",
2621
+ " }",
2622
+ " // Cutouts (e.g. an oval wire-cutter hole) as THREE.Path added to shape.holes —",
2623
+ " // dep-free boolean subtraction via the tessellator, no CSG library needed.",
2624
+ " for (const loop of holes ?? []) {",
2625
+ " if (loop.length < 3) continue;",
2626
+ " const path = new THREE.Path();",
2627
+ " path.moveTo(loop[0][0], loop[0][1]);",
2628
+ " for (let i = 1; i < loop.length; i += 1) path.lineTo(loop[i][0], loop[i][1]);",
2629
+ " path.closePath();",
2630
+ " shape.holes.push(path);",
2631
+ " }",
2632
+ " return shape;",
2633
+ "}",
2634
+ "",
2635
+ "// Build an N-gon oval loop (for hole authoring from a compact {cx,cy,rx,ry} descriptor).",
2636
+ "function ovalLoop(cx: number, cy: number, rx: number, ry: number, seg = 24): [number, number][] {",
2637
+ " const loop: [number, number][] = [];",
2638
+ " for (let i = 0; i < seg; i += 1) {",
2639
+ " const a = (i / seg) * Math.PI * 2;",
2640
+ " loop.push([cx + Math.cos(a) * rx, cy + Math.sin(a) * ry]);",
2641
+ " }",
2642
+ " return loop;",
2643
+ "}",
2644
+ "",
2645
+ "function buildExtrudeGeometry(profile: { points: [number, number][]; depth: number; holes?: [number, number][][]; ovalHoles?: { cx: number; cy: number; rx: number; ry: number }[] }): THREE.ExtrudeGeometry {",
2646
+ " const holes = [...(profile.holes ?? []), ...((profile.ovalHoles ?? []).map((o) => ovalLoop(o.cx, o.cy, o.rx, o.ry)))];",
2647
+ " const shape = buildExtrudeShape(profile.points, holes);",
2648
+ " return new THREE.ExtrudeGeometry(shape, {",
2649
+ " depth: profile.depth,",
2650
+ " bevelEnabled: false,",
2651
+ " steps: 1,",
2652
+ " });",
2653
+ "}",
2654
+ "",
2655
+ ]
2656
+ )
2657
+ if "ground-blade" in used_primitives:
2658
+ lines.extend(
2659
+ [
2660
+ "// Ground blade: lofts a beveled cross-section along [x, spineY, edgeY] stations.",
2661
+ "// Per station the section is: sharp cutting EDGE (z=0) → PRIMARY BEVEL up to the",
2662
+ "// grind line (±T) → flat/saber body → SWEDGE near the tip (spine grinds to a false",
2663
+ "// edge, z=0) or a squared spine elsewhere. Non-indexed → flat-shaded facets. UVs map",
2664
+ "// the doppler gradient along length (u) and height (v).",
2665
+ "function buildGroundBladeGeometry(spec: { stations: [number, number, number][]; thickness?: number; grindFrac?: number; swedgeFromTipFrac?: number }): THREE.BufferGeometry {",
2666
+ " const st = spec.stations;",
2667
+ " const T = (spec.thickness ?? 0.05) / 2;",
2668
+ " const grindFrac = spec.grindFrac ?? 0.55;",
2669
+ " const swedgeFrac = spec.swedgeFromTipFrac ?? 0.34;",
2670
+ " const xG = st[0][0];",
2671
+ " const xT = st[st.length - 1][0];",
2672
+ " const len = (xT - xG) || 1;",
2673
+ " // Actual blade Y bounds (stations are [x, topY, botY]) — v must span THESE, not a",
2674
+ " // hardcoded ±0.12: a blade positioned off-origin would otherwise clamp v→1 and make",
2675
+ " // every face sample the bright spine-rim row (the white-tip/washed-facet bug).",
2676
+ " let yMin = Infinity, yMax = -Infinity;",
2677
+ " for (const s of st) { yMin = Math.min(yMin, s[2]); yMax = Math.max(yMax, s[1]); }",
2678
+ " const yH = (yMax - yMin) || 1;",
2679
+ " const ring = (s: [number, number, number]): [number, number, number][] => {",
2680
+ " const [x, topY, botY] = s;",
2681
+ " const h = Math.max(1e-4, topY - botY);",
2682
+ " const grindY = botY + grindFrac * h;",
2683
+ " const swedgeY = topY - 0.42 * h;",
2684
+ " const sz = ((xT - x) / len < swedgeFrac) ? 0 : T; // swedge → sharp false edge near tip",
2685
+ " return [",
2686
+ " [x, botY, 0], [x, grindY, T], [x, swedgeY, T], [x, topY, sz],",
2687
+ " [x, topY, -sz], [x, swedgeY, -T], [x, grindY, -T],",
2688
+ " ];",
2689
+ " };",
2690
+ " const pos: number[] = [];",
2691
+ " const tri = (a: number[], b: number[], c: number[]) => { pos.push(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2]); };",
2692
+ " let A = ring(st[0]);",
2693
+ " // guard-end cap (fan) so the base is closed where it meets the guard",
2694
+ " for (let k = 1; k < 6; k++) tri(A[0], A[k], A[k + 1]);",
2695
+ " for (let i = 1; i < st.length; i++) {",
2696
+ " const B = ring(st[i]);",
2697
+ " for (let k = 0; k < 7; k++) {",
2698
+ " const k2 = (k + 1) % 7;",
2699
+ " tri(A[k], A[k2], B[k2]);",
2700
+ " tri(A[k], B[k2], B[k]);",
2701
+ " }",
2702
+ " A = B;",
2703
+ " }",
2704
+ " const g = new THREE.BufferGeometry();",
2705
+ " g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));",
2706
+ " g.computeVertexNormals();",
2707
+ " const uv: number[] = [];",
2708
+ " for (let t = 0; t < pos.length; t += 3) uv.push((pos[t] - xG) / len, (pos[t + 1] - yMin) / yH);",
2709
+ " g.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));",
2710
+ " return g;",
2711
+ "}",
2712
+ "",
2713
+ ]
2714
+ )
2715
+ if "lathe" in used_primitives:
2716
+ lines.extend(
2717
+ [
2718
+ "function buildLatheGeometry(profile: { points: [number, number][]; segments?: number }): THREE.LatheGeometry {",
2719
+ " const points = profile.points.map(([x, y]) => new THREE.Vector2(Math.max(0.0001, x), y));",
2720
+ " return new THREE.LatheGeometry(points, profile.segments ?? 24);",
2721
+ "}",
2722
+ "",
2723
+ ]
2724
+ )
2725
+ if "tube" in used_primitives:
2726
+ lines.extend(
2727
+ [
2728
+ "function buildTubeGeometry(",
2729
+ " path: { points: [number, number, number][]; radius?: number; radialSegments?: number; closed?: boolean },",
2730
+ "): THREE.TubeGeometry {",
2731
+ " const vectors = path.points.map(([x, y, z]) => new THREE.Vector3(x, y, z));",
2732
+ " const curve = new THREE.CatmullRomCurve3(vectors, path.closed ?? false);",
2733
+ " const tubularSegments = Math.max(8, path.points.length * 6);",
2734
+ " return new THREE.TubeGeometry(curve, tubularSegments, path.radius ?? 0.05, path.radialSegments ?? 8, path.closed ?? false);",
2735
+ "}",
2736
+ "",
2737
+ ]
2738
+ )
2739
+ if "tapered-sweep" in used_primitives:
2740
+ lines.extend(
2741
+ [
2742
+ "type TaperedStation = { position: [number, number, number]; rx: number; rz: number; twist?: number };",
2743
+ "",
2744
+ "// Frames come from PARALLEL TRANSPORT, not from a Frenet frame. A Frenet frame is defined by",
2745
+ "// the curve's normal, which flips sign wherever the path has an inflection or straightens out,",
2746
+ "// and every flip twists the surface 180 degrees within one segment. Carrying the previous frame",
2747
+ "// forward and removing only its along-path component keeps the twist continuous. THREE's own",
2748
+ "// extrudePath and TubeGeometry do not expose this, which is why this is hand-built.",
2749
+ "function buildTaperedSweepGeometry(",
2750
+ " sweep: { stations: TaperedStation[]; radialSegments?: number; capEnds?: boolean },",
2751
+ "): THREE.BufferGeometry {",
2752
+ " const stations = sweep.stations;",
2753
+ " if (stations.length < 2) throw new Error('tapered-sweep needs at least two stations');",
2754
+ " const radial = Math.max(3, sweep.radialSegments ?? 10);",
2755
+ " const centres = stations.map((s) => new THREE.Vector3(...s.position));",
2756
+ "",
2757
+ " const tangents = centres.map((_, i) => {",
2758
+ " const prev = centres[Math.max(0, i - 1)];",
2759
+ " const next = centres[Math.min(centres.length - 1, i + 1)];",
2760
+ " const t = next.clone().sub(prev);",
2761
+ " // Coincident neighbours would normalise to NaN and poison every downstream vertex.",
2762
+ " return t.lengthSq() < 1e-12 ? new THREE.Vector3(0, 1, 0) : t.normalize();",
2763
+ " });",
2764
+ "",
2765
+ " // Seed a reference axis that is not parallel to the first tangent, or the first cross",
2766
+ " // product is degenerate and the whole sweep collapses to a line.",
2767
+ " let ref = new THREE.Vector3(0, 0, 1);",
2768
+ " if (Math.abs(tangents[0].dot(ref)) > 0.9) ref = new THREE.Vector3(1, 0, 0);",
2769
+ "",
2770
+ " const normals: THREE.Vector3[] = [];",
2771
+ " const binormals: THREE.Vector3[] = [];",
2772
+ " let carried = ref.clone().sub(tangents[0].clone().multiplyScalar(ref.dot(tangents[0]))).normalize();",
2773
+ " for (let i = 0; i < tangents.length; i += 1) {",
2774
+ " const t = tangents[i];",
2775
+ " // Project the carried frame back onto the plane perpendicular to this tangent.",
2776
+ " const n = carried.clone().sub(t.clone().multiplyScalar(carried.dot(t)));",
2777
+ " if (n.lengthSq() < 1e-12) {",
2778
+ " const fallback = Math.abs(t.y) > 0.9 ? new THREE.Vector3(1, 0, 0) : new THREE.Vector3(0, 1, 0);",
2779
+ " n.copy(fallback.sub(t.clone().multiplyScalar(fallback.dot(t))));",
2780
+ " }",
2781
+ " n.normalize();",
2782
+ " normals.push(n);",
2783
+ " binormals.push(new THREE.Vector3().crossVectors(t, n).normalize());",
2784
+ " carried = n;",
2785
+ " }",
2786
+ "",
2787
+ " const positions: number[] = [];",
2788
+ " const uvs: number[] = [];",
2789
+ " const indices: number[] = [];",
2790
+ " const ringStart: number[] = [];",
2791
+ " const isPoint: boolean[] = [];",
2792
+ "",
2793
+ " for (let i = 0; i < stations.length; i += 1) {",
2794
+ " const st = stations[i];",
2795
+ " const v = i / (stations.length - 1);",
2796
+ " ringStart.push(positions.length / 3);",
2797
+ " // A station whose section has collapsed emits ONE vertex, not a ring of radius zero.",
2798
+ " // A degenerate ring still carries `radial` coincident vertices and `radial` zero-area",
2799
+ " // triangles, so the lock ends in a blunt cap the width of the floating-point noise",
2800
+ " // rather than at a point -- and a hair lock, a horn or a blade tip has to reach a point.",
2801
+ " if (st.rx <= 1e-6 && st.rz <= 1e-6) {",
2802
+ " isPoint.push(true);",
2803
+ " positions.push(centres[i].x, centres[i].y, centres[i].z);",
2804
+ " uvs.push(0.5, v);",
2805
+ " continue;",
2806
+ " }",
2807
+ " isPoint.push(false);",
2808
+ " const twist = ((st.twist ?? 0) * Math.PI) / 180;",
2809
+ " for (let j = 0; j <= radial; j += 1) {",
2810
+ " const theta = (j / radial) * Math.PI * 2 + twist;",
2811
+ " const offset = normals[i].clone().multiplyScalar(Math.cos(theta) * st.rx)",
2812
+ " .add(binormals[i].clone().multiplyScalar(Math.sin(theta) * st.rz));",
2813
+ " const p = centres[i].clone().add(offset);",
2814
+ " positions.push(p.x, p.y, p.z);",
2815
+ " uvs.push(j / radial, v);",
2816
+ " }",
2817
+ " }",
2818
+ "",
2819
+ " for (let i = 0; i < stations.length - 1; i += 1) {",
2820
+ " const a0 = ringStart[i];",
2821
+ " const b0 = ringStart[i + 1];",
2822
+ " if (isPoint[i] && isPoint[i + 1]) continue; // two collapsed stations bound nothing",
2823
+ " for (let j = 0; j < radial; j += 1) {",
2824
+ " // Wound so the face normal points radially OUTWARD.",
2825
+ " //",
2826
+ " // Ring vertices advance from `normal` toward `binormal`, and binormal is",
2827
+ " // tangent x normal, so increasing theta runs counter-clockwise seen from the",
2828
+ " // far end of the segment. Taking the ring-to-ring edge first therefore puts",
2829
+ " // the cross product on the inside. Measured as signed volume on the built",
2830
+ " // mesh: every tapered-sweep came out negative -- a torso at -0.0674 and a",
2831
+ " // tail at -0.0044 against a positive ellipsoid head -- so every sweep this",
2832
+ " // generator has ever emitted rendered its back faces, with normals pointing",
2833
+ " // into the solid and every lighting judgement made on the wrong surface.",
2834
+ " if (isPoint[i]) indices.push(a0, b0 + j + 1, b0 + j);",
2835
+ " else if (isPoint[i + 1]) indices.push(a0 + j, a0 + j + 1, b0);",
2836
+ " else indices.push(a0 + j, a0 + j + 1, b0 + j, a0 + j + 1, b0 + j + 1, b0 + j);",
2837
+ " }",
2838
+ " }",
2839
+ "",
2840
+ " if (sweep.capEnds ?? true) {",
2841
+ " for (const end of [0, stations.length - 1]) {",
2842
+ " if (isPoint[end]) continue; // a point end is already closed",
2843
+ " const centreIndex = positions.length / 3;",
2844
+ " positions.push(centres[end].x, centres[end].y, centres[end].z);",
2845
+ " uvs.push(0.5, end === 0 ? 0 : 1);",
2846
+ " const base = ringStart[end];",
2847
+ " for (let j = 0; j < radial; j += 1) {",
2848
+ " if (end === 0) indices.push(centreIndex, base + j + 1, base + j);",
2849
+ " else indices.push(centreIndex, base + j, base + j + 1);",
2850
+ " }",
2851
+ " }",
2852
+ " }",
2853
+ "",
2854
+ " const geometry = new THREE.BufferGeometry();",
2855
+ " geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));",
2856
+ " geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));",
2857
+ " geometry.setIndex(indices);",
2858
+ " geometry.computeVertexNormals();",
2859
+ " return geometry;",
2860
+ "}",
2861
+ "",
2862
+ ]
2863
+ )
2864
+ if "curve-sweep" in used_primitives:
2865
+ lines.extend(
2866
+ [
2867
+ "// Plan 1.3 F.6 — sweep a thin 2D cross-section along a 3D spine so a curved",
2868
+ "// form (hooked blade, handle) reads correctly from EVERY camera angle, not just",
2869
+ "// the reference angle a flat extrude happens to match. Uses ExtrudeGeometry's",
2870
+ "// native extrudePath; bevelEnabled: false keeps sharp tips (same rule as F.5).",
2871
+ "function buildCurveSweepGeometry(",
2872
+ " sweep: { spine: [number, number, number][]; crossSection: { points: [number, number][] }; closed?: boolean },",
2873
+ "): THREE.ExtrudeGeometry {",
2874
+ " const shape = new THREE.Shape();",
2875
+ " const cs = sweep.crossSection.points;",
2876
+ " if (cs.length > 0) {",
2877
+ " shape.moveTo(cs[0][0], cs[0][1]);",
2878
+ " for (let i = 1; i < cs.length; i += 1) shape.lineTo(cs[i][0], cs[i][1]);",
2879
+ " shape.closePath();",
2880
+ " }",
2881
+ " const spine = sweep.spine.map(([x, y, z]) => new THREE.Vector3(x, y, z));",
2882
+ " const path = new THREE.CatmullRomCurve3(spine, sweep.closed ?? false);",
2883
+ " return new THREE.ExtrudeGeometry(shape, {",
2884
+ " extrudePath: path,",
2885
+ " steps: Math.max(24, spine.length * 8),",
2886
+ " bevelEnabled: false,",
2887
+ " });",
2888
+ "}",
2889
+ "",
2890
+ ]
2891
+ )
2892
+
2893
+ lines.extend(
2894
+ [
2895
+ "function hashString(value: string): number {",
2896
+ " let hash = 2166136261;",
2897
+ " for (let index = 0; index < value.length; index += 1) {",
2898
+ " hash ^= value.charCodeAt(index);",
2899
+ " hash = Math.imul(hash, 16777619);",
2900
+ " }",
2901
+ " return hash >>> 0;",
2902
+ "}",
2903
+ "",
2904
+ "function readLayerNumber(value: unknown, keys: string[], fallback: number): number {",
2905
+ " if (typeof value === 'number') return value;",
2906
+ " if (value && typeof value === 'object') {",
2907
+ " const record = value as Record<string, unknown>;",
2908
+ " for (const key of keys) {",
2909
+ " if (typeof record[key] === 'number') return record[key] as number;",
2910
+ " }",
2911
+ " }",
2912
+ " return fallback;",
2913
+ "}",
2914
+ "",
2915
+ "function hexToRgb(hex: string): [number, number, number] {",
2916
+ " const normalized = /^#[0-9a-f]{3}$/i.test(hex)",
2917
+ " ? '#' + hex.slice(1).split('').map((part) => part + part).join('')",
2918
+ " : hex;",
2919
+ " const value = /^#[0-9a-f]{6}$/i.test(normalized) ? Number.parseInt(normalized.slice(1), 16) : 0x8a7a5f;",
2920
+ " return [clampAlbedoChannel((value >> 16) & 255), clampAlbedoChannel((value >> 8) & 255), clampAlbedoChannel(value & 255)];",
2921
+ "}",
2922
+ "",
2923
+ "function materialPalette(spec: SculptMaterialSpec): string[] {",
2924
+ " const palette = spec.colorVariation?.palette;",
2925
+ " if (Array.isArray(palette) && palette.length > 0) return palette.filter((value) => typeof value === 'string');",
2926
+ " const secondary = spec.albedo?.secondary;",
2927
+ " const colors = [spec.baseColor ?? spec.color ?? spec.albedo?.dominant, ...(Array.isArray(secondary) ? secondary : [])];",
2928
+ " return colors.filter((value): value is string => typeof value === 'string' && value.startsWith('#'));",
2929
+ "}",
2930
+ "",
2931
+ "function clamp01(value: number): number {",
2932
+ " return Math.max(0, Math.min(1, value));",
2933
+ "}",
2934
+ "",
2935
+ "function clampAlbedoChannel(value: number): number {",
2936
+ " return Math.max(30, Math.min(240, Math.round(value)));",
2937
+ "}",
2938
+ "",
2939
+ "function clampPbrF0(value: number): number {",
2940
+ " return Math.max(0.02, Math.min(1, value));",
2941
+ "}",
2942
+ "",
2943
+ "function clampPbrIor(value: number): number {",
2944
+ " return Math.max(1, Math.min(2.5, value));",
2945
+ "}",
2946
+ "",
2947
+ "function clampPbrMetalness(value: number): number {",
2948
+ " return value >= 0.5 ? 1 : 0;",
2949
+ "}",
2950
+ "",
2951
+ "function clampedAlbedoColor(spec: SculptMaterialSpec): THREE.Color {",
2952
+ " const source = typeof spec.baseColor === 'string' ? spec.baseColor : '#8A7A5F';",
2953
+ " // setStyle with an explicit SRGBColorSpace, NOT the numeric constructor.",
2954
+ " //",
2955
+ " // `new THREE.Color(r, g, b)` treats its arguments as LINEAR working-space components,",
2956
+ " // while an authored `baseColor` hex is sRGB. Feeding one to the other skipped the",
2957
+ " // transfer function and lifted every dark albedo: #2e2a28, authored as a near-black",
2958
+ " // vinyl, rendered at roughly sRGB 0.46 — a mid grey. The error is largest exactly where",
2959
+ " // it matters most, because the transfer curve is steepest near black.",
2960
+ " return new THREE.Color().setStyle(source, THREE.SRGBColorSpace);",
2961
+ "}",
2962
+ "",
2963
+ "function smoothCurve(value: number): number {",
2964
+ " return value * value * (3 - 2 * value);",
2965
+ "}",
2966
+ "",
2967
+ "function periodicHash(x: number, y: number, seed: number, periodX: number, periodY: number): number {",
2968
+ " const wrappedX = ((x % periodX) + periodX) % periodX;",
2969
+ " const wrappedY = ((y % periodY) + periodY) % periodY;",
2970
+ " let value = Math.imul(wrappedX + seed * 17, 374761393) ^ Math.imul(wrappedY + seed * 31, 668265263);",
2971
+ " value = Math.imul(value ^ (value >>> 13), 1274126177);",
2972
+ " return ((value ^ (value >>> 16)) >>> 0) / 4294967295;",
2973
+ "}",
2974
+ "",
2975
+ "function periodicValueNoise(u: number, v: number, seed: number, periodX: number, periodY: number): number {",
2976
+ " const x = u * periodX;",
2977
+ " const y = v * periodY;",
2978
+ " const x0 = Math.floor(x);",
2979
+ " const y0 = Math.floor(y);",
2980
+ " const tx = smoothCurve(x - x0);",
2981
+ " const ty = smoothCurve(y - y0);",
2982
+ " const a = periodicHash(x0, y0, seed, periodX, periodY);",
2983
+ " const b = periodicHash(x0 + 1, y0, seed, periodX, periodY);",
2984
+ " const c = periodicHash(x0, y0 + 1, seed, periodX, periodY);",
2985
+ " const d = periodicHash(x0 + 1, y0 + 1, seed, periodX, periodY);",
2986
+ " return THREE.MathUtils.lerp(THREE.MathUtils.lerp(a, b, tx), THREE.MathUtils.lerp(c, d, tx), ty);",
2987
+ "}",
2988
+ "",
2989
+ "type SurfaceBand = {",
2990
+ " frequency: number;",
2991
+ " amplitude: number;",
2992
+ " stretchX: number;",
2993
+ " stretchY: number;",
2994
+ " ridge: boolean;",
2995
+ "};",
2996
+ "",
2997
+ "function surfaceBands(spec: SculptMaterialSpec): SurfaceBand[] {",
2998
+ " const source = Array.isArray(spec.surfaceFrequencyBands) ? spec.surfaceFrequencyBands : [];",
2999
+ " const parsed = source.flatMap((item: unknown) => {",
3000
+ " if (!item || typeof item !== 'object') return [];",
3001
+ " const band = item as Record<string, unknown>;",
3002
+ " const frequency = typeof band.frequency === 'number' ? band.frequency : 0;",
3003
+ " const amplitude = typeof band.amplitude === 'number' ? band.amplitude : 0;",
3004
+ " if (frequency <= 0 || amplitude <= 0) return [];",
3005
+ " const stretch = Array.isArray(band.stretch) ? band.stretch : [1, 1];",
3006
+ " const description = `${String(band.pattern ?? '')} ${String(band.role ?? '')}`.toLowerCase();",
3007
+ " return [{",
3008
+ " frequency,",
3009
+ " amplitude,",
3010
+ " stretchX: typeof stretch[0] === 'number' ? Math.max(0.1, stretch[0]) : 1,",
3011
+ " stretchY: typeof stretch[1] === 'number' ? Math.max(0.1, stretch[1]) : 1,",
3012
+ " ridge: /(ridge|groove|grain|fiber|striated|crack)/.test(description),",
3013
+ " }];",
3014
+ " });",
3015
+ " return parsed.length > 0 ? parsed : [",
3016
+ " { frequency: 2, amplitude: 0.42, stretchX: 1, stretchY: 1, ridge: false },",
3017
+ " { frequency: 12, amplitude: 0.22, stretchX: 1, stretchY: 1, ridge: false },",
3018
+ " { frequency: 56, amplitude: 0.08, stretchX: 1, stretchY: 1, ridge: false },",
3019
+ " ];",
3020
+ "}",
3021
+ "",
3022
+ "function sampleSurface(u: number, v: number, bands: SurfaceBand[], seed: number): number {",
3023
+ " let value = 0;",
3024
+ " let weight = 0;",
3025
+ " for (let index = 0; index < bands.length; index += 1) {",
3026
+ " const band = bands[index];",
3027
+ " const periodX = Math.max(1, Math.round(band.frequency * band.stretchX));",
3028
+ " const periodY = Math.max(1, Math.round(band.frequency * band.stretchY));",
3029
+ " let sample = periodicValueNoise(u, v, seed + index * 1013, periodX, periodY);",
3030
+ " if (band.ridge) sample = 1 - Math.abs(sample * 2 - 1);",
3031
+ " value += sample * band.amplitude;",
3032
+ " weight += band.amplitude;",
3033
+ " }",
3034
+ " return weight > 0 ? clamp01(value / weight) : 0.5;",
3035
+ "}",
3036
+ "",
3037
+ "function mixPalette(colors: [number, number, number][], value: number): [number, number, number] {",
3038
+ " if (colors.length === 1) return colors[0];",
3039
+ " const scaled = clamp01(value) * (colors.length - 1);",
3040
+ " const index = Math.min(colors.length - 2, Math.floor(scaled));",
3041
+ " const mix = scaled - index;",
3042
+ " const a = colors[index];",
3043
+ " const b = colors[index + 1];",
3044
+ " return [",
3045
+ " Math.round(THREE.MathUtils.lerp(a[0], b[0], mix)),",
3046
+ " Math.round(THREE.MathUtils.lerp(a[1], b[1], mix)),",
3047
+ " Math.round(THREE.MathUtils.lerp(a[2], b[2], mix)),",
3048
+ " ];",
3049
+ "}",
3050
+ "",
3051
+ "type ColorGradientStop = { offset: number; color: string };",
3052
+ "type ColorGradientSpec = {",
3053
+ " type: 'linear' | 'radial';",
3054
+ " axis: [number, number];",
3055
+ " stops: ColorGradientStop[];",
3056
+ "};",
3057
+ "",
3058
+ "function parseRgba(value: string): [number, number, number] {",
3059
+ " const match = /rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)/.exec(value);",
3060
+ " if (!match) return [138, 122, 95];",
3061
+ " return [clampAlbedoChannel(Number(match[1])), clampAlbedoChannel(Number(match[2])), clampAlbedoChannel(Number(match[3]))];",
3062
+ "}",
3063
+ "",
3064
+ "// Analytical per-pixel gradient sample. The extraction schema's colorGradient carries",
3065
+ "// exact rgba(...) stop colors (see extract_part_color_recipe.py), so this samples the",
3066
+ "// same trend directly in JS math rather than round-tripping through a Canvas 2D",
3067
+ "// createLinearGradient/createRadialGradient object — same visual result, and it composes",
3068
+ "// directly with the existing noise/height-correlated colorVariation blend below.",
3069
+ "function sampleColorGradient(gradient: ColorGradientSpec, u: number, v: number): [number, number, number] {",
3070
+ " const stops = gradient.stops.length >= 2 ? gradient.stops : [{ offset: 0, color: 'rgba(138,122,95,1)' }, { offset: 1, color: 'rgba(138,122,95,1)' }];",
3071
+ " let t: number;",
3072
+ " if (gradient.type === 'radial') {",
3073
+ " const [cx, cy] = gradient.axis;",
3074
+ " const dx = u - cx;",
3075
+ " const dy = v - cy;",
3076
+ " const maxRadius = Math.max(0.001, Math.hypot(Math.max(cx, 1 - cx), Math.max(cy, 1 - cy)));",
3077
+ " t = clamp01(Math.hypot(dx, dy) / maxRadius);",
3078
+ " } else {",
3079
+ " const [ax, ay] = gradient.axis;",
3080
+ " const projection = (u - 0.5) * ax + (v - 0.5) * ay;",
3081
+ " const maxProjection = 0.5 * (Math.abs(ax) + Math.abs(ay)) || 0.5;",
3082
+ " t = clamp01(projection / maxProjection + 0.5);",
3083
+ " }",
3084
+ " const scaled = t * (stops.length - 1);",
3085
+ " const index = Math.min(stops.length - 2, Math.max(0, Math.floor(scaled)));",
3086
+ " const mix = scaled - index;",
3087
+ " const a = parseRgba(stops[index].color);",
3088
+ " const b = parseRgba(stops[index + 1].color);",
3089
+ " return [",
3090
+ " THREE.MathUtils.lerp(a[0], b[0], mix),",
3091
+ " THREE.MathUtils.lerp(a[1], b[1], mix),",
3092
+ " THREE.MathUtils.lerp(a[2], b[2], mix),",
3093
+ " ];",
3094
+ "}",
3095
+ "",
3096
+ "function writePixel(data: Uint8ClampedArray, offset: number, red: number, green: number, blue: number): void {",
3097
+ " data[offset] = Math.max(0, Math.min(255, Math.round(red)));",
3098
+ " data[offset + 1] = Math.max(0, Math.min(255, Math.round(green)));",
3099
+ " data[offset + 2] = Math.max(0, Math.min(255, Math.round(blue)));",
3100
+ " data[offset + 3] = 255;",
3101
+ "}",
3102
+ "",
3103
+ "function makeCanvas(size: number): HTMLCanvasElement {",
3104
+ " const canvas = document.createElement('canvas');",
3105
+ " canvas.width = size;",
3106
+ " canvas.height = size;",
3107
+ " return canvas;",
3108
+ "}",
3109
+ "",
3110
+ "function createMapTexture(",
3111
+ " canvas: HTMLCanvasElement,",
3112
+ " colorSpace: THREE.ColorSpace,",
3113
+ " spec: SculptMaterialSpec,",
3114
+ " options: ProceduralModelOptions,",
3115
+ "): THREE.CanvasTexture {",
3116
+ " const texture = new THREE.CanvasTexture(canvas);",
3117
+ " const projection = spec.textureProjection && typeof spec.textureProjection === 'object' ? spec.textureProjection : {};",
3118
+ " const repeat = Array.isArray(projection.repeat) ? projection.repeat : [2, 2];",
3119
+ " texture.colorSpace = colorSpace;",
3120
+ " texture.wrapS = THREE.RepeatWrapping;",
3121
+ " texture.wrapT = THREE.RepeatWrapping;",
3122
+ " texture.repeat.set(",
3123
+ " typeof repeat[0] === 'number' ? repeat[0] : 2,",
3124
+ " typeof repeat[1] === 'number' ? repeat[1] : 2,",
3125
+ " );",
3126
+ " texture.anisotropy = Math.max(1, Math.round(options.textureAnisotropy ?? projection.anisotropy ?? 8));",
3127
+ " texture.needsUpdate = true;",
3128
+ " return texture;",
3129
+ "}",
3130
+ "",
3131
+ "type ProceduralTextureSet = {",
3132
+ " albedo: THREE.Texture;",
3133
+ " roughness: THREE.Texture;",
3134
+ " height: THREE.Texture;",
3135
+ " normal: THREE.Texture;",
3136
+ " ao: THREE.Texture;",
3137
+ " source: 'reference-pixel-extraction' | 'procedural';",
3138
+ "};",
3139
+ "",
3140
+ "function referenceMapUrl(spec: SculptMaterialSpec, channel: string): string | null {",
3141
+ " const reference = spec.referencePbr;",
3142
+ " if (!reference || typeof reference !== 'object') return null;",
3143
+ " if (reference.usable === false) return null;",
3144
+ " const confidence = typeof reference.confidence === 'number'",
3145
+ " ? reference.confidence",
3146
+ " : (typeof reference.estimatedFidelity === 'number' ? reference.estimatedFidelity : 0);",
3147
+ " const threshold = typeof reference.targetThreshold === 'number' ? reference.targetThreshold : 0.7;",
3148
+ " if (confidence < threshold) return null;",
3149
+ " const maps = reference.maps;",
3150
+ " if (!maps || typeof maps !== 'object') return null;",
3151
+ " const map = (maps as Record<string, unknown>)[channel];",
3152
+ " if (!map || typeof map !== 'object') return null;",
3153
+ " const record = map as Record<string, unknown>;",
3154
+ " const url = typeof record.url === 'string' && record.url.trim() ? record.url : record.path;",
3155
+ " return typeof url === 'string' && url.trim() ? url : null;",
3156
+ "}",
3157
+ "",
3158
+ "function createLoadedMapTexture(",
3159
+ " url: string,",
3160
+ " colorSpace: THREE.ColorSpace,",
3161
+ " spec: SculptMaterialSpec,",
3162
+ " options: ProceduralModelOptions,",
3163
+ "): THREE.Texture {",
3164
+ " const texture = new THREE.TextureLoader().load(url);",
3165
+ " const projection = spec.textureProjection && typeof spec.textureProjection === 'object' ? spec.textureProjection : {};",
3166
+ " const repeat = Array.isArray(projection.repeat) ? projection.repeat : [1, 1];",
3167
+ " texture.colorSpace = colorSpace;",
3168
+ " texture.wrapS = THREE.RepeatWrapping;",
3169
+ " texture.wrapT = THREE.RepeatWrapping;",
3170
+ " texture.repeat.set(",
3171
+ " typeof repeat[0] === 'number' ? repeat[0] : 1,",
3172
+ " typeof repeat[1] === 'number' ? repeat[1] : 1,",
3173
+ " );",
3174
+ " texture.anisotropy = Math.max(1, Math.round(options.textureAnisotropy ?? projection.anisotropy ?? 8));",
3175
+ " texture.needsUpdate = true;",
3176
+ " return texture;",
3177
+ "}",
3178
+ "",
3179
+ "function makeReferenceTextureSet(spec: SculptMaterialSpec, options: ProceduralModelOptions): ProceduralTextureSet | null {",
3180
+ " const albedo = referenceMapUrl(spec, 'albedo');",
3181
+ " const roughness = referenceMapUrl(spec, 'roughness');",
3182
+ " const height = referenceMapUrl(spec, 'height');",
3183
+ " const normal = referenceMapUrl(spec, 'normal');",
3184
+ " const ao = referenceMapUrl(spec, 'ao');",
3185
+ " if (!albedo || !roughness || !height || !normal || !ao) return null;",
3186
+ " return {",
3187
+ " albedo: createLoadedMapTexture(albedo, THREE.SRGBColorSpace, spec, options),",
3188
+ " roughness: createLoadedMapTexture(roughness, THREE.NoColorSpace, spec, options),",
3189
+ " height: createLoadedMapTexture(height, THREE.NoColorSpace, spec, options),",
3190
+ " normal: createLoadedMapTexture(normal, THREE.NoColorSpace, spec, options),",
3191
+ " ao: createLoadedMapTexture(ao, THREE.NoColorSpace, spec, options),",
3192
+ " source: 'reference-pixel-extraction',",
3193
+ " };",
3194
+ "}",
3195
+ "",
3196
+ "function makeProceduralTextureSet(",
3197
+ " id: string,",
3198
+ " spec: SculptMaterialSpec,",
3199
+ " options: ProceduralModelOptions,",
3200
+ "): ProceduralTextureSet | null {",
3201
+ " if (typeof document === 'undefined') return null;",
3202
+ " const qualityFirst = (options.qualityPriority ?? 'reference-fidelity') === 'reference-fidelity';",
3203
+ " const requested = options.textureSize ?? spec.textureResolution;",
3204
+ " const requestedSize = typeof requested === 'number' && Number.isFinite(requested)",
3205
+ " ? requested",
3206
+ " : (qualityFirst ? 1024 : 512);",
3207
+ " const size = Math.max(256, Math.min(2048, 2 ** Math.round(Math.log2(requestedSize))));",
3208
+ " const canvases = {",
3209
+ " albedo: makeCanvas(size),",
3210
+ " roughness: makeCanvas(size),",
3211
+ " height: makeCanvas(size),",
3212
+ " normal: makeCanvas(size),",
3213
+ " ao: makeCanvas(size),",
3214
+ " };",
3215
+ " const contexts = {",
3216
+ " albedo: canvases.albedo.getContext('2d'),",
3217
+ " roughness: canvases.roughness.getContext('2d'),",
3218
+ " height: canvases.height.getContext('2d'),",
3219
+ " normal: canvases.normal.getContext('2d'),",
3220
+ " ao: canvases.ao.getContext('2d'),",
3221
+ " };",
3222
+ " if (!contexts.albedo || !contexts.roughness || !contexts.height || !contexts.normal || !contexts.ao) return null;",
3223
+ " const images = {",
3224
+ " albedo: contexts.albedo.createImageData(size, size),",
3225
+ " roughness: contexts.roughness.createImageData(size, size),",
3226
+ " height: contexts.height.createImageData(size, size),",
3227
+ " normal: contexts.normal.createImageData(size, size),",
3228
+ " ao: contexts.ao.createImageData(size, size),",
3229
+ " };",
3230
+ " const seed = hashString(id);",
3231
+ " const bands = surfaceBands(spec);",
3232
+ " const heightField = new Float32Array(size * size);",
3233
+ " const roughnessField = new Float32Array(size * size);",
3234
+ " const palette = materialPalette(spec);",
3235
+ " const fallback = typeof spec.baseColor === 'string' ? spec.baseColor : '#8A7A5F';",
3236
+ " const colors = (palette.length >= 2 ? palette : [fallback, '#6E614B', '#A08F70']).map(hexToRgb);",
3237
+ " const baseRoughness = clamp01(readLayerNumber(spec.roughness, ['base'], 0.76));",
3238
+ " const roughnessVariation = clamp01(readLayerNumber(spec.roughness, ['variation'], 0.18));",
3239
+ " const colorAmplitude = clamp01(readLayerNumber(spec.colorVariation, ['amplitude', 'variation'], 0.18));",
3240
+ " const heightCorrelation = clamp01(readLayerNumber(spec.colorVariation, ['heightCorrelation'], 0.3));",
3241
+ " const colorGradient: ColorGradientSpec | undefined = spec.colorGradient;",
3242
+ " for (let y = 0; y < size; y += 1) {",
3243
+ " const v = y / size;",
3244
+ " for (let x = 0; x < size; x += 1) {",
3245
+ " const u = x / size;",
3246
+ " const index = y * size + x;",
3247
+ " const height = sampleSurface(u, v, bands, seed + 101);",
3248
+ " const roughNoise = sampleSurface(u, v, bands, seed + 7001);",
3249
+ " const colorNoise = sampleSurface(u, v, bands, seed + 15013);",
3250
+ " heightField[index] = height;",
3251
+ " roughnessField[index] = clamp01(baseRoughness + (roughNoise - 0.5) * roughnessVariation * 2);",
3252
+ " let color: [number, number, number];",
3253
+ " if (colorGradient) {",
3254
+ " // Evidence-derived spatial gradient (Plan 1.3 Workstream C) takes priority",
3255
+ " // over the noise-based palette blend below — it is a measured trend, not a guess.",
3256
+ " color = sampleColorGradient(colorGradient, u, v);",
3257
+ " } else {",
3258
+ " const paletteValue = clamp01(",
3259
+ " 0.5 + (colorNoise - 0.5) * colorAmplitude * 2 + (height - 0.5) * heightCorrelation",
3260
+ " );",
3261
+ " color = mixPalette(colors, paletteValue);",
3262
+ " }",
3263
+ " writePixel(images.albedo.data, index * 4, color[0], color[1], color[2]);",
3264
+ " }",
3265
+ " }",
3266
+ " const normalStrength = Math.max(0.05, readLayerNumber(spec.normal, ['strength', 'amplitude'], 0.35));",
3267
+ " const aoStrength = clamp01(readLayerNumber(spec.ambientOcclusion, ['cavityStrength', 'strength'], 0.35));",
3268
+ " for (let y = 0; y < size; y += 1) {",
3269
+ " const up = ((y - 1 + size) % size) * size;",
3270
+ " const down = ((y + 1) % size) * size;",
3271
+ " for (let x = 0; x < size; x += 1) {",
3272
+ " const left = (x - 1 + size) % size;",
3273
+ " const right = (x + 1) % size;",
3274
+ " const index = y * size + x;",
3275
+ " const center = heightField[index];",
3276
+ " const dx = (heightField[y * size + right] - heightField[y * size + left]) * normalStrength * 6;",
3277
+ " const dy = (heightField[down + x] - heightField[up + x]) * normalStrength * 6;",
3278
+ " const inverseLength = 1 / Math.sqrt(dx * dx + dy * dy + 1);",
3279
+ " const normalX = -dx * inverseLength;",
3280
+ " const normalY = -dy * inverseLength;",
3281
+ " const normalZ = inverseLength;",
3282
+ " const neighborAverage = (",
3283
+ " heightField[y * size + left] + heightField[y * size + right]",
3284
+ " + heightField[up + x] + heightField[down + x]",
3285
+ " ) * 0.25;",
3286
+ " const cavity = Math.max(0, neighborAverage - center);",
3287
+ " const ao = clamp01(1 - aoStrength * (cavity * 12 + (1 - center) * 0.16));",
3288
+ " const offset = index * 4;",
3289
+ " const heightByte = center * 255;",
3290
+ " const roughnessByte = roughnessField[index] * 255;",
3291
+ " writePixel(images.height.data, offset, heightByte, heightByte, heightByte);",
3292
+ " writePixel(images.roughness.data, offset, roughnessByte, roughnessByte, roughnessByte);",
3293
+ " writePixel(",
3294
+ " images.normal.data, offset,",
3295
+ " (normalX * 0.5 + 0.5) * 255,",
3296
+ " (normalY * 0.5 + 0.5) * 255,",
3297
+ " (normalZ * 0.5 + 0.5) * 255,",
3298
+ " );",
3299
+ " writePixel(images.ao.data, offset, ao * 255, ao * 255, ao * 255);",
3300
+ " }",
3301
+ " }",
3302
+ " contexts.albedo.putImageData(images.albedo, 0, 0);",
3303
+ " contexts.roughness.putImageData(images.roughness, 0, 0);",
3304
+ " contexts.height.putImageData(images.height, 0, 0);",
3305
+ " contexts.normal.putImageData(images.normal, 0, 0);",
3306
+ " contexts.ao.putImageData(images.ao, 0, 0);",
3307
+ " return {",
3308
+ " albedo: createMapTexture(canvases.albedo, THREE.SRGBColorSpace, spec, options),",
3309
+ " roughness: createMapTexture(canvases.roughness, THREE.NoColorSpace, spec, options),",
3310
+ " height: createMapTexture(canvases.height, THREE.NoColorSpace, spec, options),",
3311
+ " normal: createMapTexture(canvases.normal, THREE.NoColorSpace, spec, options),",
3312
+ " ao: createMapTexture(canvases.ao, THREE.NoColorSpace, spec, options),",
3313
+ " source: 'procedural',",
3314
+ " };",
3315
+ "}",
3316
+ "",
3317
+ "function createSculptMaterial(id: string, spec: SculptMaterialSpec, options: ProceduralModelOptions, denseComponent = false): THREE.MeshPhysicalMaterial {",
3318
+ " // A material that declares -- with evidence -- that its subject carries no texture",
3319
+ " // detail gets NO texture set. Synthesising one anyway is not a harmless default: the",
3320
+ " // branch below then forces color to white and roughness to 1 and reads both from the",
3321
+ " // generated maps, so the authored albedo and the reference-derived roughness are both",
3322
+ " // discarded, and the model gains mottling the reference does not have. Measured on the",
3323
+ " // tuxedo cat, whose black fur rendered as speckled grey-and-white from a palette that",
3324
+ " // only ever described two flat regions.",
3325
+ " const textureless = (spec.textureless as { declared?: boolean } | undefined)?.declared === true;",
3326
+ " const textures = textureless",
3327
+ " ? null",
3328
+ " : makeReferenceTextureSet(spec, options) ?? makeProceduralTextureSet(id, spec, options);",
3329
+ " const material = new THREE.MeshPhysicalMaterial({",
3330
+ " color: textures ? 0xffffff : clampedAlbedoColor(spec),",
3331
+ " roughness: textures ? 1 : clamp01(readLayerNumber(spec.roughness, ['base'], 0.76)),",
3332
+ " metalness: clampPbrMetalness(readLayerNumber(spec.metalness, ['base'], 0.0)),",
3333
+ " clearcoat: clamp01(readLayerNumber(spec.clearcoat, ['base', 'amount'], 0)),",
3334
+ " clearcoatRoughness: clamp01(readLayerNumber(spec.clearcoatRoughness, ['base'], 0.25)),",
3335
+ " transmission: clamp01(readLayerNumber(spec.transmission, ['base', 'amount'], 0)),",
3336
+ " ior: clampPbrIor(readLayerNumber(spec.ior, ['base', 'value'], 1.5)),",
3337
+ " thickness: Math.max(0, readLayerNumber(spec.thickness, ['base', 'amount'], 0)),",
3338
+ " attenuationDistance: Math.max(0.001, readLayerNumber(spec.attenuationDistance, ['base', 'value'], Infinity)),",
3339
+ " attenuationColor: new THREE.Color(typeof spec.attenuationColor === 'string' ? spec.attenuationColor : '#ffffff'),",
3340
+ " sheen: clamp01(readLayerNumber(spec.sheen, ['base', 'amount'], 0)),",
3341
+ " sheenColor: new THREE.Color(typeof spec.sheenColor === 'string' ? spec.sheenColor : '#ffffff'),",
3342
+ " sheenRoughness: clamp01(readLayerNumber(spec.sheenRoughness, ['base'], 1.0)),",
3343
+ " iridescence: clamp01(readLayerNumber(spec.iridescence, ['base', 'amount'], 0)),",
3344
+ " iridescenceIOR: clampPbrIor(readLayerNumber(spec.iridescenceIOR, ['base', 'value'], 1.3)),",
3345
+ " anisotropy: clamp01(readLayerNumber(spec.anisotropy, ['base', 'amount'], 0)),",
3346
+ " anisotropyRotation: readLayerNumber(spec.anisotropy, ['rotation'], 0),",
3347
+ " specularIntensity: clampPbrF0(readLayerNumber(spec.specularF0 ?? spec.f0 ?? spec.specularIntensity, ['base', 'value'], 1.0)),",
3348
+ " specularColor: new THREE.Color(typeof spec.specularColor === 'string' ? spec.specularColor : '#ffffff'),",
3349
+ " emissive: new THREE.Color(typeof spec.emissive === 'string' ? spec.emissive : '#000000'),",
3350
+ " emissiveIntensity: Math.max(0, readLayerNumber(spec.emissiveIntensity, ['base'], 1.0)),",
3351
+ " opacity: clamp01(readLayerNumber(spec.opacity, ['base'], 1)),",
3352
+ " transparent: readLayerNumber(spec.transmission, ['base', 'amount'], 0) > 0 || readLayerNumber(spec.opacity, ['base'], 1) < 1,",
3353
+ " alphaTest: Math.max(0, readLayerNumber(spec.alpha, ['cutoff', 'alphaTest'], 0)),",
3354
+ " wireframe: options.wireframe ?? false,",
3355
+ " side: spec.doubleSided === true ? THREE.DoubleSide : THREE.FrontSide,",
3356
+ # Faceted shading is a look, not an optimisation: three.js implements it by giving every
3357
+ # face its own normals, which needs unshared vertices, so the geometry has to be
3358
+ # non-indexed and the vertex count triples (3 per face). It is opt-in per material for
3359
+ # that reason -- turning it on globally would silently spend the budget the
3360
+ # `performanceBudget.targetTriangles` tier just bought back.
3361
+ " flatShading: spec.flatShading === true,",
3362
+ " });",
3363
+ " if (textures) {",
3364
+ " material.map = textures.albedo;",
3365
+ " material.roughnessMap = textures.roughness;",
3366
+ " material.normalMap = textures.normal;",
3367
+ " material.normalScale.setScalar(Math.max(0.05, readLayerNumber(spec.normal, ['strength', 'amplitude'], 0.35)));",
3368
+ " material.aoMap = textures.ao;",
3369
+ " material.aoMap.channel = 0;",
3370
+ " material.aoMapIntensity = readLayerNumber(spec.ambientOcclusion, ['cavityStrength', 'strength'], 0.35);",
3371
+ " const denseMesh = denseComponent || spec.denseMesh === true || spec.geometryDensity === 'dense' || spec.topologyClass === 'dense';",
3372
+ " const bumpScale = Math.max(0, readLayerNumber(spec.bump, ['amplitude', 'strength'], 0));",
3373
+ " const effectiveBumpScale = denseMesh ? Math.max(0.05, bumpScale) : bumpScale;",
3374
+ " if (effectiveBumpScale > 0) {",
3375
+ " material.bumpMap = textures.height;",
3376
+ " material.bumpScale = effectiveBumpScale;",
3377
+ " }",
3378
+ " const displacementScale = Math.max(0, readLayerNumber(spec.displacement, ['amplitude', 'strength'], 0));",
3379
+ " const effectiveDisplacementScale = denseMesh ? Math.max(0.005, displacementScale) : displacementScale;",
3380
+ " if (effectiveDisplacementScale > 0) {",
3381
+ " material.displacementMap = textures.height;",
3382
+ " material.displacementScale = effectiveDisplacementScale;",
3383
+ " material.displacementBias = -effectiveDisplacementScale * 0.5;",
3384
+ " }",
3385
+ " }",
3386
+ " material.envMapIntensity = readLayerNumber(spec, ['envMapIntensity'], 0.8);",
3387
+ " material.userData.sculptMaterial = spec;",
3388
+ " material.userData.proceduralMapsIndependent = true;",
3389
+ " material.userData.pbrConstraints = { albedoRange: [30, 240], binaryMetalness: true, f0Range: [0.02, 1], iorRange: [1, 2.5] };",
3390
+ " material.userData.pbrTextureSource = textures?.source ?? 'flat-fallback';",
3391
+ " material.userData.referencePbr = spec.referencePbr ?? null;",
3392
+ " material.userData.referenceMaterialId = spec.referenceMaterialId ?? spec.materialReference?.profileId ?? null;",
3393
+ " material.userData.materialEvidence = spec.materialEvidence ?? null;",
3394
+ " material.userData.validationViews = spec.materialReference?.validationViews ?? [];",
3395
+ " material.needsUpdate = true;",
3396
+ " return material;",
3397
+ "}",
3398
+ "",
3399
+ "type AttachmentEndpoint = {",
3400
+ " start: THREE.Vector3;",
3401
+ " midpoint: THREE.Vector3;",
3402
+ " quaternion: THREE.Quaternion;",
3403
+ " length: number;",
3404
+ " baseRadius: number;",
3405
+ " endRadius: number;",
3406
+ "};",
3407
+ "",
3408
+ "function readVector3(value: unknown, fallback: [number, number, number]): THREE.Vector3 {",
3409
+ " if (Array.isArray(value) && value.length === 3 && value.every((item) => typeof item === 'number')) {",
3410
+ " return new THREE.Vector3(value[0], value[1], value[2]);",
3411
+ " }",
3412
+ " return new THREE.Vector3(fallback[0], fallback[1], fallback[2]);",
3413
+ "}",
3414
+ "",
3415
+ "function readNumber(value: unknown, fallback: number): number {",
3416
+ " return typeof value === 'number' && Number.isFinite(value) ? value : fallback;",
3417
+ "}",
3418
+ "",
3419
+ "function makeAttachmentEndpoint(attachment: unknown): AttachmentEndpoint | null {",
3420
+ " if (!attachment || typeof attachment !== 'object') return null;",
3421
+ " const record = attachment as Record<string, unknown>;",
3422
+ " const start = readVector3(record.localStart, [0, 0, 0]);",
3423
+ " const end = readVector3(record.localEnd, [0, 1, 0]);",
3424
+ " const delta = end.clone().sub(start);",
3425
+ " const length = delta.length();",
3426
+ " if (length <= 0.0001) return null;",
3427
+ " const direction = delta.clone().normalize();",
3428
+ " const quaternion = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction);",
3429
+ " const baseRadius = Math.max(0.005, readNumber(record.baseRadius, 0.06));",
3430
+ " const endRadius = Math.max(0.003, readNumber(record.endRadius, baseRadius * 0.55));",
3431
+ " return {",
3432
+ " start,",
3433
+ " midpoint: delta.multiplyScalar(0.5),",
3434
+ " quaternion,",
3435
+ " length,",
3436
+ " baseRadius,",
3437
+ " endRadius,",
3438
+ " };",
3439
+ "}",
3440
+ "",
3441
+ f"// Generated from ObjectSculptSpec target: {target}",
3442
+ f"// Sculpt build pass: {pass_id}",
3443
+ "// This factory is intentionally pass-gated. Finish browser screenshot review before unlocking deeper passes.",
3444
+ f"export function {function_name}(options: ProceduralModelOptions = {{}}): THREE.Group {{",
3445
+ " const root = new THREE.Group();",
3446
+ f" root.name = {json.dumps(target)};",
3447
+ f" root.userData.reconstructionEvidence = {json_literal(reconstruction_evidence)};",
3448
+ f" root.userData.materialPipeline = {json_literal(spec.get('materialPipeline', {}))};",
3449
+ f" root.userData.materialReferenceRegistry = {json_literal(spec.get('materialReference', spec.get('materialPipeline', {}).get('registry') if isinstance(spec.get('materialPipeline'), dict) else None))};",
3450
+ "",
3451
+ " const materialMap: Record<string, THREE.Material> = {};",
3452
+ ]
3453
+ )
3454
+ for material_id, material in materials.items():
3455
+ lines.extend(
3456
+ [
3457
+ f" materialMap[{json.dumps(material_id)}] = createSculptMaterial(",
3458
+ f" {json.dumps(material_id)},",
3459
+ f" {json_literal(material)},",
3460
+ " options",
3461
+ " );",
3462
+ ]
3463
+ )
3464
+ lines.extend(
3465
+ [
3466
+ "",
3467
+ " const nodes: Record<string, THREE.Object3D> = { root };",
3468
+ " const meshes: Record<string, THREE.Mesh> = {};",
3469
+ " const sockets: Record<string, THREE.Object3D> = {};",
3470
+ " const colliders: Record<string, unknown> = {};",
3471
+ " const destructionGroups: Record<string, THREE.Object3D[]> = {};",
3472
+ ]
3473
+ )
3474
+
3475
+ # Components that get a bone need to be SkinnedMesh from the moment they are constructed --
3476
+ # a plain THREE.Mesh cannot be promoted to one after the fact. On the pivot track this set is
3477
+ # empty, so every component stays a THREE.Mesh and the emitted output is unchanged.
3478
+ skinned_ids = (
3479
+ {str(b.get("component") or b.get("id"))
3480
+ for b in spec["rig"]["bones"] if isinstance(b, dict) and b.get("id")}
3481
+ if rig_is_bone_track(spec) else set()
3482
+ )
3483
+
3484
+ for index, component in enumerate(components):
3485
+ component_id = str(component.get("id") or f"component-{index}")
3486
+ component_var = local_var("mesh", component_id, index)
3487
+ node_var = local_var("node", component_id, index)
3488
+ primitive = str(component.get("primitive") or "box")
3489
+ if primitive not in VALID_PRIMITIVES:
3490
+ primitive = "box"
3491
+ transform = component.get("transform", {}) if isinstance(component.get("transform"), dict) else {}
3492
+ action_profile = component.get("actionProfile") if isinstance(component.get("actionProfile"), dict) else {}
3493
+ sockets_spec = action_profile.get("sockets", []) if isinstance(action_profile.get("sockets"), list) else []
3494
+ destruction = action_profile.get("destruction") if isinstance(action_profile.get("destruction"), dict) else {}
3495
+ fracture_group = destruction.get("fractureGroup") if isinstance(destruction, dict) else None
3496
+ attachment = component.get("attachment") if isinstance(component.get("attachment"), dict) else None
3497
+ attachment_var = local_var("attachment", component_id, index)
3498
+ endpoint_var = local_var("endpoint", component_id, index)
3499
+ material_id = str(component.get("material") or next(iter(materials.keys()), "base"))
3500
+ component_material = materials.get(material_id)
3501
+ material_expression = (
3502
+ f"createSculptMaterial({json.dumps(material_id)}, {json_literal(component_material)}, options, true)"
3503
+ if component_uses_dense_height_maps(component) and component_material is not None
3504
+ else f"materialMap[{json.dumps(material_id)}] ?? new THREE.MeshStandardMaterial({{ color: 0x888888 }})"
3505
+ )
3506
+ parent = component.get("parent") or "root"
3507
+ name = str(component.get("name") or component_id)
3508
+ descriptor = component.get("geometryDescriptor")
3509
+ geometry_descriptor = descriptor if isinstance(descriptor, dict) else {}
3510
+ sdf = descriptor.get("sdf") if isinstance(descriptor, dict) else None
3511
+ visual_hull = descriptor.get("visualHull") if isinstance(descriptor, dict) else None
3512
+ is_implicit = component.get("topologyClass") == "implicit" and isinstance(sdf, dict)
3513
+ is_visual_hull = isinstance(visual_hull, dict)
3514
+ iterations = subdivision_iterations(component)
3515
+ effective_primitive = resolve_instanced_cluster_base(primitive, geometry_descriptor, VALID_PRIMITIVES)
3516
+ if is_visual_hull:
3517
+ base_geometry_lines = [f" const geometry = buildVisualHullGeometry({json_literal(visual_hull)});"]
3518
+ elif is_implicit:
3519
+ # An SDF's density comes from its sampling grid, not from segment counts, so the
3520
+ # tessellation tier has to reach it separately or it stays the one uncapped source
3521
+ # of triangles in a budgeted model. Marching-cubes output grows with the SURFACE it
3522
+ # crosses, so triangles scale as O(N^2), not O(N^3) -- measured on a capsule field:
3523
+ # N 64 -> 96 -> 128 gave 3,432 -> 7,840 -> 13,960 crossing cells, matching N^2
3524
+ # (1.78, 2.25, 1.78 against predicted 1.78, 2.25, 1.78). Halving N therefore buys
3525
+ # back about 4x, which is why a cap rather than a rewrite is enough here.
3526
+ base_geometry_lines = [
3527
+ f" const geometry = polygonizeSdf({json_literal(capped_sdf(sdf, seg))});"
3528
+ ]
3529
+ else:
3530
+ geometry_expression = (
3531
+ "new THREE.BoxGeometry(1, 1, 1)"
3532
+ if iterations > 0 and effective_primitive == "box"
3533
+ else geometry_for(primitive, component, iterations > 0, seg)
3534
+ )
3535
+ base_geometry_lines = [
3536
+ f" const geometry = {endpoint_var}",
3537
+ f" ? new THREE.CylinderGeometry({endpoint_var}.endRadius, {endpoint_var}.baseRadius, {endpoint_var}.length, {seg['ATTACHMENT_CYLINDER_RADIAL_SEGMENTS']}, {seg['ATTACHMENT_CYLINDER_HEIGHT_SEGMENTS']})",
3538
+ f" : {geometry_expression};",
3539
+ ]
3540
+ if iterations > 0:
3541
+ geometry_lines = [
3542
+ f" const {component_var}Geometry = (() => {{",
3543
+ *base_geometry_lines,
3544
+ f" return subdivideCatmullClark(geometry, {iterations});",
3545
+ " })();",
3546
+ ]
3547
+ elif is_visual_hull:
3548
+ geometry_lines = [f" const {component_var}Geometry = buildVisualHullGeometry({json_literal(visual_hull)});"]
3549
+ elif is_implicit:
3550
+ geometry_lines = [
3551
+ f" const {component_var}Geometry = polygonizeSdf({json_literal(capped_sdf(sdf, seg))});"
3552
+ ]
3553
+ else:
3554
+ geometry_lines = [
3555
+ f" const {component_var}Geometry = {endpoint_var}",
3556
+ f" ? new THREE.CylinderGeometry({endpoint_var}.endRadius, {endpoint_var}.baseRadius, {endpoint_var}.length, {seg['ATTACHMENT_CYLINDER_RADIAL_SEGMENTS']}, {seg['ATTACHMENT_CYLINDER_HEIGHT_SEGMENTS']})",
3557
+ f" : {geometry_for(primitive, component, False, seg)};",
3558
+ ]
3559
+ ratio = decimate_ratio(component)
3560
+ if ratio is not None:
3561
+ # Renaming the dense result and binding the decimated one to the name everything
3562
+ # downstream already uses keeps this a single insertion: mesh construction, the
3563
+ # skin-weight pass and every gate go on reading `<component>Geometry`, and the
3564
+ # decimation lands before any of them. In particular it lands before the bind pass
3565
+ # recomputes skinIndex/skinWeight from `position`, so no skinning data is ever
3566
+ # carried across a vertex merge.
3567
+ dense_var = f"{component_var}GeometryDense"
3568
+ geometry_lines[0] = geometry_lines[0].replace(
3569
+ f"const {component_var}Geometry =", f"const {dense_var} =", 1
3570
+ )
3571
+ geometry_lines.append(
3572
+ f" const {component_var}Geometry = decimateGeometry({dense_var}, {ratio});"
3573
+ )
3574
+ lines.extend(
3575
+ [
3576
+ "",
3577
+ *(
3578
+ [f" const {attachment_var} = {json.dumps(attachment, ensure_ascii=False)};"]
3579
+ if primitive in ATTACHMENT_PRIMITIVES and not is_implicit
3580
+ else []
3581
+ ),
3582
+ # Endpoint-DERIVED GEOMETRY only for primitives that are attachment shapes.
3583
+ #
3584
+ # An `attachment` block is a contract -- parent socket, contact type, embed depth,
3585
+ # local start and end -- and the structural pass requires one on every child
3586
+ # appendage. It is NOT a statement that the part is a tapered cylinder. Deriving
3587
+ # geometry from it unconditionally silently overrode the authored primitive: an
3588
+ # ellipsoid head, a tapered-sweep ear and a swept tail all came out as cylinders
3589
+ # between their two endpoints, the spec validated, the factory built, and the
3590
+ # wrong shape shipped. That is the same failure mode `GeometryNotImplementedError`
3591
+ # exists to prevent one step earlier.
3592
+ #
3593
+ # So the branch is gated on ATTACHMENT_PRIMITIVES. Every other primitive keeps the
3594
+ # geometry it declared and uses the attachment as what it is: a contract the
3595
+ # anchor gate reads.
3596
+ (
3597
+ f" const {endpoint_var} = makeAttachmentEndpoint({attachment_var});"
3598
+ # `not is_implicit` as well as the primitive test. An implicit component's
3599
+ # geometry comes from the SDF and its placement from its own transform, but it
3600
+ # still has to declare SOME `primitive` -- the shipped fixture uses "capsule" --
3601
+ # and that lands it in ATTACHMENT_PRIMITIVES. Taking the endpoint branch then
3602
+ # moved the node to `attachment.localStart`: a head authored at y 0.705 was
3603
+ # emitted at y -0.195, inside the body, and the model rendered with no head at
3604
+ # all.
3605
+ if primitive in ATTACHMENT_PRIMITIVES and not is_implicit
3606
+ # `makeAttachmentEndpoint(null)` rather than a bare `null`, so the
3607
+ # binding keeps its `AttachmentEndpoint | null` type. A literal null narrows to
3608
+ # `never` and every later `endpoint.start` stops compiling.
3609
+ else f" const {endpoint_var} = makeAttachmentEndpoint(null);"
3610
+ ),
3611
+ f" const {node_var} = new THREE.Group();",
3612
+ f" {node_var}.name = {json.dumps(name + '__pivot')};",
3613
+ # PLAN_1.5 WS-E: the hierarchy transform (this pivot Group) never carries
3614
+ # non-uniform scale. A part's shape dimensions are baked directly into its
3615
+ # geometry (see `{component_var}Geometry.scale(...)` below) instead of onto
3616
+ # this node, so a non-uniform component cannot distort a child parented
3617
+ # under it. Position/rotation still cascade normally through the Group chain.
3618
+ f" {node_var}.scale.set(1, 1, 1);",
3619
+ f" if ({endpoint_var}) {{",
3620
+ f" {node_var}.position.copy({endpoint_var}.start);",
3621
+ # The pivot sits AT the joint and the limb's own direction lives on the mesh
3622
+ # inside it (mesh.quaternion = endpoint.quaternion), so rotating this node
3623
+ # rotates the limb about its joint -- which is exactly what a pose is. This used
3624
+ # to be forced to (0,0,0), which silently discarded every authored rotation on
3625
+ # precisely the components that articulate: every capsule/cylinder limb carries
3626
+ # an attachment block and so takes this branch. `anatomy.pose.jointAngles` had
3627
+ # no observable effect until this line stopped zeroing it.
3628
+ f" {node_var}.rotation.set({vector(transform.get('rotation'), [0, 0, 0])});",
3629
+ " } else {",
3630
+ f" {node_var}.position.set({vector(transform.get('position'), [0, 0, 0])});",
3631
+ f" {node_var}.rotation.set({vector(transform.get('rotation'), [0, 0, 0])});",
3632
+ " }",
3633
+ f" {node_var}.userData.sculptComponent = {json.dumps(component, ensure_ascii=False)};",
3634
+ f" {node_var}.userData.actionProfile = {json.dumps(action_profile, ensure_ascii=False)};",
3635
+ f" (nodes[{json.dumps(str(parent))}] ?? root).add({node_var});",
3636
+ f" nodes[{json.dumps(component_id)}] = {node_var};",
3637
+ *geometry_lines,
3638
+ # Attachment geometry (the endpoint branch above) already derives its exact
3639
+ # radius/length from the measured endpoints, so it is not re-scaled here.
3640
+ # Every other primitive is authored unit-sized in geometry_for(); its real
3641
+ # dimensions are applied to the vertex data now, not to the pivot's .scale.
3642
+ f" if (!{endpoint_var}) {{",
3643
+ f" {component_var}Geometry.scale({scale_vector(component, transform)});",
3644
+ " }",
3645
+ # After the scale, so the ramp spans the mass's real extent rather than its unit
3646
+ # extent, and before the mesh, so the colour attribute exists when the material
3647
+ # reads it.
3648
+ *(
3649
+ [
3650
+ f" applyRootTipGradient({component_var}Geometry, "
3651
+ f"{json.dumps(gradient['rootColor'])}, {json.dumps(gradient['tipColor'])}, "
3652
+ f"{json.dumps(gradient['axis'])});"
3653
+ ]
3654
+ if (gradient := root_tip_gradient(component))
3655
+ else []
3656
+ ),
3657
+ *(
3658
+ [
3659
+ f" applyVertexPaint({component_var}Geometry, "
3660
+ f"{json.dumps(paint['baseColor'])}, "
3661
+ f"{json.dumps(paint['regions'], ensure_ascii=False)});"
3662
+ ]
3663
+ if (paint := vertex_paint(component))
3664
+ else []
3665
+ ),
3666
+ f" const {component_var} = new THREE."
3667
+ f"{'SkinnedMesh' if component_id in skinned_ids else 'Mesh'}(",
3668
+ f" {component_var}Geometry,",
3669
+ f" {material_expression}",
3670
+ " );",
3671
+ f" {component_var}.name = {json.dumps(name)};",
3672
+ # Cloned before enabling vertex colours: materials are shared by id, and flipping
3673
+ # the flag in place would tint every other component using the same material.
3674
+ *(
3675
+ [
3676
+ f" {component_var}.material = {component_var}.material.clone();",
3677
+ f" {component_var}.material.vertexColors = true;",
3678
+ ]
3679
+ if root_tip_gradient(component) or vertex_paint(component)
3680
+ else []
3681
+ ),
3682
+ # With vertexColors on, three MULTIPLIES material.color by the vertex colour. A
3683
+ # paint block already carries the component's full albedo -- its own baseColor for
3684
+ # the unpainted surface and a region colour where a region claims it -- so leaving
3685
+ # the material's albedo in place squares it. Measured: a 0.027 linear black fur
3686
+ # against a 0.027 black material renders at 0.0007, and the white sock authored at
3687
+ # 0.937 comes out at 0.025, i.e. darker than the fur is supposed to be. The region
3688
+ # boundary is still exactly where the gate measures it, and is invisible.
3689
+ #
3690
+ # Only for `vertexPaint`. `rootTipGradient` is a SHADING ramp that is meant to
3691
+ # modulate the material's own colour, so it keeps the multiply.
3692
+ *(
3693
+ # Cast: `Mesh.material` is typed `Material | Material[]`, and `color`
3694
+ # lives on the concrete material rather than on the base class. `vertexColors`
3695
+ # above needs no cast because it IS on `Material`.
3696
+ [
3697
+ f" ({component_var}.material as THREE.MeshPhysicalMaterial)"
3698
+ ".color.setRGB(1, 1, 1);"
3699
+ ]
3700
+ if vertex_paint(component)
3701
+ else []
3702
+ ),
3703
+ f" if ({endpoint_var}) {{",
3704
+ f" {component_var}.position.copy({endpoint_var}.midpoint);",
3705
+ f" {component_var}.quaternion.copy({endpoint_var}.quaternion);",
3706
+ " }",
3707
+ f" {component_var}.castShadow = options.castShadow ?? true;",
3708
+ f" {component_var}.receiveShadow = options.receiveShadow ?? true;",
3709
+ f" {component_var}.userData.sculptComponent = {json.dumps(component, ensure_ascii=False)};",
3710
+ f" {node_var}.add({component_var});",
3711
+ f" meshes[{json.dumps(component_id)}] = {component_var};",
3712
+ f" colliders[{json.dumps(component_id)}] = {json.dumps(action_profile.get('collider', {}), ensure_ascii=False)};",
3713
+ ]
3714
+ )
3715
+ if isinstance(fracture_group, str) and fracture_group:
3716
+ lines.extend(
3717
+ [
3718
+ f" destructionGroups[{json.dumps(fracture_group)}] ??= [];",
3719
+ f" destructionGroups[{json.dumps(fracture_group)}].push({node_var});",
3720
+ ]
3721
+ )
3722
+ for socket_index, socket in enumerate(sockets_spec):
3723
+ if not isinstance(socket, dict):
3724
+ continue
3725
+ socket_id = str(socket.get("id") or f"socket-{socket_index}")
3726
+ socket_var = local_var("socket", f"{component_id}_{socket_id}", socket_index)
3727
+ local_position = socket.get("localPosition", socket.get("position"))
3728
+ local_rotation = socket.get("localRotation", socket.get("rotation"))
3729
+ socket_key = f"{component_id}:{socket_id}"
3730
+ lines.extend(
3731
+ [
3732
+ f" const {socket_var} = new THREE.Object3D();",
3733
+ f" {socket_var}.name = {json.dumps(socket_id)};",
3734
+ f" {socket_var}.position.set({vector(local_position, [0, 0, 0])});",
3735
+ f" {socket_var}.rotation.set({vector(local_rotation, [0, 0, 0])});",
3736
+ f" {socket_var}.userData.socket = {json.dumps(socket, ensure_ascii=False)};",
3737
+ f" {node_var}.add({socket_var});",
3738
+ f" sockets[{json.dumps(socket_key)}] = {socket_var};",
3739
+ ]
3740
+ )
3741
+
3742
+ # Repetition systems (spokes, fasteners, teeth, slats): the spec models these
3743
+ # as a count + placement + instanceScale rather than N hand-authored components.
3744
+ # They are emitted here, parented to the referenced node, and pass-gated by the
3745
+ # same macro/meso/micro levels as componentTree so blockout stays clay-macro.
3746
+ allowed_levels = PASS_LEVELS.get(pass_id, {"macro"})
3747
+ known_ids = {str(c.get("id")) for c in all_components if isinstance(c, dict)}
3748
+ # Ids that already exist as built geometry: components in their own right, plus the SDF
3749
+ # primitives that make up an implicit component. A repetition system naming these is describing
3750
+ # parts that have already been authored, not asking for new ones.
3751
+ realised_ids = set(known_ids)
3752
+ for component in all_components:
3753
+ if not isinstance(component, dict):
3754
+ continue
3755
+ descriptor = component.get("geometryDescriptor")
3756
+ sdf = descriptor.get("sdf") if isinstance(descriptor, dict) else None
3757
+ for primitive in (sdf or {}).get("primitives", []) or []:
3758
+ if isinstance(primitive, dict) and primitive.get("id"):
3759
+ realised_ids.add(str(primitive["id"]))
3760
+
3761
+ for rep_index, system in enumerate(spec.get("repetitionSystems", [])):
3762
+ if not isinstance(system, dict):
3763
+ continue
3764
+ # A repetition system whose members are ALL already built is documentation, not an
3765
+ # instruction, and instancing it emits a second copy of parts that exist.
3766
+ #
3767
+ # The tuxedo cat declares limb-set, whisker-set and toe-set with elementComponentIds naming
3768
+ # the four legs (SDF primitives inside the fused body), the eight whiskers and the six toes
3769
+ # (each an authored component that already emits its own mesh), and a PROSE placement —
3770
+ # "three per front paw at x offsets -0.040, 0.0, +0.040" — rather than a {mode, axis,
3771
+ # radius} object. The emitter below reads that string as an empty dict and falls through to
3772
+ # its defaults, so each system came out as an InstancedMesh of unit BOXES centred on the
3773
+ # origin, spanning -0.5..0.5 on every axis.
3774
+ #
3775
+ # That is not merely ugly. geometry.json is measured by run_geometry_gates.py, and the
3776
+ # boxes dragged the model's minimum Y from 0.0012 to -0.5 — half a unit underground — so
3777
+ # belly-clearance-over-torso-depth was computed against a ground line that does not exist
3778
+ # and "failed" for a reason that had nothing to do with the belly.
3779
+ #
3780
+ # Skipping requires ALL members to be realised, so a genuine instancing system — whose
3781
+ # members are deliberately not authored one by one — still emits.
3782
+ element_ids = [str(e) for e in (system.get("elementComponentIds") or []) if e]
3783
+ if element_ids and all(e in realised_ids for e in element_ids):
3784
+ lines.append(
3785
+ f" // repetition system {json.dumps(str(system.get('id') or f'rep_{rep_index}'))} "
3786
+ f"describes {len(element_ids)} parts that are already built individually; "
3787
+ "not instanced."
3788
+ )
3789
+ continue
3790
+ level = str(system.get("level") or "meso")
3791
+ if level not in allowed_levels:
3792
+ continue
3793
+ parent_id = str(system.get("parent") or "root")
3794
+ if parent_id not in known_ids and parent_id != "root":
3795
+ parent_id = "root"
3796
+ placement = system.get("placement", {}) if isinstance(system.get("placement"), dict) else {}
3797
+ count = int(system.get("count") or 0)
3798
+ if count <= 0:
3799
+ continue
3800
+ primitive = str(system.get("primitive") or "box")
3801
+ if primitive not in VALID_PRIMITIVES:
3802
+ primitive = "box"
3803
+ rep_material = str(system.get("material") or next(iter(materials.keys()), "base"))
3804
+ scale = system.get("instanceScale", [0.1, 0.1, 0.1])
3805
+ axis = placement.get("axis", [0, 0, 1])
3806
+ radius = placement.get("radius", 0.0)
3807
+ start_deg = placement.get("startAngleDeg", 0)
3808
+ mode = str(placement.get("mode") or "radial")
3809
+ rep_var = f"rep_{rep_index}"
3810
+ lines.extend(
3811
+ [
3812
+ "",
3813
+ f" // repetition system: {system.get('id') or rep_var} (InstancedMesh, {mode}, count={count}, level={level})",
3814
+ " {",
3815
+ f" const parent = nodes[{json.dumps(parent_id)}] ?? root;",
3816
+ f" const geo = {geometry_for(primitive, {}, False, seg)};",
3817
+ f" const mat = materialMap[{json.dumps(rep_material)}] ?? new THREE.MeshStandardMaterial({{ color: 0x888888 }});",
3818
+ " // Contract (PLAN_1.5 WS-E): instanceScale is ABSOLUTE, in the parent pivot's",
3819
+ " // local units -- it is never multiplied by the parent component's own declared",
3820
+ " // dimensional scale. This falls out of the same fix as componentTree: the pivot",
3821
+ " // Group this cluster is parented to always carries identity scale (dimensions are",
3822
+ " // baked into that component's OWN geometry, not exposed on the Group), so an",
3823
+ " // instanced fastener/tooth/spoke sized [0.05, 0.05, 0.05] renders at exactly that",
3824
+ " // size regardless of how non-uniformly its host component is shaped, and a",
3825
+ " // `radial` ring's placement stays circular instead of being squashed into an",
3826
+ " // ellipse by a non-uniform host.",
3827
+ f" const scl = [{vector(scale, [0.1, 0.1, 0.1])}];",
3828
+ f" const axis = new THREE.Vector3({vector(axis, [0, 0, 1])}).normalize();",
3829
+ f" const radius = {float(radius) if isinstance(radius, (int, float)) else 0.0};",
3830
+ " const seed = Math.abs(axis.z) < 0.9 ? new THREE.Vector3(0, 0, 1) : new THREE.Vector3(1, 0, 0);",
3831
+ " const perp = new THREE.Vector3().crossVectors(axis, seed).normalize();",
3832
+ " // One InstancedMesh = one draw call for all repeated parts (teeth/fasteners/spokes),",
3833
+ " // replacing the former per-instance Mesh clone loop (real-time perf principle).",
3834
+ f" const cluster = new THREE.InstancedMesh(geo, mat, {count});",
3835
+ " const _m = new THREE.Matrix4();",
3836
+ " const _p = new THREE.Vector3();",
3837
+ " const _q = new THREE.Quaternion();",
3838
+ " const _s = new THREE.Vector3(scl[0], scl[1], scl[2]);",
3839
+ f" for (let i = 0; i < {count}; i++) {{",
3840
+ f" const ang = (({float(start_deg) if isinstance(start_deg,(int,float)) else 0.0}) + (i * 360) / {count}) * Math.PI / 180;",
3841
+ " const dir = perp.clone().applyQuaternion(new THREE.Quaternion().setFromAxisAngle(axis, ang));",
3842
+ " _p.copy(radius > 0 ? dir.clone().multiplyScalar(radius * 0.5) : new THREE.Vector3());",
3843
+ " _q.setFromUnitVectors(new THREE.Vector3(1, 0, 0), dir);",
3844
+ " _m.compose(_p, _q, _s);",
3845
+ " cluster.setMatrixAt(i, _m);",
3846
+ " }",
3847
+ " cluster.instanceMatrix.needsUpdate = true;",
3848
+ " cluster.castShadow = options.castShadow ?? true;",
3849
+ " cluster.receiveShadow = options.receiveShadow ?? true;",
3850
+ f" cluster.name = {json.dumps(str(system.get('id') or rep_var))};",
3851
+ " parent.add(cluster);",
3852
+ " }",
3853
+ ]
3854
+ )
3855
+
3856
+ # Deferred to here, after every node is parented, because the march runs in the TARGET's frame
3857
+ # and needs both world matrices. Running it at each component's own emission site would depend
3858
+ # on the target already existing, which makes a legal forward reference silently do nothing.
3859
+ if stand_proud_jobs or stand_proud_skipped:
3860
+ lines.append("")
3861
+ lines.append(" // standProud: hold these components outside the surfaces they cover.")
3862
+ for note in stand_proud_skipped:
3863
+ lines.append(f" // SKIPPED {note}")
3864
+ for job in stand_proud_jobs:
3865
+ marcher = json.dumps(job["componentId"])
3866
+ proud_target_key = json.dumps(job["targetId"])
3867
+ lines.extend([
3868
+ f" if (meshes[{marcher}] && nodes[{proud_target_key}]) {{",
3869
+ " applyStandProud(",
3870
+ f" meshes[{marcher}].geometry,",
3871
+ f" meshes[{marcher}],",
3872
+ f" nodes[{proud_target_key}],",
3873
+ f" {json_literal({'rings': job['rings']})},",
3874
+ f" {job['clearance']},",
3875
+ f" {job['maxPush']},",
3876
+ " );",
3877
+ " }",
3878
+ ])
3879
+
3880
+ lines.extend(emit_rig_hierarchy(spec))
3881
+
3882
+ look_dev_targets = spec.get("lookDevTargets", {})
3883
+ lighting_from_photo = spec.get("lightingFromPhoto", [])
3884
+ lines.extend(
3885
+ [
3886
+ "",
3887
+ " root.userData.sculptRuntime = { nodes, meshes, sockets, colliders, destructionGroups } satisfies ProceduralModelRuntime;",
3888
+ f" root.userData.lookDevTargets = {json_literal(look_dev_targets)};",
3889
+ " root.userData.actionReadiness = {",
3890
+ " note: 'Use root.userData.sculptRuntime.nodes for transforms, sockets for attachments, colliders for physics proxies, and destructionGroups for breakable sets.',",
3891
+ " };",
3892
+ " return root;",
3893
+ "}",
3894
+ "",
3895
+ f"export function create{type_name}LookDevLights(",
3896
+ " mode: 'neutral' | 'grazing' | 'reference' = 'neutral',",
3897
+ "): THREE.Group {",
3898
+ " const lights = new THREE.Group();",
3899
+ f" lights.name = {json.dumps(target + ' look-dev lights')};",
3900
+ " const hemi = new THREE.HemisphereLight(",
3901
+ " mode === 'reference' ? 0xfff0d6 : 0xf2f4ff,",
3902
+ " 0x363b42,",
3903
+ " mode === 'grazing' ? 0.28 : mode === 'reference' ? 0.72 : 0.85,",
3904
+ " );",
3905
+ " lights.add(hemi);",
3906
+ " const key = new THREE.DirectionalLight(",
3907
+ " mode === 'reference' ? 0xffcf8a : 0xfff4e8,",
3908
+ " mode === 'grazing' ? 4.2 : mode === 'reference' ? 2.6 : 2.15,",
3909
+ " );",
3910
+ " if (mode === 'grazing') key.position.set(7.5, 1.1, 4.0);",
3911
+ " else if (mode === 'reference') key.position.set(-4.5, 7.5, 5.0);",
3912
+ " else key.position.set(-4.0, 6.0, 5.5);",
3913
+ " key.castShadow = true;",
3914
+ " key.shadow.mapSize.set(4096, 4096);",
3915
+ " key.shadow.bias = -0.00025;",
3916
+ " key.shadow.normalBias = 0.018;",
3917
+ " key.shadow.radius = 7;",
3918
+ " key.shadow.blurSamples = 24;",
3919
+ " key.shadow.camera.near = 0.5;",
3920
+ " key.shadow.camera.far = 30;",
3921
+ " key.shadow.camera.left = -2.6;",
3922
+ " key.shadow.camera.right = 2.6;",
3923
+ " key.shadow.camera.top = 2.6;",
3924
+ " key.shadow.camera.bottom = -2.6;",
3925
+ " key.shadow.camera.updateProjectionMatrix();",
3926
+ " lights.add(key);",
3927
+ " const fill = new THREE.DirectionalLight(0xa8c4ff, mode === 'grazing' ? 0.12 : 0.42);",
3928
+ " fill.position.set(4.0, 3.0, 3.5);",
3929
+ " lights.add(fill);",
3930
+ " const rim = new THREE.DirectionalLight(0xfff1c4, mode === 'grazing' ? 0.28 : 0.85);",
3931
+ " rim.position.set(0.5, 4.5, -6.0);",
3932
+ " lights.add(rim);",
3933
+ " lights.userData.reviewMode = mode;",
3934
+ f" lights.userData.lightingFromPhoto = {json_literal(lighting_from_photo)};",
3935
+ f" lights.userData.lookDevTargets = {json_literal(look_dev_targets)};",
3936
+ " return lights;",
3937
+ "}",
3938
+ "",
3939
+ "// PBR materials (clearcoat/iridescence/transmission/anisotropy) need an environment",
3940
+ "// map to visually behave as intended — call this once per renderer and assign the",
3941
+ "// result to scene.environment before rendering. No external HDR asset required.",
3942
+ f"export function create{type_name}Environment(renderer: THREE.WebGLRenderer): THREE.Texture {{",
3943
+ " const pmrem = new THREE.PMREMGenerator(renderer);",
3944
+ " const texture = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;",
3945
+ " pmrem.dispose();",
3946
+ " return texture;",
3947
+ "}",
3948
+ "",
3949
+ "// Plan 1.3 §3.2 — auto-framing by bounding box. The Divine Eye can only compare a",
3950
+ "// render to the reference if the object is FRAMED consistently (an object framed",
3951
+ "// differently scores as wrong even when its shape is right). This positions the camera",
3952
+ "// deterministically from the object's bounding box so it fills the frame at a stable",
3953
+ "// margin, and sets near/far to the object scale. Call after adding the model to the",
3954
+ "// scene, and again on resize (after updating camera.aspect).",
3955
+ f"export function frame{type_name}Camera(",
3956
+ " camera: THREE.PerspectiveCamera,",
3957
+ " object: THREE.Object3D,",
3958
+ " options: { margin?: number; azimuthDeg?: number; elevationDeg?: number } = {},",
3959
+ "): void {",
3960
+ " const box = new THREE.Box3().setFromObject(object);",
3961
+ " if (box.isEmpty()) return;",
3962
+ " const size = box.getSize(new THREE.Vector3());",
3963
+ " const center = box.getCenter(new THREE.Vector3());",
3964
+ " const margin = options.margin ?? 1.15;",
3965
+ " const maxDim = Math.max(size.x, size.y, size.z) * margin;",
3966
+ " const fov = (camera.fov * Math.PI) / 180;",
3967
+ " // distance so the largest object dimension fits vertically in the frame",
3968
+ " const distance = (maxDim / 2) / Math.tan(fov / 2);",
3969
+ " const az = ((options.azimuthDeg ?? 0) * Math.PI) / 180;",
3970
+ " const el = ((options.elevationDeg ?? 0) * Math.PI) / 180;",
3971
+ " const dir = new THREE.Vector3(",
3972
+ " Math.sin(az) * Math.cos(el),",
3973
+ " Math.sin(el),",
3974
+ " Math.cos(az) * Math.cos(el),",
3975
+ " );",
3976
+ " camera.position.copy(center).addScaledVector(dir, distance);",
3977
+ " camera.near = Math.max(0.01, distance - maxDim);",
3978
+ " camera.far = distance + maxDim * 2;",
3979
+ " camera.lookAt(center);",
3980
+ " camera.updateProjectionMatrix();",
3981
+ "}",
3982
+ "",
3983
+ "// Plan 1.3 §3.2c — PRESENTATION composer (DOF + bloom). CRITICAL (R-POSTFX): this is",
3984
+ "// for the showcase/hero render ONLY. The Divine Eye's EVALUATION render MUST use a",
3985
+ "// plain renderer with NO composer — bloom blows highlights and DOF blurs edges, which",
3986
+ "// would corrupt the deterministic IoU/DCD/edge/blowout signals. Enable dof/bloom ONLY",
3987
+ "// when the reference photo actually exhibits them (detect_reference_effects.py authorizes).",
3988
+ f"export function create{type_name}PresentationComposer(",
3989
+ " renderer: THREE.WebGLRenderer,",
3990
+ " scene: THREE.Scene,",
3991
+ " camera: THREE.Camera,",
3992
+ " options: { dof?: boolean; bloom?: boolean; bloomStrength?: number; dofFocus?: number; dofAperture?: number } = {},",
3993
+ "): EffectComposer {",
3994
+ " const composer = new EffectComposer(renderer);",
3995
+ " composer.addPass(new RenderPass(scene, camera));",
3996
+ " if (options.dof) {",
3997
+ " composer.addPass(new BokehPass(scene, camera, {",
3998
+ " focus: options.dofFocus ?? 10.0,",
3999
+ " aperture: options.dofAperture ?? 0.0002,",
4000
+ " maxblur: 0.01,",
4001
+ " }));",
4002
+ " }",
4003
+ " if (options.bloom) {",
4004
+ " const size = new THREE.Vector2();",
4005
+ " renderer.getSize(size);",
4006
+ " composer.addPass(new UnrealBloomPass(size, options.bloomStrength ?? 0.4, 0.4, 0.85));",
4007
+ " }",
4008
+ " return composer;",
4009
+ "}",
4010
+ "",
4011
+ f"export function configure{type_name}Renderer(renderer: THREE.WebGLRenderer): void {{",
4012
+ " // Load-bearing for view-dependent finishes (anodized / Doppler): without ACES + sRGB",
4013
+ " // the environment reflection reads flat/washed instead of a believable metal response.",
4014
+ " renderer.toneMapping = THREE.ACESFilmicToneMapping;",
4015
+ " renderer.outputColorSpace = THREE.SRGBColorSpace;",
4016
+ "}",
4017
+ "",
4018
+ f"export function create{type_name}InspectControls(",
4019
+ " camera: THREE.Camera,",
4020
+ " domElement: HTMLElement,",
4021
+ "): OrbitControls {",
4022
+ " // View-dependent finishes only read correctly once the user orbits — their color",
4023
+ " // comes from the environment reflection, not albedo, so free rotation matters here.",
4024
+ " const controls = new OrbitControls(camera, domElement);",
4025
+ " controls.enableDamping = true;",
4026
+ " controls.minDistance = 1.0;",
4027
+ " controls.maxDistance = 8.0;",
4028
+ " controls.autoRotate = false;",
4029
+ " return controls;",
4030
+ "}",
4031
+ "",
4032
+ ]
4033
+ )
4034
+ return "\n".join(lines)
4035
+
4036
+
4037
+ def main(argv: list[str]) -> int:
4038
+ parser = argparse.ArgumentParser(description=__doc__)
4039
+ parser.add_argument("spec", type=Path)
4040
+ parser.add_argument("--out", type=Path, required=True)
4041
+ parser.add_argument(
4042
+ "--pass-id",
4043
+ help="Build pass to generate. Defaults to the current unlocked sculptPipeline pass.",
4044
+ )
4045
+ parser.add_argument("--force", action="store_true")
4046
+ parser.add_argument(
4047
+ "--allow-nonstrict",
4048
+ action="store_true",
4049
+ help="Test-fixture escape hatch only; emits non-production code and cannot be used with --pass-id.",
4050
+ )
4051
+ parser.add_argument(
4052
+ "--blocked-report",
4053
+ type=Path,
4054
+ help="Write the machine-readable BLOCKED report when strict-quality prevents generation.",
4055
+ )
4056
+ args = parser.parse_args(argv)
4057
+
4058
+ spec_path = args.spec.expanduser().resolve()
4059
+ spec = load_spec(spec_path)
4060
+ _errors, warnings, strict_failures = strict_quality_failures(spec)
4061
+ if strict_failures and not args.allow_nonstrict:
4062
+ emit_blocked(
4063
+ blocked_report(spec_path, strict_failures, warnings, args.pass_id),
4064
+ args.blocked_report,
4065
+ )
4066
+ return 2
4067
+ if args.allow_nonstrict and args.pass_id:
4068
+ parser.error("--allow-nonstrict is test-only and cannot be combined with --pass-id")
4069
+ if _errors:
4070
+ parser.error(f"spec validation failed: {'; '.join(_errors)}")
4071
+ if args.allow_nonstrict:
4072
+ print("WARNING: generating a non-production test-fixture factory (--allow-nonstrict)", file=sys.stderr)
4073
+ pass_id = args.pass_id or unlocked_pass(spec)
4074
+ try:
4075
+ assert_pass_unlocked(spec, pass_id)
4076
+ except ValueError as exc:
4077
+ parser.error(str(exc))
4078
+ gaps = pass_specific_gaps(spec, pass_id)
4079
+ if gaps:
4080
+ parser.error(f"build pass {pass_id!r} needs spec refinement: {'; '.join(gaps)}")
4081
+ output = args.out.expanduser().resolve()
4082
+ if output.exists() and not args.force:
4083
+ parser.error(f"{output} already exists; use --force to overwrite")
4084
+ output.parent.mkdir(parents=True, exist_ok=True)
4085
+ try:
4086
+ rendered = generate(spec, pass_id)
4087
+ except GeometryNotImplementedError as exc:
4088
+ parser.error(
4089
+ f"primitive {str(exc)!r} is accepted by validation but has no codegen "
4090
+ f"implementation yet in geometry_for() — refine-spec to a supported primitive "
4091
+ f"or implement it before generating this component"
4092
+ )
4093
+ output.write_text(rendered, encoding="utf-8")
4094
+ print(output)
4095
+ return 0
4096
+
4097
+
4098
+ if __name__ == "__main__":
4099
+ raise SystemExit(main(sys.argv[1:]))