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,102 @@
1
+ #!/usr/bin/env python3
2
+ """Manifest helpers for the v2 browser multi-pass evidence contract."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import hashlib
7
+ from pathlib import Path
8
+ from typing import Any, Callable
9
+
10
+
11
+ PASS_IDS = (
12
+ "beauty",
13
+ "alpha-silhouette",
14
+ "semantic-id",
15
+ "depth",
16
+ "normal",
17
+ "roughness-material-id",
18
+ )
19
+
20
+
21
+ def default_pass_records(prefix: str) -> dict[str, dict[str, Any]]:
22
+ prefix = prefix.rstrip("/")
23
+ return {
24
+ pass_id: {"path": f"{prefix}/{pass_id}.png", "status": "pending"}
25
+ for pass_id in PASS_IDS
26
+ }
27
+
28
+
29
+ def _sha256(path: Path) -> str:
30
+ digest = hashlib.sha256()
31
+ with path.open("rb") as handle:
32
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
33
+ digest.update(chunk)
34
+ return digest.hexdigest()
35
+
36
+
37
+ def record_pass(
38
+ manifest_path: Path,
39
+ pass_record: dict[str, Any],
40
+ image_path: Path,
41
+ probe: Callable[[Path], dict[str, Any]],
42
+ ) -> dict[str, Any]:
43
+ image_path = image_path.expanduser().resolve()
44
+ if not image_path.is_file():
45
+ raise ValueError(f"pass image does not exist: {image_path}")
46
+ image = probe(image_path)
47
+ if not image.get("type") or not image.get("width") or not image.get("height"):
48
+ raise ValueError(f"pass image is not readable: {image_path}")
49
+ try:
50
+ relative = image_path.relative_to(manifest_path.parent.resolve()).as_posix()
51
+ except ValueError:
52
+ relative = str(image_path)
53
+ pass_record.update(
54
+ {
55
+ "path": relative,
56
+ "status": "recorded",
57
+ "image": image,
58
+ "sha256": _sha256(image_path),
59
+ }
60
+ )
61
+ return pass_record
62
+
63
+
64
+ def validate_pass_records(
65
+ manifest_path: Path,
66
+ records: Any,
67
+ probe: Callable[[Path], dict[str, Any]],
68
+ *,
69
+ require_complete: bool,
70
+ label: str,
71
+ ) -> list[str]:
72
+ errors: list[str] = []
73
+ if not isinstance(records, dict):
74
+ if require_complete:
75
+ errors.append(f"{label} pass records are missing")
76
+ return errors
77
+ for pass_id in PASS_IDS:
78
+ record = records.get(pass_id)
79
+ if not isinstance(record, dict):
80
+ if require_complete:
81
+ errors.append(f"{label} pass is missing: {pass_id}")
82
+ continue
83
+ if record.get("status") != "recorded":
84
+ if require_complete:
85
+ errors.append(f"{label} pass is not recorded: {pass_id}")
86
+ continue
87
+ value = record.get("path")
88
+ if not value:
89
+ errors.append(f"{label} pass has no path: {pass_id}")
90
+ continue
91
+ path_value = Path(value).expanduser()
92
+ path = path_value if path_value.is_absolute() else manifest_path.parent / path_value
93
+ if not path.is_file():
94
+ errors.append(f"{label} pass file is missing: {path}")
95
+ continue
96
+ image = probe(path)
97
+ if not image.get("type") or not image.get("width") or not image.get("height"):
98
+ errors.append(f"{label} pass is unreadable: {path}")
99
+ expected_hash = record.get("sha256")
100
+ if expected_hash and expected_hash != _sha256(path):
101
+ errors.append(f"{label} pass hash changed: {path}")
102
+ return errors
@@ -0,0 +1,143 @@
1
+ #!/usr/bin/env python3
2
+ """Stdlib objectness proxy (OSIM-lite) for the Divine Eye — Plan 1.3 task #18, Pillar-1 safe.
3
+
4
+ A pure-Python gradient-orientation-histogram (HOG-like) descriptor compared by cosine
5
+ similarity. The object's foreground is masked, cropped to its bbox, and resampled to a
6
+ canonical square grid, so the descriptor is invariant to:
7
+ - background (foreground mask drops it)
8
+ - position (bbox crop)
9
+ - scale (resample to a fixed grid)
10
+ - absolute brightness / colour (gradient *orientations*, per-cell L2-normalised)
11
+
12
+ Those are exactly the photo-vs-procedural axes where silhouette-IoU, SSIM and edge-overlap
13
+ collapse (a faithful reconstruction on a dark background vs a white-bg studio photo). This
14
+ is the graceful *stdlib floor* objectness signal — no numpy, no weights, no download. A
15
+ learned CNN-OSIM remains an optional V2 upgrade behind the same signal name.
16
+
17
+ CLI: objectness.py --reference REF --render RENDER [--json]
18
+ API: objectness_similarity(ref_path, render_path) -> float in [0,1]
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import json
24
+ import math
25
+ import sys
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage1_intake"))
30
+ from extract_pbr_evidence import build_foreground_mask, load_image # noqa: E402
31
+
32
+ GRID = 96 # canonical square the object bbox is resampled to
33
+ CELLS = 8 # CELLS x CELLS spatial cells
34
+ BINS = 9 # orientation bins over 0..180 (unsigned gradient)
35
+
36
+
37
+ def _to_gray(pixels: list[tuple[int, int, int, int]]) -> list[int]:
38
+ return [(p[0] * 30 + p[1] * 59 + p[2] * 11) // 100 for p in pixels]
39
+
40
+
41
+ def _bbox(mask: list[bool], w: int, h: int) -> tuple[int, int, int, int]:
42
+ minx = miny = 1 << 30
43
+ maxx = maxy = -1
44
+ for y in range(h):
45
+ row = y * w
46
+ for x in range(w):
47
+ if mask[row + x]:
48
+ if x < minx:
49
+ minx = x
50
+ if x > maxx:
51
+ maxx = x
52
+ if y < miny:
53
+ miny = y
54
+ if y > maxy:
55
+ maxy = y
56
+ if maxx < 0: # empty mask -> whole frame
57
+ return (0, 0, w, h)
58
+ return (minx, miny, maxx + 1, maxy + 1)
59
+
60
+
61
+ def _resample_bbox(gray: list[int], w: int, h: int, box: tuple[int, int, int, int], n: int) -> list[float]:
62
+ x0, y0, x1, y1 = box
63
+ bw = max(1, x1 - x0)
64
+ bh = max(1, y1 - y0)
65
+ out = [0.0] * (n * n)
66
+ for j in range(n):
67
+ sy = min(h - 1, y0 + (j * bh) // n)
68
+ base = sy * w
69
+ for i in range(n):
70
+ sx = min(w - 1, x0 + (i * bw) // n)
71
+ out[j * n + i] = float(gray[base + sx])
72
+ return out
73
+
74
+
75
+ def descriptor(path: str | Path) -> list[float]:
76
+ """HOG-like descriptor of the object's foreground, canonicalised for pose/scale/bg."""
77
+ w, h, pixels, _ = load_image(Path(path))
78
+ gray = _to_gray(pixels)
79
+ mask, _diag, _warn = build_foreground_mask(w, h, pixels)
80
+ x0, y0, x1, y1 = _bbox(mask, w, h)
81
+ # pad the bbox so the object's silhouette contour (its strongest shape cue) lands
82
+ # INSIDE the resampled grid — a solid object cropped flush would otherwise put its
83
+ # only edges on the border (skipped by the gradient loop) and yield a zero descriptor.
84
+ px = int((x1 - x0) * 0.10) + 2
85
+ py = int((y1 - y0) * 0.10) + 2
86
+ box = (max(0, x0 - px), max(0, y0 - py), min(w, x1 + px), min(h, y1 + py))
87
+ g = _resample_bbox(gray, w, h, box, GRID)
88
+
89
+ hist = [0.0] * (CELLS * CELLS * BINS)
90
+ cell = GRID // CELLS
91
+ for y in range(1, GRID - 1):
92
+ row = y * GRID
93
+ cy = min(CELLS - 1, y // cell)
94
+ for x in range(1, GRID - 1):
95
+ gx = g[row + x + 1] - g[row + x - 1]
96
+ gy = g[(y + 1) * GRID + x] - g[(y - 1) * GRID + x]
97
+ mag = math.hypot(gx, gy)
98
+ if mag < 1e-6:
99
+ continue
100
+ ang = math.degrees(math.atan2(gy, gx)) % 180.0
101
+ b = int(ang / 180.0 * BINS) % BINS
102
+ cx = min(CELLS - 1, x // cell)
103
+ hist[(cy * CELLS + cx) * BINS + b] += mag
104
+ # per-cell L2 block normalisation -> contrast/brightness invariance
105
+ for c in range(CELLS * CELLS):
106
+ base = c * BINS
107
+ norm = math.sqrt(sum(hist[base + k] ** 2 for k in range(BINS))) + 1e-6
108
+ for k in range(BINS):
109
+ hist[base + k] /= norm
110
+ return hist
111
+
112
+
113
+ def cosine(a: list[float], b: list[float]) -> float:
114
+ dot = sum(x * y for x, y in zip(a, b))
115
+ na = math.sqrt(sum(x * x for x in a))
116
+ nb = math.sqrt(sum(y * y for y in b))
117
+ if na < 1e-9 or nb < 1e-9:
118
+ return 0.0
119
+ return max(0.0, min(1.0, dot / (na * nb)))
120
+
121
+
122
+ def objectness_similarity(ref_path: str | Path, render_path: str | Path) -> float:
123
+ """Cosine similarity of the two objectness descriptors, in [0,1]. 1 = same structure."""
124
+ return cosine(descriptor(ref_path), descriptor(render_path))
125
+
126
+
127
+ def main(argv: list[str] | None = None) -> int:
128
+ ap = argparse.ArgumentParser(description="Stdlib objectness (OSIM-lite) similarity")
129
+ ap.add_argument("--reference", required=True)
130
+ ap.add_argument("--render", required=True)
131
+ ap.add_argument("--json", action="store_true")
132
+ args = ap.parse_args(argv)
133
+ score = objectness_similarity(args.reference, args.render)
134
+ out: dict[str, Any] = {"objectness": round(score, 4), "grid": GRID, "cells": CELLS, "bins": BINS}
135
+ if args.json:
136
+ print(json.dumps(out))
137
+ else:
138
+ print(f"objectness similarity: {score:.4f}")
139
+ return 0
140
+
141
+
142
+ if __name__ == "__main__":
143
+ raise SystemExit(main())
@@ -0,0 +1,376 @@
1
+ #!/usr/bin/env python3
2
+ """Does one part pass through another?
3
+
4
+ `self_intersection.py` catches a surface folded through ITS OWN volume. It says nothing about two
5
+ separate meshes occupying the same space, and that is a different, equally common defect: an arm
6
+ inside a torso, a staff through a hat, a strap sunk into a shoulder. Each mesh is individually
7
+ flawless, so every per-mesh gate passes, and the model is still broken.
8
+
9
+ Method: ray parity again, but across meshes. Sample vertices of A, count crossings of B's triangles
10
+ along a fixed direction; odd means the vertex is inside B. As in the sibling module, a grazing hit is
11
+ reported as UNDECIDED rather than rounded into a verdict, and the sampling budget is reported so a
12
+ clean result over a strided sample is never mistaken for a clean result over the whole mesh.
13
+
14
+ Touching is not penetrating. A hand gripping a staff shares a surface, and a gate that flagged that
15
+ would be useless on exactly the models it is meant to check, so `allowedPairs` exists for parts that
16
+ are supposed to be in contact and `penetrationDepth` distinguishes a skim from a part buried inside
17
+ another.
18
+
19
+ Pure Python 3.10+ stdlib.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import math
27
+ import sys
28
+ from pathlib import Path
29
+ from typing import Any
30
+
31
+ MAX_SAMPLED_VERTICES = 2000
32
+ EPSILON = 1e-9
33
+ # Three fixed, mutually non-parallel directions. Deterministic on purpose: a `random` direction makes
34
+ # a gate that disagrees with itself between runs, and an intermittent gate gets switched off.
35
+ _DIRECTIONS = (
36
+ (0.5773502691896258, 0.5773502691896258, 0.5773502691896258),
37
+ (-0.8017837257372732, 0.5345224838248488, 0.2672612419124244),
38
+ (0.2672612419124244, -0.8017837257372732, 0.5345224838248488),
39
+ )
40
+ GRAZING_LIMIT = 1e-7
41
+
42
+
43
+ def _triangles(indices: Any) -> list[tuple[int, int, int]]:
44
+ if indices and isinstance(indices[0], (list, tuple)):
45
+ return [(int(t[0]), int(t[1]), int(t[2])) for t in indices]
46
+ return [
47
+ (int(indices[i]), int(indices[i + 1]), int(indices[i + 2]))
48
+ for i in range(0, len(indices) - 2, 3)
49
+ ]
50
+
51
+
52
+ def _bounds(vertices: list[list[float]]) -> tuple[list[float], list[float]]:
53
+ low = [min(v[axis] for v in vertices) for axis in range(3)]
54
+ high = [max(v[axis] for v in vertices) for axis in range(3)]
55
+ return low, high
56
+
57
+
58
+ def _boxes_overlap(a: tuple[list[float], list[float]], b: tuple[list[float], list[float]]) -> bool:
59
+ return all(a[0][axis] <= b[1][axis] and b[0][axis] <= a[1][axis] for axis in range(3))
60
+
61
+
62
+ GRID_CELLS = 48
63
+
64
+
65
+ class _DirectionIndex:
66
+ """Triangles bucketed by their footprint on the plane perpendicular to one ray direction.
67
+
68
+ Without this the test is every sample against every triangle. That is fine on a twelve-triangle
69
+ fixture and hopeless on a real model: 2000 samples x 8300 triangles x 3 directions is 50 million
70
+ ray-triangle tests for ONE ordered pair, and an eight-mesh audit has fifty-six of them. Measured
71
+ on the actual character, the brute-force version did not finish in ten minutes. Because every
72
+ sample shares the same direction, the projection basis and the buckets are built once per pair and
73
+ reused, so each sample only tests the triangles whose footprint covers it.
74
+ """
75
+
76
+ def __init__(self, direction, vertices, faces):
77
+ dx, dy, dz = direction
78
+ # Any vector not parallel to the direction gives a usable basis; picking the axis the
79
+ # direction is *least* aligned with keeps the cross product well conditioned.
80
+ smallest = min(range(3), key=lambda axis: abs(direction[axis]))
81
+ helper = [0.0, 0.0, 0.0]
82
+ helper[smallest] = 1.0
83
+ ux = helper[1] * dz - helper[2] * dy
84
+ uy = helper[2] * dx - helper[0] * dz
85
+ uz = helper[0] * dy - helper[1] * dx
86
+ length = math.sqrt(ux * ux + uy * uy + uz * uz)
87
+ self.u = (ux / length, uy / length, uz / length)
88
+ self.v = (
89
+ dy * self.u[2] - dz * self.u[1],
90
+ dz * self.u[0] - dx * self.u[2],
91
+ dx * self.u[1] - dy * self.u[0],
92
+ )
93
+ self.faces = faces
94
+ self.vertices = vertices
95
+
96
+ boxes = []
97
+ min_a = min_b = float("inf")
98
+ max_a = max_b = float("-inf")
99
+ for face in faces:
100
+ aa = [self._project(vertices[i]) for i in face]
101
+ lo_a = min(p[0] for p in aa)
102
+ hi_a = max(p[0] for p in aa)
103
+ lo_b = min(p[1] for p in aa)
104
+ hi_b = max(p[1] for p in aa)
105
+ boxes.append((lo_a, hi_a, lo_b, hi_b))
106
+ min_a, max_a = min(min_a, lo_a), max(max_a, hi_a)
107
+ min_b, max_b = min(min_b, lo_b), max(max_b, hi_b)
108
+
109
+ self.min_a, self.min_b = min_a, min_b
110
+ self.span_a = max(max_a - min_a, 1e-9)
111
+ self.span_b = max(max_b - min_b, 1e-9)
112
+ self.buckets: dict[tuple[int, int], list[int]] = {}
113
+ for index, (lo_a, hi_a, lo_b, hi_b) in enumerate(boxes):
114
+ for cell_a in range(self._cell(lo_a, min_a, self.span_a), self._cell(hi_a, min_a, self.span_a) + 1):
115
+ for cell_b in range(self._cell(lo_b, min_b, self.span_b), self._cell(hi_b, min_b, self.span_b) + 1):
116
+ self.buckets.setdefault((cell_a, cell_b), []).append(index)
117
+
118
+ def _project(self, point) -> tuple[float, float]:
119
+ return (
120
+ point[0] * self.u[0] + point[1] * self.u[1] + point[2] * self.u[2],
121
+ point[0] * self.v[0] + point[1] * self.v[1] + point[2] * self.v[2],
122
+ )
123
+
124
+ @staticmethod
125
+ def _cell(value: float, low: float, span: float) -> int:
126
+ # Clamped, never rejected. A point landing one cell past the end -- which is exactly where the
127
+ # vertex defining the projection's maximum sits -- would otherwise return no candidates and a
128
+ # confident "outside".
129
+ return max(0, min(GRID_CELLS - 1, int((value - low) / span * GRID_CELLS)))
130
+
131
+ def candidates(self, point) -> list[int]:
132
+ a, b = self._project(point)
133
+ return self.buckets.get(
134
+ (self._cell(a, self.min_a, self.span_a), self._cell(b, self.min_b, self.span_b)), []
135
+ )
136
+
137
+
138
+ def _crossings(
139
+ origin: tuple[float, float, float],
140
+ direction: tuple[float, float, float],
141
+ vertices: list[list[float]],
142
+ faces: list[tuple[int, int, int]],
143
+ index: "_DirectionIndex | None" = None,
144
+ ) -> tuple[int, bool]:
145
+ """Möller-Trumbore parity. Returns (crossings, reliable)."""
146
+ ox, oy, oz = origin
147
+ dx, dy, dz = direction
148
+ crossings = 0
149
+ reliable = True
150
+ candidate_faces = faces if index is None else [faces[i] for i in index.candidates(origin)]
151
+ for a, b, c in candidate_faces:
152
+ p0, p1, p2 = vertices[a], vertices[b], vertices[c]
153
+ e1 = (p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2])
154
+ e2 = (p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2])
155
+ px = dy * e2[2] - dz * e2[1]
156
+ py = dz * e2[0] - dx * e2[2]
157
+ pz = dx * e2[1] - dy * e2[0]
158
+ determinant = e1[0] * px + e1[1] * py + e1[2] * pz
159
+ if abs(determinant) < GRAZING_LIMIT:
160
+ # Edge-on: the intersection is numerically meaningless, so the whole ray is untrusted.
161
+ reliable = False
162
+ continue
163
+ inverse = 1.0 / determinant
164
+ tx, ty, tz = ox - p0[0], oy - p0[1], oz - p0[2]
165
+ u = (tx * px + ty * py + tz * pz) * inverse
166
+ if u < -EPSILON or u > 1.0 + EPSILON:
167
+ continue
168
+ qx = ty * e1[2] - tz * e1[1]
169
+ qy = tz * e1[0] - tx * e1[2]
170
+ qz = tx * e1[1] - ty * e1[0]
171
+ v = (dx * qx + dy * qy + dz * qz) * inverse
172
+ if v < -EPSILON or u + v > 1.0 + EPSILON:
173
+ continue
174
+ distance = (e2[0] * qx + e2[1] * qy + e2[2] * qz) * inverse
175
+ if distance <= EPSILON:
176
+ continue
177
+ # A hit exactly on a shared edge belongs to two triangles and would be counted twice.
178
+ if abs(u) < 1e-7 or abs(v) < 1e-7 or abs(u + v - 1.0) < 1e-7:
179
+ reliable = False
180
+ crossings += 1
181
+ return crossings, reliable
182
+
183
+
184
+ def build_indices(vertices, faces) -> list[_DirectionIndex]:
185
+ """One acceleration structure per ray direction, built once and reused across every sample."""
186
+ return [_DirectionIndex(direction, vertices, faces) for direction in _DIRECTIONS]
187
+
188
+
189
+ def point_inside(
190
+ point: tuple[float, float, float],
191
+ vertices: list[list[float]],
192
+ faces: list[tuple[int, int, int]],
193
+ indices: list[_DirectionIndex] | None = None,
194
+ ) -> str:
195
+ """'inside', 'outside', or 'undecided' by majority over three fixed ray directions."""
196
+ votes = []
197
+ for position, direction in enumerate(_DIRECTIONS):
198
+ crossings, reliable = _crossings(
199
+ point, direction, vertices, faces, indices[position] if indices else None
200
+ )
201
+ if reliable:
202
+ votes.append(crossings % 2 == 1)
203
+ if len(votes) < 2:
204
+ return "undecided"
205
+ inside_votes = sum(1 for vote in votes if vote)
206
+ if inside_votes * 2 == len(votes):
207
+ return "undecided"
208
+ return "inside" if inside_votes * 2 > len(votes) else "outside"
209
+
210
+
211
+ def _sample_points(vertices: list[list[float]], faces: list[tuple[int, int, int]]) -> list[list[float]]:
212
+ """Vertices, plus edge midpoints and face centroids.
213
+
214
+ Vertices alone are not enough, and the failure is not exotic. A bar driven through a block has
215
+ every one of its corners OUTSIDE the block and every corner of the block outside the bar -- the
216
+ two surfaces interpenetrate entirely across faces, and a vertex-only test reports a clean pass on
217
+ a model with a pole through its chest. Midpoints and centroids put samples on the parts of the
218
+ surface that are actually inside the other mesh.
219
+
220
+ This is still SAMPLING, not exact surface intersection: a part thin enough to thread between the
221
+ samples goes unseen. Detecting that needs an edge-versus-triangle test on every pair of faces,
222
+ which is a different cost class. The limit is stated in the result rather than left implied.
223
+ """
224
+ points = [list(vertex) for vertex in vertices]
225
+ seen_edges: set[tuple[int, int]] = set()
226
+ for a, b, c in faces:
227
+ for u, v in ((a, b), (b, c), (c, a)):
228
+ key = (u, v) if u < v else (v, u)
229
+ if key in seen_edges:
230
+ continue
231
+ seen_edges.add(key)
232
+ points.append([(vertices[u][i] + vertices[v][i]) / 2 for i in range(3)])
233
+ points.append([(vertices[a][i] + vertices[b][i] + vertices[c][i]) / 3 for i in range(3)])
234
+ return points
235
+
236
+
237
+ def analyze_pair(
238
+ a: dict[str, Any],
239
+ b: dict[str, Any],
240
+ max_samples: int = MAX_SAMPLED_VERTICES,
241
+ ) -> dict[str, Any]:
242
+ a_vertices, b_vertices = a["vertices"], b["vertices"]
243
+ b_faces = _triangles(b["indices"])
244
+ a_samples = _sample_points(a_vertices, _triangles(a["indices"]))
245
+ a_box, b_box = _bounds(a_vertices), _bounds(b_vertices)
246
+ name_a, name_b = str(a.get("name", "a")), str(b.get("name", "b"))
247
+ if not _boxes_overlap(a_box, b_box):
248
+ # Cheap rejection, and reported as such: "0 inside" from a test that never ran and "0 inside"
249
+ # from a test that ran are different claims.
250
+ return {
251
+ "a": name_a, "b": name_b, "boundsOverlap": False, "penetrating": False,
252
+ "insideVertexCount": 0, "undecidedVertexCount": 0,
253
+ "sampledVertexCount": 0, "totalVertexCount": len(a_samples), "samplingStride": 0,
254
+ "penetrationDepth": 0.0,
255
+ }
256
+
257
+ b_indices = build_indices(b_vertices, b_faces)
258
+ stride = max(1, math.ceil(len(a_samples) / max_samples))
259
+ inside = 0
260
+ undecided = 0
261
+ sampled = 0
262
+ deepest = 0.0
263
+ worst_points: list[list[float]] = []
264
+ for index in range(0, len(a_samples), stride):
265
+ vertex = a_samples[index]
266
+ sampled += 1
267
+ verdict = point_inside((vertex[0], vertex[1], vertex[2]), b_vertices, b_faces, b_indices)
268
+ if verdict == "undecided":
269
+ undecided += 1
270
+ continue
271
+ if verdict != "inside":
272
+ continue
273
+ inside += 1
274
+ # Depth measured to B's bounding box rather than to its surface: a surface distance needs a
275
+ # full closest-point query per vertex, and the box distance already separates a skimming
276
+ # contact from a part sitting well inside another, which is the decision being made.
277
+ depth = min(
278
+ min(vertex[axis] - b_box[0][axis], b_box[1][axis] - vertex[axis])
279
+ for axis in range(3)
280
+ )
281
+ if depth > deepest:
282
+ deepest = depth
283
+ if len(worst_points) < 8:
284
+ worst_points.append([round(component, 4) for component in vertex])
285
+
286
+ return {
287
+ "a": name_a, "b": name_b, "boundsOverlap": True,
288
+ "penetrating": inside > 0,
289
+ "insideVertexCount": inside,
290
+ "undecidedVertexCount": undecided,
291
+ "sampledVertexCount": sampled,
292
+ "totalVertexCount": len(a_samples),
293
+ "samplingStride": stride,
294
+ "penetrationDepth": round(deepest, 6),
295
+ "samplePoints": worst_points,
296
+ "samplingLimitation": (
297
+ "samples are vertices, edge midpoints and face centroids; a part thin enough to thread "
298
+ "between them is not detected, which needs an edge-versus-triangle test"
299
+ ),
300
+ }
301
+
302
+
303
+ def analyze_meshes(
304
+ meshes: list[dict[str, Any]],
305
+ allowed_pairs: list[list[str]] | None = None,
306
+ max_samples: int = MAX_SAMPLED_VERTICES,
307
+ ) -> dict[str, Any]:
308
+ """Every ordered pair, minus the pairs declared as legitimately in contact."""
309
+ allowed = {frozenset(pair) for pair in (allowed_pairs or [])}
310
+ usable = [m for m in meshes if isinstance(m.get("vertices"), list) and m.get("vertices")
311
+ and isinstance(m.get("indices"), list) and len(m["indices"]) >= 3]
312
+ skipped = [str(m.get("name", "?")) for m in meshes if m not in usable]
313
+
314
+ pairs: list[dict[str, Any]] = []
315
+ failures: list[str] = []
316
+ for i, first in enumerate(usable):
317
+ for second in usable[i + 1:]:
318
+ names = frozenset((str(first.get("name", "a")), str(second.get("name", "b"))))
319
+ if names in allowed:
320
+ continue
321
+ # Both directions: A's vertices can all sit outside B while B's sit inside A, whenever one
322
+ # part is much smaller than the other.
323
+ for source, target in ((first, second), (second, first)):
324
+ result = analyze_pair(source, target, max_samples)
325
+ if result["penetrating"]:
326
+ failures.append(
327
+ f"{result['a']} penetrates {result['b']}: {result['insideVertexCount']} of "
328
+ f"{result['sampledVertexCount']} sampled vertices are inside it, depth "
329
+ f"{result['penetrationDepth']}"
330
+ )
331
+ if result["boundsOverlap"]:
332
+ pairs.append(result)
333
+
334
+ return {
335
+ "pairs": pairs,
336
+ "failures": failures,
337
+ "penetrating": bool(failures),
338
+ "meshCount": len(usable),
339
+ "skippedMeshes": skipped,
340
+ "allowedPairs": [sorted(pair) for pair in allowed],
341
+ "passed": not failures,
342
+ }
343
+
344
+
345
+ def _format_summary(result: dict[str, Any]) -> str:
346
+ lines = [f"meshes: {result['meshCount']}, pairs with overlapping bounds: {len(result['pairs'])}"]
347
+ if result["skippedMeshes"]:
348
+ lines.append(f"skipped (no usable geometry): {result['skippedMeshes']}")
349
+ for failure in result["failures"]:
350
+ lines.append(f" [PENETRATION] {failure}")
351
+ lines.append("verdict: PASS" if result["passed"] else "verdict: GATE FAILURE")
352
+ return "\n".join(lines)
353
+
354
+
355
+ def main(argv: list[str]) -> int:
356
+ parser = argparse.ArgumentParser(description="Detect one part passing through another.")
357
+ parser.add_argument("meshes", type=Path)
358
+ parser.add_argument("--allow", action="append", default=[],
359
+ help="a pair permitted to touch, as 'nameA,nameB' (repeatable)")
360
+ parser.add_argument("--max-samples", type=int, default=MAX_SAMPLED_VERTICES)
361
+ parser.add_argument("--json", action="store_true")
362
+ args = parser.parse_args(argv)
363
+ try:
364
+ payload = json.loads(args.meshes.read_text())
365
+ meshes = payload["meshes"] if isinstance(payload, dict) and isinstance(payload.get("meshes"), list) else [payload]
366
+ allowed = [pair.split(",") for pair in args.allow]
367
+ result = analyze_meshes(meshes, allowed, args.max_samples)
368
+ except Exception as exc:
369
+ print(f"error: {exc}", file=sys.stderr)
370
+ return 2
371
+ print(json.dumps(result, indent=2) if args.json else _format_summary(result))
372
+ return 0 if result["passed"] else 1
373
+
374
+
375
+ if __name__ == "__main__":
376
+ raise SystemExit(main(sys.argv[1:]))