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,230 @@
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ import sys
8
+ import tempfile
9
+ from pathlib import Path
10
+ from typing import Any, Final
11
+
12
+ from forge.stage1_intake.check_reference_admission import check_admission
13
+ from forge.stage1_intake.cs2_foundation import enrich_manifest_with_metadata, normalize_cs2_metadata, resolve_identity
14
+ from forge.stage1_intake.cs2_review_contract import build_review_scene
15
+ from forge.stage1_intake.detect_cs2 import detect_cs2_signals
16
+ from forge.stage1_intake.probe_image import probe
17
+
18
+ SCHEMA_VERSION: Final[int] = 1
19
+ SUPPORTED_FAMILIES: Final[frozenset[str]] = frozenset({"knife"})
20
+ UNSUPPORTED_FAMILIES: Final[frozenset[str]] = frozenset(
21
+ {"pistol", "rifle", "smg", "sniper", "heavy", "glove"}
22
+ )
23
+ # Knife subtypes that have a dedicated geometry adapter. A subtype absent here is
24
+ # `unsupported-subtype`, never silently routed through another subtype's tree.
25
+ KNIFE_SUBTYPES: Final[frozenset[str]] = frozenset(
26
+ {"karambit", "butterfly", "bayonet", "m9", "flip", "gut", "falchion", "bowie", "navaja",
27
+ "talon", "classic"}
28
+ )
29
+ ROUTES: Final[frozenset[str]] = frozenset(
30
+ {"reference-projection", "authored-texture", "procedural-finish"}
31
+ )
32
+ TIERS: Final[frozenset[str]] = frozenset(
33
+ {"image-only", "metadata-assisted", "exact-texture"}
34
+ )
35
+ STATES: Final[frozenset[str]] = frozenset(
36
+ {"proceed", "request-input", "fallback", "rejected", "unsupported-family", "unsupported-subtype"}
37
+ )
38
+
39
+
40
+ def build_classification_record(
41
+ item_family: str,
42
+ subtype: str | None,
43
+ confidence: float,
44
+ evidence_refs: list[str],
45
+ *,
46
+ provider: str = "offline-fixture",
47
+ version: str = "1",
48
+ timeout: bool = False,
49
+ ) -> dict[str, Any]:
50
+ if item_family not in SUPPORTED_FAMILIES | UNSUPPORTED_FAMILIES:
51
+ raise ValueError(f"unsupported item family label: {item_family}")
52
+ if not 0.0 <= confidence <= 1.0:
53
+ raise ValueError("classification confidence must be between 0 and 1")
54
+ return {
55
+ "itemFamily": item_family,
56
+ "subtype": subtype,
57
+ "confidence": round(confidence, 4),
58
+ "evidenceRefs": list(evidence_refs),
59
+ "provider": provider,
60
+ "version": version,
61
+ "timedOut": timeout,
62
+ }
63
+
64
+
65
+ def _classification_error(record: Any) -> str | None:
66
+ if not isinstance(record, dict):
67
+ return "authoritative classification record is required"
68
+ family = record.get("itemFamily")
69
+ confidence = record.get("confidence")
70
+ refs = record.get("evidenceRefs")
71
+ if not isinstance(family, str) or family not in SUPPORTED_FAMILIES | UNSUPPORTED_FAMILIES:
72
+ return "classification itemFamily is missing or invalid"
73
+ if not isinstance(confidence, (int, float)) or isinstance(confidence, bool) or not 0 <= confidence <= 1:
74
+ return "classification confidence is missing or invalid"
75
+ if not isinstance(refs, list) or not refs or not all(isinstance(item, str) and item for item in refs):
76
+ return "classification evidenceRefs must contain at least one reference"
77
+ if not isinstance(record.get("provider"), str) or not isinstance(record.get("version"), str):
78
+ return "classification provider/version are required"
79
+ return None
80
+
81
+
82
+ def _heuristic_signal(reference: Path) -> dict[str, Any]:
83
+ try:
84
+ return detect_cs2_signals(reference)
85
+ except (OSError, ValueError) as exc:
86
+ return {"is_cs2_candidate": False, "confidence": 0.0, "signals": [], "error": str(exc)}
87
+
88
+
89
+ def build_manifest(
90
+ reference: Path,
91
+ classification: dict[str, Any] | None,
92
+ *,
93
+ route: str = "reference-projection",
94
+ exactness_tier: str = "image-only",
95
+ metadata: dict[str, Any] | None = None,
96
+ texture_source: str = "image-only",
97
+ explicit_identity: dict[str, Any] | None = None,
98
+ ) -> dict[str, Any]:
99
+ resolved = reference.expanduser().resolve()
100
+ technical: dict[str, Any] = probe(resolved) if resolved.exists() else {"path": str(resolved), "warnings": ["file does not exist"]}
101
+ admission: dict[str, Any] = check_admission(resolved) if resolved.exists() else {"admitted": False, "reasons": ["reference does not exist"]}
102
+ heuristic = _heuristic_signal(resolved) if resolved.exists() else {"is_cs2_candidate": False, "confidence": 0.0, "signals": []}
103
+ warnings: list[str] = []
104
+ if heuristic.get("is_cs2_candidate"):
105
+ warnings.append("heuristicSignal")
106
+ if technical.get("warnings"):
107
+ warnings.extend(str(item) for item in technical["warnings"])
108
+ if route not in ROUTES:
109
+ raise ValueError(f"unknown route {route!r}")
110
+ if exactness_tier not in TIERS:
111
+ raise ValueError(f"unknown exactness tier {exactness_tier!r}")
112
+ manifest: dict[str, Any] = {
113
+ "schemaVersion": SCHEMA_VERSION,
114
+ "state": "rejected" if not admission.get("admitted") else "request-input",
115
+ "sourceViews": [{
116
+ "role": "reference",
117
+ "path": str(resolved),
118
+ "hash": admission.get("provenance", {}).get("pHash"),
119
+ "width": technical.get("width"),
120
+ "height": technical.get("height"),
121
+ "coverage": admission.get("provenance", {}).get("foregroundCoverage"),
122
+ "duplicate": admission.get("provenance", {}).get("duplicateOfHash") is not None,
123
+ }],
124
+ "admission": admission,
125
+ "probe": technical,
126
+ "heuristicSignal": heuristic,
127
+ "exactnessTier": exactness_tier,
128
+ "route": route,
129
+ "textureSource": texture_source,
130
+ "identity": {"provenance": "unknown", "confidence": 0.0},
131
+ "finish": {"provenance": "visual-observation", "confidence": 0.0},
132
+ "assets": {"source": texture_source, "records": []},
133
+ "camera": {"status": "unknown", "provenance": "not-supplied"},
134
+ "provenance": {"reference": "user-supplied", "metadata": "not-supplied"},
135
+ "assumptions": {"float": "unknown", "paintSeed": "unknown", "hiddenRegions": "inferred"},
136
+ "confidence": {"overall": 0.0, "hiddenRegions": 0.25},
137
+ "warnings": warnings,
138
+ "extensions": {},
139
+ "reviewScene": build_review_scene("not-supplied"),
140
+ }
141
+ if not admission.get("admitted"):
142
+ manifest["rejectionReasons"] = admission.get("reasons", ["reference failed admission"])
143
+ return manifest
144
+ error = _classification_error(classification)
145
+ if error:
146
+ manifest["warnings"].append(error)
147
+ return manifest
148
+ assert isinstance(classification, dict)
149
+ family = classification["itemFamily"]
150
+ subtype = classification.get("subtype")
151
+ manifest["classification"] = classification
152
+ manifest["itemFamily"] = family
153
+ manifest["subtype"] = subtype
154
+ manifest["identity"] = {"provenance": "classification-record", "confidence": classification["confidence"]}
155
+ manifest["confidence"] = {"overall": classification["confidence"], "hiddenRegions": 0.25}
156
+ manifest["identity"] = resolve_identity(explicit_identity, metadata, classification)
157
+ if family not in SUPPORTED_FAMILIES:
158
+ manifest["state"] = "unsupported-family"
159
+ manifest["unsupportedReason"] = f"no adapter registered for {family}"
160
+ elif subtype and subtype not in KNIFE_SUBTYPES:
161
+ manifest["state"] = "unsupported-subtype"
162
+ manifest["unsupportedReason"] = f"no knife adapter fixture for {subtype}"
163
+ else:
164
+ manifest["state"] = "proceed"
165
+ manifest["componentAdapter"] = "cs2-knife-v1"
166
+ if metadata:
167
+ manifest = enrich_manifest_with_metadata(manifest, {"status": "resolved", "identity": metadata})
168
+ manifest["metadata"] = normalize_cs2_metadata(metadata)
169
+ manifest["provenance"]["metadata"] = metadata.get("source", "provided")
170
+ return manifest
171
+
172
+
173
+ def validate_manifest(manifest: dict[str, Any]) -> bool:
174
+ required = {"schemaVersion", "state", "sourceViews", "admission", "exactnessTier", "route", "warnings"}
175
+ if not required.issubset(manifest):
176
+ return False
177
+ if manifest["schemaVersion"] != SCHEMA_VERSION or manifest["state"] not in STATES:
178
+ return False
179
+ if manifest["route"] not in ROUTES or manifest["exactnessTier"] not in TIERS:
180
+ return False
181
+ if not isinstance(manifest["sourceViews"], list) or not isinstance(manifest["warnings"], list):
182
+ return False
183
+ if manifest["state"] == "proceed" and manifest.get("itemFamily") != "knife":
184
+ return False
185
+ return True
186
+
187
+
188
+ def persist_manifest(manifest: dict[str, Any], output: Path) -> None:
189
+ if not validate_manifest(manifest):
190
+ raise ValueError("refusing to persist invalid cs2-intake manifest")
191
+ output = output.expanduser().resolve()
192
+ output.parent.mkdir(parents=True, exist_ok=True)
193
+ fd, temp_name = tempfile.mkstemp(prefix=f".{output.name}.", suffix=".tmp", dir=output.parent)
194
+ try:
195
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
196
+ json.dump(manifest, handle, indent=2, ensure_ascii=False)
197
+ handle.write("\n")
198
+ handle.flush()
199
+ os.fsync(handle.fileno())
200
+ os.replace(temp_name, output)
201
+ finally:
202
+ if os.path.exists(temp_name):
203
+ os.unlink(temp_name)
204
+
205
+
206
+ def main(argv: list[str]) -> int:
207
+ parser = argparse.ArgumentParser(description=__doc__)
208
+ parser.add_argument("reference", type=Path)
209
+ parser.add_argument("--classification", type=Path, help="offline authoritative classification JSON")
210
+ parser.add_argument("--out", type=Path, required=True)
211
+ parser.add_argument("--route", choices=sorted(ROUTES), default="reference-projection")
212
+ parser.add_argument("--exactness-tier", choices=sorted(TIERS), default="image-only")
213
+ parser.add_argument("--cs2-pipeline", choices=("legacy", "manifest-v1"), default="manifest-v1")
214
+ parser.add_argument("--resume", action="store_true", help="reuse a valid existing manifest at --out")
215
+ args = parser.parse_args(argv)
216
+ if args.resume and args.out.exists():
217
+ existing = json.loads(args.out.read_text(encoding="utf-8"))
218
+ if isinstance(existing, dict) and validate_manifest(existing):
219
+ print(json.dumps({"state": existing["state"], "out": str(args.out.resolve()), "resumed": True}, ensure_ascii=False))
220
+ return 0
221
+ classification = json.loads(args.classification.read_text(encoding="utf-8")) if args.classification else None
222
+ manifest = build_manifest(args.reference, classification, route=args.route, exactness_tier=args.exactness_tier)
223
+ manifest["extensions"]["compatibilityMode"] = args.cs2_pipeline
224
+ persist_manifest(manifest, args.out)
225
+ print(json.dumps({"state": manifest["state"], "out": str(args.out.resolve())}, ensure_ascii=False))
226
+ return 0 if manifest["state"] in {"proceed", "request-input", "fallback"} else 2
227
+
228
+
229
+ if __name__ == "__main__":
230
+ raise SystemExit(main(sys.argv[1:]))
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+
6
+ GOLDEN_THRESHOLDS = {
7
+ "silhouetteIoU": 0.85,
8
+ "aspectRatioDelta": 0.05,
9
+ "scaleDelta": 0.08,
10
+ "paintedRegionMask": 0.85,
11
+ "colorRegion": 0.80,
12
+ "patternRegion": 0.75,
13
+ "wearRegion": 0.70,
14
+ }
15
+
16
+
17
+ def build_review_scene(environment_hash: str) -> dict[str, Any]:
18
+ return {
19
+ "version": "cs2-knife-review-v1",
20
+ "camera": {"fovDegrees": 40.0, "position": [0.0, 0.0, 3.0], "target": [0.0, 0.0, 0.0]},
21
+ "objectTransform": {"position": [0.0, 0.0, 0.0], "rotation": [0.0, 0.0, 0.0], "scale": [1.0, 1.0, 1.0]},
22
+ "environmentHash": environment_hash,
23
+ "exposure": 1.0,
24
+ "toneMapping": "ACESFilmic",
25
+ "resolution": [1024, 1024],
26
+ "background": "#20242a",
27
+ "rendererVersion": "three-r170",
28
+ "thresholds": dict(GOLDEN_THRESHOLDS),
29
+ "orbitViewpoints": [{"yaw": 35.0, "pitch": 8.0}, {"yaw": -35.0, "pitch": 8.0}],
30
+ }
31
+
32
+
33
+ def validate_review_scene(scene: dict[str, Any]) -> list[str]:
34
+ required = {"version", "camera", "objectTransform", "environmentHash", "exposure", "toneMapping", "resolution", "background", "rendererVersion", "thresholds", "orbitViewpoints"}
35
+ errors = [f"missing {field}" for field in sorted(required - set(scene))]
36
+ if scene.get("version") != "cs2-knife-review-v1":
37
+ errors.append("unsupported review scene version")
38
+ if scene.get("thresholds") != GOLDEN_THRESHOLDS:
39
+ errors.append("golden thresholds do not match the frozen fixture contract")
40
+ if len(scene.get("orbitViewpoints", [])) != 2:
41
+ errors.append("exactly two orbit viewpoints are required")
42
+ return errors
@@ -0,0 +1,352 @@
1
+ #!/usr/bin/env python3
2
+ """Approximate a neutral (de-lit) albedo from a single reference photo.
3
+
4
+ This is an approximation, not true inverse rendering. A single photo bakes
5
+ together albedo, direct light, ambient occlusion, and specular response
6
+ into one signal, and there is no way to fully separate those from pixels
7
+ alone. This script applies a per-pixel normalization against a low-frequency
8
+ luminance estimate (a box-blur "lighting" proxy): pixels darker than their
9
+ local neighborhood get brightened, pixels brighter than their neighborhood
10
+ get darkened, pulling the image toward flat, even lighting. Strong specular
11
+ hotspots, deep occlusion shadows, and directional cues that vary faster than
12
+ the blur radius will not be fully removed. Always review the output next to
13
+ the source image before treating it as a projection albedo.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import json
20
+ import shutil
21
+ import struct
22
+ import subprocess
23
+ import sys
24
+ import tempfile
25
+ import zlib
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
30
+ from jpeg import UnsupportedJpeg, decode_jpeg, is_jpeg # noqa: E402
31
+
32
+
33
+ PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
34
+
35
+
36
+ def clamp(value: float, minimum: float, maximum: float) -> float:
37
+ return max(minimum, min(maximum, value))
38
+
39
+
40
+ def clamp01(value: float) -> float:
41
+ return clamp(value, 0.0, 1.0)
42
+
43
+
44
+ def srgb_luma(rgb: tuple[int, int, int]) -> float:
45
+ red, green, blue = rgb
46
+ return (0.2126 * red + 0.7152 * green + 0.0722 * blue) / 255.0
47
+
48
+
49
+ def percentile(values: list[float], fraction: float, fallback: float = 0.0) -> float:
50
+ if not values:
51
+ return fallback
52
+ ordered = sorted(values)
53
+ index = int(round(clamp01(fraction) * (len(ordered) - 1)))
54
+ return ordered[index]
55
+
56
+
57
+ def paeth_predictor(a: int, b: int, c: int) -> int:
58
+ p = a + b - c
59
+ pa = abs(p - a)
60
+ pb = abs(p - b)
61
+ pc = abs(p - c)
62
+ if pa <= pb and pa <= pc:
63
+ return a
64
+ if pb <= pc:
65
+ return b
66
+ return c
67
+
68
+
69
+ def read_png(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]]]:
70
+ data = path.read_bytes()
71
+ if not data.startswith(PNG_SIGNATURE):
72
+ raise ValueError("not a PNG file")
73
+ cursor = len(PNG_SIGNATURE)
74
+ width = height = bit_depth = color_type = None
75
+ idat = bytearray()
76
+ interlace = 0
77
+ while cursor + 8 <= len(data):
78
+ length = struct.unpack(">I", data[cursor : cursor + 4])[0]
79
+ chunk_type = data[cursor + 4 : cursor + 8]
80
+ chunk_data = data[cursor + 8 : cursor + 8 + length]
81
+ cursor += 12 + length
82
+ if chunk_type == b"IHDR":
83
+ width, height, bit_depth, color_type, _, _, interlace = struct.unpack(">IIBBBBB", chunk_data)
84
+ elif chunk_type == b"IDAT":
85
+ idat.extend(chunk_data)
86
+ elif chunk_type == b"IEND":
87
+ break
88
+ if width is None or height is None or bit_depth != 8 or interlace != 0:
89
+ raise ValueError("unsupported PNG; expected 8-bit non-interlaced image")
90
+ channels_by_type = {0: 1, 2: 3, 4: 2, 6: 4}
91
+ if color_type not in channels_by_type:
92
+ raise ValueError("unsupported PNG color type; convert to RGB/RGBA first")
93
+ channels = channels_by_type[color_type]
94
+ row_bytes = width * channels
95
+ raw = zlib.decompress(bytes(idat))
96
+ rows: list[bytearray] = []
97
+ offset = 0
98
+ previous = bytearray(row_bytes)
99
+ for _ in range(height):
100
+ filter_type = raw[offset]
101
+ offset += 1
102
+ row = bytearray(raw[offset : offset + row_bytes])
103
+ offset += row_bytes
104
+ for index in range(row_bytes):
105
+ left = row[index - channels] if index >= channels else 0
106
+ up = previous[index]
107
+ up_left = previous[index - channels] if index >= channels else 0
108
+ if filter_type == 1:
109
+ row[index] = (row[index] + left) & 0xFF
110
+ elif filter_type == 2:
111
+ row[index] = (row[index] + up) & 0xFF
112
+ elif filter_type == 3:
113
+ row[index] = (row[index] + ((left + up) // 2)) & 0xFF
114
+ elif filter_type == 4:
115
+ predictor = paeth_predictor(left, up, up_left)
116
+ row[index] = (row[index] + predictor) & 0xFF
117
+ elif filter_type != 0:
118
+ raise ValueError(f"unsupported PNG filter {filter_type}")
119
+ rows.append(row)
120
+ previous = row
121
+ pixels: list[tuple[int, int, int, int]] = []
122
+ for row in rows:
123
+ for x in range(width):
124
+ base = x * channels
125
+ if color_type == 0:
126
+ gray = row[base]
127
+ pixels.append((gray, gray, gray, 255))
128
+ elif color_type == 2:
129
+ pixels.append((row[base], row[base + 1], row[base + 2], 255))
130
+ elif color_type == 4:
131
+ gray = row[base]
132
+ pixels.append((gray, gray, gray, row[base + 1]))
133
+ elif color_type == 6:
134
+ pixels.append((row[base], row[base + 1], row[base + 2], row[base + 3]))
135
+ return width, height, pixels
136
+
137
+
138
+ def write_png_rgba(path: Path, width: int, height: int, rgba: bytes) -> None:
139
+ if len(rgba) != width * height * 4:
140
+ raise ValueError("RGBA payload has the wrong size")
141
+ path.parent.mkdir(parents=True, exist_ok=True)
142
+
143
+ def chunk(kind: bytes, payload: bytes) -> bytes:
144
+ checksum = zlib.crc32(kind)
145
+ checksum = zlib.crc32(payload, checksum) & 0xFFFFFFFF
146
+ return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", checksum)
147
+
148
+ scanlines = bytearray()
149
+ stride = width * 4
150
+ for y in range(height):
151
+ scanlines.append(0)
152
+ scanlines.extend(rgba[y * stride : (y + 1) * stride])
153
+ ihdr = struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)
154
+ path.write_bytes(
155
+ PNG_SIGNATURE
156
+ + chunk(b"IHDR", ihdr)
157
+ + chunk(b"IDAT", zlib.compress(bytes(scanlines), level=6))
158
+ + chunk(b"IEND", b"")
159
+ )
160
+
161
+
162
+ def load_image(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]], list[str]]:
163
+ warnings: list[str] = []
164
+ try:
165
+ return (*read_png(path), warnings)
166
+ except Exception as direct_error:
167
+ jpeg_bytes = path.read_bytes()
168
+ if is_jpeg(jpeg_bytes):
169
+ try:
170
+ return (*decode_jpeg(jpeg_bytes), warnings)
171
+ except UnsupportedJpeg as unsupported:
172
+ warnings.append(f"{path.name} needs an external converter: {unsupported}")
173
+ sips = shutil.which("sips")
174
+ if not sips:
175
+ raise ValueError(
176
+ f"could not decode {path.name} as PNG and macOS sips is unavailable: {direct_error}"
177
+ ) from direct_error
178
+ with tempfile.TemporaryDirectory() as tmpdir:
179
+ converted = Path(tmpdir) / "converted.png"
180
+ command = [sips, "-s", "format", "png", str(path), "--out", str(converted)]
181
+ result = subprocess.run(command, capture_output=True, text=True, check=False)
182
+ if result.returncode != 0:
183
+ raise ValueError(result.stderr.strip() or result.stdout.strip() or "sips conversion failed")
184
+ warnings.append("source image was converted to PNG with macOS sips before pixel extraction")
185
+ width, height, pixels = read_png(converted)
186
+ return width, height, pixels, warnings
187
+
188
+
189
+ def blur_scalar(values: list[float], width: int, height: int, radius: int) -> list[float]:
190
+ if radius <= 0:
191
+ return values[:]
192
+ horizontal = [0.0] * (width * height)
193
+ for y in range(height):
194
+ row_offset = y * width
195
+ running = 0.0
196
+ count = 0
197
+ for x in range(-radius, width + radius):
198
+ if 0 <= x < width:
199
+ running += values[row_offset + x]
200
+ count += 1
201
+ remove = x - radius * 2 - 1
202
+ if 0 <= remove < width:
203
+ running -= values[row_offset + remove]
204
+ count -= 1
205
+ write_x = x - radius
206
+ if 0 <= write_x < width:
207
+ horizontal[row_offset + write_x] = running / max(1, count)
208
+ vertical = [0.0] * (width * height)
209
+ for x in range(width):
210
+ running = 0.0
211
+ count = 0
212
+ for y in range(-radius, height + radius):
213
+ if 0 <= y < height:
214
+ running += horizontal[y * width + x]
215
+ count += 1
216
+ remove = y - radius * 2 - 1
217
+ if 0 <= remove < height:
218
+ running -= horizontal[remove * width + x]
219
+ count -= 1
220
+ write_y = y - radius
221
+ if 0 <= write_y < height:
222
+ vertical[write_y * width + x] = running / max(1, count)
223
+ return vertical
224
+
225
+
226
+ def delight(
227
+ width: int,
228
+ height: int,
229
+ pixels: list[tuple[int, int, int, int]],
230
+ strength: float,
231
+ blur_radius: int,
232
+ ) -> tuple[bytes, dict[str, Any]]:
233
+ lumas = [srgb_luma(pixel[:3]) for pixel in pixels]
234
+ target = percentile(lumas, 0.5, 0.5)
235
+ low_frequency = blur_scalar(lumas, width, height, blur_radius)
236
+ out = bytearray()
237
+ corrections: list[float] = []
238
+ for (red, green, blue, alpha), low in zip(pixels, low_frequency):
239
+ shade = clamp(low, 0.05, 1.0)
240
+ raw_scale = target / shade
241
+ # strength blends between no correction (1.0) and the full normalization
242
+ scale = 1.0 + (raw_scale - 1.0) * clamp01(strength)
243
+ scale = clamp(scale, 0.35, 2.6)
244
+ corrections.append(scale)
245
+ out.extend(
246
+ (
247
+ round(clamp(red * scale, 0, 255)),
248
+ round(clamp(green * scale, 0, 255)),
249
+ round(clamp(blue * scale, 0, 255)),
250
+ alpha,
251
+ )
252
+ )
253
+ luma_before_range = percentile(lumas, 0.95, 0.8) - percentile(lumas, 0.05, 0.2)
254
+ stats = {
255
+ "targetLuma": round(target, 4),
256
+ "blurRadius": blur_radius,
257
+ "lumaRangeBefore": round(luma_before_range, 4),
258
+ "meanCorrectionScale": round(sum(corrections) / max(1, len(corrections)), 4),
259
+ "maxCorrectionScale": round(max(corrections, default=1.0), 4),
260
+ "minCorrectionScale": round(min(corrections, default=1.0), 4),
261
+ }
262
+ return bytes(out), stats
263
+
264
+
265
+ def estimate_confidence(stats: dict[str, Any], strength: float, warnings: list[str]) -> tuple[float, list[str]]:
266
+ notes: list[str] = []
267
+ luma_range = float(stats.get("lumaRangeBefore", 0.4))
268
+ # a very large baked lighting range means more got corrected but also more
269
+ # residual error is likely, since the box blur is only a crude lighting proxy
270
+ range_penalty = clamp01((luma_range - 0.35) * 0.6)
271
+ strength_bonus = clamp01(strength) * 0.15
272
+ confidence = clamp01(0.55 - range_penalty * 0.25 + strength_bonus - min(0.1, len(warnings) * 0.04))
273
+ confidence = min(0.72, confidence) # single-image de-lighting is always capped
274
+ notes.append("single-image de-lighting cannot separate true albedo from baked light/AO/specular; confidence is capped")
275
+ if luma_range > 0.5:
276
+ notes.append("wide baked lighting range detected; expect visible residual shading after correction")
277
+ return round(confidence, 3), notes
278
+
279
+
280
+ def main(argv: list[str]) -> int:
281
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
282
+ parser.add_argument("image", type=Path)
283
+ parser.add_argument("--out", type=Path, required=True, help="Output de-lit PNG path")
284
+ parser.add_argument("--report", type=Path, help="Write the JSON report to this path (also printed to stdout)")
285
+ parser.add_argument(
286
+ "--strength",
287
+ type=float,
288
+ default=0.6,
289
+ help="0.0 = no correction (passthrough), 1.0 = full normalization against the blurred luminance proxy (default 0.6)",
290
+ )
291
+ parser.add_argument(
292
+ "--blur-radius",
293
+ type=int,
294
+ default=0,
295
+ help="Box-blur radius in pixels for the low-frequency lighting estimate; 0 = auto from image size",
296
+ )
297
+ args = parser.parse_args(argv)
298
+
299
+ image = args.image.expanduser().resolve()
300
+ if not image.exists():
301
+ parser.error(f"{image} does not exist")
302
+ out_path = args.out.expanduser().resolve()
303
+
304
+ try:
305
+ width, height, pixels, load_warnings = load_image(image)
306
+ blur_radius = args.blur_radius if args.blur_radius > 0 else max(6, min(48, min(width, height) // 20))
307
+ strength = clamp01(args.strength)
308
+ delit_rgba, stats = delight(width, height, pixels, strength, blur_radius)
309
+ write_png_rgba(out_path, width, height, delit_rgba)
310
+
311
+ confidence, confidence_notes = estimate_confidence(stats, strength, load_warnings)
312
+ report = {
313
+ "delightReference": {
314
+ "version": "1.0",
315
+ "sourceImage": str(image),
316
+ "outputImage": str(out_path),
317
+ "method": (
318
+ "per-pixel normalization against a box-blurred luminance proxy; an approximation of "
319
+ "de-lighting, not physically based inverse rendering or true light/albedo separation"
320
+ ),
321
+ "strength": strength,
322
+ "confidence": confidence,
323
+ "stats": stats,
324
+ "limitations": [
325
+ "this is an approximation, not true inverse rendering; it cannot recover ground-truth albedo",
326
+ "sharp specular highlights and hard shadow edges narrower than the blur radius will remain baked in",
327
+ "deep occlusion shadows (creases, undercuts) are only partially lifted",
328
+ "must be reviewed visually next to the source image before use as a projection albedo",
329
+ ]
330
+ + confidence_notes
331
+ + load_warnings,
332
+ "note": (
333
+ "If shadows or highlights are still visible in the output, try a larger --strength or a "
334
+ "smaller --blur-radius so the correction responds to tighter lighting gradients, then "
335
+ "re-review; this script does not know when the correction is visually sufficient."
336
+ ),
337
+ }
338
+ }
339
+ text = json.dumps(report, indent=2, ensure_ascii=False)
340
+ if args.report:
341
+ report_path = args.report.expanduser().resolve()
342
+ report_path.parent.mkdir(parents=True, exist_ok=True)
343
+ report_path.write_text(text + "\n", encoding="utf-8")
344
+ print(text)
345
+ return 0
346
+ except Exception as exc:
347
+ print(f"error: {exc}", file=sys.stderr)
348
+ return 1
349
+
350
+
351
+ if __name__ == "__main__":
352
+ raise SystemExit(main(sys.argv[1:]))