vibedgames 0.10.0 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/assets/rebuild-object/.cache/spec-search/core_3d.json +1 -0
  2. package/assets/rebuild-object/.cache/spec-search/cs2.json +1 -0
  3. package/assets/rebuild-object/LICENSE +201 -0
  4. package/assets/rebuild-object/NOTICE +7 -0
  5. package/assets/rebuild-object/docs/materials/material-reference.json +2324 -0
  6. package/assets/rebuild-object/docs/specs/render-profile.v2.example.json +63 -0
  7. package/assets/rebuild-object/docs/specs/render-profile.v2.schema.json +56 -0
  8. package/assets/rebuild-object/docs/specs/vocabulary/README.md +86 -0
  9. package/assets/rebuild-object/docs/specs/vocabulary/core_3d.jsonl +12 -0
  10. package/assets/rebuild-object/docs/specs/vocabulary/core_3d_reconstruction.jsonl +37 -0
  11. package/assets/rebuild-object/docs/specs/vocabulary/cs2.jsonl +8 -0
  12. package/assets/rebuild-object/docs/specs/vocabulary/cs2_reconstruction.jsonl +62 -0
  13. package/assets/rebuild-object/forge/_shared/artifact_cache.py +54 -0
  14. package/assets/rebuild-object/forge/_shared/chirality.py +272 -0
  15. package/assets/rebuild-object/forge/_shared/color_metrics.py +107 -0
  16. package/assets/rebuild-object/forge/_shared/feature_acceptance_policy.py +113 -0
  17. package/assets/rebuild-object/forge/_shared/image_hash.py +113 -0
  18. package/assets/rebuild-object/forge/_shared/jpeg.py +448 -0
  19. package/assets/rebuild-object/forge/_shared/material_physics.py +253 -0
  20. package/assets/rebuild-object/forge/_shared/pipeline_routing.py +177 -0
  21. package/assets/rebuild-object/forge/_shared/scalp_field.py +302 -0
  22. package/assets/rebuild-object/forge/_shared/sdf_primitives.py +172 -0
  23. package/assets/rebuild-object/forge/_shared/spec_search.py +1792 -0
  24. package/assets/rebuild-object/forge/_shared/spec_search_profiles.json +58 -0
  25. package/assets/rebuild-object/forge/_shared/status_banner.py +35 -0
  26. package/assets/rebuild-object/forge/_shared/subdivision.py +232 -0
  27. package/assets/rebuild-object/forge/_shared/vertex_paint.py +236 -0
  28. package/assets/rebuild-object/forge/_shared/workflow_state.py +406 -0
  29. package/assets/rebuild-object/forge/materials/__init__.py +17 -0
  30. package/assets/rebuild-object/forge/materials/compatibility.py +106 -0
  31. package/assets/rebuild-object/forge/materials/reference.py +240 -0
  32. package/assets/rebuild-object/forge/next.py +116 -0
  33. package/assets/rebuild-object/forge/report.py +38 -0
  34. package/assets/rebuild-object/forge/requirements.txt +6 -0
  35. package/assets/rebuild-object/forge/stage1_intake/analyze_texture.py +255 -0
  36. package/assets/rebuild-object/forge/stage1_intake/bind_detail_properties.py +99 -0
  37. package/assets/rebuild-object/forge/stage1_intake/build_detail_inventory.py +349 -0
  38. package/assets/rebuild-object/forge/stage1_intake/camera_fitting_math.py +133 -0
  39. package/assets/rebuild-object/forge/stage1_intake/camera_fitting_solver.py +197 -0
  40. package/assets/rebuild-object/forge/stage1_intake/camera_fitting_types.py +291 -0
  41. package/assets/rebuild-object/forge/stage1_intake/camera_image_helpers.py +133 -0
  42. package/assets/rebuild-object/forge/stage1_intake/check_intake_correctness.py +116 -0
  43. package/assets/rebuild-object/forge/stage1_intake/check_reference_admission.py +203 -0
  44. package/assets/rebuild-object/forge/stage1_intake/cs2_foundation.py +139 -0
  45. package/assets/rebuild-object/forge/stage1_intake/cs2_manifest.py +230 -0
  46. package/assets/rebuild-object/forge/stage1_intake/cs2_review_contract.py +42 -0
  47. package/assets/rebuild-object/forge/stage1_intake/delight_albedo.py +352 -0
  48. package/assets/rebuild-object/forge/stage1_intake/detect_cs2.py +276 -0
  49. package/assets/rebuild-object/forge/stage1_intake/detect_reference_effects.py +275 -0
  50. package/assets/rebuild-object/forge/stage1_intake/extract_cs2_textures.py +126 -0
  51. package/assets/rebuild-object/forge/stage1_intake/extract_gradient_stops.py +149 -0
  52. package/assets/rebuild-object/forge/stage1_intake/extract_hair_evidence.py +385 -0
  53. package/assets/rebuild-object/forge/stage1_intake/extract_landmarks.py +456 -0
  54. package/assets/rebuild-object/forge/stage1_intake/extract_part_color_recipe.py +496 -0
  55. package/assets/rebuild-object/forge/stage1_intake/extract_pbr_evidence.py +843 -0
  56. package/assets/rebuild-object/forge/stage1_intake/fetch_cs2_metadata.py +147 -0
  57. package/assets/rebuild-object/forge/stage1_intake/label_glb_nodes.py +318 -0
  58. package/assets/rebuild-object/forge/stage1_intake/locate_cs2_vpk.py +73 -0
  59. package/assets/rebuild-object/forge/stage1_intake/material_region_analysis.py +227 -0
  60. package/assets/rebuild-object/forge/stage1_intake/probe_glb.py +357 -0
  61. package/assets/rebuild-object/forge/stage1_intake/probe_image.py +168 -0
  62. package/assets/rebuild-object/forge/stage1_intake/run_vision_adapter.py +45 -0
  63. package/assets/rebuild-object/forge/stage1_intake/search_specs.py +258 -0
  64. package/assets/rebuild-object/forge/stage1_intake/semantic_decomposition.py +119 -0
  65. package/assets/rebuild-object/forge/stage1_intake/solve_camera_pose.py +254 -0
  66. package/assets/rebuild-object/forge/stage2_spec/apply_material_analysis.py +192 -0
  67. package/assets/rebuild-object/forge/stage2_spec/cs2_adapters.py +62 -0
  68. package/assets/rebuild-object/forge/stage2_spec/derive_geometry.py +118 -0
  69. package/assets/rebuild-object/forge/stage2_spec/hair_profile.py +306 -0
  70. package/assets/rebuild-object/forge/stage2_spec/humanoid_proportions.py +214 -0
  71. package/assets/rebuild-object/forge/stage2_spec/new_pre_spec_assessment.py +343 -0
  72. package/assets/rebuild-object/forge/stage2_spec/new_sculpt_spec.py +2396 -0
  73. package/assets/rebuild-object/forge/stage2_spec/validate_sculpt_spec.py +2871 -0
  74. package/assets/rebuild-object/forge/stage3_build/bake_projected_texture.py +181 -0
  75. package/assets/rebuild-object/forge/stage3_build/decimate.py +272 -0
  76. package/assets/rebuild-object/forge/stage3_build/generate_threejs_factory.py +4099 -0
  77. package/assets/rebuild-object/forge/stage3_build/module_cache.py +155 -0
  78. package/assets/rebuild-object/forge/stage3_build/morph_targets.py +178 -0
  79. package/assets/rebuild-object/forge/stage3_build/orchestrate_passes.py +653 -0
  80. package/assets/rebuild-object/forge/stage3_build/uv_unwrap.py +622 -0
  81. package/assets/rebuild-object/forge/stage3_build/visual_hull.py +357 -0
  82. package/assets/rebuild-object/forge/stage4_review/_fit_divine_eye.py +64 -0
  83. package/assets/rebuild-object/forge/stage4_review/append_review.py +453 -0
  84. package/assets/rebuild-object/forge/stage4_review/attachment_anchor.py +349 -0
  85. package/assets/rebuild-object/forge/stage4_review/calibrate_eye.py +131 -0
  86. package/assets/rebuild-object/forge/stage4_review/check_part_coverage.py +298 -0
  87. package/assets/rebuild-object/forge/stage4_review/compare_region_passes.py +169 -0
  88. package/assets/rebuild-object/forge/stage4_review/correction_loop.py +258 -0
  89. package/assets/rebuild-object/forge/stage4_review/cs2_review.py +224 -0
  90. package/assets/rebuild-object/forge/stage4_review/diagnose_render.py +356 -0
  91. package/assets/rebuild-object/forge/stage4_review/diagnose_render_multi_angle.py +143 -0
  92. package/assets/rebuild-object/forge/stage4_review/divine_eye.py +461 -0
  93. package/assets/rebuild-object/forge/stage4_review/fit_params.py +381 -0
  94. package/assets/rebuild-object/forge/stage4_review/geometry_integrity.py +294 -0
  95. package/assets/rebuild-object/forge/stage4_review/hair_gate.py +216 -0
  96. package/assets/rebuild-object/forge/stage4_review/interior_difference.py +188 -0
  97. package/assets/rebuild-object/forge/stage4_review/joint_loops.py +209 -0
  98. package/assets/rebuild-object/forge/stage4_review/make_comparison_sheet.py +292 -0
  99. package/assets/rebuild-object/forge/stage4_review/material_comparator.py +181 -0
  100. package/assets/rebuild-object/forge/stage4_review/material_feedback.py +143 -0
  101. package/assets/rebuild-object/forge/stage4_review/material_gate.py +126 -0
  102. package/assets/rebuild-object/forge/stage4_review/material_views.py +184 -0
  103. package/assets/rebuild-object/forge/stage4_review/mesh_reference_compare.py +362 -0
  104. package/assets/rebuild-object/forge/stage4_review/multi_pass.py +102 -0
  105. package/assets/rebuild-object/forge/stage4_review/objectness.py +143 -0
  106. package/assets/rebuild-object/forge/stage4_review/pairwise_penetration.py +376 -0
  107. package/assets/rebuild-object/forge/stage4_review/per_feature.py +215 -0
  108. package/assets/rebuild-object/forge/stage4_review/render_bridge.py +556 -0
  109. package/assets/rebuild-object/forge/stage4_review/scalp_exposure.py +257 -0
  110. package/assets/rebuild-object/forge/stage4_review/self_intersection.py +592 -0
  111. package/assets/rebuild-object/forge/stage4_review/swept_arc_gate.py +336 -0
  112. package/assets/rebuild-object/forge/stage4_review/turntable_gate.py +415 -0
  113. package/assets/rebuild-object/forge/stage4_review/validate_render_profile.py +182 -0
  114. package/assets/rebuild-object/forge/stage4_review/vertex_region_gate.py +456 -0
  115. package/assets/rebuild-object/forge/stage4_review/vlm_gate.py +196 -0
  116. package/assets/rebuild-object/forge/stage5_rig/NOTES.md +149 -0
  117. package/assets/rebuild-object/forge/stage5_rig/__init__.py +6 -0
  118. package/assets/rebuild-object/forge/stage5_rig/emit_rig.py +420 -0
  119. package/assets/rebuild-object/forge/stage5_rig/geodesic_skinning.py +508 -0
  120. package/assets/rebuild-object/forge/stage5_rig/rig_spec.py +174 -0
  121. package/assets/rebuild-object/forge/stage5_rig/validate_rig_payload.py +195 -0
  122. package/assets/rebuild-object/forge/state.py +98 -0
  123. package/assets/rebuild-object/steps.json +381 -0
  124. package/dist/{chunk-FXXVXDTW.js → chunk-24TITAFS.js} +1 -1
  125. package/dist/{chunk-OGX4DKIS.js → chunk-2C5PG2QO.js} +1 -1
  126. package/dist/{chunk-HYOXGNWS.js → chunk-2DEVOKI7.js} +1 -1
  127. package/dist/{chunk-RRI23NK2.js → chunk-2GHPYT2P.js} +1 -1
  128. package/dist/{chunk-S7HYWITX.js → chunk-2HXGMXGC.js} +1 -1
  129. package/dist/{chunk-N2UHAQXC.js → chunk-36FORP7T.js} +0 -1
  130. package/dist/{chunk-VB4WLJR2.js → chunk-3IXRQTRF.js} +1 -1
  131. package/dist/{chunk-2KVQJKIZ.js → chunk-4ENHS32B.js} +23 -36
  132. package/dist/{chunk-SXYQL4GK.js → chunk-4YHA32OE.js} +1 -1
  133. package/dist/{chunk-4FJXCS3K.js → chunk-4ZGQKPK5.js} +1 -1
  134. package/dist/{chunk-SBXCK2I2.js → chunk-6CLUPFQA.js} +2 -2
  135. package/dist/{chunk-TXOE5UY5.js → chunk-7WTF2BA4.js} +1 -1
  136. package/dist/{chunk-R2WVORGD.js → chunk-AAXZNK4Z.js} +1 -1
  137. package/dist/{chunk-DOOQUFPG.js → chunk-ALLBT4FB.js} +1 -1
  138. package/dist/{chunk-HRKVAXNN.js → chunk-BAZDPPIG.js} +5 -5
  139. package/dist/{chunk-RPJR3S5S.js → chunk-CYDENLZ4.js} +5 -8
  140. package/dist/{chunk-I5LELJSK.js → chunk-DKSUD44G.js} +1 -1
  141. package/dist/{chunk-43P4U7CB.js → chunk-DWWSJKTE.js} +1 -1
  142. package/dist/{chunk-SUSX3QIA.js → chunk-E72TFJZP.js} +1 -1
  143. package/dist/{chunk-E3FJUPLT.js → chunk-EUAAQMUA.js} +2 -0
  144. package/dist/{chunk-U6DTE5IX.js → chunk-F7LYJSZE.js} +1 -1
  145. package/dist/{chunk-MEAO33XW.js → chunk-FMON3C74.js} +8 -8
  146. package/dist/{chunk-GLEW7VJQ.js → chunk-FPILHRLZ.js} +1 -1
  147. package/dist/{chunk-OPUCUUID.js → chunk-G63MXDX2.js} +4 -0
  148. package/dist/{chunk-4UU622RK.js → chunk-GGO6ZYYI.js} +1 -3
  149. package/dist/{chunk-2ZKS7V72.js → chunk-GZCRYYS6.js} +5 -5
  150. package/dist/{chunk-E7NDOZ27.js → chunk-LE4GVTYI.js} +8 -8
  151. package/dist/{chunk-RKS7SI5L.js → chunk-NO6KPV64.js} +1 -1
  152. package/dist/{chunk-KJK5CB6E.js → chunk-NXW3Z4Y4.js} +1 -1
  153. package/dist/{chunk-7RPLQWR2.js → chunk-OHOAZGO4.js} +1 -1
  154. package/dist/chunk-PYJNI5WD.js +83 -0
  155. package/dist/{chunk-NCX6LYNJ.js → chunk-Q4XAGTFX.js} +1 -1
  156. package/dist/{chunk-3UGGMFJJ.js → chunk-QMZBSVKF.js} +1 -1
  157. package/dist/{chunk-ABTUEIRC.js → chunk-QO66UBOS.js} +2 -2
  158. package/dist/{chunk-LONQWRTR.js → chunk-S4KVGQQO.js} +8 -8
  159. package/dist/{chunk-HX5Q63UA.js → chunk-T777EXAO.js} +1 -1
  160. package/dist/{chunk-UQ7VO6B3.js → chunk-TZZNRA3S.js} +1 -1
  161. package/dist/{chunk-CTY2WZQK.js → chunk-UC3QLWMQ.js} +1 -1
  162. package/dist/{chunk-MR5KIFI7.js → chunk-UDJH2RED.js} +3 -3
  163. package/dist/{chunk-ZHLPE6LI.js → chunk-UIKYK7KI.js} +1 -1
  164. package/dist/{chunk-KAGVI3CE.js → chunk-UJRSQO2B.js} +1 -1
  165. package/dist/{chunk-Q2QC6KAZ.js → chunk-V7LEYVXB.js} +29 -25
  166. package/dist/{chunk-DB7WVFS7.js → chunk-WRMQEXUC.js} +1 -1
  167. package/dist/{chunk-HSMG6U7J.js → chunk-WXSBNC67.js} +3 -9
  168. package/dist/{chunk-QLCVLCPM.js → chunk-X4QIOXNQ.js} +1 -1
  169. package/dist/{chunk-5YPLKGY3.js → chunk-Y6WHUK2O.js} +1 -1
  170. package/dist/{chunk-VZEJ2ZHE.js → chunk-Z3E7ORGQ.js} +5 -5
  171. package/dist/index.js +20 -20
  172. package/package.json +32 -22
  173. package/dist/{chunk-Q3XQPNF6.js → chunk-BN7TR6OR.js} +3 -3
  174. package/dist/{chunk-LORGE2NB.js → chunk-U2NCN5RO.js} +3 -3
  175. package/dist/{chunk-UPHB5HWO.js → chunk-VQTTSPA3.js} +3 -3
