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,216 @@
1
+ #!/usr/bin/env python3
2
+ """Compare a render's hair against the reference's, and say which differences are which kind.
3
+
4
+ WHY THE HARD/SOFT SPLIT IS THE POINT. Every hair failure recorded in this pipeline falls into one of
5
+ two classes that want opposite responses:
6
+
7
+ a bald patch the skull is showing through. Always wrong, at any coverage number, and no
8
+ amount of matching elsewhere compensates. HARD.
9
+ a coverage shortfall there is less hair than the reference has. Often true and often the best
10
+ available compromise at a given triangle budget. SOFT.
11
+
12
+ Conflating them is what produced four wrong fixes in one session. A coverage shortfall was read as
13
+ "add more hair", the masses were widened, and the widening pushed them off the skull -- turning a
14
+ soft signal into a hard failure while the coverage number barely moved. The measured result: closure
15
+ 42.2% to 40.9%, worse on all six views, with crown scalp exposure UP 14.9 points on the worst view.
16
+
17
+ So a shortfall never authorises widening on its own. `scalpExposure` runs first, geometrically, and
18
+ its verdict dominates.
19
+
20
+ Pure Python 3.10+ standard library.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import sys
27
+ from pathlib import Path
28
+ from typing import Any, Sequence
29
+
30
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage1_intake"))
31
+
32
+ from extract_hair_evidence import extract_hair_evidence # noqa: E402
33
+
34
+ # A band whose coverage is this far below the reference is worth reporting. Not calibrated: chosen
35
+ # to sit just under the smallest shortfall that proved visible by eye (the profile mid band, which
36
+ # read 41.5% against 7.8%).
37
+ BAND_SHORTFALL_SOFT = 0.08
38
+ # Hairline offset, as a fraction of figure height, beyond which the face has visibly the wrong
39
+ # amount of forehead. Derived from the head being roughly 0.13 of figure height: a tenth of a head.
40
+ HAIRLINE_OFFSET_MAX = 0.013
41
+ # Specular band position difference, in scalp v units, beyond which the highlight reads as sitting
42
+ # on the wrong part of the head. Uncalibrated.
43
+ SPECULAR_OFFSET_MAX = 0.15
44
+
45
+
46
+ def compare_views(reference: dict[str, Any], render: dict[str, Any]) -> dict[str, Any]:
47
+ """Per-view band, hairline and shading deltas between two hair-evidence reports."""
48
+ views: dict[str, Any] = {}
49
+ for name, reference_view in reference.get("views", {}).items():
50
+ render_view = render.get("views", {}).get(name)
51
+ if not isinstance(render_view, dict):
52
+ views[name] = {"status": "missing-from-render"}
53
+ continue
54
+ if reference_view.get("status") != "measured" or render_view.get("status") != "measured":
55
+ views[name] = {
56
+ "status": "not-measurable",
57
+ "referenceStatus": reference_view.get("status"),
58
+ "renderStatus": render_view.get("status"),
59
+ }
60
+ continue
61
+
62
+ bands = {}
63
+ for band, reference_band in reference_view.get("bands", {}).items():
64
+ render_band = render_view.get("bands", {}).get(band, {})
65
+ delta = round(render_band.get("coverage", 0.0) - reference_band.get("coverage", 0.0), 4)
66
+ bands[band] = {
67
+ "reference": reference_band.get("coverage"),
68
+ "render": render_band.get("coverage"),
69
+ "delta": delta,
70
+ "shortfall": delta <= -BAND_SHORTFALL_SOFT,
71
+ }
72
+
73
+ reference_hairline = reference_view.get("hairline")
74
+ render_hairline = render_view.get("hairline")
75
+ hairline_offset = (
76
+ round(render_hairline - reference_hairline, 4)
77
+ if reference_hairline is not None and render_hairline is not None
78
+ else None
79
+ )
80
+
81
+ reference_specular = reference_view.get("shading", {}).get("specularBandV")
82
+ render_specular = render_view.get("shading", {}).get("specularBandV")
83
+ specular_offset = (
84
+ round(render_specular - reference_specular, 4)
85
+ if reference_specular is not None and render_specular is not None
86
+ else None
87
+ )
88
+
89
+ views[name] = {
90
+ "status": "compared",
91
+ "bands": bands,
92
+ "hairlineOffset": hairline_offset,
93
+ "specularOffset": specular_offset,
94
+ "hairFractionDelta": round(
95
+ render_view.get("hairFraction", 0.0) - reference_view.get("hairFraction", 0.0), 4
96
+ ),
97
+ }
98
+ return views
99
+
100
+
101
+ def hair_gate(
102
+ reference_views: dict[str, Path],
103
+ render_views: dict[str, Path],
104
+ scalp_exposure_report: dict[str, Any] | None = None,
105
+ ) -> dict[str, Any]:
106
+ """The whole hair verdict: one hard channel, several soft ones.
107
+
108
+ `scalp_exposure_report` is the output of `scalp_exposure.py`. It is optional only so this module
109
+ can be used on captures alone, and its absence is reported as a gap rather than treated as a
110
+ pass -- an image-only comparison cannot see a bald patch reliably, which is the entire reason
111
+ the geometric gate exists.
112
+ """
113
+ reference = extract_hair_evidence(reference_views)
114
+ render = extract_hair_evidence(render_views)
115
+ views = compare_views(reference, render)
116
+
117
+ hard: list[str] = []
118
+ soft: list[str] = []
119
+
120
+ if scalp_exposure_report is None:
121
+ soft.append(
122
+ "scalpExposure was not supplied; a pixel comparison cannot reliably see a bald patch, "
123
+ "so this verdict is incomplete. Run vg asset rebuild-object scalp-exposure."
124
+ )
125
+ elif scalp_exposure_report.get("verdict") == "fail":
126
+ hard.append(
127
+ f"scalpExposure {scalp_exposure_report.get('exposedFraction')} exceeds "
128
+ f"{scalp_exposure_report.get('hardMax')}: the skull is uncovered and will render bald. "
129
+ f"No coverage improvement elsewhere compensates for this."
130
+ )
131
+
132
+ for name, view in views.items():
133
+ if view.get("status") != "compared":
134
+ soft.append(f"{name}: {view.get('status')}")
135
+ continue
136
+ for band, data in view.get("bands", {}).items():
137
+ if data.get("shortfall"):
138
+ soft.append(
139
+ f"{name}/{band}: coverage {data['render']} against reference {data['reference']} "
140
+ f"(delta {data['delta']})"
141
+ )
142
+ offset = view.get("hairlineOffset")
143
+ if offset is not None and abs(offset) > HAIRLINE_OFFSET_MAX:
144
+ soft.append(f"{name}: hairline off by {offset} of figure height")
145
+ specular = view.get("specularOffset")
146
+ if specular is not None and abs(specular) > SPECULAR_OFFSET_MAX:
147
+ soft.append(
148
+ f"{name}: highlight band off by {specular} in scalp v; this is a MATERIAL "
149
+ f"difference, not a geometry one, and adding hair will not move it"
150
+ )
151
+
152
+ return {
153
+ "schemaVersion": 1,
154
+ "kind": "hair-gate",
155
+ "verdict": "fail" if hard else ("review" if soft else "pass"),
156
+ # Whether the HARD channel actually ran, kept separate from the verdict. "review" with the
157
+ # geometric gate present means "checked, here are notes"; "review" with it absent means "I
158
+ # could not check the one thing that is always a failure". Collapsing those two into one
159
+ # word let a run with no bald-patch check at all exit 0.
160
+ "hardChannelPresent": scalp_exposure_report is not None,
161
+ "hardFailures": hard,
162
+ "softSignals": soft,
163
+ "views": views,
164
+ "referenceNotObserved": reference.get("notObserved", []),
165
+ "renderNotObserved": render.get("notObserved", []),
166
+ "thresholds": {
167
+ "bandShortfallSoft": BAND_SHORTFALL_SOFT,
168
+ "hairlineOffsetMax": HAIRLINE_OFFSET_MAX,
169
+ "specularOffsetMax": SPECULAR_OFFSET_MAX,
170
+ "uncalibrated": True,
171
+ },
172
+ "note": (
173
+ "A band shortfall is a soft signal and never on its own authorises widening the masses. "
174
+ "That exact response was measured: widening took closure from 42.2% to 40.9%, worse on "
175
+ "all six views, because the widened mass slid off the skull rather than growing on it."
176
+ ),
177
+ }
178
+
179
+
180
+ def _pairs(entries: Sequence[str], parser: argparse.ArgumentParser) -> dict[str, Path]:
181
+ views: dict[str, Path] = {}
182
+ for entry in entries:
183
+ if "=" not in entry:
184
+ parser.error(f"expected view=path, got {entry!r}")
185
+ name, _, raw = entry.partition("=")
186
+ views[name] = Path(raw)
187
+ return views
188
+
189
+
190
+ def main(argv: Sequence[str] | None = None) -> int:
191
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
192
+ parser.add_argument("--reference", nargs="+", required=True, help="view=path pairs")
193
+ parser.add_argument("--render", nargs="+", required=True, help="view=path pairs")
194
+ parser.add_argument("--scalp-exposure", help="JSON report from scalp_exposure.py")
195
+ parser.add_argument("--out")
196
+ args = parser.parse_args(argv)
197
+
198
+ exposure = json.loads(Path(args.scalp_exposure).read_text()) if args.scalp_exposure else None
199
+ report = hair_gate(_pairs(args.reference, parser), _pairs(args.render, parser), exposure)
200
+ text = json.dumps(report, indent=2)
201
+ if args.out:
202
+ Path(args.out).write_text(text + "\n")
203
+ print(text)
204
+
205
+ # 1 = a hard failure. 2 = the hard channel never ran, so this verdict is incomplete and must not
206
+ # read as approval to a caller that only checks for zero. 0 = the hard gate ran and passed;
207
+ # soft signals alone do not fail a build, by design.
208
+ if report["verdict"] == "fail":
209
+ return 1
210
+ if not report["hardChannelPresent"]:
211
+ return 2
212
+ return 0
213
+
214
+
215
+ if __name__ == "__main__":
216
+ raise SystemExit(main())
@@ -0,0 +1,188 @@
1
+ #!/usr/bin/env python3
2
+ """Appearance difference INSIDE the silhouette, banded by height, against a baseline render.
3
+
4
+ Silhouette IoU is computed from the figure cells that lie on the outline -- about 11% of them at
5
+ grid 192. This reads the other 89%.
6
+
7
+ It exists because of a measured result, not a theory. A finished face and the same model with its
8
+ face deleted -- nose, mouth, eyes and both brows set invisible, hair material swapped for skin --
9
+ scored 0.8803 and 0.8803 on the outline metric, identical to four decimals. Adding an entire mouth
10
+ moved that metric by -0.0002, in the wrong direction. An outline metric cannot answer whether a face
11
+ is right, or even whether it is present, so it must not be the signal a correction loop optimises
12
+ for interior work.
13
+
14
+ Both renders are aligned by their foreground bounding box -- the same normalisation the IoU scorer
15
+ performs -- then resampled to a common lattice. Only cells that are figure in BOTH are compared, so
16
+ outline agreement cannot leak back in and inflate the result. The number is mean absolute luminance
17
+ difference as a fraction of full range: 0.000 is identical inside the mask, larger is further from
18
+ the baseline.
19
+
20
+ Restrict with --from/--to to read one region. On a standing figure the head is roughly the top 19%
21
+ of figure height, i.e. `--from 0 --to 0.19`.
22
+
23
+ BBOX CONVENTION. This module uses half-open corners `(x0, y0, x1, y1)`, matching
24
+ `objectness._bbox`. It deliberately does NOT use `diagnose_render.bbox_of`, which returns
25
+ `(x0, y0, width, height)` -- passing one where the other is expected produces confident garbage
26
+ rather than an error, and that exact substitution has already cost this project a debugging session.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import argparse
31
+ import json
32
+ import sys
33
+ from pathlib import Path
34
+ from typing import Any
35
+
36
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage1_intake"))
37
+ from extract_pbr_evidence import build_foreground_mask, load_image # noqa: E402
38
+
39
+ from diagnose_render import mask_is_inverted # noqa: E402
40
+
41
+ GRID = 192 # the lattice the audit's published numbers were computed on; changing it changes them
42
+
43
+
44
+ def _bbox_corners(mask: list[bool], width: int, height: int) -> tuple[int, int, int, int]:
45
+ """Half-open `(x0, y0, x1, y1)`. An empty mask returns the whole frame."""
46
+ min_x = min_y = 1 << 30
47
+ max_x = max_y = -1
48
+ for y in range(height):
49
+ row = y * width
50
+ for x in range(width):
51
+ if mask[row + x]:
52
+ if x < min_x:
53
+ min_x = x
54
+ if x > max_x:
55
+ max_x = x
56
+ if y < min_y:
57
+ min_y = y
58
+ if y > max_y:
59
+ max_y = y
60
+ if max_x < 0:
61
+ return (0, 0, width, height)
62
+ return (min_x, min_y, max_x + 1, max_y + 1)
63
+
64
+
65
+ def sample(png_path: Path, grid: int = GRID) -> tuple[list[float], list[bool], list[str]]:
66
+ """Per-cell mean channel value and figure-majority flag, over the foreground bounding box.
67
+
68
+ The cell value is an AREA MEAN, not a point sample. At grid 192 over a 1024px render each cell
69
+ covers roughly 5x5 source pixels; point sampling would alias hard edges and make the result
70
+ depend on where the lattice happened to land.
71
+ """
72
+ width, height, pixels, load_warnings = load_image(png_path)
73
+ mask, _diagnostics, mask_warnings = build_foreground_mask(width, height, pixels)
74
+ x0, y0, x1, y1 = _bbox_corners(mask, width, height)
75
+ box_w = max(1, x1 - x0)
76
+ box_h = max(1, y1 - y0)
77
+
78
+ values = [0.0] * (grid * grid)
79
+ solid = [False] * (grid * grid)
80
+ for gy in range(grid):
81
+ ys = y0 + gy * box_h // grid
82
+ ye = max(y0 + (gy + 1) * box_h // grid, ys + 1)
83
+ for gx in range(grid):
84
+ xs = x0 + gx * box_w // grid
85
+ xe = max(x0 + (gx + 1) * box_w // grid, xs + 1)
86
+ total = 0
87
+ counted = 0
88
+ foreground = 0
89
+ for y in range(ys, min(ye, height)):
90
+ row = y * width
91
+ for x in range(xs, min(xe, width)):
92
+ red, green, blue, _alpha = pixels[row + x]
93
+ total += red + green + blue
94
+ counted += 1
95
+ if mask[row + x]:
96
+ foreground += 1
97
+ index = gy * grid + gx
98
+ values[index] = (total / (3 * counted)) if counted else 0.0
99
+ solid[index] = bool(counted) and foreground > counted / 2
100
+ return values, solid, list(load_warnings) + list(mask_warnings)
101
+
102
+
103
+ def compare(
104
+ baseline_png: Path,
105
+ render_png: Path,
106
+ band_from: float = 0.0,
107
+ band_to: float = 1.0,
108
+ grid: int = GRID,
109
+ ) -> dict[str, Any]:
110
+ """Mean absolute luminance difference over cells that are figure in both, within a height band.
111
+
112
+ `cellsCompared` is reported alongside the score for the same reason every other gate here
113
+ reports its sample count: a small difference over four cells is not evidence.
114
+ """
115
+ baseline_values, baseline_solid, baseline_warnings = sample(baseline_png, grid)
116
+ render_values, render_solid, render_warnings = sample(render_png, grid)
117
+
118
+ first_row = int(band_from * grid)
119
+ last_row = max(int(band_to * grid), first_row + 1)
120
+ shared = [
121
+ gy * grid + gx
122
+ for gy in range(first_row, min(last_row, grid))
123
+ for gx in range(grid)
124
+ if baseline_solid[gy * grid + gx] and render_solid[gy * grid + gx]
125
+ ]
126
+
127
+ result: dict[str, Any] = {
128
+ "schemaVersion": 1,
129
+ "kind": "interior-difference",
130
+ "baseline": str(baseline_png),
131
+ "render": str(render_png),
132
+ "band": {"from": band_from, "to": band_to},
133
+ "grid": grid,
134
+ "cellsCompared": len(shared),
135
+ "warnings": baseline_warnings + render_warnings,
136
+ }
137
+ # Same hard refusal divine_eye makes. A mask that fell back to whole-frame coverage marks every
138
+ # cell solid, so this metric would compare background against background and return a confident
139
+ # number about nothing -- worse than the outline metric it replaces, because the number looks
140
+ # like interior evidence.
141
+ if mask_is_inverted(baseline_warnings) or mask_is_inverted(render_warnings):
142
+ result["interiorDifference"] = None
143
+ result["status"] = "foreground-mask-fell-back-to-whole-frame"
144
+ return result
145
+ if not shared:
146
+ result["interiorDifference"] = None
147
+ result["status"] = "no-overlapping-figure-cells"
148
+ return result
149
+
150
+ total = sum(abs(baseline_values[i] - render_values[i]) for i in shared)
151
+ result["interiorDifference"] = total / len(shared) / 255.0
152
+ result["status"] = "measured"
153
+ return result
154
+
155
+
156
+ def main(argv: list[str] | None = None) -> int:
157
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
158
+ parser.add_argument("baseline", type=Path)
159
+ parser.add_argument("renders", nargs="+", type=Path)
160
+ parser.add_argument("--from", dest="band_from", type=float, default=0.0)
161
+ parser.add_argument("--to", dest="band_to", type=float, default=1.0)
162
+ parser.add_argument("--grid", type=int, default=GRID)
163
+ parser.add_argument("--json", action="store_true")
164
+ args = parser.parse_args(argv)
165
+
166
+ results = [
167
+ compare(args.baseline, render, args.band_from, args.band_to, args.grid)
168
+ for render in args.renders
169
+ ]
170
+ if args.json:
171
+ print(json.dumps(results if len(results) > 1 else results[0], indent=2))
172
+ return 0
173
+
174
+ print(f"band y/H {args.band_from:.2f}..{args.band_to:.2f} vs {args.baseline.name}")
175
+ for result in results:
176
+ name = Path(result["render"]).name
177
+ if result["interiorDifference"] is None:
178
+ print(f" {name:<34} {result['status']}")
179
+ else:
180
+ print(
181
+ f" {name:<34} interior difference {result['interiorDifference']:.4f}"
182
+ f" ({result['cellsCompared']} cells)"
183
+ )
184
+ return 0
185
+
186
+
187
+ if __name__ == "__main__":
188
+ raise SystemExit(main())
@@ -0,0 +1,209 @@
1
+ #!/usr/bin/env python3
2
+ """Does the mesh carry enough edge loops at each joint to survive being bent?
3
+
4
+ A skinned joint with too few rings of geometry across it collapses when it flexes: the elbow pinches
5
+ into a crease, the knee loses its volume, the shoulder creases into a fold. No amount of weight
6
+ tuning fixes it, because there is simply nothing there to deform -- the vertices needed to describe a
7
+ bent surface do not exist.
8
+
9
+ The usual answer to this in a mesh-generation pipeline is retopology, and the honest industry position
10
+ is that automatic remeshing does NOT reliably produce deformation-grade topology; people still
11
+ retopologize by hand. But that constraint belongs to pipelines that receive a finished mesh. A
12
+ procedural generator writes its own topology, so it can place loops at joints BY CONSTRUCTION and
13
+ never need to repair them afterwards. This module is the gate that makes that a requirement rather
14
+ than a hope.
15
+
16
+ Method: for each joint, take the vertices within a radius of it, project them onto the bone axis, and
17
+ count how many distinct bands along that axis they occupy. Bands, not raw vertex count: ten thousand
18
+ vertices in two rings still cannot bend, and counting vertices would call that mesh dense and pass it.
19
+
20
+ The gate deliberately does not try to identify true quad edge loops. Recovering loop structure from a
21
+ triangle soup is fragile, and the property that actually matters for deformation -- enough
22
+ independently movable rings across the joint -- is exactly what band counting measures.
23
+
24
+ Pure Python 3.10+ stdlib.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import json
31
+ import math
32
+ import sys
33
+ from pathlib import Path
34
+ from typing import Any
35
+
36
+ MIN_LOOPS_PER_JOINT = 3
37
+ DEFAULT_RADIUS_SCALE = 0.35
38
+ BAND_TOLERANCE = 0.5
39
+
40
+
41
+ def _triangles(indices: list[Any]) -> list[tuple[int, int, int]]:
42
+ if indices and isinstance(indices[0], (list, tuple)):
43
+ return [(int(t[0]), int(t[1]), int(t[2])) for t in indices]
44
+ return [
45
+ (int(indices[i]), int(indices[i + 1]), int(indices[i + 2]))
46
+ for i in range(0, len(indices) - 2, 3)
47
+ ]
48
+
49
+
50
+ def _sub(a, b):
51
+ return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
52
+
53
+
54
+ def _dot(a, b):
55
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
56
+
57
+
58
+ def _norm(a):
59
+ return math.sqrt(_dot(a, a))
60
+
61
+
62
+ def count_loops_at_joint(
63
+ vertices: list[list[float]],
64
+ joint: list[float],
65
+ axis_start: list[float],
66
+ axis_end: list[float],
67
+ radius: float,
68
+ band_tolerance: float = BAND_TOLERANCE,
69
+ ) -> dict[str, Any]:
70
+ """Count distinct vertex bands along the bone axis within `radius` of the joint.
71
+
72
+ `band_tolerance` is a fraction of the mean gap between consecutive projections: two vertices
73
+ closer together than that are the same ring. Using an absolute epsilon instead would make the
74
+ count depend on the model's units, so the same character at two scales would score differently.
75
+ """
76
+ direction = _sub(axis_end, axis_start)
77
+ length = _norm(direction)
78
+ if length <= 1e-12:
79
+ return {"loops": 0, "vertexCount": 0, "reason": "bone has zero length"}
80
+ axis = [component / length for component in direction]
81
+
82
+ # An AXIAL window, not a sphere around the joint. A sphere drops rings simply because the limb is
83
+ # thick -- on a tube of radius 0.5 spanning a bone of length 2, the rings either side of the joint
84
+ # sit 0.707 away and a 0.7 sphere excludes every one of them, scoring a perfectly bendable joint
85
+ # as having a single loop. Thickness has nothing to do with whether a joint can bend; what matters
86
+ # is how many bands sit ALONG the bone near the joint. The radial cap only keeps unrelated
87
+ # geometry that happens to run parallel from being counted.
88
+ radial_cap = radius * 2.0
89
+ projections: list[float] = []
90
+ for vertex in vertices:
91
+ offset = _sub(vertex, joint)
92
+ along = _dot(offset, axis)
93
+ if abs(along) > radius:
94
+ continue
95
+ radial = math.sqrt(max(0.0, _dot(offset, offset) - along * along))
96
+ if radial > radial_cap:
97
+ continue
98
+ projections.append(along)
99
+ if len(projections) < 2:
100
+ return {"loops": len(projections), "vertexCount": len(projections)}
101
+
102
+ projections.sort()
103
+ span = projections[-1] - projections[0]
104
+ if span <= 1e-12:
105
+ return {"loops": 1, "vertexCount": len(projections)}
106
+ mean_gap = span / max(1, len(projections) - 1)
107
+ threshold = mean_gap * band_tolerance
108
+
109
+ loops = 1
110
+ previous = projections[0]
111
+ for value in projections[1:]:
112
+ if value - previous > threshold:
113
+ loops += 1
114
+ previous = value
115
+ return {"loops": loops, "vertexCount": len(projections), "axialSpan": round(span, 6)}
116
+
117
+
118
+ def analyze_joint_loops(
119
+ meshes: list[dict[str, Any]],
120
+ bones: list[dict[str, Any]],
121
+ min_loops: int = MIN_LOOPS_PER_JOINT,
122
+ radius_scale: float = DEFAULT_RADIUS_SCALE,
123
+ ) -> dict[str, Any]:
124
+ """Check every bone's joint against the pooled surface of all supplied meshes.
125
+
126
+ Pooled rather than per mesh: a joint often sits where two components meet, and asking each mesh
127
+ separately would let a joint pass because one half of it happens to be dense while the other has
128
+ nothing there at all.
129
+ """
130
+ pooled: list[list[float]] = []
131
+ for mesh in meshes:
132
+ vertices = mesh.get("vertices")
133
+ if isinstance(vertices, list):
134
+ pooled.extend(vertices)
135
+ if not pooled:
136
+ raise ValueError("no vertices supplied")
137
+
138
+ reports: list[dict[str, Any]] = []
139
+ failures: list[str] = []
140
+ for bone in bones:
141
+ joint = bone.get("jointPos")
142
+ tip = bone.get("tipPos")
143
+ if not isinstance(joint, list) or not isinstance(tip, list):
144
+ continue
145
+ bone_length = _norm(_sub(tip, joint))
146
+ radius = bone_length * radius_scale
147
+ measured = count_loops_at_joint(pooled, joint, joint, tip, radius)
148
+ record = {
149
+ "bone": str(bone.get("id")),
150
+ "radius": round(radius, 6),
151
+ "minLoops": min_loops,
152
+ **measured,
153
+ }
154
+ record["passes"] = measured["loops"] >= min_loops
155
+ if not record["passes"]:
156
+ failures.append(
157
+ f"{record['bone']}: {measured['loops']} loop(s) within {record['radius']} of the "
158
+ f"joint, needs {min_loops}; this joint will crease rather than bend"
159
+ )
160
+ reports.append(record)
161
+
162
+ return {
163
+ "joints": reports,
164
+ "failures": failures,
165
+ "jointCount": len(reports),
166
+ "failingJointCount": len(failures),
167
+ "passed": not failures,
168
+ "note": (
169
+ "loops are counted as distinct vertex bands along the bone axis, not as recovered quad "
170
+ "loops; a dense joint with only two bands still cannot bend and is reported as such"
171
+ ),
172
+ }
173
+
174
+
175
+ def _format_summary(result: dict[str, Any]) -> str:
176
+ lines = [f"joints checked: {result['jointCount']}"]
177
+ for record in result["joints"]:
178
+ flag = "ok" if record["passes"] else "TOO FEW LOOPS"
179
+ lines.append(
180
+ f" [{flag}] {record['bone']} loops={record['loops']} "
181
+ f"vertices={record['vertexCount']} radius={record['radius']}"
182
+ )
183
+ lines.append("verdict: PASS" if result["passed"] else "verdict: GATE FAILURE")
184
+ return "\n".join(lines)
185
+
186
+
187
+ def main(argv: list[str]) -> int:
188
+ parser = argparse.ArgumentParser(description="Check edge-loop density at rig joints.")
189
+ parser.add_argument("meshes", type=Path, help="JSON with a meshes array, or a single mesh")
190
+ parser.add_argument("--bones", type=Path, required=True)
191
+ parser.add_argument("--min-loops", type=int, default=MIN_LOOPS_PER_JOINT)
192
+ parser.add_argument("--radius-scale", type=float, default=DEFAULT_RADIUS_SCALE)
193
+ parser.add_argument("--json", action="store_true")
194
+ args = parser.parse_args(argv)
195
+ try:
196
+ payload = json.loads(args.meshes.read_text())
197
+ meshes = payload["meshes"] if isinstance(payload, dict) and isinstance(payload.get("meshes"), list) else [payload]
198
+ result = analyze_joint_loops(
199
+ meshes, json.loads(args.bones.read_text()), args.min_loops, args.radius_scale
200
+ )
201
+ except Exception as exc:
202
+ print(f"error: {exc}", file=sys.stderr)
203
+ return 2
204
+ print(json.dumps(result, indent=2) if args.json else _format_summary(result))
205
+ return 0 if result["passed"] else 1
206
+
207
+
208
+ if __name__ == "__main__":
209
+ raise SystemExit(main(sys.argv[1:]))