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.
- package/assets/rebuild-object/.cache/spec-search/core_3d.json +1 -0
- package/assets/rebuild-object/.cache/spec-search/cs2.json +1 -0
- package/assets/rebuild-object/LICENSE +201 -0
- package/assets/rebuild-object/NOTICE +7 -0
- package/assets/rebuild-object/docs/materials/material-reference.json +2324 -0
- package/assets/rebuild-object/docs/specs/render-profile.v2.example.json +63 -0
- package/assets/rebuild-object/docs/specs/render-profile.v2.schema.json +56 -0
- package/assets/rebuild-object/docs/specs/vocabulary/README.md +86 -0
- package/assets/rebuild-object/docs/specs/vocabulary/core_3d.jsonl +12 -0
- package/assets/rebuild-object/docs/specs/vocabulary/core_3d_reconstruction.jsonl +37 -0
- package/assets/rebuild-object/docs/specs/vocabulary/cs2.jsonl +8 -0
- package/assets/rebuild-object/docs/specs/vocabulary/cs2_reconstruction.jsonl +62 -0
- package/assets/rebuild-object/forge/_shared/artifact_cache.py +54 -0
- package/assets/rebuild-object/forge/_shared/chirality.py +272 -0
- package/assets/rebuild-object/forge/_shared/color_metrics.py +107 -0
- package/assets/rebuild-object/forge/_shared/feature_acceptance_policy.py +113 -0
- package/assets/rebuild-object/forge/_shared/image_hash.py +113 -0
- package/assets/rebuild-object/forge/_shared/jpeg.py +448 -0
- package/assets/rebuild-object/forge/_shared/material_physics.py +253 -0
- package/assets/rebuild-object/forge/_shared/pipeline_routing.py +177 -0
- package/assets/rebuild-object/forge/_shared/scalp_field.py +302 -0
- package/assets/rebuild-object/forge/_shared/sdf_primitives.py +172 -0
- package/assets/rebuild-object/forge/_shared/spec_search.py +1792 -0
- package/assets/rebuild-object/forge/_shared/spec_search_profiles.json +58 -0
- package/assets/rebuild-object/forge/_shared/status_banner.py +35 -0
- package/assets/rebuild-object/forge/_shared/subdivision.py +232 -0
- package/assets/rebuild-object/forge/_shared/vertex_paint.py +236 -0
- package/assets/rebuild-object/forge/_shared/workflow_state.py +406 -0
- package/assets/rebuild-object/forge/materials/__init__.py +17 -0
- package/assets/rebuild-object/forge/materials/compatibility.py +106 -0
- package/assets/rebuild-object/forge/materials/reference.py +240 -0
- package/assets/rebuild-object/forge/next.py +116 -0
- package/assets/rebuild-object/forge/report.py +38 -0
- package/assets/rebuild-object/forge/requirements.txt +6 -0
- package/assets/rebuild-object/forge/stage1_intake/analyze_texture.py +255 -0
- package/assets/rebuild-object/forge/stage1_intake/bind_detail_properties.py +99 -0
- package/assets/rebuild-object/forge/stage1_intake/build_detail_inventory.py +349 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_fitting_math.py +133 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_fitting_solver.py +197 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_fitting_types.py +291 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_image_helpers.py +133 -0
- package/assets/rebuild-object/forge/stage1_intake/check_intake_correctness.py +116 -0
- package/assets/rebuild-object/forge/stage1_intake/check_reference_admission.py +203 -0
- package/assets/rebuild-object/forge/stage1_intake/cs2_foundation.py +139 -0
- package/assets/rebuild-object/forge/stage1_intake/cs2_manifest.py +230 -0
- package/assets/rebuild-object/forge/stage1_intake/cs2_review_contract.py +42 -0
- package/assets/rebuild-object/forge/stage1_intake/delight_albedo.py +352 -0
- package/assets/rebuild-object/forge/stage1_intake/detect_cs2.py +276 -0
- package/assets/rebuild-object/forge/stage1_intake/detect_reference_effects.py +275 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_cs2_textures.py +126 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_gradient_stops.py +149 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_hair_evidence.py +385 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_landmarks.py +456 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_part_color_recipe.py +496 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_pbr_evidence.py +843 -0
- package/assets/rebuild-object/forge/stage1_intake/fetch_cs2_metadata.py +147 -0
- package/assets/rebuild-object/forge/stage1_intake/label_glb_nodes.py +318 -0
- package/assets/rebuild-object/forge/stage1_intake/locate_cs2_vpk.py +73 -0
- package/assets/rebuild-object/forge/stage1_intake/material_region_analysis.py +227 -0
- package/assets/rebuild-object/forge/stage1_intake/probe_glb.py +357 -0
- package/assets/rebuild-object/forge/stage1_intake/probe_image.py +168 -0
- package/assets/rebuild-object/forge/stage1_intake/run_vision_adapter.py +45 -0
- package/assets/rebuild-object/forge/stage1_intake/search_specs.py +258 -0
- package/assets/rebuild-object/forge/stage1_intake/semantic_decomposition.py +119 -0
- package/assets/rebuild-object/forge/stage1_intake/solve_camera_pose.py +254 -0
- package/assets/rebuild-object/forge/stage2_spec/apply_material_analysis.py +192 -0
- package/assets/rebuild-object/forge/stage2_spec/cs2_adapters.py +62 -0
- package/assets/rebuild-object/forge/stage2_spec/derive_geometry.py +118 -0
- package/assets/rebuild-object/forge/stage2_spec/hair_profile.py +306 -0
- package/assets/rebuild-object/forge/stage2_spec/humanoid_proportions.py +214 -0
- package/assets/rebuild-object/forge/stage2_spec/new_pre_spec_assessment.py +343 -0
- package/assets/rebuild-object/forge/stage2_spec/new_sculpt_spec.py +2396 -0
- package/assets/rebuild-object/forge/stage2_spec/validate_sculpt_spec.py +2871 -0
- package/assets/rebuild-object/forge/stage3_build/bake_projected_texture.py +181 -0
- package/assets/rebuild-object/forge/stage3_build/decimate.py +272 -0
- package/assets/rebuild-object/forge/stage3_build/generate_threejs_factory.py +4099 -0
- package/assets/rebuild-object/forge/stage3_build/module_cache.py +155 -0
- package/assets/rebuild-object/forge/stage3_build/morph_targets.py +178 -0
- package/assets/rebuild-object/forge/stage3_build/orchestrate_passes.py +653 -0
- package/assets/rebuild-object/forge/stage3_build/uv_unwrap.py +622 -0
- package/assets/rebuild-object/forge/stage3_build/visual_hull.py +357 -0
- package/assets/rebuild-object/forge/stage4_review/_fit_divine_eye.py +64 -0
- package/assets/rebuild-object/forge/stage4_review/append_review.py +453 -0
- package/assets/rebuild-object/forge/stage4_review/attachment_anchor.py +349 -0
- package/assets/rebuild-object/forge/stage4_review/calibrate_eye.py +131 -0
- package/assets/rebuild-object/forge/stage4_review/check_part_coverage.py +298 -0
- package/assets/rebuild-object/forge/stage4_review/compare_region_passes.py +169 -0
- package/assets/rebuild-object/forge/stage4_review/correction_loop.py +258 -0
- package/assets/rebuild-object/forge/stage4_review/cs2_review.py +224 -0
- package/assets/rebuild-object/forge/stage4_review/diagnose_render.py +356 -0
- package/assets/rebuild-object/forge/stage4_review/diagnose_render_multi_angle.py +143 -0
- package/assets/rebuild-object/forge/stage4_review/divine_eye.py +461 -0
- package/assets/rebuild-object/forge/stage4_review/fit_params.py +381 -0
- package/assets/rebuild-object/forge/stage4_review/geometry_integrity.py +294 -0
- package/assets/rebuild-object/forge/stage4_review/hair_gate.py +216 -0
- package/assets/rebuild-object/forge/stage4_review/interior_difference.py +188 -0
- package/assets/rebuild-object/forge/stage4_review/joint_loops.py +209 -0
- package/assets/rebuild-object/forge/stage4_review/make_comparison_sheet.py +292 -0
- package/assets/rebuild-object/forge/stage4_review/material_comparator.py +181 -0
- package/assets/rebuild-object/forge/stage4_review/material_feedback.py +143 -0
- package/assets/rebuild-object/forge/stage4_review/material_gate.py +126 -0
- package/assets/rebuild-object/forge/stage4_review/material_views.py +184 -0
- package/assets/rebuild-object/forge/stage4_review/mesh_reference_compare.py +362 -0
- package/assets/rebuild-object/forge/stage4_review/multi_pass.py +102 -0
- package/assets/rebuild-object/forge/stage4_review/objectness.py +143 -0
- package/assets/rebuild-object/forge/stage4_review/pairwise_penetration.py +376 -0
- package/assets/rebuild-object/forge/stage4_review/per_feature.py +215 -0
- package/assets/rebuild-object/forge/stage4_review/render_bridge.py +556 -0
- package/assets/rebuild-object/forge/stage4_review/scalp_exposure.py +257 -0
- package/assets/rebuild-object/forge/stage4_review/self_intersection.py +592 -0
- package/assets/rebuild-object/forge/stage4_review/swept_arc_gate.py +336 -0
- package/assets/rebuild-object/forge/stage4_review/turntable_gate.py +415 -0
- package/assets/rebuild-object/forge/stage4_review/validate_render_profile.py +182 -0
- package/assets/rebuild-object/forge/stage4_review/vertex_region_gate.py +456 -0
- package/assets/rebuild-object/forge/stage4_review/vlm_gate.py +196 -0
- package/assets/rebuild-object/forge/stage5_rig/NOTES.md +149 -0
- package/assets/rebuild-object/forge/stage5_rig/__init__.py +6 -0
- package/assets/rebuild-object/forge/stage5_rig/emit_rig.py +420 -0
- package/assets/rebuild-object/forge/stage5_rig/geodesic_skinning.py +508 -0
- package/assets/rebuild-object/forge/stage5_rig/rig_spec.py +174 -0
- package/assets/rebuild-object/forge/stage5_rig/validate_rig_payload.py +195 -0
- package/assets/rebuild-object/forge/state.py +98 -0
- package/assets/rebuild-object/steps.json +381 -0
- package/dist/{chunk-FB3UDZAV.js → chunk-24TITAFS.js} +1 -1
- package/dist/{chunk-QNWCBPVO.js → chunk-2C5PG2QO.js} +1 -1
- package/dist/{chunk-4RYTTD4D.js → chunk-2DEVOKI7.js} +1 -1
- package/dist/{chunk-RRI23NK2.js → chunk-2GHPYT2P.js} +1 -1
- package/dist/{chunk-QEKVZ7BX.js → chunk-2HXGMXGC.js} +1 -1
- package/dist/{chunk-N2UHAQXC.js → chunk-36FORP7T.js} +0 -1
- package/dist/{chunk-DH6WPL3X.js → chunk-3IXRQTRF.js} +1 -1
- package/dist/{chunk-SXYQL4GK.js → chunk-4YHA32OE.js} +1 -1
- package/dist/{chunk-V5ADM3WC.js → chunk-4ZGQKPK5.js} +1 -1
- package/dist/{chunk-BJAN3RMY.js → chunk-6CLUPFQA.js} +1 -1
- package/dist/{chunk-52E6EKZV.js → chunk-7WTF2BA4.js} +1 -1
- package/dist/{chunk-P74GTK23.js → chunk-AAXZNK4Z.js} +1 -1
- package/dist/{chunk-F4J6XCHT.js → chunk-ALLBT4FB.js} +1 -1
- package/dist/{chunk-HRKVAXNN.js → chunk-BAZDPPIG.js} +5 -5
- package/dist/{chunk-RPJR3S5S.js → chunk-CYDENLZ4.js} +5 -8
- package/dist/{chunk-I5LELJSK.js → chunk-DKSUD44G.js} +1 -1
- package/dist/{chunk-43P4U7CB.js → chunk-DWWSJKTE.js} +1 -1
- package/dist/{chunk-6IUFHPMV.js → chunk-E72TFJZP.js} +1 -1
- package/dist/{chunk-E3FJUPLT.js → chunk-EUAAQMUA.js} +2 -0
- package/dist/{chunk-37LLKM73.js → chunk-F7LYJSZE.js} +1 -1
- package/dist/{chunk-MEAO33XW.js → chunk-FMON3C74.js} +8 -8
- package/dist/{chunk-YLUB6252.js → chunk-FPILHRLZ.js} +1 -1
- package/dist/{chunk-4UU622RK.js → chunk-GGO6ZYYI.js} +1 -3
- package/dist/{chunk-2ZKS7V72.js → chunk-GZCRYYS6.js} +5 -5
- package/dist/{chunk-E7NDOZ27.js → chunk-LE4GVTYI.js} +8 -8
- package/dist/{chunk-UTSSDFQL.js → chunk-NO6KPV64.js} +1 -1
- package/dist/{chunk-W2QPNAZ3.js → chunk-NXW3Z4Y4.js} +1 -1
- package/dist/{chunk-NG2X3SMF.js → chunk-OHOAZGO4.js} +1 -1
- package/dist/chunk-PYJNI5WD.js +83 -0
- package/dist/{chunk-VUV5U4J5.js → chunk-Q4XAGTFX.js} +1 -1
- package/dist/{chunk-3UGGMFJJ.js → chunk-QMZBSVKF.js} +1 -1
- package/dist/{chunk-ABTUEIRC.js → chunk-QO66UBOS.js} +2 -2
- package/dist/{chunk-LONQWRTR.js → chunk-S4KVGQQO.js} +8 -8
- package/dist/{chunk-FJXPMA63.js → chunk-T777EXAO.js} +1 -1
- package/dist/{chunk-YXOGRERG.js → chunk-TZZNRA3S.js} +1 -1
- package/dist/{chunk-CTY2WZQK.js → chunk-UC3QLWMQ.js} +1 -1
- package/dist/{chunk-MR5KIFI7.js → chunk-UDJH2RED.js} +3 -3
- package/dist/{chunk-FNJL6Z5C.js → chunk-UIKYK7KI.js} +1 -1
- package/dist/{chunk-PKM3JOKQ.js → chunk-UJRSQO2B.js} +1 -1
- package/dist/{chunk-ALPTHSUT.js → chunk-V7LEYVXB.js} +28 -24
- package/dist/{chunk-DPLFCKXP.js → chunk-WRMQEXUC.js} +1 -1
- package/dist/{chunk-HSMG6U7J.js → chunk-WXSBNC67.js} +3 -9
- package/dist/{chunk-HSCTPDEU.js → chunk-X4QIOXNQ.js} +1 -1
- package/dist/{chunk-72KHWZMN.js → chunk-Y6WHUK2O.js} +1 -1
- package/dist/{chunk-VZEJ2ZHE.js → chunk-Z3E7ORGQ.js} +5 -5
- package/dist/index.js +20 -20
- package/package.json +32 -22
- package/dist/{chunk-OFJIG4K3.js → chunk-4ENHS32B.js} +0 -0
- package/dist/{chunk-Q3XQPNF6.js → chunk-BN7TR6OR.js} +3 -3
- package/dist/{chunk-LORGE2NB.js → chunk-U2NCN5RO.js} +3 -3
- package/dist/{chunk-UPHB5HWO.js → chunk-VQTTSPA3.js} +3 -3
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Extract a structured per-component color/material recipe from a crop.
|
|
3
|
+
|
|
4
|
+
Plan 1.3 Workstream C. Extends extract_pbr_evidence.py's pixel-evidence approach
|
|
5
|
+
with CIE L*a*b* clustering (not RGB), Bradford chromatic adaptation, specular-
|
|
6
|
+
hotspot-based roughness estimation, and optional smooth color-gradient detection.
|
|
7
|
+
Colors are emitted as "rgba(r, g, b, a)" strings, matching the Canvas 2D
|
|
8
|
+
addColorStop(offset, color) signature the codegen already consumes, so no
|
|
9
|
+
format conversion is needed between extraction and generate_threejs_factory.py.
|
|
10
|
+
|
|
11
|
+
Pure Python 3.10+ standard library only — no PIL/numpy, matching the rest of forge/.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import math
|
|
19
|
+
import sys
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
24
|
+
from extract_pbr_evidence import ( # noqa: E402
|
|
25
|
+
build_foreground_mask,
|
|
26
|
+
clamp,
|
|
27
|
+
clamp01,
|
|
28
|
+
load_image,
|
|
29
|
+
mask_bbox,
|
|
30
|
+
representative_samples,
|
|
31
|
+
resample_crop,
|
|
32
|
+
slugify,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
|
|
36
|
+
from artifact_cache import cache_key, get_cached, manifest_path_for, put_cached # noqa: E402
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# ---------- CIE L*a*b* conversion (sRGB, D65 reference white) ----------
|
|
40
|
+
|
|
41
|
+
_D65 = (0.95047, 1.0, 1.08883)
|
|
42
|
+
|
|
43
|
+
# sRGB (linear) -> XYZ, D65
|
|
44
|
+
_RGB_TO_XYZ = (
|
|
45
|
+
(0.4124564, 0.3575761, 0.1804375),
|
|
46
|
+
(0.2126729, 0.7151522, 0.0721750),
|
|
47
|
+
(0.0193339, 0.1191920, 0.9503041),
|
|
48
|
+
)
|
|
49
|
+
_XYZ_TO_RGB = (
|
|
50
|
+
(3.2404542, -1.5371385, -0.4985314),
|
|
51
|
+
(-0.9692660, 1.8760108, 0.0415560),
|
|
52
|
+
(0.0556434, -0.2040259, 1.0572252),
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
# Bradford cone-response matrix, used for chromatic adaptation.
|
|
56
|
+
_BRADFORD = (
|
|
57
|
+
(0.8951, 0.2664, -0.1614),
|
|
58
|
+
(-0.7502, 1.7135, 0.0367),
|
|
59
|
+
(0.0389, -0.0685, 1.0296),
|
|
60
|
+
)
|
|
61
|
+
_BRADFORD_INV = (
|
|
62
|
+
(0.9869929, -0.1470543, 0.1599627),
|
|
63
|
+
(0.4323053, 0.5183603, 0.0492912),
|
|
64
|
+
(-0.0085287, 0.0400428, 0.9684867),
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _matmul3(matrix: tuple[tuple[float, float, float], ...], vector: tuple[float, float, float]) -> tuple[float, float, float]:
|
|
69
|
+
return tuple(
|
|
70
|
+
sum(matrix[row][col] * vector[col] for col in range(3)) for row in range(3)
|
|
71
|
+
) # type: ignore[return-value]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _srgb_to_linear(channel: float) -> float:
|
|
75
|
+
c = channel / 255.0
|
|
76
|
+
if c <= 0.04045:
|
|
77
|
+
return c / 12.92
|
|
78
|
+
return ((c + 0.055) / 1.055) ** 2.4
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _linear_to_srgb(channel: float) -> float:
|
|
82
|
+
c = clamp01(channel)
|
|
83
|
+
if c <= 0.0031308:
|
|
84
|
+
srgb = c * 12.92
|
|
85
|
+
else:
|
|
86
|
+
srgb = 1.055 * (c ** (1.0 / 2.4)) - 0.055
|
|
87
|
+
return clamp(srgb * 255.0, 0.0, 255.0)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _lab_f(t: float) -> float:
|
|
91
|
+
delta = 6.0 / 29.0
|
|
92
|
+
if t > delta ** 3:
|
|
93
|
+
return t ** (1.0 / 3.0)
|
|
94
|
+
return t / (3.0 * delta * delta) + 4.0 / 29.0
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _lab_f_inv(t: float) -> float:
|
|
98
|
+
delta = 6.0 / 29.0
|
|
99
|
+
if t > delta:
|
|
100
|
+
return t ** 3
|
|
101
|
+
return 3.0 * delta * delta * (t - 4.0 / 29.0)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def rgb_to_xyz(rgb: tuple[int, int, int]) -> tuple[float, float, float]:
|
|
105
|
+
linear = tuple(_srgb_to_linear(channel) for channel in rgb)
|
|
106
|
+
return _matmul3(_RGB_TO_XYZ, linear) # type: ignore[arg-type]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def xyz_to_rgb(xyz: tuple[float, float, float]) -> tuple[int, int, int]:
|
|
110
|
+
linear = _matmul3(_XYZ_TO_RGB, xyz)
|
|
111
|
+
return tuple(round(_linear_to_srgb(channel)) for channel in linear) # type: ignore[return-value]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def xyz_to_lab(xyz: tuple[float, float, float], white: tuple[float, float, float] = _D65) -> tuple[float, float, float]:
|
|
115
|
+
xr, yr, zr = (xyz[i] / white[i] for i in range(3))
|
|
116
|
+
fx, fy, fz = _lab_f(xr), _lab_f(yr), _lab_f(zr)
|
|
117
|
+
l_star = 116.0 * fy - 16.0
|
|
118
|
+
a_star = 500.0 * (fx - fy)
|
|
119
|
+
b_star = 200.0 * (fy - fz)
|
|
120
|
+
return (l_star, a_star, b_star)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def lab_to_xyz(lab: tuple[float, float, float], white: tuple[float, float, float] = _D65) -> tuple[float, float, float]:
|
|
124
|
+
l_star, a_star, b_star = lab
|
|
125
|
+
fy = (l_star + 16.0) / 116.0
|
|
126
|
+
fx = fy + a_star / 500.0
|
|
127
|
+
fz = fy - b_star / 200.0
|
|
128
|
+
return (white[0] * _lab_f_inv(fx), white[1] * _lab_f_inv(fy), white[2] * _lab_f_inv(fz))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def srgb_to_lab(rgb: tuple[int, int, int]) -> tuple[float, float, float]:
|
|
132
|
+
return xyz_to_lab(rgb_to_xyz(rgb))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def lab_to_rgb(lab: tuple[float, float, float]) -> tuple[int, int, int]:
|
|
136
|
+
return xyz_to_rgb(lab_to_xyz(lab))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def lab_to_rgba(lab: tuple[float, float, float], alpha: float = 1.0) -> str:
|
|
140
|
+
r, g, b = lab_to_rgb(lab)
|
|
141
|
+
return f"rgba({r}, {g}, {b}, {round(clamp01(alpha), 3)})"
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def lab_distance(a: tuple[float, float, float], b: tuple[float, float, float]) -> float:
|
|
145
|
+
"""CIE76 (Euclidean Lab) distance — sufficient for this project's thresholds."""
|
|
146
|
+
return math.sqrt(sum((a[i] - b[i]) ** 2 for i in range(3)))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def bradford_adapt(
|
|
150
|
+
lab: tuple[float, float, float],
|
|
151
|
+
source_white: tuple[float, float, float],
|
|
152
|
+
target_white: tuple[float, float, float] = _D65,
|
|
153
|
+
) -> tuple[float, float, float]:
|
|
154
|
+
"""Chromatic-adapt a Lab color from an estimated source illuminant to target_white
|
|
155
|
+
(D65 by default) via the Bradford cone-response transform, approximating a neutral
|
|
156
|
+
white-balance so warm/cool ambient light doesn't skew the extracted albedo."""
|
|
157
|
+
xyz = lab_to_xyz(lab, white=source_white)
|
|
158
|
+
src_cone = _matmul3(_BRADFORD, source_white)
|
|
159
|
+
dst_cone = _matmul3(_BRADFORD, target_white)
|
|
160
|
+
cone = _matmul3(_BRADFORD, xyz)
|
|
161
|
+
adapted_cone = tuple(
|
|
162
|
+
cone[i] * (dst_cone[i] / src_cone[i] if src_cone[i] else 1.0) for i in range(3)
|
|
163
|
+
)
|
|
164
|
+
adapted_xyz = _matmul3(_BRADFORD_INV, adapted_cone) # type: ignore[arg-type]
|
|
165
|
+
return xyz_to_lab(adapted_xyz, white=target_white)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
# ---------- Lab-space k-means palette ----------
|
|
169
|
+
|
|
170
|
+
def lab_kmeans_palette(samples: list[tuple[float, float, float]], k: int) -> list[dict[str, Any]]:
|
|
171
|
+
if not samples:
|
|
172
|
+
return []
|
|
173
|
+
k = max(1, min(k, len(samples)))
|
|
174
|
+
ordered = sorted(samples, key=lambda lab: lab[0])
|
|
175
|
+
centers = [ordered[int((index + 0.5) * (len(ordered) - 1) / k)] for index in range(k)]
|
|
176
|
+
groups: list[list[tuple[float, float, float]]] = [[] for _ in centers]
|
|
177
|
+
for _ in range(8):
|
|
178
|
+
groups = [[] for _ in centers]
|
|
179
|
+
for sample in samples:
|
|
180
|
+
nearest = min(range(len(centers)), key=lambda idx: lab_distance(sample, centers[idx]))
|
|
181
|
+
groups[nearest].append(sample)
|
|
182
|
+
new_centers = []
|
|
183
|
+
for group, center in zip(groups, centers):
|
|
184
|
+
if not group:
|
|
185
|
+
new_centers.append(center)
|
|
186
|
+
continue
|
|
187
|
+
new_centers.append(tuple(sum(s[c] for s in group) / len(group) for c in range(3)))
|
|
188
|
+
centers = new_centers # type: ignore[assignment]
|
|
189
|
+
total = len(samples)
|
|
190
|
+
result = [
|
|
191
|
+
{"center": centers[index], "share_pct": len(group) / total}
|
|
192
|
+
for index, group in enumerate(groups)
|
|
193
|
+
if group
|
|
194
|
+
]
|
|
195
|
+
result.sort(key=lambda entry: entry["share_pct"], reverse=True)
|
|
196
|
+
return result
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# ---------- Hotspot-based roughness (Cook-Torrance half-angle proxy) ----------
|
|
200
|
+
|
|
201
|
+
def estimate_roughness_from_hotspot(
|
|
202
|
+
lumas: list[float],
|
|
203
|
+
mask: list[bool],
|
|
204
|
+
) -> tuple[float, str]:
|
|
205
|
+
"""Sharp/tight hotspot -> low roughness; wide/diffuse hotspot -> high roughness.
|
|
206
|
+
This is a proxy measurement (spatial spread of the brightest foreground pixels),
|
|
207
|
+
not a true BRDF fit, but it is a real measurement off the pixels rather than a
|
|
208
|
+
heuristic default."""
|
|
209
|
+
foreground_lumas = [luma for luma, keep in zip(lumas, mask) if keep]
|
|
210
|
+
if not foreground_lumas:
|
|
211
|
+
return 0.7, "no foreground pixels; default mid-roughness"
|
|
212
|
+
peak = max(foreground_lumas)
|
|
213
|
+
# Measure what fraction of the surface reads as "near the actual peak
|
|
214
|
+
# brightness" (within 0.1 luma of it), not "above a fixed percentile" — a
|
|
215
|
+
# percentile-based cutoff breaks down when the highlight covers only a tiny
|
|
216
|
+
# fraction of pixels, since the percentile value itself then falls back into
|
|
217
|
+
# the dark background range and every pixel spuriously satisfies ">= cutoff".
|
|
218
|
+
near_peak_threshold = max(0.0, peak - 0.1)
|
|
219
|
+
hotspot_fraction = sum(1 for luma in foreground_lumas if luma >= near_peak_threshold) / len(foreground_lumas)
|
|
220
|
+
# A tight/sharp specular hotspot occupies a small fraction of the surface near
|
|
221
|
+
# peak brightness; a broad/diffuse highlight covers much more of the surface.
|
|
222
|
+
spread = clamp01(hotspot_fraction * 2.0)
|
|
223
|
+
roughness = clamp(0.12 + spread * 0.75, 0.05, 0.95)
|
|
224
|
+
if spread < 0.3:
|
|
225
|
+
evidence = "sharp, tight specular hotspot — supports low roughness/high specularity"
|
|
226
|
+
elif spread > 0.7:
|
|
227
|
+
evidence = "broad, gradually-fading highlight — supports high roughness/diffuse response"
|
|
228
|
+
else:
|
|
229
|
+
evidence = "moderate hotspot spread — mid-range roughness"
|
|
230
|
+
return round(roughness, 3), evidence
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
# ---------- Material classification (rule-based, evidence-cited) ----------
|
|
234
|
+
|
|
235
|
+
def classify_material(
|
|
236
|
+
dominant_lab: tuple[float, float, float],
|
|
237
|
+
saturation: float,
|
|
238
|
+
hotspot_roughness: float,
|
|
239
|
+
) -> tuple[str, float]:
|
|
240
|
+
lightness = dominant_lab[0]
|
|
241
|
+
chroma = math.sqrt(dominant_lab[1] ** 2 + dominant_lab[2] ** 2)
|
|
242
|
+
if saturation < 0.12 and hotspot_roughness < 0.3:
|
|
243
|
+
return "metal", round(clamp(0.55 + (0.3 - hotspot_roughness) * 0.8, 0.4, 0.85), 3)
|
|
244
|
+
if saturation < 0.15 and lightness > 70 and hotspot_roughness < 0.45:
|
|
245
|
+
return "glass", round(clamp(0.45 + (70 - abs(lightness - 85)) * 0.005, 0.35, 0.75), 3)
|
|
246
|
+
if chroma > 25 and hotspot_roughness > 0.55:
|
|
247
|
+
return "fabric", round(clamp(0.4 + (hotspot_roughness - 0.55) * 0.6, 0.35, 0.7), 3)
|
|
248
|
+
if chroma > 15 and hotspot_roughness < 0.5:
|
|
249
|
+
return "plastic", round(clamp(0.4 + (0.5 - hotspot_roughness) * 0.5, 0.35, 0.7), 3)
|
|
250
|
+
if lightness < 45 and chroma < 20:
|
|
251
|
+
return "stone", round(0.45, 3)
|
|
252
|
+
return "unknown", round(0.3, 3)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
# ---------- Color-gradient detection ----------
|
|
256
|
+
|
|
257
|
+
_GRADIENT_MIN_DELTA_E = 8.0
|
|
258
|
+
_GRADIENT_MIN_MONOTONIC_FRACTION = 0.8
|
|
259
|
+
_GRADIENT_STOP_OFFSETS = (0.0, 0.55, 1.0)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _sample_axis(
|
|
263
|
+
size: int,
|
|
264
|
+
lab_grid: list[tuple[float, float, float]],
|
|
265
|
+
mask_grid: list[bool],
|
|
266
|
+
start: tuple[float, float],
|
|
267
|
+
end: tuple[float, float],
|
|
268
|
+
steps: int = 9,
|
|
269
|
+
) -> list[tuple[float, float, float]] | None:
|
|
270
|
+
samples: list[tuple[float, float, float]] = []
|
|
271
|
+
for step in range(steps):
|
|
272
|
+
t = step / (steps - 1)
|
|
273
|
+
x = start[0] + (end[0] - start[0]) * t
|
|
274
|
+
y = start[1] + (end[1] - start[1]) * t
|
|
275
|
+
sx = min(size - 1, max(0, int(round(x))))
|
|
276
|
+
sy = min(size - 1, max(0, int(round(y))))
|
|
277
|
+
index = sy * size + sx
|
|
278
|
+
if not mask_grid[index]:
|
|
279
|
+
return None
|
|
280
|
+
samples.append(lab_grid[index])
|
|
281
|
+
return samples
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _is_monotonic(values: list[float]) -> bool:
|
|
285
|
+
"""Strictly-equal consecutive samples count as neutral (support neither direction),
|
|
286
|
+
not as evidence for both — otherwise an aliased flat/oscillating signal (e.g. nearest-
|
|
287
|
+
pixel sampling across a checkerboard) can spuriously look monotonic when ties inflate
|
|
288
|
+
whichever real direction happens to have a one-sample edge."""
|
|
289
|
+
if len(values) < 2:
|
|
290
|
+
return True
|
|
291
|
+
increasing = sum(1 for i in range(1, len(values)) if values[i] > values[i - 1])
|
|
292
|
+
decreasing = sum(1 for i in range(1, len(values)) if values[i] < values[i - 1])
|
|
293
|
+
fraction = max(increasing, decreasing) / (len(values) - 1)
|
|
294
|
+
return fraction >= _GRADIENT_MIN_MONOTONIC_FRACTION
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def detect_color_gradient(
|
|
298
|
+
size: int,
|
|
299
|
+
lab_grid: list[tuple[float, float, float]],
|
|
300
|
+
mask_grid: list[bool],
|
|
301
|
+
) -> dict[str, Any] | None:
|
|
302
|
+
"""Tests 4 linear axes + 1 radial-from-centroid axis; returns the strongest
|
|
303
|
+
candidate that clears BOTH the magnitude (ΔE >= 8.0) and monotonicity (>=80%
|
|
304
|
+
consistent-direction sample pairs) gates, or None if nothing qualifies. Both
|
|
305
|
+
gates are required — magnitude alone would accept textured/patterned regions
|
|
306
|
+
with real-but-non-directional color variance (see Risk R8)."""
|
|
307
|
+
foreground_indices = [i for i, keep in enumerate(mask_grid) if keep]
|
|
308
|
+
if len(foreground_indices) < 9:
|
|
309
|
+
return None
|
|
310
|
+
xs = [i % size for i in foreground_indices]
|
|
311
|
+
ys = [i // size for i in foreground_indices]
|
|
312
|
+
x0, x1 = min(xs), max(xs)
|
|
313
|
+
y0, y1 = min(ys), max(ys)
|
|
314
|
+
cx, cy = sum(xs) / len(xs), sum(ys) / len(ys)
|
|
315
|
+
candidates: list[tuple[str, tuple[float, float], tuple[float, float], tuple[float, float]]] = [
|
|
316
|
+
("linear", (x0, cy), (x1, cy), (1.0, 0.0)),
|
|
317
|
+
("linear", (cx, y0), (cx, y1), (0.0, 1.0)),
|
|
318
|
+
("linear", (x0, y0), (x1, y1), (0.7071, 0.7071)),
|
|
319
|
+
("linear", (x0, y1), (x1, y0), (0.7071, -0.7071)),
|
|
320
|
+
("radial", (cx, cy), (x1, cy), (1.0, 0.0)),
|
|
321
|
+
]
|
|
322
|
+
best: dict[str, Any] | None = None
|
|
323
|
+
best_delta_e = 0.0
|
|
324
|
+
for kind, start, end, axis in candidates:
|
|
325
|
+
samples = _sample_axis(size, lab_grid, mask_grid, start, end)
|
|
326
|
+
if samples is None:
|
|
327
|
+
continue
|
|
328
|
+
delta_e = lab_distance(samples[0], samples[-1])
|
|
329
|
+
if delta_e < _GRADIENT_MIN_DELTA_E:
|
|
330
|
+
continue
|
|
331
|
+
if not all(_is_monotonic([s[channel] for s in samples]) for channel in range(3)):
|
|
332
|
+
continue
|
|
333
|
+
if delta_e > best_delta_e:
|
|
334
|
+
best_delta_e = delta_e
|
|
335
|
+
stops = []
|
|
336
|
+
for offset in _GRADIENT_STOP_OFFSETS:
|
|
337
|
+
idx = min(len(samples) - 1, max(0, round(offset * (len(samples) - 1))))
|
|
338
|
+
stops.append({"offset": offset, "color": lab_to_rgba(samples[idx])})
|
|
339
|
+
axis_field = list(axis) if kind == "linear" else [cx / size, cy / size]
|
|
340
|
+
best = {
|
|
341
|
+
"type": kind,
|
|
342
|
+
"axis": axis_field,
|
|
343
|
+
"stops": stops,
|
|
344
|
+
"confidence": round(clamp01(delta_e / 30.0), 3),
|
|
345
|
+
}
|
|
346
|
+
return best
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
# ---------- Top-level recipe assembly ----------
|
|
350
|
+
|
|
351
|
+
def build_recipe(
|
|
352
|
+
component_id: str,
|
|
353
|
+
crop_path: Path,
|
|
354
|
+
target_threshold: float = 0.7,
|
|
355
|
+
material_class_hint: str | None = None,
|
|
356
|
+
size: int = 96,
|
|
357
|
+
) -> dict[str, Any]:
|
|
358
|
+
width, height, pixels, _load_warnings = load_image(crop_path)
|
|
359
|
+
rgba_pixels = pixels
|
|
360
|
+
rgb_pixels = [(r, g, b) for r, g, b, _a in rgba_pixels]
|
|
361
|
+
mask, _mask_diag, _mask_warnings = build_foreground_mask(width, height, rgba_pixels)
|
|
362
|
+
bbox = mask_bbox(width, height, mask)
|
|
363
|
+
sampled_pixels, sampled_mask = resample_crop(width, height, rgba_pixels, mask, bbox, size)
|
|
364
|
+
|
|
365
|
+
lab_grid = [srgb_to_lab(pixel) for pixel in sampled_pixels]
|
|
366
|
+
lumas = [0.2126 * p[0] / 255.0 + 0.7152 * p[1] / 255.0 + 0.0722 * p[2] / 255.0 for p in sampled_pixels]
|
|
367
|
+
|
|
368
|
+
foreground_lab = [lab for lab, keep in zip(lab_grid, sampled_mask) if keep]
|
|
369
|
+
samples_for_kmeans = representative_samples(foreground_lab, [True] * len(foreground_lab), limit=4000) if foreground_lab else []
|
|
370
|
+
clusters = lab_kmeans_palette(samples_for_kmeans, k=3)
|
|
371
|
+
|
|
372
|
+
if not clusters:
|
|
373
|
+
raise ValueError(f"no foreground pixels found in crop for component {component_id!r}")
|
|
374
|
+
|
|
375
|
+
dominant_lab = clusters[0]["center"]
|
|
376
|
+
secondary_lab = clusters[1]["center"] if len(clusters) > 1 else dominant_lab
|
|
377
|
+
|
|
378
|
+
background_white = _D65 # neutral D65 assumption; refine with a metered gray card in future work
|
|
379
|
+
dominant_adapted = bradford_adapt(dominant_lab, source_white=background_white)
|
|
380
|
+
secondary_adapted = bradford_adapt(secondary_lab, source_white=background_white)
|
|
381
|
+
|
|
382
|
+
roughness, hotspot_evidence = estimate_roughness_from_hotspot(lumas, sampled_mask)
|
|
383
|
+
|
|
384
|
+
dominant_rgb = lab_to_rgb(dominant_adapted)
|
|
385
|
+
saturation = 0.0 if max(dominant_rgb) == 0 else (max(dominant_rgb) - min(dominant_rgb)) / max(dominant_rgb)
|
|
386
|
+
material_class, material_confidence = classify_material(dominant_adapted, saturation, roughness)
|
|
387
|
+
if material_class_hint:
|
|
388
|
+
material_class = material_class_hint
|
|
389
|
+
material_confidence = max(material_confidence, 0.6)
|
|
390
|
+
|
|
391
|
+
metalness = 1.0 if material_class == "metal" else 0.0
|
|
392
|
+
|
|
393
|
+
gradient = detect_color_gradient(size, lab_grid, sampled_mask)
|
|
394
|
+
|
|
395
|
+
recipe: dict[str, Any] = {
|
|
396
|
+
"componentId": component_id,
|
|
397
|
+
"dominantAlbedo": lab_to_rgba(dominant_adapted),
|
|
398
|
+
"secondaryAlbedo": lab_to_rgba(secondary_adapted),
|
|
399
|
+
"materialClass": material_class,
|
|
400
|
+
"materialClassConfidence": material_confidence,
|
|
401
|
+
"roughnessEstimate": roughness,
|
|
402
|
+
"metalnessEstimate": metalness,
|
|
403
|
+
"highlightEvidence": hotspot_evidence,
|
|
404
|
+
"sourceCropPath": str(crop_path.resolve()),
|
|
405
|
+
"labClusterMeta": {
|
|
406
|
+
"clusterCount": len(clusters),
|
|
407
|
+
"dominantClusterSharePct": round(clusters[0]["share_pct"], 3),
|
|
408
|
+
},
|
|
409
|
+
}
|
|
410
|
+
if gradient is not None:
|
|
411
|
+
recipe["colorGradient"] = gradient
|
|
412
|
+
return recipe
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def main(argv: list[str]) -> int:
|
|
416
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
417
|
+
parser.add_argument("crop", type=Path)
|
|
418
|
+
parser.add_argument("--component-id", required=True)
|
|
419
|
+
parser.add_argument("--material-class-hint")
|
|
420
|
+
parser.add_argument("--target-threshold", type=float, default=0.7)
|
|
421
|
+
parser.add_argument("--spec", type=Path, help="ObjectSculptSpec JSON to patch")
|
|
422
|
+
parser.add_argument("--in-place", action="store_true", help="Patch --spec in place when confidence passes")
|
|
423
|
+
parser.add_argument("--out-spec", type=Path, help="Write patched spec to this path")
|
|
424
|
+
parser.add_argument("--allow-low-confidence", action="store_true")
|
|
425
|
+
parser.add_argument("--no-cache", action="store_true", help="Skip the hash-based extraction cache")
|
|
426
|
+
args = parser.parse_args(argv)
|
|
427
|
+
|
|
428
|
+
try:
|
|
429
|
+
crop_path = args.crop.expanduser().resolve()
|
|
430
|
+
cache_dir = (args.spec.expanduser().resolve().parent if args.spec else crop_path.parent)
|
|
431
|
+
manifest_path = manifest_path_for(cache_dir, "color_recipe_cache.json")
|
|
432
|
+
key = cache_key(crop_path, Path(__file__).resolve())
|
|
433
|
+
cached = None if args.no_cache else get_cached(manifest_path, key)
|
|
434
|
+
if cached is not None:
|
|
435
|
+
# The cache key is crop+script content only (no component-id), since the
|
|
436
|
+
# pixel-derived data is identical regardless of which component reuses this
|
|
437
|
+
# exact crop — but componentId is a contextual label, not derived from
|
|
438
|
+
# pixels, so it must be re-stamped to the CURRENT invocation's value.
|
|
439
|
+
recipe = dict(cached)
|
|
440
|
+
recipe["componentId"] = args.component_id
|
|
441
|
+
recipe["cacheHit"] = True
|
|
442
|
+
else:
|
|
443
|
+
recipe = build_recipe(
|
|
444
|
+
args.component_id,
|
|
445
|
+
crop_path,
|
|
446
|
+
target_threshold=args.target_threshold,
|
|
447
|
+
material_class_hint=args.material_class_hint,
|
|
448
|
+
)
|
|
449
|
+
recipe["cacheHit"] = False
|
|
450
|
+
if not args.no_cache:
|
|
451
|
+
put_cached(manifest_path, key, {k: v for k, v in recipe.items() if k != "cacheHit"})
|
|
452
|
+
ok = recipe["materialClassConfidence"] >= args.target_threshold
|
|
453
|
+
if args.spec:
|
|
454
|
+
if not ok and not args.allow_low_confidence:
|
|
455
|
+
raise ValueError(
|
|
456
|
+
f"materialClassConfidence {recipe['materialClassConfidence']} is below target "
|
|
457
|
+
f"{args.target_threshold}; spec was not patched (use --allow-low-confidence to override)"
|
|
458
|
+
)
|
|
459
|
+
spec_path = args.spec.expanduser().resolve()
|
|
460
|
+
spec = json.loads(spec_path.read_text(encoding="utf-8"))
|
|
461
|
+
components = spec.get("componentTree", [])
|
|
462
|
+
target = next((c for c in components if isinstance(c, dict) and c.get("id") == args.component_id), None)
|
|
463
|
+
if target is None:
|
|
464
|
+
raise ValueError(f"component {args.component_id!r} not found in spec componentTree")
|
|
465
|
+
# cacheHit is a runtime diagnostic for this invocation, not evidence data —
|
|
466
|
+
# don't persist it into the spec's colorMaterialRecipe.
|
|
467
|
+
target["colorMaterialRecipe"] = {k: v for k, v in recipe.items() if k != "cacheHit"}
|
|
468
|
+
# colorMaterialRecipe lives on the component (evidence/audit trail: which crop,
|
|
469
|
+
# what confidence). But generate_threejs_factory.py's texture codegen reads
|
|
470
|
+
# colorGradient off the shared MATERIAL entry (materials[] is the actual
|
|
471
|
+
# rendering unit, referenced by id from possibly-multiple components) — so a
|
|
472
|
+
# detected gradient must also be mirrored onto that material to actually render.
|
|
473
|
+
if "colorGradient" in recipe:
|
|
474
|
+
material_id = target.get("material")
|
|
475
|
+
material = next(
|
|
476
|
+
(m for m in spec.get("materials", []) if isinstance(m, dict) and m.get("id") == material_id),
|
|
477
|
+
None,
|
|
478
|
+
)
|
|
479
|
+
if material is not None:
|
|
480
|
+
material["colorGradient"] = recipe["colorGradient"]
|
|
481
|
+
output = spec_path if args.in_place else (args.out_spec.expanduser().resolve() if args.out_spec else None)
|
|
482
|
+
if output:
|
|
483
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
484
|
+
output.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
485
|
+
print(json.dumps(recipe, indent=2, ensure_ascii=False))
|
|
486
|
+
# Low confidence without --spec is informational only (nothing was patched,
|
|
487
|
+
# so there's nothing to "fail"); the --spec low-confidence case already
|
|
488
|
+
# raised above and was caught by the except clause below.
|
|
489
|
+
return 0
|
|
490
|
+
except Exception as exc:
|
|
491
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
492
|
+
return 1
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
if __name__ == "__main__":
|
|
496
|
+
raise SystemExit(main(sys.argv[1:]))
|