@@ -0,0 +1,126 @@
1
+ #!/usr/bin/env python3
2
+ """Blocking acceptance gate for the wired material pipeline."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ ROOT = Path(__file__).resolve().parents[2]
13
+ sys.path.insert(0, str(ROOT / "forge"))
14
+ from materials.compatibility import check_compatibility # noqa: E402
15
+
16
+
17
+ def run_material_gate(
18
+ spec: dict[str, Any],
19
+ *,
20
+ analysis: dict[str, Any] | None = None,
21
+ comparisons: list[dict[str, Any]] | None = None,
22
+ view_plan: dict[str, Any] | None = None,
23
+ require_visual_evidence: bool = True,
24
+ ) -> dict[str, Any]:
25
+ failures: list[str] = []
26
+ warnings: list[str] = []
27
+ pipeline = spec.get("materialPipeline")
28
+ if not isinstance(pipeline, dict):
29
+ failures.append("spec is not wired to materialPipeline")
30
+ elif pipeline.get("status") != "proceed":
31
+ failures.append(f"materialPipeline status is {pipeline.get('status')!r}, not proceed")
32
+ if isinstance(pipeline, dict):
33
+ for item in pipeline.get("unresolvedNotObservedMaterials", []):
34
+ if isinstance(item, dict):
35
+ failures.append(
36
+ f"material {item.get('materialId')!r} is not observed: "
37
+ f"{item.get('reason', 'additional reference required')}"
38
+ )
39
+ if analysis is not None and analysis.get("status") != "proceed":
40
+ failures.append(f"material analysis status is {analysis.get('status')!r}, not proceed")
41
+ regions = pipeline.get("regions", []) if isinstance(pipeline, dict) else []
42
+ if not isinstance(regions, list) or not regions:
43
+ failures.append("no material regions are available for gating")
44
+ else:
45
+ for region in regions:
46
+ if not isinstance(region, dict):
47
+ failures.append("materialPipeline contains a malformed region")
48
+ continue
49
+ if region.get("status") != "proceed":
50
+ failures.append(f"region {region.get('regionId')!r} is not proceed")
51
+ comparison_records = comparisons or []
52
+ if require_visual_evidence and not comparison_records:
53
+ failures.append("no material crop comparison evidence was supplied")
54
+ for comparison in comparison_records:
55
+ if not comparison.get("passed"):
56
+ failures.append(
57
+ f"material comparison failed for {comparison.get('materialId')!r}: "
58
+ + ", ".join(comparison.get("mismatches", []))
59
+ )
60
+ if view_plan is not None:
61
+ views = view_plan.get("views", [])
62
+ if not isinstance(views, list) or len(views) < 4:
63
+ failures.append("material view plan must contain at least four camera azimuths/views")
64
+ captures = view_plan.get("captureValidation", [])
65
+ if require_visual_evidence and captures and any(not item.get("passed") for item in captures if isinstance(item, dict)):
66
+ failures.append("one or more saved material captures failed readback/coverage validation")
67
+ environment = view_plan.get("environment")
68
+ if not isinstance(environment, dict) or environment.get("required") is not True:
69
+ failures.append("controlled material views must require a stable environment")
70
+ compatibility = check_compatibility(spec)
71
+ failures.extend(f"compatibility: {item}" for item in compatibility["failures"])
72
+ warnings.extend(compatibility["warnings"])
73
+ return {
74
+ "schemaVersion": 1,
75
+ "kind": "img2threejs.material-gate",
76
+ "passed": not failures,
77
+ "failures": failures,
78
+ "warnings": warnings,
79
+ "comparisonCount": len(comparison_records),
80
+ "compatibility": compatibility,
81
+ "requiredEvidence": [
82
+ "materialPipeline.status=proceed",
83
+ "all material regions status=proceed",
84
+ "per-region crop comparison passed",
85
+ "multi-angle controlled view plan and screenshot readback",
86
+ "geometry/UV/skinning/collision/LOD material ID compatibility passed",
87
+ ],
88
+ }
89
+
90
+
91
+ def main(argv: list[str]) -> int:
92
+ parser = argparse.ArgumentParser(description=__doc__)
93
+ parser.add_argument("spec", type=Path)
94
+ parser.add_argument("--analysis", type=Path)
95
+ parser.add_argument("--comparison", type=Path, action="append", default=[])
96
+ parser.add_argument("--view-plan", type=Path)
97
+ parser.add_argument("--out", type=Path, required=True)
98
+ parser.add_argument("--in-place", action="store_true", help="record materialGate on the spec")
99
+ parser.add_argument("--allow-no-visual-evidence", action="store_true")
100
+ args = parser.parse_args(argv)
101
+ try:
102
+ spec = json.loads(args.spec.read_text(encoding="utf-8"))
103
+ analysis = json.loads(args.analysis.read_text(encoding="utf-8")) if args.analysis else None
104
+ comparisons = [json.loads(path.read_text(encoding="utf-8")) for path in args.comparison]
105
+ view_plan = json.loads(args.view_plan.read_text(encoding="utf-8")) if args.view_plan else None
106
+ result = run_material_gate(
107
+ spec,
108
+ analysis=analysis,
109
+ comparisons=comparisons,
110
+ view_plan=view_plan,
111
+ require_visual_evidence=not args.allow_no_visual_evidence,
112
+ )
113
+ if args.in_place:
114
+ spec["materialGate"] = result
115
+ args.spec.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
116
+ args.out.parent.mkdir(parents=True, exist_ok=True)
117
+ args.out.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
118
+ print(json.dumps({"passed": result["passed"], "failures": result["failures"], "out": str(args.out.resolve())}, indent=2))
119
+ return 0 if result["passed"] else 2
120
+ except Exception as exc:
121
+ print(f"error: {exc}", file=sys.stderr)
122
+ return 1
123
+
124
+
125
+ if __name__ == "__main__":
126
+ raise SystemExit(main(sys.argv[1:]))
@@ -0,0 +1,184 @@
1
+ #!/usr/bin/env python3
2
+ """Build deterministic material camera/crop/microscope review plans.
3
+
4
+ The forge cannot invent a browser screenshot, but it can make the required
5
+ camera contract explicit and validate every crop before a renderer or vision
6
+ provider consumes it. A showcase/browser adapter uses the emitted plan to
7
+ capture the same views across iterations.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import math
15
+ import sys
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ ROOT = Path(__file__).resolve().parents[2]
20
+ sys.path.insert(0, str(ROOT / "forge" / "stage1_intake"))
21
+ from extract_pbr_evidence import build_foreground_mask, load_image, write_png_rgb # noqa: E402
22
+
23
+
24
+ DEFAULT_AZIMUTHS = (0.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0)
25
+ DEFAULT_VALIDATION_VIEWS = (
26
+ "albedo-unlit", "neutral-studio", "grazing", "environment-reflection", "reference-beauty"
27
+ )
28
+
29
+
30
+ def _norm(value: float) -> float:
31
+ return round(float(value) % 360.0, 3)
32
+
33
+
34
+ def build_view_plan(
35
+ component_id: str,
36
+ region_id: str,
37
+ *,
38
+ validation_views: list[str] | None = None,
39
+ azimuths: tuple[float, ...] = DEFAULT_AZIMUTHS,
40
+ elevation: float = 8.0,
41
+ zoom: float = 2.5,
42
+ target: tuple[float, float, float] = (0.0, 0.0, 0.0),
43
+ required_transmission: bool = False,
44
+ ) -> dict[str, Any]:
45
+ views = list(validation_views or DEFAULT_VALIDATION_VIEWS)
46
+ if required_transmission and "backlight-transmission" not in views:
47
+ views.append("backlight-transmission")
48
+ captures: list[dict[str, Any]] = []
49
+ for view_name in views:
50
+ for azimuth in azimuths:
51
+ captures.append({
52
+ "id": f"{region_id}-{view_name}-{int(_norm(azimuth)):03d}",
53
+ "componentId": component_id,
54
+ "regionId": region_id,
55
+ "view": view_name,
56
+ "camera": {
57
+ "azimuthDegrees": _norm(azimuth),
58
+ "elevationDegrees": elevation,
59
+ "rollDegrees": 0.0,
60
+ "target": list(target),
61
+ "zoom": zoom,
62
+ },
63
+ "cropPolicy": {
64
+ "mode": "visible-footprint",
65
+ "paddingFraction": 0.12,
66
+ "minCoverage": 0.03,
67
+ "maxCoverage": 0.92,
68
+ "microscope": view_name in {"grazing", "environment-reflection", "backlight-transmission"},
69
+ },
70
+ })
71
+ return {
72
+ "schemaVersion": 1,
73
+ "kind": "img2threejs.material-view-plan",
74
+ "componentId": component_id,
75
+ "regionId": region_id,
76
+ "environment": {
77
+ "required": True,
78
+ "prefilter": "PMREMGenerator",
79
+ "workingColorSpace": "LinearSRGBColorSpace",
80
+ "displayColorSpace": "SRGBColorSpace",
81
+ "toneMapping": "ACESFilmicToneMapping",
82
+ "exposure": 1.0,
83
+ "stableHash": "img2threejs-material-neutral-studio-v1",
84
+ },
85
+ "views": captures,
86
+ "captureRequirements": [
87
+ "save PNG/JPEG to workspace",
88
+ "read the saved image back before scoring",
89
+ "record renderer version, environment hash and camera transform",
90
+ "compare the full visible component footprint, not an isolated hidden surface",
91
+ ],
92
+ }
93
+
94
+
95
+ def crop_visible_footprint(source: Path, bbox: dict[str, Any], output: Path, padding_fraction: float = 0.12) -> dict[str, Any]:
96
+ width, height, pixels, warnings = load_image(source)
97
+ required = ("x", "y", "width", "height")
98
+ if not isinstance(bbox, dict) or not all(isinstance(bbox.get(key), (int, float)) for key in required):
99
+ raise ValueError("visible-footprint bbox requires x, y, width and height")
100
+ x, y, box_width, box_height = (float(bbox[key]) for key in required)
101
+ if bbox.get("normalized") is True:
102
+ x, box_width = x * width, box_width * width
103
+ y, box_height = y * height, box_height * height
104
+ pad_x = box_width * max(0.0, padding_fraction)
105
+ pad_y = box_height * max(0.0, padding_fraction)
106
+ x0 = max(0, math.floor(x - pad_x))
107
+ y0 = max(0, math.floor(y - pad_y))
108
+ x1 = min(width, math.ceil(x + box_width + pad_x))
109
+ y1 = min(height, math.ceil(y + box_height + pad_y))
110
+ crop_width, crop_height = x1 - x0, y1 - y0
111
+ if crop_width < 8 or crop_height < 8:
112
+ raise ValueError("visible footprint crop is too small")
113
+ rgb = bytearray()
114
+ for row in range(y0, y1):
115
+ for column in range(x0, x1):
116
+ red, green, blue, alpha = pixels[row * width + column]
117
+ rgb.extend((red, green, blue) if alpha >= 16 else (0, 0, 0))
118
+ write_png_rgb(output, crop_width, crop_height, bytes(rgb))
119
+ mask, diagnostics, mask_warnings = build_foreground_mask(crop_width, crop_height, [(*rgb[i:i + 3], 255) for i in range(0, len(rgb), 3)])
120
+ coverage = sum(mask) / max(1, len(mask))
121
+ if coverage < 0.03:
122
+ raise ValueError("visible footprint crop contains too little foreground")
123
+ return {
124
+ "path": str(output.resolve()),
125
+ "bbox": {"x": x0, "y": y0, "width": crop_width, "height": crop_height},
126
+ "coverage": round(coverage, 4),
127
+ "diagnostics": diagnostics,
128
+ "warnings": warnings + mask_warnings,
129
+ "readback": {"width": crop_width, "height": crop_height, "pixels": crop_width * crop_height},
130
+ }
131
+
132
+
133
+ def validate_capture(path: Path, *, min_width: int = 64, min_height: int = 64) -> dict[str, Any]:
134
+ width, height, pixels, warnings = load_image(path)
135
+ mask, diagnostics, mask_warnings = build_foreground_mask(width, height, pixels)
136
+ coverage = sum(mask) / max(1, len(mask))
137
+ failures: list[str] = []
138
+ if width < min_width or height < min_height:
139
+ failures.append(f"capture is {width}x{height}; minimum is {min_width}x{min_height}")
140
+ if coverage < 0.03:
141
+ failures.append("capture foreground coverage is below 3%")
142
+ return {
143
+ "path": str(path.resolve()),
144
+ "readable": True,
145
+ "width": width,
146
+ "height": height,
147
+ "foregroundCoverage": round(coverage, 4),
148
+ "diagnostics": diagnostics,
149
+ "warnings": warnings + mask_warnings,
150
+ "passed": not failures,
151
+ "failures": failures,
152
+ }
153
+
154
+
155
+ def main(argv: list[str]) -> int:
156
+ parser = argparse.ArgumentParser(description=__doc__)
157
+ parser.add_argument("--component-id", required=True)
158
+ parser.add_argument("--region-id", required=True)
159
+ parser.add_argument("--out", type=Path, required=True)
160
+ parser.add_argument("--validation-view", action="append", dest="validation_views")
161
+ parser.add_argument("--transmission", action="store_true")
162
+ parser.add_argument("--capture", type=Path, action="append", default=[])
163
+ args = parser.parse_args(argv)
164
+ try:
165
+ result = build_view_plan(
166
+ args.component_id,
167
+ args.region_id,
168
+ validation_views=args.validation_views,
169
+ required_transmission=args.transmission,
170
+ )
171
+ if args.capture:
172
+ result["captureValidation"] = [validate_capture(path) for path in args.capture]
173
+ result["capturePassed"] = all(item["passed"] for item in result["captureValidation"])
174
+ args.out.parent.mkdir(parents=True, exist_ok=True)
175
+ args.out.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
176
+ print(json.dumps({"out": str(args.out.resolve()), "views": len(result["views"]), "capturePassed": result.get("capturePassed", True)}, indent=2))
177
+ return 0 if result.get("capturePassed", True) else 2
178
+ except Exception as exc:
179
+ print(f"error: {exc}", file=sys.stderr)
180
+ return 1
181
+
182
+
183
+ if __name__ == "__main__":
184
+ raise SystemExit(main(sys.argv[1:]))
@@ -0,0 +1,362 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Compare a candidate mesh against a reference mesh, band by band, and say WHERE it is wrong.
4
+
5
+ This exists because every silhouette comparison in this project so far has measured something other
6
+ than what it claimed. The ground plane sat inside the foreground mask; the capture clipped both
7
+ subjects at the frame edge so their aspect ratios agreed by construction; and three separate attempts
8
+ sliced both models into height bands measured down from the top of the bounding box -- where this
9
+ model's top is a single ear tip and the reference's is two ears side by side, so every band below was
10
+ offset and the numbers described the misalignment rather than the shapes.
11
+
12
+ Three decisions follow from that history:
13
+
14
+ FEET, NOT BBOX TOP. Both meshes are translated so their lowest point is 0 and scaled so their height
15
+ is 1. The ground is a landmark both subjects genuinely share; the top of the bounding box is whatever
16
+ happens to poke up highest, which is exactly the thing that differs.
17
+
18
+ PERCENTILES, NOT EXTREMES. A staff is long, thin and contributes very few vertices, but it dominates
19
+ any min/max width. The 5th-95th percentile of each band reports the BODY, which is what proportion
20
+ work needs; the raw extent is still reported alongside so a genuine prop difference stays visible.
21
+
22
+ CENTROID OFFSET, NOT ONLY WIDTH. Two bands can be the same width and still be in different places.
23
+ Reporting the lateral and depth centroid of each band catches a limb that is the right size and the
24
+ wrong side -- a defect a width-only comparison passes silently.
25
+
26
+ Reads .glb (uncompressed) with the standard library only, per this package's no-dependency rule.
27
+
28
+ Usage:
29
+ mesh_reference_compare.py REFERENCE.glb CANDIDATE.glb [--bands N] [--json]
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import argparse
34
+ import json
35
+ import struct
36
+ import sys
37
+ from pathlib import Path
38
+
39
+ GLB_MAGIC = 0x46546C67
40
+ CHUNK_JSON = 0x4E4F534A
41
+ CHUNK_BIN = 0x004E4942
42
+ FLOAT32 = 5126
43
+ COMPONENTS = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4}
44
+
45
+
46
+ def read_glb_positions(path: Path) -> list[tuple[float, float, float]]:
47
+ """Every POSITION vertex in the file, in node-transformed world space.
48
+
49
+ Node transforms are applied because a mesh parked under a translated or scaled node would
50
+ otherwise be compared in the wrong place — and that failure looks like a proportion error.
51
+ """
52
+ data = path.read_bytes()
53
+ magic, _version, _length = struct.unpack_from("<III", data, 0)
54
+ if magic != GLB_MAGIC:
55
+ sys.exit(f"{path} is not a GLB")
56
+
57
+ offset, gltf, binary = 12, None, None
58
+ while offset < len(data):
59
+ chunk_len, chunk_type = struct.unpack_from("<II", data, offset)
60
+ body = data[offset + 8: offset + 8 + chunk_len]
61
+ if chunk_type == CHUNK_JSON:
62
+ gltf = json.loads(body)
63
+ elif chunk_type == CHUNK_BIN:
64
+ binary = body
65
+ offset += 8 + chunk_len + (-chunk_len % 4)
66
+
67
+ if gltf is None or binary is None:
68
+ sys.exit(f"{path}: missing JSON or BIN chunk")
69
+ required = gltf.get("extensionsRequired", [])
70
+ if any("draco" in e.lower() or "meshopt" in e.lower() for e in required):
71
+ sys.exit(f"{path}: compressed ({required}); this reader handles uncompressed GLB only")
72
+
73
+ views, accessors = gltf.get("bufferViews", []), gltf.get("accessors", [])
74
+
75
+ def read_accessor(index: int) -> list[tuple[float, float, float]]:
76
+ acc = accessors[index]
77
+ if acc.get("componentType") != FLOAT32 or acc.get("type") != "VEC3":
78
+ sys.exit(f"{path}: POSITION accessor {index} is not float32 VEC3")
79
+ view = views[acc["bufferView"]]
80
+ start = view.get("byteOffset", 0) + acc.get("byteOffset", 0)
81
+ stride = view.get("byteStride") or 12
82
+ out = []
83
+ for i in range(acc["count"]):
84
+ out.append(struct.unpack_from("<3f", binary, start + i * stride))
85
+ return out
86
+
87
+ # Full 4x4 composition, because the two shortcuts here were both wrong.
88
+ #
89
+ # The first version handled only translation and uniform scale and IGNORED node rotation
90
+ # entirely -- a rotated limb would have been measured in the wrong place with no complaint. The
91
+ # second refused any node carrying a `matrix`, which is exactly how three.js's GLTFExporter
92
+ # writes this project's own model, so the candidate could not be read at all. Composing real
93
+ # matrices removes both special cases.
94
+ nodes = gltf.get("nodes", [])
95
+ meshes = gltf.get("meshes", [])
96
+ points: list[tuple[float, float, float]] = []
97
+
98
+ def local_matrix(node: dict) -> list[float]:
99
+ if "matrix" in node:
100
+ return list(node["matrix"]) # glTF stores column-major
101
+ tx, ty, tz = node.get("translation", [0.0, 0.0, 0.0])
102
+ qx, qy, qz, qw = node.get("rotation", [0.0, 0.0, 0.0, 1.0])
103
+ sx, sy, sz = node.get("scale", [1.0, 1.0, 1.0])
104
+ xx, yy, zz = qx * qx, qy * qy, qz * qz
105
+ xy, xz, yz = qx * qy, qx * qz, qy * qz
106
+ wx, wy, wz = qw * qx, qw * qy, qw * qz
107
+ return [
108
+ (1 - 2 * (yy + zz)) * sx, (2 * (xy + wz)) * sx, (2 * (xz - wy)) * sx, 0.0,
109
+ (2 * (xy - wz)) * sy, (1 - 2 * (xx + zz)) * sy, (2 * (yz + wx)) * sy, 0.0,
110
+ (2 * (xz + wy)) * sz, (2 * (yz - wx)) * sz, (1 - 2 * (xx + yy)) * sz, 0.0,
111
+ tx, ty, tz, 1.0,
112
+ ]
113
+
114
+ def multiply(a: list[float], b: list[float]) -> list[float]:
115
+ out = [0.0] * 16
116
+ for col in range(4):
117
+ for row in range(4):
118
+ out[col * 4 + row] = sum(a[k * 4 + row] * b[col * 4 + k] for k in range(4))
119
+ return out
120
+
121
+ def apply(m: list[float], x: float, y: float, z: float) -> tuple[float, float, float]:
122
+ return (
123
+ m[0] * x + m[4] * y + m[8] * z + m[12],
124
+ m[1] * x + m[5] * y + m[9] * z + m[13],
125
+ m[2] * x + m[6] * y + m[10] * z + m[14],
126
+ )
127
+
128
+ IDENTITY = [1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0]
129
+
130
+ def walk(node_index: int, parent: list[float]) -> None:
131
+ node = nodes[node_index]
132
+ world = multiply(parent, local_matrix(node))
133
+ if "mesh" in node:
134
+ for prim in meshes[node["mesh"]]["primitives"]:
135
+ pos = prim.get("attributes", {}).get("POSITION")
136
+ if pos is None:
137
+ continue
138
+ for x, y, z in read_accessor(pos):
139
+ points.append(apply(world, x, y, z))
140
+ for child in node.get("children", []):
141
+ walk(child, world)
142
+
143
+ scene = gltf.get("scenes", [{}])[gltf.get("scene", 0)]
144
+ for root in scene.get("nodes", range(len(nodes))):
145
+ walk(root, IDENTITY)
146
+ if not points:
147
+ sys.exit(f"{path}: no POSITION data found")
148
+ return points
149
+
150
+
151
+ def percentile(values: list[float], q: float) -> float:
152
+ if not values:
153
+ return 0.0
154
+ ordered = sorted(values)
155
+ k = (len(ordered) - 1) * q
156
+ lo = int(k)
157
+ hi = min(lo + 1, len(ordered) - 1)
158
+ return ordered[lo] + (ordered[hi] - ordered[lo]) * (k - lo)
159
+
160
+
161
+ def normalise(points: list[tuple[float, float, float]]) -> list[tuple[float, float, float]]:
162
+ """Feet to 0, height to 1, and centred laterally on the body's own median.
163
+
164
+ Centring on the MEDIAN x rather than the bbox centre matters for the same reason percentiles
165
+ matter for width: one long horizontal prop drags a bbox centre sideways, and every centroid
166
+ offset below would then be measured against a datum the body is not standing on.
167
+ """
168
+ ys = [p[1] for p in points]
169
+ y0, y1 = min(ys), max(ys)
170
+ height = y1 - y0
171
+ if height <= 0:
172
+ sys.exit("degenerate mesh: zero height")
173
+ mx = percentile([p[0] for p in points], 0.5)
174
+ mz = percentile([p[2] for p in points], 0.5)
175
+ return [((p[0] - mx) / height, (p[1] - y0) / height, (p[2] - mz) / height) for p in points]
176
+
177
+
178
+ def width_curve(points: list[tuple[float, float, float]], slices: int = 160) -> list[float]:
179
+ """Percentile width at every height, smoothed — the curve landmarks are read off."""
180
+ buckets: list[list[float]] = [[] for _ in range(slices)]
181
+ for x, y, _z in points:
182
+ buckets[min(slices - 1, int(y * slices))].append(x)
183
+ raw = [percentile(b, 0.95) - percentile(b, 0.05) if len(b) >= 20 else 0.0 for b in buckets]
184
+ smoothed = []
185
+ for i in range(slices):
186
+ window = raw[max(0, i - 2): min(slices, i + 3)]
187
+ smoothed.append(sum(window) / len(window))
188
+ return smoothed
189
+
190
+
191
+ def find_landmarks(points: list[tuple[float, float, float]]) -> dict[str, float]:
192
+ """Locate the waist and the neck as the narrowest points of the body's width curve.
193
+
194
+ Equal-percentage bands only correspond between two subjects when the subjects share proportions.
195
+ These two do not -- one is far more compact than the other -- so band 75 is the head on one and
196
+ the upper chest on the other, and a deviation table built that way describes the mismatch rather
197
+ than the shapes. Three earlier comparisons in this project failed exactly there.
198
+
199
+ A standing figure's width curve has two reliable minima: the waist between hips and ribs, and the
200
+ neck between shoulders and skull. Both are found as the narrowest slice inside a generous search
201
+ window rather than at a fixed height, so they track the subject instead of assuming it.
202
+ """
203
+ curve = width_curve(points)
204
+ n = len(curve)
205
+
206
+ def narrowest(lo: float, hi: float) -> float:
207
+ segment = [(curve[i], i) for i in range(int(n * lo), int(n * hi)) if curve[i] > 0]
208
+ if not segment:
209
+ return (lo + hi) / 2
210
+ return min(segment)[1] / n
211
+
212
+ waist = narrowest(0.35, 0.68)
213
+
214
+ def neck_above(waist_h: float) -> float:
215
+ """The first true pinch ABOVE the waist, not merely the smallest slice in a fixed window.
216
+
217
+ A fixed 0.62-0.90 window picked the waist twice on this project's own model: its narrowest
218
+ slice sits at 0.61, inside that window, so waist and neck were reported 0.006 apart and every
219
+ band between them collapsed. Requiring a clear margin above the waist and an actual local
220
+ minimum -- narrower than the curve a few slices either side -- finds the pinch below the skull
221
+ instead of re-finding the one below the ribs.
222
+ """
223
+ start = int(n * min(0.92, waist_h + 0.08))
224
+ best, best_width = None, None
225
+ for i in range(start, int(n * 0.94)):
226
+ if curve[i] <= 0:
227
+ continue
228
+ lo_i, hi_i = max(0, i - 3), min(n - 1, i + 3)
229
+ if curve[i] <= curve[lo_i] and curve[i] <= curve[hi_i]:
230
+ if best_width is None or curve[i] < best_width:
231
+ best, best_width = i, curve[i]
232
+ return (best / n) if best is not None else min(0.92, waist_h + 0.15)
233
+
234
+ return {"ground": 0.0, "waist": waist, "neck": neck_above(waist), "top": 1.0}
235
+
236
+
237
+ def landmark_bands(points: list[tuple[float, float, float]], per_segment: int) -> list[dict]:
238
+ """Band between anatomical landmarks, so band k means the same body region in both meshes."""
239
+ marks = find_landmarks(points)
240
+ edges: list[float] = []
241
+ for lo, hi in (("ground", "waist"), ("waist", "neck"), ("neck", "top")):
242
+ a, b = marks[lo], marks[hi]
243
+ edges.extend(a + (b - a) * i / per_segment for i in range(per_segment))
244
+ edges.append(1.0)
245
+
246
+ profile = []
247
+ for i in range(len(edges) - 1):
248
+ lo, hi = edges[i], edges[i + 1]
249
+ bucket = [p for p in points if lo <= p[1] < hi]
250
+ if len(bucket) < 20:
251
+ profile.append({"band": i, "points": len(bucket), "lo": lo, "hi": hi})
252
+ continue
253
+ xs = [p[0] for p in bucket]
254
+ zs = [p[2] for p in bucket]
255
+ profile.append({
256
+ "band": i, "points": len(bucket), "lo": lo, "hi": hi,
257
+ "width": percentile(xs, 0.95) - percentile(xs, 0.05),
258
+ "depth": percentile(zs, 0.95) - percentile(zs, 0.05),
259
+ "centroidX": percentile(xs, 0.5), "centroidZ": percentile(zs, 0.5),
260
+ })
261
+ return profile, marks
262
+
263
+
264
+ def band_profile(points: list[tuple[float, float, float]], bands: int) -> list[dict]:
265
+ buckets: list[list[tuple[float, float, float]]] = [[] for _ in range(bands)]
266
+ for p in points:
267
+ idx = min(bands - 1, int(p[1] * bands))
268
+ buckets[idx].append(p)
269
+ profile = []
270
+ for i, bucket in enumerate(buckets):
271
+ if len(bucket) < 20:
272
+ profile.append({"band": i, "points": len(bucket)})
273
+ continue
274
+ xs = [p[0] for p in bucket]
275
+ zs = [p[2] for p in bucket]
276
+ profile.append({
277
+ "band": i,
278
+ "points": len(bucket),
279
+ "width": percentile(xs, 0.95) - percentile(xs, 0.05),
280
+ "depth": percentile(zs, 0.95) - percentile(zs, 0.05),
281
+ "widthFull": max(xs) - min(xs),
282
+ "centroidX": percentile(xs, 0.5),
283
+ "centroidZ": percentile(zs, 0.5),
284
+ })
285
+ return profile
286
+
287
+
288
+ def main() -> None:
289
+ parser = argparse.ArgumentParser(description=__doc__,
290
+ formatter_class=argparse.RawDescriptionHelpFormatter)
291
+ parser.add_argument("reference", type=Path)
292
+ parser.add_argument("candidate", type=Path)
293
+ parser.add_argument("--bands", type=int, default=20)
294
+ parser.add_argument("--json", action="store_true")
295
+ parser.add_argument("--align", choices=("height", "landmarks"), default="landmarks",
296
+ help="landmarks (default) bands between the waist and neck it "
297
+ "finds in each mesh; height bands by raw percentage and "
298
+ "only corresponds when both subjects share proportions")
299
+ args = parser.parse_args()
300
+
301
+ ref_pts = normalise(read_glb_positions(args.reference))
302
+ cand_pts = normalise(read_glb_positions(args.candidate))
303
+ if args.align == "landmarks":
304
+ ref, ref_marks = landmark_bands(ref_pts, max(2, args.bands // 3))
305
+ cand, cand_marks = landmark_bands(cand_pts, max(2, args.bands // 3))
306
+ else:
307
+ ref, cand = band_profile(ref_pts, args.bands), band_profile(cand_pts, args.bands)
308
+ ref_marks = cand_marks = None
309
+
310
+ rows, errors = [], []
311
+ for r, c in zip(ref, cand):
312
+ if "width" not in r or "width" not in c:
313
+ continue
314
+ row = {
315
+ "band": r["band"],
316
+ "lowPct": round(r["band"] / args.bands * 100),
317
+ "highPct": round((r["band"] + 1) / args.bands * 100),
318
+ "refWidth": round(r["width"], 4), "candWidth": round(c["width"], 4),
319
+ "refDepth": round(r["depth"], 4), "candDepth": round(c["depth"], 4),
320
+ "widthDelta": round(c["width"] - r["width"], 4),
321
+ "depthDelta": round(c["depth"] - r["depth"], 4),
322
+ "centroidXDelta": round(c["centroidX"] - r["centroidX"], 4),
323
+ "centroidZDelta": round(c["centroidZ"] - r["centroidZ"], 4),
324
+ }
325
+ rows.append(row)
326
+ errors.append(abs(row["widthDelta"]) + abs(row["depthDelta"]))
327
+
328
+ score = sum(errors) / (2 * len(errors)) if errors else 0.0
329
+ report = {
330
+ "reference": str(args.reference), "candidate": str(args.candidate),
331
+ "bands": args.bands, "meanBandError": round(score, 5), "rows": rows,
332
+ "note": "0 = feet, 100 = top. Widths are 5-95 percentile, normalised by subject height, "
333
+ "so a thin prop cannot dominate. Both meshes are aligned on the ground plane, not "
334
+ "on the bounding-box top.",
335
+ }
336
+
337
+ if args.json:
338
+ print(json.dumps(report, indent=2))
339
+ return
340
+
341
+ if ref_marks:
342
+ print(f"landmarks reference: waist {ref_marks['waist']:.3f} neck {ref_marks['neck']:.3f}")
343
+ print(f"landmarks candidate: waist {cand_marks['waist']:.3f} neck {cand_marks['neck']:.3f}")
344
+ print(f"reference: {args.reference.name}")
345
+ print(f"candidate: {args.candidate.name}")
346
+ print(f"\n{'band':>10}{'ref w':>9}{'cand w':>9}{'Δw':>8}{'ref d':>9}{'cand d':>9}{'Δd':>8}"
347
+ f"{'Δcx':>8}{'Δcz':>8}")
348
+ for row in rows:
349
+ print(f"{row['lowPct']:>4}-{row['highPct']:<5}"
350
+ f"{row['refWidth']:>9.3f}{row['candWidth']:>9.3f}{row['widthDelta']:>+8.3f}"
351
+ f"{row['refDepth']:>9.3f}{row['candDepth']:>9.3f}{row['depthDelta']:>+8.3f}"
352
+ f"{row['centroidXDelta']:>+8.3f}{row['centroidZDelta']:>+8.3f}")
353
+ print(f"\nmean band error = {score:.5f}")
354
+ worst = sorted(rows, key=lambda r: -(abs(r["widthDelta"]) + abs(r["depthDelta"])))[:5]
355
+ print("\nworst bands:")
356
+ for row in worst:
357
+ print(f" {row['lowPct']:>3}-{row['highPct']:<4} Δw {row['widthDelta']:+.3f} "
358
+ f"Δd {row['depthDelta']:+.3f} Δcx {row['centroidXDelta']:+.3f}")
359
+
360
+
361
+ if __name__ == "__main__":
362
+ main()