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,843 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Extract reference-derived PBR map evidence from an object image.
|
|
3
|
+
|
|
4
|
+
This is not photogrammetry and it does not claim exact inverse rendering from a
|
|
5
|
+
single image. It extracts pixel evidence that is useful for procedural PBR:
|
|
6
|
+
albedo palette, de-lit albedo, roughness estimate, height, normal, and AO maps.
|
|
7
|
+
If the estimated confidence is below the requested target, the script exits
|
|
8
|
+
non-zero and refuses to patch the sculpt spec unless --allow-low-confidence is
|
|
9
|
+
passed.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import json
|
|
16
|
+
import math
|
|
17
|
+
import shutil
|
|
18
|
+
import struct
|
|
19
|
+
import subprocess
|
|
20
|
+
import sys
|
|
21
|
+
import tempfile
|
|
22
|
+
import zlib
|
|
23
|
+
from collections import Counter
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
|
|
28
|
+
from jpeg import UnsupportedJpeg, decode_jpeg, is_jpeg # noqa: E402
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def slugify(value: str) -> str:
|
|
35
|
+
parts: list[str] = []
|
|
36
|
+
last_dash = False
|
|
37
|
+
for char in value.strip().lower():
|
|
38
|
+
if char.isalnum():
|
|
39
|
+
parts.append(char)
|
|
40
|
+
last_dash = False
|
|
41
|
+
elif not last_dash:
|
|
42
|
+
parts.append("-")
|
|
43
|
+
last_dash = True
|
|
44
|
+
return "".join(parts).strip("-") or "material"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def clamp(value: float, minimum: float, maximum: float) -> float:
|
|
48
|
+
return max(minimum, min(maximum, value))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def clamp01(value: float) -> float:
|
|
52
|
+
return clamp(value, 0.0, 1.0)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def srgb_luma(rgb: tuple[int, int, int]) -> float:
|
|
56
|
+
red, green, blue = rgb
|
|
57
|
+
return (0.2126 * red + 0.7152 * green + 0.0722 * blue) / 255.0
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def color_distance(a: tuple[int, int, int], b: tuple[int, int, int]) -> float:
|
|
61
|
+
return math.sqrt(sum((a[index] - b[index]) ** 2 for index in range(3)))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def saturation(rgb: tuple[int, int, int]) -> float:
|
|
65
|
+
high = max(rgb)
|
|
66
|
+
low = min(rgb)
|
|
67
|
+
return 0.0 if high <= 0 else (high - low) / high
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def percentile(values: list[float], fraction: float, fallback: float = 0.0) -> float:
|
|
71
|
+
if not values:
|
|
72
|
+
return fallback
|
|
73
|
+
ordered = sorted(values)
|
|
74
|
+
index = int(round(clamp01(fraction) * (len(ordered) - 1)))
|
|
75
|
+
return ordered[index]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def median_color(samples: list[tuple[int, int, int]]) -> tuple[int, int, int]:
|
|
79
|
+
if not samples:
|
|
80
|
+
return (255, 255, 255)
|
|
81
|
+
return tuple(
|
|
82
|
+
int(percentile([float(sample[channel]) for sample in samples], 0.5))
|
|
83
|
+
for channel in range(3)
|
|
84
|
+
) # type: ignore[return-value]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def read_png(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]]]:
|
|
88
|
+
data = path.read_bytes()
|
|
89
|
+
if not data.startswith(PNG_SIGNATURE):
|
|
90
|
+
raise ValueError("not a PNG file")
|
|
91
|
+
cursor = len(PNG_SIGNATURE)
|
|
92
|
+
width = height = bit_depth = color_type = None
|
|
93
|
+
idat = bytearray()
|
|
94
|
+
interlace = 0
|
|
95
|
+
while cursor + 8 <= len(data):
|
|
96
|
+
length = struct.unpack(">I", data[cursor : cursor + 4])[0]
|
|
97
|
+
chunk_type = data[cursor + 4 : cursor + 8]
|
|
98
|
+
chunk_data = data[cursor + 8 : cursor + 8 + length]
|
|
99
|
+
cursor += 12 + length
|
|
100
|
+
if chunk_type == b"IHDR":
|
|
101
|
+
width, height, bit_depth, color_type, _, _, interlace = struct.unpack(">IIBBBBB", chunk_data)
|
|
102
|
+
elif chunk_type == b"IDAT":
|
|
103
|
+
idat.extend(chunk_data)
|
|
104
|
+
elif chunk_type == b"IEND":
|
|
105
|
+
break
|
|
106
|
+
if width is None or height is None or bit_depth != 8 or interlace != 0:
|
|
107
|
+
raise ValueError("unsupported PNG; expected 8-bit non-interlaced image")
|
|
108
|
+
channels_by_type = {0: 1, 2: 3, 4: 2, 6: 4}
|
|
109
|
+
if color_type not in channels_by_type:
|
|
110
|
+
raise ValueError("unsupported PNG color type; convert to RGB/RGBA first")
|
|
111
|
+
channels = channels_by_type[color_type]
|
|
112
|
+
row_bytes = width * channels
|
|
113
|
+
raw = zlib.decompress(bytes(idat))
|
|
114
|
+
rows: list[bytearray] = []
|
|
115
|
+
offset = 0
|
|
116
|
+
previous = bytearray(row_bytes)
|
|
117
|
+
for _ in range(height):
|
|
118
|
+
filter_type = raw[offset]
|
|
119
|
+
offset += 1
|
|
120
|
+
row = bytearray(raw[offset : offset + row_bytes])
|
|
121
|
+
offset += row_bytes
|
|
122
|
+
for index in range(row_bytes):
|
|
123
|
+
left = row[index - channels] if index >= channels else 0
|
|
124
|
+
up = previous[index]
|
|
125
|
+
up_left = previous[index - channels] if index >= channels else 0
|
|
126
|
+
if filter_type == 1:
|
|
127
|
+
row[index] = (row[index] + left) & 0xFF
|
|
128
|
+
elif filter_type == 2:
|
|
129
|
+
row[index] = (row[index] + up) & 0xFF
|
|
130
|
+
elif filter_type == 3:
|
|
131
|
+
row[index] = (row[index] + ((left + up) // 2)) & 0xFF
|
|
132
|
+
elif filter_type == 4:
|
|
133
|
+
predictor = paeth_predictor(left, up, up_left)
|
|
134
|
+
row[index] = (row[index] + predictor) & 0xFF
|
|
135
|
+
elif filter_type != 0:
|
|
136
|
+
raise ValueError(f"unsupported PNG filter {filter_type}")
|
|
137
|
+
rows.append(row)
|
|
138
|
+
previous = row
|
|
139
|
+
pixels: list[tuple[int, int, int, int]] = []
|
|
140
|
+
for row in rows:
|
|
141
|
+
for x in range(width):
|
|
142
|
+
base = x * channels
|
|
143
|
+
if color_type == 0:
|
|
144
|
+
gray = row[base]
|
|
145
|
+
pixels.append((gray, gray, gray, 255))
|
|
146
|
+
elif color_type == 2:
|
|
147
|
+
pixels.append((row[base], row[base + 1], row[base + 2], 255))
|
|
148
|
+
elif color_type == 4:
|
|
149
|
+
gray = row[base]
|
|
150
|
+
pixels.append((gray, gray, gray, row[base + 1]))
|
|
151
|
+
elif color_type == 6:
|
|
152
|
+
pixels.append((row[base], row[base + 1], row[base + 2], row[base + 3]))
|
|
153
|
+
return width, height, pixels
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def paeth_predictor(a: int, b: int, c: int) -> int:
|
|
157
|
+
p = a + b - c
|
|
158
|
+
pa = abs(p - a)
|
|
159
|
+
pb = abs(p - b)
|
|
160
|
+
pc = abs(p - c)
|
|
161
|
+
if pa <= pb and pa <= pc:
|
|
162
|
+
return a
|
|
163
|
+
if pb <= pc:
|
|
164
|
+
return b
|
|
165
|
+
return c
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def write_png_rgb(path: Path, width: int, height: int, rgb: bytes) -> None:
|
|
169
|
+
if len(rgb) != width * height * 3:
|
|
170
|
+
raise ValueError("RGB payload has the wrong size")
|
|
171
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
172
|
+
|
|
173
|
+
def chunk(kind: bytes, payload: bytes) -> bytes:
|
|
174
|
+
checksum = zlib.crc32(kind)
|
|
175
|
+
checksum = zlib.crc32(payload, checksum) & 0xFFFFFFFF
|
|
176
|
+
return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", checksum)
|
|
177
|
+
|
|
178
|
+
scanlines = bytearray()
|
|
179
|
+
stride = width * 3
|
|
180
|
+
for y in range(height):
|
|
181
|
+
scanlines.append(0)
|
|
182
|
+
scanlines.extend(rgb[y * stride : (y + 1) * stride])
|
|
183
|
+
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
|
184
|
+
path.write_bytes(
|
|
185
|
+
PNG_SIGNATURE
|
|
186
|
+
+ chunk(b"IHDR", ihdr)
|
|
187
|
+
+ chunk(b"IDAT", zlib.compress(bytes(scanlines), level=6))
|
|
188
|
+
+ chunk(b"IEND", b"")
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def load_image(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]], list[str]]:
|
|
193
|
+
warnings: list[str] = []
|
|
194
|
+
try:
|
|
195
|
+
return (*read_png(path), warnings)
|
|
196
|
+
except Exception as direct_error:
|
|
197
|
+
jpeg_bytes = path.read_bytes()
|
|
198
|
+
if is_jpeg(jpeg_bytes):
|
|
199
|
+
try:
|
|
200
|
+
return (*decode_jpeg(jpeg_bytes), warnings)
|
|
201
|
+
except UnsupportedJpeg as unsupported:
|
|
202
|
+
warnings.append(f"{path.name} needs an external converter: {unsupported}")
|
|
203
|
+
sips = shutil.which("sips")
|
|
204
|
+
if not sips:
|
|
205
|
+
raise ValueError(
|
|
206
|
+
f"could not decode {path.name} as PNG and macOS sips is unavailable: {direct_error}"
|
|
207
|
+
) from direct_error
|
|
208
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
209
|
+
converted = Path(tmpdir) / "converted.png"
|
|
210
|
+
command = [sips, "-s", "format", "png", str(path), "--out", str(converted)]
|
|
211
|
+
result = subprocess.run(command, capture_output=True, text=True, check=False)
|
|
212
|
+
if result.returncode != 0:
|
|
213
|
+
raise ValueError(result.stderr.strip() or result.stdout.strip() or "sips conversion failed")
|
|
214
|
+
warnings.append("source image was converted to PNG with macOS sips before pixel extraction")
|
|
215
|
+
width, height, pixels = read_png(converted)
|
|
216
|
+
return width, height, pixels, warnings
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def sample_corner_background(
|
|
220
|
+
width: int,
|
|
221
|
+
height: int,
|
|
222
|
+
pixels: list[tuple[int, int, int, int]],
|
|
223
|
+
) -> tuple[tuple[int, int, int], float]:
|
|
224
|
+
radius = max(3, min(width, height) // 40)
|
|
225
|
+
samples: list[tuple[int, int, int]] = []
|
|
226
|
+
corner_ranges = [
|
|
227
|
+
(0, radius, 0, radius),
|
|
228
|
+
(width - radius, width, 0, radius),
|
|
229
|
+
(0, radius, height - radius, height),
|
|
230
|
+
(width - radius, width, height - radius, height),
|
|
231
|
+
]
|
|
232
|
+
for x0, x1, y0, y1 in corner_ranges:
|
|
233
|
+
for y in range(max(0, y0), min(height, y1)):
|
|
234
|
+
for x in range(max(0, x0), min(width, x1)):
|
|
235
|
+
red, green, blue, alpha = pixels[y * width + x]
|
|
236
|
+
if alpha > 16:
|
|
237
|
+
samples.append((red, green, blue))
|
|
238
|
+
background = median_color(samples)
|
|
239
|
+
noise = percentile([color_distance(sample, background) for sample in samples], 0.75, 0.0)
|
|
240
|
+
return background, noise
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def build_foreground_mask(
|
|
244
|
+
width: int,
|
|
245
|
+
height: int,
|
|
246
|
+
pixels: list[tuple[int, int, int, int]],
|
|
247
|
+
) -> tuple[list[bool], dict[str, Any], list[str]]:
|
|
248
|
+
warnings: list[str] = []
|
|
249
|
+
alpha_values = [pixel[3] for pixel in pixels]
|
|
250
|
+
transparent_fraction = sum(1 for alpha in alpha_values if alpha < 245) / max(1, len(alpha_values))
|
|
251
|
+
background, background_noise = sample_corner_background(width, height, pixels)
|
|
252
|
+
threshold = max(24.0, background_noise * 2.4)
|
|
253
|
+
mask: list[bool] = []
|
|
254
|
+
if transparent_fraction > 0.03:
|
|
255
|
+
for red, green, blue, alpha in pixels:
|
|
256
|
+
mask.append(alpha > 24)
|
|
257
|
+
else:
|
|
258
|
+
for red, green, blue, alpha in pixels:
|
|
259
|
+
rgb = (red, green, blue)
|
|
260
|
+
distance = color_distance(rgb, background)
|
|
261
|
+
sat = saturation(rgb)
|
|
262
|
+
luma = srgb_luma(rgb)
|
|
263
|
+
mask.append(alpha > 16 and (distance > threshold or (sat > 0.16 and luma < 0.94)))
|
|
264
|
+
coverage = sum(1 for value in mask if value) / max(1, len(mask))
|
|
265
|
+
if coverage < 0.035:
|
|
266
|
+
warnings.append("foreground mask is tiny; material extraction is likely unreliable")
|
|
267
|
+
mask = [pixel[3] > 16 for pixel in pixels]
|
|
268
|
+
coverage = sum(1 for value in mask if value) / max(1, len(mask))
|
|
269
|
+
if coverage > 0.9:
|
|
270
|
+
warnings.append("image is not clearly isolated from background; using most pixels as material evidence")
|
|
271
|
+
return (
|
|
272
|
+
mask,
|
|
273
|
+
{
|
|
274
|
+
"backgroundColor": rgb_to_hex(background),
|
|
275
|
+
"backgroundNoise": round(background_noise, 3),
|
|
276
|
+
"transparentPixelFraction": round(transparent_fraction, 4),
|
|
277
|
+
"foregroundCoverage": round(coverage, 4),
|
|
278
|
+
},
|
|
279
|
+
warnings,
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def mask_bbox(width: int, height: int, mask: list[bool]) -> tuple[int, int, int, int]:
|
|
284
|
+
xs: list[int] = []
|
|
285
|
+
ys: list[int] = []
|
|
286
|
+
for index, value in enumerate(mask):
|
|
287
|
+
if value:
|
|
288
|
+
ys.append(index // width)
|
|
289
|
+
xs.append(index % width)
|
|
290
|
+
if not xs or not ys:
|
|
291
|
+
return (0, 0, width, height)
|
|
292
|
+
padding = max(2, min(width, height) // 80)
|
|
293
|
+
x0 = max(0, min(xs) - padding)
|
|
294
|
+
y0 = max(0, min(ys) - padding)
|
|
295
|
+
x1 = min(width, max(xs) + padding + 1)
|
|
296
|
+
y1 = min(height, max(ys) + padding + 1)
|
|
297
|
+
return (x0, y0, max(1, x1 - x0), max(1, y1 - y0))
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def resample_crop(
|
|
301
|
+
width: int,
|
|
302
|
+
height: int,
|
|
303
|
+
pixels: list[tuple[int, int, int, int]],
|
|
304
|
+
mask: list[bool],
|
|
305
|
+
bbox: tuple[int, int, int, int],
|
|
306
|
+
size: int,
|
|
307
|
+
) -> tuple[list[tuple[int, int, int]], list[bool]]:
|
|
308
|
+
x0, y0, crop_w, crop_h = bbox
|
|
309
|
+
sampled_pixels: list[tuple[int, int, int]] = []
|
|
310
|
+
sampled_mask: list[bool] = []
|
|
311
|
+
for y in range(size):
|
|
312
|
+
source_y = y0 + (y + 0.5) * crop_h / size
|
|
313
|
+
sy = min(height - 1, max(0, int(source_y)))
|
|
314
|
+
for x in range(size):
|
|
315
|
+
source_x = x0 + (x + 0.5) * crop_w / size
|
|
316
|
+
sx = min(width - 1, max(0, int(source_x)))
|
|
317
|
+
index = sy * width + sx
|
|
318
|
+
red, green, blue, alpha = pixels[index]
|
|
319
|
+
sampled_pixels.append((red, green, blue))
|
|
320
|
+
sampled_mask.append(mask[index] and alpha > 16)
|
|
321
|
+
return sampled_pixels, sampled_mask
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def representative_samples(
|
|
325
|
+
pixels: list[tuple[int, int, int]],
|
|
326
|
+
mask: list[bool],
|
|
327
|
+
limit: int = 7000,
|
|
328
|
+
) -> list[tuple[int, int, int]]:
|
|
329
|
+
candidates = [pixel for pixel, keep in zip(pixels, mask) if keep]
|
|
330
|
+
if not candidates:
|
|
331
|
+
candidates = pixels
|
|
332
|
+
if len(candidates) <= limit:
|
|
333
|
+
return candidates
|
|
334
|
+
step = max(1, len(candidates) // limit)
|
|
335
|
+
return candidates[::step][:limit]
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def kmeans_palette(samples: list[tuple[int, int, int]], k: int = 5) -> list[str]:
|
|
339
|
+
if not samples:
|
|
340
|
+
return ["#8A7A5F"]
|
|
341
|
+
ordered = sorted(samples, key=lambda rgb: (srgb_luma(rgb), rgb[0], rgb[1], rgb[2]))
|
|
342
|
+
centers = [
|
|
343
|
+
ordered[int((index + 0.5) * (len(ordered) - 1) / k)]
|
|
344
|
+
for index in range(k)
|
|
345
|
+
]
|
|
346
|
+
for _ in range(8):
|
|
347
|
+
groups: list[list[tuple[int, int, int]]] = [[] for _ in centers]
|
|
348
|
+
for sample in samples:
|
|
349
|
+
nearest = min(range(len(centers)), key=lambda idx: color_distance(sample, centers[idx]))
|
|
350
|
+
groups[nearest].append(sample)
|
|
351
|
+
new_centers: list[tuple[int, int, int]] = []
|
|
352
|
+
for group, center in zip(groups, centers):
|
|
353
|
+
if not group:
|
|
354
|
+
new_centers.append(center)
|
|
355
|
+
continue
|
|
356
|
+
new_centers.append(
|
|
357
|
+
tuple(int(round(sum(sample[channel] for sample in group) / len(group))) for channel in range(3))
|
|
358
|
+
) # type: ignore[arg-type]
|
|
359
|
+
centers = new_centers
|
|
360
|
+
counts = Counter(
|
|
361
|
+
min(range(len(centers)), key=lambda idx: color_distance(sample, centers[idx]))
|
|
362
|
+
for sample in samples
|
|
363
|
+
)
|
|
364
|
+
palette = [rgb_to_hex(centers[index]) for index, _ in counts.most_common()]
|
|
365
|
+
return palette[:k]
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def rgb_to_hex(rgb: tuple[int, int, int]) -> str:
|
|
369
|
+
return "#{:02X}{:02X}{:02X}".format(*rgb)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def blur_scalar(values: list[float], size: int, radius: int) -> list[float]:
|
|
373
|
+
if radius <= 0:
|
|
374
|
+
return values[:]
|
|
375
|
+
horizontal = [0.0] * (size * size)
|
|
376
|
+
for y in range(size):
|
|
377
|
+
row_offset = y * size
|
|
378
|
+
running = 0.0
|
|
379
|
+
count = 0
|
|
380
|
+
for x in range(-radius, size + radius):
|
|
381
|
+
if 0 <= x < size:
|
|
382
|
+
running += values[row_offset + x]
|
|
383
|
+
count += 1
|
|
384
|
+
remove = x - radius * 2 - 1
|
|
385
|
+
if 0 <= remove < size:
|
|
386
|
+
running -= values[row_offset + remove]
|
|
387
|
+
count -= 1
|
|
388
|
+
write_x = x - radius
|
|
389
|
+
if 0 <= write_x < size:
|
|
390
|
+
horizontal[row_offset + write_x] = running / max(1, count)
|
|
391
|
+
vertical = [0.0] * (size * size)
|
|
392
|
+
for x in range(size):
|
|
393
|
+
running = 0.0
|
|
394
|
+
count = 0
|
|
395
|
+
for y in range(-radius, size + radius):
|
|
396
|
+
if 0 <= y < size:
|
|
397
|
+
running += horizontal[y * size + x]
|
|
398
|
+
count += 1
|
|
399
|
+
remove = y - radius * 2 - 1
|
|
400
|
+
if 0 <= remove < size:
|
|
401
|
+
running -= horizontal[remove * size + x]
|
|
402
|
+
count -= 1
|
|
403
|
+
write_y = y - radius
|
|
404
|
+
if 0 <= write_y < size:
|
|
405
|
+
vertical[write_y * size + x] = running / max(1, count)
|
|
406
|
+
return vertical
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def make_maps(
|
|
410
|
+
pixels: list[tuple[int, int, int]],
|
|
411
|
+
mask: list[bool],
|
|
412
|
+
size: int,
|
|
413
|
+
palette: list[str],
|
|
414
|
+
) -> tuple[dict[str, bytes], dict[str, Any]]:
|
|
415
|
+
masked_lumas = [srgb_luma(pixel) for pixel, keep in zip(pixels, mask) if keep]
|
|
416
|
+
fallback_luma = percentile(masked_lumas, 0.5, 0.55)
|
|
417
|
+
fallback_color = hex_to_rgb(palette[0] if palette else "#8A7A5F")
|
|
418
|
+
lumas = [srgb_luma(pixel) if keep else fallback_luma for pixel, keep in zip(pixels, mask)]
|
|
419
|
+
blur_radius = max(4, min(28, size // 48))
|
|
420
|
+
low_frequency = blur_scalar(lumas, size, blur_radius)
|
|
421
|
+
p05 = percentile(masked_lumas, 0.05, 0.2)
|
|
422
|
+
p95 = percentile(masked_lumas, 0.95, 0.8)
|
|
423
|
+
value_range = max(0.08, p95 - p05)
|
|
424
|
+
high_pass = [
|
|
425
|
+
clamp((luma - low + value_range * 0.5) / value_range, 0.0, 1.0)
|
|
426
|
+
for luma, low in zip(lumas, low_frequency)
|
|
427
|
+
]
|
|
428
|
+
height = blur_scalar(high_pass, size, max(1, size // 256))
|
|
429
|
+
gradient_values: list[float] = []
|
|
430
|
+
for y in range(size):
|
|
431
|
+
for x in range(size):
|
|
432
|
+
left = height[y * size + max(0, x - 1)]
|
|
433
|
+
right = height[y * size + min(size - 1, x + 1)]
|
|
434
|
+
up = height[max(0, y - 1) * size + x]
|
|
435
|
+
down = height[min(size - 1, y + 1) * size + x]
|
|
436
|
+
gradient_values.append(math.sqrt((right - left) ** 2 + (down - up) ** 2))
|
|
437
|
+
grad_p90 = percentile(gradient_values, 0.9, 0.0)
|
|
438
|
+
normal_strength = clamp(10.0 + grad_p90 * 75.0, 10.0, 38.0)
|
|
439
|
+
albedo = bytearray()
|
|
440
|
+
roughness = bytearray()
|
|
441
|
+
height_map = bytearray()
|
|
442
|
+
normal = bytearray()
|
|
443
|
+
ao = bytearray()
|
|
444
|
+
roughness_values: list[float] = []
|
|
445
|
+
for index, ((red, green, blue), keep) in enumerate(zip(pixels, mask)):
|
|
446
|
+
luma = lumas[index]
|
|
447
|
+
shade = clamp(low_frequency[index], 0.08, 1.0)
|
|
448
|
+
scale = clamp((fallback_luma / shade) ** 0.42, 0.72, 1.35)
|
|
449
|
+
if keep:
|
|
450
|
+
out_r = clamp(red * scale, 0, 255)
|
|
451
|
+
out_g = clamp(green * scale, 0, 255)
|
|
452
|
+
out_b = clamp(blue * scale, 0, 255)
|
|
453
|
+
else:
|
|
454
|
+
out_r, out_g, out_b = fallback_color
|
|
455
|
+
albedo.extend((round(out_r), round(out_g), round(out_b)))
|
|
456
|
+
h = height[index]
|
|
457
|
+
local_gradient = gradient_values[index]
|
|
458
|
+
bright_highlight = max(0.0, luma - p95) / max(0.02, 1.0 - p95)
|
|
459
|
+
rough = clamp01(0.68 + min(0.22, local_gradient * 2.6) + (0.5 - h) * 0.12 - bright_highlight * 0.22)
|
|
460
|
+
roughness_values.append(rough)
|
|
461
|
+
rough_byte = round(rough * 255)
|
|
462
|
+
roughness.extend((rough_byte, rough_byte, rough_byte))
|
|
463
|
+
height_byte = round(h * 255)
|
|
464
|
+
height_map.extend((height_byte, height_byte, height_byte))
|
|
465
|
+
for y in range(size):
|
|
466
|
+
for x in range(size):
|
|
467
|
+
index = y * size + x
|
|
468
|
+
left = height[y * size + max(0, x - 1)]
|
|
469
|
+
right = height[y * size + min(size - 1, x + 1)]
|
|
470
|
+
up = height[max(0, y - 1) * size + x]
|
|
471
|
+
down = height[min(size - 1, y + 1) * size + x]
|
|
472
|
+
dx = (right - left) * normal_strength
|
|
473
|
+
dy = (down - up) * normal_strength
|
|
474
|
+
inv_len = 1.0 / math.sqrt(dx * dx + dy * dy + 1.0)
|
|
475
|
+
nx = -dx * inv_len
|
|
476
|
+
ny = -dy * inv_len
|
|
477
|
+
nz = inv_len
|
|
478
|
+
normal.extend(
|
|
479
|
+
(
|
|
480
|
+
round((nx * 0.5 + 0.5) * 255),
|
|
481
|
+
round((ny * 0.5 + 0.5) * 255),
|
|
482
|
+
round((nz * 0.5 + 0.5) * 255),
|
|
483
|
+
)
|
|
484
|
+
)
|
|
485
|
+
neighbors = (
|
|
486
|
+
left
|
|
487
|
+
+ right
|
|
488
|
+
+ up
|
|
489
|
+
+ down
|
|
490
|
+
) * 0.25
|
|
491
|
+
cavity = max(0.0, neighbors - height[index])
|
|
492
|
+
ao_value = clamp01(1.0 - cavity * 8.0 - max(0.0, 0.35 - height[index]) * 0.16)
|
|
493
|
+
ao_byte = round(ao_value * 255)
|
|
494
|
+
ao.extend((ao_byte, ao_byte, ao_byte))
|
|
495
|
+
return (
|
|
496
|
+
{
|
|
497
|
+
"albedo": bytes(albedo),
|
|
498
|
+
"roughness": bytes(roughness),
|
|
499
|
+
"height": bytes(height_map),
|
|
500
|
+
"normal": bytes(normal),
|
|
501
|
+
"ao": bytes(ao),
|
|
502
|
+
},
|
|
503
|
+
{
|
|
504
|
+
"valueRange": round(value_range, 4),
|
|
505
|
+
"heightP90Gradient": round(grad_p90, 5),
|
|
506
|
+
"roughnessBase": round(percentile(roughness_values, 0.5, 0.72), 3),
|
|
507
|
+
"roughnessVariation": round(max(0.05, percentile(roughness_values, 0.85, 0.82) - percentile(roughness_values, 0.15, 0.62)), 3),
|
|
508
|
+
"normalStrength": round(normal_strength / 64.0, 3),
|
|
509
|
+
"blurRadius": blur_radius,
|
|
510
|
+
},
|
|
511
|
+
)
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def hex_to_rgb(value: str) -> tuple[int, int, int]:
|
|
515
|
+
if len(value) == 4 and value.startswith("#"):
|
|
516
|
+
return tuple(int(char * 2, 16) for char in value[1:]) # type: ignore[return-value]
|
|
517
|
+
if len(value) == 7 and value.startswith("#"):
|
|
518
|
+
return (int(value[1:3], 16), int(value[3:5], 16), int(value[5:7], 16))
|
|
519
|
+
return (138, 122, 95)
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def surface_bands_from_stats(stats: dict[str, Any]) -> list[dict[str, Any]]:
|
|
523
|
+
value_range = float(stats.get("valueRange", 0.4))
|
|
524
|
+
detail = float(stats.get("heightP90Gradient", 0.02))
|
|
525
|
+
return [
|
|
526
|
+
{
|
|
527
|
+
"id": "macro",
|
|
528
|
+
"frequency": 2.0,
|
|
529
|
+
"amplitude": round(clamp(0.28 + value_range * 0.35, 0.22, 0.52), 3),
|
|
530
|
+
"role": "reference-derived broad albedo and height breakup",
|
|
531
|
+
},
|
|
532
|
+
{
|
|
533
|
+
"id": "meso",
|
|
534
|
+
"frequency": 14.0,
|
|
535
|
+
"amplitude": round(clamp(0.15 + detail * 4.2, 0.12, 0.35), 3),
|
|
536
|
+
"role": "reference-derived cracks, ridges, pores, grain, or leaf clusters",
|
|
537
|
+
},
|
|
538
|
+
{
|
|
539
|
+
"id": "micro",
|
|
540
|
+
"frequency": 72.0,
|
|
541
|
+
"amplitude": round(clamp(0.055 + detail * 2.4, 0.045, 0.14), 3),
|
|
542
|
+
"role": "reference-derived micro highlight breakup under grazing light",
|
|
543
|
+
},
|
|
544
|
+
]
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def estimate_confidence(
|
|
548
|
+
width: int,
|
|
549
|
+
height: int,
|
|
550
|
+
mask_diagnostics: dict[str, Any],
|
|
551
|
+
stats: dict[str, Any],
|
|
552
|
+
warnings: list[str],
|
|
553
|
+
single_image: bool,
|
|
554
|
+
) -> tuple[float, list[str]]:
|
|
555
|
+
confidence_notes: list[str] = []
|
|
556
|
+
min_dim = min(width, height)
|
|
557
|
+
resolution_score = clamp(min_dim / 1024.0, 0.35, 1.0)
|
|
558
|
+
coverage = float(mask_diagnostics.get("foregroundCoverage", 1.0))
|
|
559
|
+
if 0.08 <= coverage <= 0.82:
|
|
560
|
+
mask_score = 1.0
|
|
561
|
+
elif 0.035 <= coverage < 0.08:
|
|
562
|
+
mask_score = 0.55
|
|
563
|
+
confidence_notes.append("foreground mask is very small")
|
|
564
|
+
elif coverage > 0.9:
|
|
565
|
+
mask_score = 0.68
|
|
566
|
+
confidence_notes.append("object/background separation is weak")
|
|
567
|
+
else:
|
|
568
|
+
mask_score = 0.78
|
|
569
|
+
value_range = float(stats.get("valueRange", 0.0))
|
|
570
|
+
dynamic_score = clamp(value_range / 0.48, 0.35, 1.0)
|
|
571
|
+
detail_score = clamp(float(stats.get("heightP90Gradient", 0.0)) * 52.0, 0.35, 1.0)
|
|
572
|
+
warning_penalty = min(0.16, len(warnings) * 0.035)
|
|
573
|
+
single_image_cap = 0.86 if single_image else 0.93
|
|
574
|
+
confidence = (
|
|
575
|
+
0.44
|
|
576
|
+
+ resolution_score * 0.14
|
|
577
|
+
+ mask_score * 0.14
|
|
578
|
+
+ dynamic_score * 0.12
|
|
579
|
+
+ detail_score * 0.16
|
|
580
|
+
- warning_penalty
|
|
581
|
+
)
|
|
582
|
+
confidence = min(single_image_cap, clamp01(confidence))
|
|
583
|
+
if single_image:
|
|
584
|
+
confidence_notes.append("single-image inverse rendering cannot prove true physical PBR; confidence is capped")
|
|
585
|
+
if dynamic_score < 0.5:
|
|
586
|
+
confidence_notes.append("low value range weakens height/roughness inference")
|
|
587
|
+
if detail_score < 0.5:
|
|
588
|
+
confidence_notes.append("low high-frequency detail weakens normal/roughness inference")
|
|
589
|
+
return round(confidence, 3), confidence_notes
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def map_url(url_prefix: str, filename: str) -> str:
|
|
593
|
+
if not url_prefix:
|
|
594
|
+
return filename
|
|
595
|
+
return url_prefix.rstrip("/") + "/" + filename
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def material_patch(
|
|
599
|
+
material_id: str,
|
|
600
|
+
image: Path,
|
|
601
|
+
out_dir: Path,
|
|
602
|
+
url_prefix: str,
|
|
603
|
+
size: int,
|
|
604
|
+
threshold: float,
|
|
605
|
+
confidence: float,
|
|
606
|
+
verdict: str,
|
|
607
|
+
palette: list[str],
|
|
608
|
+
map_stats: dict[str, Any],
|
|
609
|
+
diagnostics: dict[str, Any],
|
|
610
|
+
warnings: list[str],
|
|
611
|
+
) -> dict[str, Any]:
|
|
612
|
+
prefix = slugify(material_id)
|
|
613
|
+
maps = {
|
|
614
|
+
channel: {
|
|
615
|
+
"path": str((out_dir / f"{prefix}_{channel}.png").resolve()),
|
|
616
|
+
"url": map_url(url_prefix, f"{prefix}_{channel}.png"),
|
|
617
|
+
"channel": channel,
|
|
618
|
+
"source": "reference-pixel-extraction",
|
|
619
|
+
}
|
|
620
|
+
for channel in ("albedo", "roughness", "height", "normal", "ao")
|
|
621
|
+
}
|
|
622
|
+
usable = confidence >= threshold
|
|
623
|
+
return {
|
|
624
|
+
"referencePbr": {
|
|
625
|
+
"version": "1.0",
|
|
626
|
+
"sourceImage": str(image.resolve()),
|
|
627
|
+
"extractor": "stage1_intake/extract_pbr_evidence.py",
|
|
628
|
+
"method": "single-image pixel evidence with de-lighting estimate; not photogrammetry",
|
|
629
|
+
"usable": usable,
|
|
630
|
+
"verdict": verdict,
|
|
631
|
+
"confidence": confidence,
|
|
632
|
+
"estimatedFidelity": confidence,
|
|
633
|
+
"targetThreshold": threshold,
|
|
634
|
+
"hardLimit": "A single image cannot uniquely recover true albedo/roughness/normal/AO; maps are reference-derived estimates.",
|
|
635
|
+
"maps": maps,
|
|
636
|
+
"diagnostics": diagnostics,
|
|
637
|
+
"warnings": warnings,
|
|
638
|
+
},
|
|
639
|
+
"textureResolution": size,
|
|
640
|
+
"albedo": {
|
|
641
|
+
"dominant": palette[0],
|
|
642
|
+
"secondary": palette[1:4],
|
|
643
|
+
"samplingNotes": "Reference-derived from foreground pixels; de-lit to reduce baked shadows/highlights.",
|
|
644
|
+
"map": maps["albedo"],
|
|
645
|
+
},
|
|
646
|
+
"colorVariation": {
|
|
647
|
+
"palette": palette,
|
|
648
|
+
"pattern": "reference-derived pixel palette",
|
|
649
|
+
"amplitude": round(clamp(float(map_stats.get("valueRange", 0.4)) * 0.42, 0.08, 0.35), 3),
|
|
650
|
+
"heightCorrelation": 0.42,
|
|
651
|
+
},
|
|
652
|
+
"roughness": {
|
|
653
|
+
"base": map_stats["roughnessBase"],
|
|
654
|
+
"variation": map_stats["roughnessVariation"],
|
|
655
|
+
"map": maps["roughness"],
|
|
656
|
+
"localResponse": "reference-derived roughness estimate; cavities and textured zones trend rougher, bright highlights trend smoother",
|
|
657
|
+
},
|
|
658
|
+
"normal": {
|
|
659
|
+
"pattern": "reference-derived height-gradient normal map",
|
|
660
|
+
"strength": map_stats["normalStrength"],
|
|
661
|
+
"map": maps["normal"],
|
|
662
|
+
"heightSource": maps["height"],
|
|
663
|
+
"space": "tangent",
|
|
664
|
+
},
|
|
665
|
+
"bump": {
|
|
666
|
+
"pattern": "reference-derived height field",
|
|
667
|
+
"amplitude": round(clamp(float(map_stats.get("heightP90Gradient", 0.02)) * 0.45, 0.01, 0.08), 3),
|
|
668
|
+
"map": maps["height"],
|
|
669
|
+
},
|
|
670
|
+
"ambientOcclusion": {
|
|
671
|
+
"cavityStrength": 0.38,
|
|
672
|
+
"contactShadowBias": 0.35,
|
|
673
|
+
"map": maps["ao"],
|
|
674
|
+
"notes": "Reference-derived cavity estimate from local height minima; verify against grazing-light screenshot.",
|
|
675
|
+
},
|
|
676
|
+
"surfaceFrequencyBands": surface_bands_from_stats(map_stats),
|
|
677
|
+
"localOverrides": [
|
|
678
|
+
{
|
|
679
|
+
"id": "reference-pbr-pixel-evidence",
|
|
680
|
+
"type": "material-map-evidence",
|
|
681
|
+
"evidenceRefs": ["full-object"],
|
|
682
|
+
"channels": ["albedo", "roughness", "height", "normal", "ambient-occlusion"],
|
|
683
|
+
"notes": "Use generated maps as material evidence, then refine after browser screenshot comparison.",
|
|
684
|
+
}
|
|
685
|
+
],
|
|
686
|
+
"shaderNotes": [
|
|
687
|
+
"Reference-derived maps are estimates from image pixels; verify with neutral, grazing, and reference-matched renders.",
|
|
688
|
+
"Do not treat baked image shadows as final albedo; rerun extraction with a tighter material crop if highlights/shadows pollute the maps.",
|
|
689
|
+
],
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
def merge_material_patch(spec: dict[str, Any], material_id: str, patch: dict[str, Any]) -> None:
|
|
694
|
+
materials = spec.get("materials")
|
|
695
|
+
if not isinstance(materials, list):
|
|
696
|
+
raise ValueError("spec.materials must be an array")
|
|
697
|
+
material = next(
|
|
698
|
+
(item for item in materials if isinstance(item, dict) and item.get("id") == material_id),
|
|
699
|
+
None,
|
|
700
|
+
)
|
|
701
|
+
if material is None:
|
|
702
|
+
raise ValueError(f"could not find material {material_id!r} in spec")
|
|
703
|
+
for key, value in patch.items():
|
|
704
|
+
if key == "localOverrides" and isinstance(material.get(key), list) and isinstance(value, list):
|
|
705
|
+
material[key].extend(value)
|
|
706
|
+
elif key == "shaderNotes" and isinstance(material.get(key), list) and isinstance(value, list):
|
|
707
|
+
material[key].extend(value)
|
|
708
|
+
else:
|
|
709
|
+
material[key] = value
|
|
710
|
+
history = spec.setdefault("pbrExtractionHistory", [])
|
|
711
|
+
if isinstance(history, list):
|
|
712
|
+
history.append(
|
|
713
|
+
{
|
|
714
|
+
"materialId": material_id,
|
|
715
|
+
"confidence": patch["referencePbr"]["confidence"],
|
|
716
|
+
"verdict": patch["referencePbr"]["verdict"],
|
|
717
|
+
"usable": patch["referencePbr"]["usable"],
|
|
718
|
+
"maps": patch["referencePbr"]["maps"],
|
|
719
|
+
}
|
|
720
|
+
)
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
def extract(args: argparse.Namespace) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
724
|
+
image = args.image.expanduser().resolve()
|
|
725
|
+
if not image.exists():
|
|
726
|
+
raise ValueError(f"{image} does not exist")
|
|
727
|
+
size = int(2 ** round(math.log2(args.size)))
|
|
728
|
+
size = max(256, min(2048, size))
|
|
729
|
+
out_dir = args.out_dir.expanduser().resolve()
|
|
730
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
731
|
+
width, height, source_pixels, load_warnings = load_image(image)
|
|
732
|
+
mask, mask_diag, mask_warnings = build_foreground_mask(width, height, source_pixels)
|
|
733
|
+
bbox = mask_bbox(width, height, mask)
|
|
734
|
+
sampled_pixels, sampled_mask = resample_crop(width, height, source_pixels, mask, bbox, size)
|
|
735
|
+
samples = representative_samples(sampled_pixels, sampled_mask)
|
|
736
|
+
palette = kmeans_palette(samples, max(2, min(6, args.palette_size)))
|
|
737
|
+
maps, map_stats = make_maps(sampled_pixels, sampled_mask, size, palette)
|
|
738
|
+
for channel, payload in maps.items():
|
|
739
|
+
write_png_rgb(out_dir / f"{slugify(args.material_id)}_{channel}.png", size, size, payload)
|
|
740
|
+
warnings = load_warnings + mask_warnings
|
|
741
|
+
diagnostics = {
|
|
742
|
+
"sourceWidth": width,
|
|
743
|
+
"sourceHeight": height,
|
|
744
|
+
"mapSize": size,
|
|
745
|
+
"cropBBoxPixels": {
|
|
746
|
+
"x": bbox[0],
|
|
747
|
+
"y": bbox[1],
|
|
748
|
+
"width": bbox[2],
|
|
749
|
+
"height": bbox[3],
|
|
750
|
+
},
|
|
751
|
+
"mask": mask_diag,
|
|
752
|
+
"mapStats": map_stats,
|
|
753
|
+
"palette": palette,
|
|
754
|
+
}
|
|
755
|
+
confidence, confidence_notes = estimate_confidence(
|
|
756
|
+
width,
|
|
757
|
+
height,
|
|
758
|
+
mask_diag,
|
|
759
|
+
map_stats,
|
|
760
|
+
warnings,
|
|
761
|
+
single_image=not args.multi_view_reference,
|
|
762
|
+
)
|
|
763
|
+
warnings.extend(confidence_notes)
|
|
764
|
+
threshold = clamp01(args.target_threshold)
|
|
765
|
+
verdict = "pass" if confidence >= threshold else ("conditional" if confidence >= threshold - 0.12 else "reject")
|
|
766
|
+
patch = material_patch(
|
|
767
|
+
args.material_id,
|
|
768
|
+
image,
|
|
769
|
+
out_dir,
|
|
770
|
+
args.url_prefix,
|
|
771
|
+
size,
|
|
772
|
+
threshold,
|
|
773
|
+
confidence,
|
|
774
|
+
verdict,
|
|
775
|
+
palette,
|
|
776
|
+
map_stats,
|
|
777
|
+
diagnostics,
|
|
778
|
+
warnings,
|
|
779
|
+
)
|
|
780
|
+
report = {
|
|
781
|
+
"ok": confidence >= threshold,
|
|
782
|
+
"verdict": verdict,
|
|
783
|
+
"confidence": confidence,
|
|
784
|
+
"estimatedFidelity": confidence,
|
|
785
|
+
"targetThreshold": threshold,
|
|
786
|
+
"materialId": args.material_id,
|
|
787
|
+
"sourceImage": str(image),
|
|
788
|
+
"outDir": str(out_dir),
|
|
789
|
+
"palette": palette,
|
|
790
|
+
"maps": patch["referencePbr"]["maps"],
|
|
791
|
+
"diagnostics": diagnostics,
|
|
792
|
+
"warnings": warnings,
|
|
793
|
+
"limitation": "single-image PBR extraction is an estimate; 70%+ extraction confidence still needs render screenshot review",
|
|
794
|
+
}
|
|
795
|
+
return report, patch
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
def main(argv: list[str]) -> int:
|
|
799
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
800
|
+
parser.add_argument("image", type=Path)
|
|
801
|
+
parser.add_argument("--out-dir", type=Path, required=True)
|
|
802
|
+
parser.add_argument("--material-id", default="base")
|
|
803
|
+
parser.add_argument("--size", type=int, default=1024)
|
|
804
|
+
parser.add_argument("--palette-size", type=int, default=5)
|
|
805
|
+
parser.add_argument("--target-threshold", type=float, default=0.7)
|
|
806
|
+
parser.add_argument("--url-prefix", default="")
|
|
807
|
+
parser.add_argument("--spec", type=Path, help="Optional ObjectSculptSpec JSON to patch")
|
|
808
|
+
parser.add_argument("--in-place", action="store_true", help="Patch --spec in place when confidence passes")
|
|
809
|
+
parser.add_argument("--out-spec", type=Path, help="Write patched spec to this path")
|
|
810
|
+
parser.add_argument("--report", type=Path, help="Write extraction report JSON")
|
|
811
|
+
parser.add_argument("--allow-low-confidence", action="store_true", help="Patch/write even when confidence is below threshold")
|
|
812
|
+
parser.add_argument("--multi-view-reference", action="store_true", help="Raise confidence cap when image belongs to a multi-view reference set")
|
|
813
|
+
args = parser.parse_args(argv)
|
|
814
|
+
|
|
815
|
+
try:
|
|
816
|
+
report, patch = extract(args)
|
|
817
|
+
if args.report:
|
|
818
|
+
args.report.expanduser().resolve().parent.mkdir(parents=True, exist_ok=True)
|
|
819
|
+
args.report.expanduser().resolve().write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
820
|
+
if args.spec:
|
|
821
|
+
if not report["ok"] and not args.allow_low_confidence:
|
|
822
|
+
raise ValueError(
|
|
823
|
+
f"PBR extraction confidence {report['confidence']} is below target "
|
|
824
|
+
f"{report['targetThreshold']}; spec was not patched"
|
|
825
|
+
)
|
|
826
|
+
spec_path = args.spec.expanduser().resolve()
|
|
827
|
+
spec = json.loads(spec_path.read_text(encoding="utf-8"))
|
|
828
|
+
if not isinstance(spec, dict):
|
|
829
|
+
raise ValueError("spec must be a JSON object")
|
|
830
|
+
merge_material_patch(spec, args.material_id, patch)
|
|
831
|
+
output = spec_path if args.in_place else (args.out_spec.expanduser().resolve() if args.out_spec else None)
|
|
832
|
+
if output:
|
|
833
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
834
|
+
output.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
835
|
+
print(json.dumps(report, indent=2, ensure_ascii=False))
|
|
836
|
+
return 0 if report["ok"] or args.allow_low_confidence else 1
|
|
837
|
+
except Exception as exc:
|
|
838
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
839
|
+
return 1
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
if __name__ == "__main__":
|
|
843
|
+
raise SystemExit(main(sys.argv[1:]))
|