@babylonjs-toolkit/agent 1.2.0 → 1.2.1
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/README.md +3 -2
- package/package.json +1 -1
- package/skills/bt-atlas/SKILL.md +22 -5
- package/skills/bt-design/references/3d-hero-docs.md +10 -3
- package/skills/bt-design/references/3d-hero-scroll.md +30 -5
- package/skills/bt-gauntlet/SKILL.md +4 -4
- package/skills/bt-gauntlet/references/spec-composition.md +4 -2
- package/skills/bt-gauntlet/references/target-images.md +28 -4
- package/skills/bt-gauntlet/references/unity-pipeline.md +30 -8
- package/skills/bt-hero/SKILL.md +3 -3
- package/skills/bt-landing/SKILL.md +1 -1
- package/skills/bt-prototype/SKILL.md +3 -3
- package/skills/bt-unwrap/SKILL.md +396 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/bt_unwrap.py +678 -0
- package/skills/bt-unwrap/scripts/blender/image_utils.py +264 -0
- package/skills/bt-unwrap/scripts/blender/mesh_tools.py +508 -0
- package/skills/bt-unwrap/scripts/blender/model_io.py +135 -0
- package/skills/bt-unwrap/scripts/blender/previews.py +205 -0
- package/skills/bt-unwrap/scripts/blender/rasterizer.py +217 -0
- package/skills/bt-unwrap/scripts/blender/reference_views.py +945 -0
- package/skills/bt-unwrap/scripts/blender/reference_warp.py +571 -0
- package/skills/bt-unwrap/scripts/blender/texture_bake.py +390 -0
- package/skills/bt-unwrap/scripts/blender/texture_compose.py +596 -0
- package/skills/bt-unwrap/scripts/blender/uv_layout.py +605 -0
- package/skills/bt-unwrap/scripts/bt-unwrap.mjs +165 -0
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Texture compositing for bt-unwrap. Every face of the model gets ONE source of color: the reference view that
|
|
3
|
+
sees it best, or the model's own baked texture. On smooth panels a reference is a decal and wins wherever it
|
|
4
|
+
sees the face well; in cluttered parts (engines, cockpits, suspension — where much of the surface is hidden
|
|
5
|
+
behind other parts) it must also show the same features as the model's own texture, because there a
|
|
6
|
+
generated image and a generated mesh rarely draw the same parts. Neighbouring faces are pulled toward the
|
|
7
|
+
same choice, so the result is made of whole patches; colors are blended only across the single ring of
|
|
8
|
+
faces where two patches meet, so nothing is averaged into a ghost. Each view's exposure is evened out, the
|
|
9
|
+
source texture's colors are matched to the references, and island edges are padded.
|
|
10
|
+
|
|
11
|
+
This is the per-face view selection used to texture meshes from photographs (Waechter et al., "Let There Be
|
|
12
|
+
Color!", 2014), with the model's own baked texture as one more candidate.
|
|
13
|
+
"""
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
import image_utils
|
|
19
|
+
import rasterizer
|
|
20
|
+
import reference_views
|
|
21
|
+
import uv_layout
|
|
22
|
+
|
|
23
|
+
TEXEL_CHUNK = 2_000_000
|
|
24
|
+
COLOR_MATCH_MINIMUM_TEXELS = 2_000
|
|
25
|
+
COLOR_MATCH_GAIN_LIMITS = (0.5, 2.0)
|
|
26
|
+
STRONG_COVERAGE = 0.9
|
|
27
|
+
EXPOSURE_HEAD_ON = 0.5 # texels a view sees this directly, and agrees on, measure its exposure
|
|
28
|
+
EXPOSURE_MINIMUM_TEXELS = 2_000 # views with fewer such texels keep a gain of 1
|
|
29
|
+
EXPOSURE_GAIN_LIMIT = 1.8 # no view is brightened or darkened more than this
|
|
30
|
+
SOURCE_LABEL = 0 # face label of the model's own texture; view n has label n + 1
|
|
31
|
+
LABEL_PASSES = 10 # smoothing passes of the face labels
|
|
32
|
+
# A seam between two choices costs more where they look different there: seams settle in plain areas
|
|
33
|
+
# instead of cutting through a logo. Cost per shared edge = smoothness * (1 + this * color difference).
|
|
34
|
+
SEAM_COLOR_WEIGHT = 4.0
|
|
35
|
+
UNAVAILABLE_COLOR_DIFFERENCE = 1.0 # color difference assumed where a choice cannot paint a face
|
|
36
|
+
MINIMUM_SEEN_SHARE = 0.5 # a view must see this share of a face for the refusal reason to be 'other'
|
|
37
|
+
# Clutter: how much of the surface within this distance (share of the model diagonal) is hidden from the
|
|
38
|
+
# views that face it. This share of hidden surface counts as fully cluttered.
|
|
39
|
+
CLUTTER_RADIUS_FRACTION = 0.012
|
|
40
|
+
CLUTTER_FULL_SHARE = 0.35
|
|
41
|
+
CLUTTER_OPEN_COLOR = np.array((0.15, 0.35, 0.75), dtype=np.float32) # clutter map: open surface
|
|
42
|
+
CLUTTER_CLUTTERED_COLOR = np.array((1.00, 0.55, 0.10), dtype=np.float32) # ... cluttered surface
|
|
43
|
+
CLUTTER_FACING = 0.3 # views facing a face at least this much (mean) judge whether it is hidden
|
|
44
|
+
|
|
45
|
+
# Coverage map colors: which view painted a texel, and why a texel kept the model's own texture.
|
|
46
|
+
VIEW_COLORS = {
|
|
47
|
+
"front": (0.20, 0.45, 1.00), "rear": (1.00, 0.85, 0.15), "left": (0.20, 0.85, 0.30),
|
|
48
|
+
"right": (0.10, 0.85, 0.85), "top": (0.85, 0.25, 0.95), "bottom": (1.00, 0.55, 0.15),
|
|
49
|
+
"front_left": (0.95, 0.95, 0.95), "front_right": (0.65, 1.00, 0.10),
|
|
50
|
+
"rear_left": (0.55, 0.35, 0.15), "rear_right": (0.15, 0.20, 0.60),
|
|
51
|
+
}
|
|
52
|
+
EXTRA_VIEW_COLORS = ((0.55, 0.55, 0.10), (0.00, 0.45, 0.40), (0.75, 0.65, 1.00), (1.00, 0.60, 0.50))
|
|
53
|
+
REFUSED_HIDDEN_COLOR = (0.90, 0.05, 0.05) # the best view faced it but other geometry hid it
|
|
54
|
+
REFUSED_OUTSIDE_COLOR = (1.00, 0.45, 0.70) # it projected off the subject
|
|
55
|
+
REFUSED_INCONSISTENT_COLOR = (0.02, 0.02, 0.02) # the view shows something else than the model's own texture
|
|
56
|
+
UNSEEN_COLOR = (0.22, 0.22, 0.22) # no view faces it closely enough (or the source scored higher)
|
|
57
|
+
REFUSAL_NONE, REFUSAL_HIDDEN, REFUSAL_OUTSIDE, REFUSAL_INCONSISTENT = 0, 1, 2, 3
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class TexelSurface:
|
|
62
|
+
"""For every covered texel of the new layout: where it is on the model and which way it faces."""
|
|
63
|
+
|
|
64
|
+
size: int
|
|
65
|
+
texel_index: np.ndarray # int64 flat indices (row * size + column) of covered texels
|
|
66
|
+
triangle_index: np.ndarray # int64 triangle under each covered texel
|
|
67
|
+
barycentric: np.ndarray # float32 (count, 3) position of each texel inside its triangle
|
|
68
|
+
positions: np.ndarray # float32 (count, 3) world position
|
|
69
|
+
normals: np.ndarray # float32 (count, 3) smoothed normal, used to weigh reference views
|
|
70
|
+
|
|
71
|
+
def covered_mask(self) -> np.ndarray:
|
|
72
|
+
"""Boolean (size, size) mask of texels that lie on the model."""
|
|
73
|
+
mask = np.zeros(self.size * self.size, dtype=bool)
|
|
74
|
+
mask[self.texel_index] = True
|
|
75
|
+
return mask.reshape(self.size, self.size)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def build_texel_surface(triangles, size: int, vertex_normals: np.ndarray) -> TexelSurface:
|
|
79
|
+
"""
|
|
80
|
+
Rasterizes the new UV layout to find the surface point behind every texel.
|
|
81
|
+
|
|
82
|
+
:param triangles: TriangleSet with the working UV layer.
|
|
83
|
+
:param size: Texture size in pixels.
|
|
84
|
+
:param vertex_normals: float32 (vertex_count, 3) smoothed normals numbered like triangles.vertex_index.
|
|
85
|
+
Weighing views by these keeps a lumpy panel from flickering between views.
|
|
86
|
+
:returns: The covered texels with their positions and normals.
|
|
87
|
+
"""
|
|
88
|
+
uv_pixels = triangles.uvs[uv_layout.NEW_UV_LAYER].astype(np.float64) * size
|
|
89
|
+
triangle_id, barycentric = rasterizer.rasterize_ids(uv_pixels, size, size)
|
|
90
|
+
texel_index = np.flatnonzero(triangle_id >= 0)
|
|
91
|
+
triangle_index = triangle_id[texel_index]
|
|
92
|
+
weights = barycentric[texel_index]
|
|
93
|
+
positions = (triangles.positions[triangle_index] * weights[:, :, None]).sum(axis=1).astype(np.float32)
|
|
94
|
+
normals = (vertex_normals[triangles.vertex_index[triangle_index]] * weights[:, :, None]).sum(axis=1)
|
|
95
|
+
normals /= np.maximum(np.linalg.norm(normals, axis=1, keepdims=True), 1e-20)
|
|
96
|
+
return TexelSurface(size=size, texel_index=texel_index, triangle_index=triangle_index,
|
|
97
|
+
barycentric=weights.astype(np.float32), positions=positions,
|
|
98
|
+
normals=normals.astype(np.float32))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass
|
|
102
|
+
class ViewSamples:
|
|
103
|
+
"""What one reference offers: its color at every texel it may paint, and per-face totals for choosing."""
|
|
104
|
+
|
|
105
|
+
view: str
|
|
106
|
+
texels: np.ndarray # int64 indices into the covered-texel arrays, where the view may paint
|
|
107
|
+
colors: np.ndarray # float32 (count, 3) sRGB colors sampled from the reference
|
|
108
|
+
facing: np.ndarray # float32 (count,) how directly each of those texels faces the view, 0..1
|
|
109
|
+
trust: np.ndarray # float32 (count,) agreement with the model's own texture there, 0..1
|
|
110
|
+
face_facing: np.ndarray # float32 (triangles,) sum of facing over every texel of the face
|
|
111
|
+
face_active: np.ndarray # float32 (triangles,) texels of the face that face the view at all
|
|
112
|
+
face_visible: np.ndarray # float32 (triangles,) ...that it can see
|
|
113
|
+
face_inside: np.ndarray # float32 (triangles,) ...and that land on its subject (the paintable ones)
|
|
114
|
+
face_seen_facing: np.ndarray # float32 (triangles,) sum of facing over the paintable texels
|
|
115
|
+
face_trust: np.ndarray # float32 (triangles,) sum of trust over the paintable texels
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def compose_color(baked_color: np.ndarray, surface: TexelSurface, triangles, references: list, options,
|
|
119
|
+
model_diagonal: float, padding: int) -> tuple:
|
|
120
|
+
"""
|
|
121
|
+
Builds the final base color: every face takes its color from its chosen view or from the color-matched
|
|
122
|
+
source texture, with soft hand-overs only where choices meet, then pads around islands.
|
|
123
|
+
|
|
124
|
+
:param baked_color: float32 (size, size, 4) baked source base color (sRGB values).
|
|
125
|
+
:param surface: Covered texels of the new layout.
|
|
126
|
+
:param triangles: TriangleSet of the final mesh (vertex numbering and positions for the face choices).
|
|
127
|
+
:param references: Aligned references.
|
|
128
|
+
:param options: Parsed options (ref_strength, ref_source_score, ref_seam_smoothness, color_match, padding ...).
|
|
129
|
+
:param model_diagonal: Bounding-box diagonal in meters.
|
|
130
|
+
:param padding: Island edge padding in pixels at this texture size.
|
|
131
|
+
:returns: (final color float32 (size, size, 4), statistics dict, diagnostic maps: name -> float32
|
|
132
|
+
(size, size, 4) texture for the same layout — 'coverage' (see coverage_image) and 'clutter' (see
|
|
133
|
+
clutter_image); empty when there are no references).
|
|
134
|
+
"""
|
|
135
|
+
size = surface.size
|
|
136
|
+
flat_color = baked_color.reshape(-1, 4).copy()
|
|
137
|
+
source_colors = flat_color[surface.texel_index, :3]
|
|
138
|
+
statistics = {"reference_painted_percent": 0.0, "per_view_percent": {}, "color_match": {"applied": False}}
|
|
139
|
+
diagnostic_maps = {}
|
|
140
|
+
|
|
141
|
+
used = [reference for reference in references if reference.used]
|
|
142
|
+
if used:
|
|
143
|
+
samples = [_sample_view(reference, surface, triangles.count, options, model_diagonal) for reference in used]
|
|
144
|
+
gains = exposure_gains(samples, source_colors) if options.exposure_match else {}
|
|
145
|
+
_apply_gains(samples, gains)
|
|
146
|
+
clutter = face_clutter(samples, surface, triangles, model_diagonal)
|
|
147
|
+
labels = choose_face_sources(samples, surface, triangles, source_colors, clutter, options)
|
|
148
|
+
vertex_weights = _vertex_label_weights(triangles, labels, len(samples) + 1)
|
|
149
|
+
reference_colors, coverage, dominant = _blend_views(samples, surface, triangles, vertex_weights)
|
|
150
|
+
coverage = coverage * options.ref_strength
|
|
151
|
+
if options.color_match:
|
|
152
|
+
source_colors, match_report = match_source_colors(source_colors, reference_colors, coverage)
|
|
153
|
+
statistics["color_match"] = match_report
|
|
154
|
+
flat_color[surface.texel_index, :3] = source_colors * (1.0 - coverage[:, None]) + \
|
|
155
|
+
reference_colors * coverage[:, None]
|
|
156
|
+
views = [view_samples.view for view_samples in samples]
|
|
157
|
+
refusal = _face_refusals(samples, surface, triangles.count, clutter)
|
|
158
|
+
statistics["reference_painted_percent"] = round(float((coverage > 0.5).mean()) * 100.0, 1)
|
|
159
|
+
statistics["per_view_percent"] = {view: round(float(((dominant == index) & (coverage > 0.5)).mean()) * 100.0, 1)
|
|
160
|
+
for index, view in enumerate(views)}
|
|
161
|
+
statistics["exposure_gains"] = {view: np.round(gain, 3).tolist() for view, gain in gains.items()}
|
|
162
|
+
statistics["face_choices"] = {"source": int((labels == SOURCE_LABEL).sum()),
|
|
163
|
+
**{view: int((labels == index + 1).sum()) for index, view in enumerate(views)}}
|
|
164
|
+
statistics["cluttered_face_percent"] = round(float((clutter >= 0.5).mean()) * 100.0, 1)
|
|
165
|
+
statistics["coverage"] = coverage_summary(views, coverage, dominant, refusal[surface.triangle_index])
|
|
166
|
+
diagnostic_maps["coverage"] = coverage_image(surface, views, coverage, dominant,
|
|
167
|
+
refusal[surface.triangle_index], padding)
|
|
168
|
+
diagnostic_maps["clutter"] = clutter_image(surface, clutter[surface.triangle_index], padding)
|
|
169
|
+
else:
|
|
170
|
+
flat_color[surface.texel_index, :3] = source_colors
|
|
171
|
+
|
|
172
|
+
flat_color[:, 3] = 1.0
|
|
173
|
+
color = flat_color.reshape(size, size, 4)
|
|
174
|
+
color = image_utils.dilate_colors(color, surface.covered_mask(), padding)
|
|
175
|
+
return color, statistics, diagnostic_maps
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _sample_view(reference, surface: TexelSurface, triangle_count: int, options, model_diagonal: float) -> ViewSamples:
|
|
179
|
+
"""Samples one reference at every texel it faces, can see, lands on its subject, and agrees with the source."""
|
|
180
|
+
count = surface.texel_index.size
|
|
181
|
+
sampling_mask = image_utils.erode_mask(reference.mask, options.ref_edge_inset)
|
|
182
|
+
height, width = reference.mask.shape
|
|
183
|
+
direction = reference.direction.astype(np.float32)
|
|
184
|
+
minimum_facing = np.cos(np.radians(options.ref_max_angle))
|
|
185
|
+
depth_tolerance = options.depth_tolerance * model_diagonal
|
|
186
|
+
parts = {"texels": [], "colors": [], "facing": [], "trust": []}
|
|
187
|
+
face_totals = {name: np.zeros(triangle_count, dtype=np.float64)
|
|
188
|
+
for name in ("face_facing", "face_active", "face_visible", "face_inside", "face_seen_facing",
|
|
189
|
+
"face_trust")}
|
|
190
|
+
for start in range(0, count, TEXEL_CHUNK):
|
|
191
|
+
chunk = slice(start, min(start + TEXEL_CHUNK, count))
|
|
192
|
+
facing = np.clip((surface.normals[chunk] @ direction - minimum_facing) / max(1.0 - minimum_facing, 1e-6),
|
|
193
|
+
0.0, 1.0)
|
|
194
|
+
active = np.flatnonzero(facing > 1e-3)
|
|
195
|
+
if active.size == 0:
|
|
196
|
+
continue
|
|
197
|
+
faces = surface.triangle_index[chunk][active]
|
|
198
|
+
points = surface.positions[chunk][active].astype(np.float64)
|
|
199
|
+
pixel_points = reference_views.map_to_reference(reference, points)
|
|
200
|
+
pixel_x, pixel_y = pixel_points[:, 0], pixel_points[:, 1]
|
|
201
|
+
# Visibility is a property of the mesh, so it uses the mesh's own projection; color comes from where
|
|
202
|
+
# the local warp says the matching content really is in the image.
|
|
203
|
+
nearest_depth = image_utils.sample_nearest(reference.depth, pixel_x, pixel_y)
|
|
204
|
+
visible = reference_views.depth_along(points, reference.direction) >= nearest_depth - depth_tolerance
|
|
205
|
+
if reference.warp is not None:
|
|
206
|
+
shift = reference.warp.displacement_at(pixel_x, pixel_y)
|
|
207
|
+
pixel_x, pixel_y = pixel_x + shift[:, 0], pixel_y + shift[:, 1]
|
|
208
|
+
inside = (pixel_x >= 0) & (pixel_x < width) & (pixel_y >= 0) & (pixel_y < height)
|
|
209
|
+
inside &= image_utils.sample_nearest(sampling_mask, pixel_x, pixel_y) & visible
|
|
210
|
+
trust = reference.agreement.at(pixel_x, pixel_y) if reference.agreement is not None \
|
|
211
|
+
else np.ones(active.size, dtype=np.float32)
|
|
212
|
+
active_facing = facing[active]
|
|
213
|
+
paintable = inside
|
|
214
|
+
|
|
215
|
+
def add(name: str, values: np.ndarray) -> None:
|
|
216
|
+
face_totals[name] += np.bincount(faces, weights=values, minlength=triangle_count)
|
|
217
|
+
|
|
218
|
+
add("face_facing", active_facing)
|
|
219
|
+
add("face_active", np.ones(active.size))
|
|
220
|
+
add("face_visible", visible.astype(np.float64))
|
|
221
|
+
add("face_inside", inside.astype(np.float64))
|
|
222
|
+
add("face_seen_facing", np.where(paintable, active_facing, 0.0))
|
|
223
|
+
add("face_trust", np.where(paintable, trust, 0.0))
|
|
224
|
+
if not paintable.any():
|
|
225
|
+
continue
|
|
226
|
+
parts["texels"].append(chunk.start + active[paintable])
|
|
227
|
+
parts["colors"].append(image_utils.sample_bilinear(reference.pixels[:, :, :3], pixel_x[paintable],
|
|
228
|
+
pixel_y[paintable]).astype(np.float32))
|
|
229
|
+
parts["facing"].append(active_facing[paintable].astype(np.float32))
|
|
230
|
+
parts["trust"].append(trust[paintable].astype(np.float32))
|
|
231
|
+
empty = {"texels": np.zeros(0, dtype=np.int64), "colors": np.zeros((0, 3), dtype=np.float32),
|
|
232
|
+
"facing": np.zeros(0, dtype=np.float32), "trust": np.zeros(0, dtype=np.float32)}
|
|
233
|
+
joined = {name: np.concatenate(chunks) if chunks else empty[name] for name, chunks in parts.items()}
|
|
234
|
+
return ViewSamples(view=reference.view, **joined,
|
|
235
|
+
**{name: values.astype(np.float32) for name, values in face_totals.items()})
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def exposure_gains(samples: list, source_colors: np.ndarray) -> dict:
|
|
239
|
+
"""
|
|
240
|
+
Evens out the lighting baked into each reference (a backlit rear view, a bright top view). The baked
|
|
241
|
+
source texture is the yardstick: the generator fused all its views into one consistently lit texture,
|
|
242
|
+
and the local warp has aligned every reference to it. Over each view's head-on, agreeing region, the
|
|
243
|
+
ratio of source to reference brightness says how much brighter or darker that view was lit. Only the
|
|
244
|
+
differences BETWEEN views are corrected — the gains are normalised so the references keep their overall
|
|
245
|
+
brightness.
|
|
246
|
+
|
|
247
|
+
:param samples: ViewSamples for every used reference.
|
|
248
|
+
:param source_colors: float32 (count, 3) baked source sRGB colors, one per covered texel.
|
|
249
|
+
:returns: view -> float array (3,) of linear-light gains.
|
|
250
|
+
"""
|
|
251
|
+
ratios, weights, views = [], [], []
|
|
252
|
+
for view_samples in samples:
|
|
253
|
+
# Only where the view agrees with the source texture: a chrome reflection or a part drawn differently
|
|
254
|
+
# says nothing about how brightly the view was lit.
|
|
255
|
+
head_on = (view_samples.facing >= EXPOSURE_HEAD_ON) & (view_samples.trust >= EXPOSURE_HEAD_ON)
|
|
256
|
+
if head_on.sum() < EXPOSURE_MINIMUM_TEXELS:
|
|
257
|
+
continue
|
|
258
|
+
source_mean = image_utils.srgb_to_linear(source_colors[view_samples.texels[head_on]]).mean(axis=0)
|
|
259
|
+
reference_mean = image_utils.srgb_to_linear(view_samples.colors[head_on]).mean(axis=0)
|
|
260
|
+
ratios.append(np.log((source_mean + 1e-4) / (reference_mean + 1e-4)))
|
|
261
|
+
weights.append(float(head_on.sum()))
|
|
262
|
+
views.append(view_samples.view)
|
|
263
|
+
if len(views) < 2:
|
|
264
|
+
return {}
|
|
265
|
+
log_ratios = np.array(ratios)
|
|
266
|
+
weight_share = np.array(weights) / np.sum(weights)
|
|
267
|
+
log_gains = log_ratios - (weight_share[:, None] * log_ratios).sum(axis=0, keepdims=True)
|
|
268
|
+
gains = np.clip(np.exp(log_gains), 1.0 / EXPOSURE_GAIN_LIMIT, EXPOSURE_GAIN_LIMIT)
|
|
269
|
+
return {view: gains[index].astype(np.float32) for index, view in enumerate(views)}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _apply_gains(samples: list, gains: dict) -> None:
|
|
273
|
+
"""Applies each view's exposure gain to its sampled colors, in linear light."""
|
|
274
|
+
for view_samples in samples:
|
|
275
|
+
if view_samples.view in gains and view_samples.colors.size:
|
|
276
|
+
linear = image_utils.srgb_to_linear(view_samples.colors) * gains[view_samples.view][None, :]
|
|
277
|
+
view_samples.colors = image_utils.linear_to_srgb(linear).astype(np.float32)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def face_clutter(samples: list, surface: TexelSurface, triangles, model_diagonal: float) -> np.ndarray:
|
|
281
|
+
"""
|
|
282
|
+
How cluttered the model is around each face: the share of nearby surface (within CLUTTER_RADIUS_FRACTION
|
|
283
|
+
of the model diagonal) that the views facing it cannot see, because other parts are in the way. An
|
|
284
|
+
engine, a cockpit or a suspension scores high; a wing, a side panel or a nose scores near zero.
|
|
285
|
+
|
|
286
|
+
:returns: float32 (triangles,), 0 = open .. 1 = cluttered.
|
|
287
|
+
"""
|
|
288
|
+
face_texels = np.maximum(np.bincount(surface.triangle_index, minlength=triangles.count), 1).astype(np.float32)
|
|
289
|
+
mean_facing = np.stack([view_samples.face_facing / face_texels for view_samples in samples], axis=1)
|
|
290
|
+
seen_share = np.stack([view_samples.face_visible / np.maximum(view_samples.face_active, 1.0)
|
|
291
|
+
for view_samples in samples], axis=1)
|
|
292
|
+
judged = mean_facing >= CLUTTER_FACING
|
|
293
|
+
best_seen = np.where(judged, seen_share, -1.0).max(axis=1)
|
|
294
|
+
has_judge = judged.any(axis=1)
|
|
295
|
+
hidden = np.where(has_judge, 1.0 - np.clip(best_seen, 0.0, 1.0), 0.0)
|
|
296
|
+
|
|
297
|
+
edge_one = triangles.positions[:, 1] - triangles.positions[:, 0]
|
|
298
|
+
edge_two = triangles.positions[:, 2] - triangles.positions[:, 0]
|
|
299
|
+
weight = 0.5 * np.linalg.norm(np.cross(edge_one, edge_two), axis=1) * has_judge
|
|
300
|
+
cell = max(CLUTTER_RADIUS_FRACTION * model_diagonal, 1e-9)
|
|
301
|
+
voxel = np.floor(triangles.positions.mean(axis=1) / cell).astype(np.int64)
|
|
302
|
+
voxel -= voxel.min(axis=0)
|
|
303
|
+
span = voxel.max(axis=0) + 3
|
|
304
|
+
keys = ((voxel[:, 0] + 1) * span[1] + voxel[:, 1] + 1) * span[2] + voxel[:, 2] + 1
|
|
305
|
+
unique_keys, voxel_index = np.unique(keys, return_inverse=True)
|
|
306
|
+
hidden_sum = np.bincount(voxel_index, weights=hidden * weight)
|
|
307
|
+
weight_sum = np.bincount(voxel_index, weights=weight)
|
|
308
|
+
# Each face reads its own voxel and the 26 around it, so the neighbourhood is a smooth ball, not a grid cell.
|
|
309
|
+
near_hidden = np.zeros(triangles.count)
|
|
310
|
+
near_weight = np.zeros(triangles.count)
|
|
311
|
+
for offset_x in (-1, 0, 1):
|
|
312
|
+
for offset_y in (-1, 0, 1):
|
|
313
|
+
for offset_z in (-1, 0, 1):
|
|
314
|
+
neighbour_keys = keys + (offset_x * span[1] + offset_y) * span[2] + offset_z
|
|
315
|
+
position = np.clip(np.searchsorted(unique_keys, neighbour_keys), 0, unique_keys.size - 1)
|
|
316
|
+
found = unique_keys[position] == neighbour_keys
|
|
317
|
+
near_hidden[found] += hidden_sum[position[found]]
|
|
318
|
+
near_weight[found] += weight_sum[position[found]]
|
|
319
|
+
share = near_hidden / np.maximum(near_weight, 1e-12)
|
|
320
|
+
return np.clip(share / CLUTTER_FULL_SHARE, 0.0, 1.0).astype(np.float32)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def choose_face_sources(samples: list, surface: TexelSurface, triangles, source_colors: np.ndarray,
|
|
324
|
+
clutter: np.ndarray, options) -> np.ndarray:
|
|
325
|
+
"""
|
|
326
|
+
Picks one color source per face. A view scores by how head-on it sees the face and how much of the face
|
|
327
|
+
it can paint; in cluttered parts the score also shrinks as far as the view disagrees with the model's own
|
|
328
|
+
texture there. The model's own texture scores --ref-source-score. Neighbouring faces then vote: a face
|
|
329
|
+
pays --ref-seam-smoothness for every neighbour that chose differently, more where the two choices look
|
|
330
|
+
different there, so whole panels come from one view and seams settle in plain areas rather than through
|
|
331
|
+
logos.
|
|
332
|
+
|
|
333
|
+
:param samples: ViewSamples for every used reference.
|
|
334
|
+
:param surface: Covered texels (per-face texel counts).
|
|
335
|
+
:param triangles: TriangleSet of the final mesh.
|
|
336
|
+
:param source_colors: float32 (count, 3) baked source color per covered texel.
|
|
337
|
+
:param clutter: float32 (triangles,) face_clutter.
|
|
338
|
+
:param options: Parsed options (ref_source_score, ref_seam_smoothness).
|
|
339
|
+
:returns: int array (triangles,) of labels: SOURCE_LABEL, or n + 1 for view n.
|
|
340
|
+
"""
|
|
341
|
+
face_texels = np.bincount(surface.triangle_index, minlength=triangles.count).astype(np.float32)
|
|
342
|
+
scores = np.zeros((triangles.count, len(samples) + 1), dtype=np.float32)
|
|
343
|
+
scores[:, SOURCE_LABEL] = options.ref_source_score
|
|
344
|
+
for index, view_samples in enumerate(samples):
|
|
345
|
+
seen = view_samples.face_seen_facing / np.maximum(face_texels, 1.0)
|
|
346
|
+
trust = view_samples.face_trust / np.maximum(view_samples.face_inside, 1.0)
|
|
347
|
+
scores[:, index + 1] = seen * (1.0 - clutter * (1.0 - trust))
|
|
348
|
+
# Faces too small to hold a texel have no preference of their own; their neighbours decide.
|
|
349
|
+
scores[face_texels == 0, :] = 0.0
|
|
350
|
+
labels = scores.argmax(axis=1)
|
|
351
|
+
pairs = triangle_adjacency(triangles.vertex_index)
|
|
352
|
+
if pairs.size == 0 or options.ref_seam_smoothness <= 0.0:
|
|
353
|
+
return labels
|
|
354
|
+
face_colors = _face_label_colors(samples, surface, triangles.count, source_colors)
|
|
355
|
+
face_index = np.arange(triangles.count)
|
|
356
|
+
for _ in range(LABEL_PASSES):
|
|
357
|
+
penalty = np.zeros_like(scores)
|
|
358
|
+
for face, neighbour in ((pairs[:, 0], pairs[:, 1]), (pairs[:, 1], pairs[:, 0])):
|
|
359
|
+
neighbour_label = labels[neighbour]
|
|
360
|
+
# How different every candidate label looks from the neighbour's choice, on both faces.
|
|
361
|
+
difference = (_color_difference(face_colors[face], face_colors[face, neighbour_label]) +
|
|
362
|
+
_color_difference(face_colors[neighbour], face_colors[neighbour, neighbour_label])) / 2.0
|
|
363
|
+
edge_cost = options.ref_seam_smoothness * (1.0 + SEAM_COLOR_WEIGHT * difference)
|
|
364
|
+
edge_cost[np.arange(face.size), neighbour_label] = 0.0
|
|
365
|
+
np.add.at(penalty, face, edge_cost)
|
|
366
|
+
total = scores - penalty
|
|
367
|
+
updated = total.argmax(axis=1)
|
|
368
|
+
keep = total[face_index, updated] <= total[face_index, labels] + 1e-6
|
|
369
|
+
updated[keep] = labels[keep]
|
|
370
|
+
if np.array_equal(updated, labels):
|
|
371
|
+
break
|
|
372
|
+
labels = updated
|
|
373
|
+
return labels
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _face_label_colors(samples: list, surface: TexelSurface, triangle_count: int,
|
|
377
|
+
source_colors: np.ndarray) -> np.ndarray:
|
|
378
|
+
"""
|
|
379
|
+
Mean color of every face under every choice (the source texture, then each view), NaN where a view
|
|
380
|
+
cannot paint the face.
|
|
381
|
+
|
|
382
|
+
:returns: float32 (triangles, labels, 3).
|
|
383
|
+
"""
|
|
384
|
+
colors = np.full((triangle_count, len(samples) + 1, 3), np.nan, dtype=np.float32)
|
|
385
|
+
texel_count = np.bincount(surface.triangle_index, minlength=triangle_count).astype(np.float64)
|
|
386
|
+
for channel in range(3):
|
|
387
|
+
sums = np.bincount(surface.triangle_index, weights=source_colors[:, channel], minlength=triangle_count)
|
|
388
|
+
colors[:, SOURCE_LABEL, channel] = np.where(texel_count > 0, sums / np.maximum(texel_count, 1.0), np.nan)
|
|
389
|
+
for index, view_samples in enumerate(samples):
|
|
390
|
+
faces = surface.triangle_index[view_samples.texels]
|
|
391
|
+
painted = np.bincount(faces, minlength=triangle_count).astype(np.float64)
|
|
392
|
+
for channel in range(3):
|
|
393
|
+
sums = np.bincount(faces, weights=view_samples.colors[:, channel], minlength=triangle_count)
|
|
394
|
+
colors[:, index + 1, channel] = np.where(painted > 0, sums / np.maximum(painted, 1.0), np.nan)
|
|
395
|
+
return colors
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _color_difference(candidates: np.ndarray, chosen: np.ndarray) -> np.ndarray:
|
|
399
|
+
"""
|
|
400
|
+
Mean absolute sRGB difference between every candidate's color and a chosen color, per face.
|
|
401
|
+
|
|
402
|
+
:param candidates: float32 (faces, labels, 3).
|
|
403
|
+
:param chosen: float32 (faces, 3).
|
|
404
|
+
:returns: float32 (faces, labels); UNAVAILABLE_COLOR_DIFFERENCE where either color is missing.
|
|
405
|
+
"""
|
|
406
|
+
difference = np.abs(candidates - chosen[:, None, :]).mean(axis=2)
|
|
407
|
+
return np.where(np.isnan(difference), UNAVAILABLE_COLOR_DIFFERENCE, difference).astype(np.float32)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def triangle_adjacency(vertex_index: np.ndarray) -> np.ndarray:
|
|
411
|
+
"""
|
|
412
|
+
Pairs of triangles that share an edge.
|
|
413
|
+
|
|
414
|
+
:param vertex_index: int array (triangles, 3) of vertex numbers.
|
|
415
|
+
:returns: int64 array (pairs, 2).
|
|
416
|
+
"""
|
|
417
|
+
edges = np.stack((vertex_index[:, [0, 1]], vertex_index[:, [1, 2]], vertex_index[:, [2, 0]]), axis=1)
|
|
418
|
+
edges = np.sort(edges.reshape(-1, 2), axis=1)
|
|
419
|
+
owner = np.repeat(np.arange(vertex_index.shape[0]), 3)
|
|
420
|
+
keys = edges[:, 0] * (int(vertex_index.max()) + 1) + edges[:, 1]
|
|
421
|
+
order = np.argsort(keys, kind="stable")
|
|
422
|
+
same = keys[order][1:] == keys[order][:-1]
|
|
423
|
+
return np.stack((owner[order][:-1][same], owner[order][1:][same]), axis=1).astype(np.int64)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _vertex_label_weights(triangles, labels: np.ndarray, label_count: int) -> np.ndarray:
|
|
427
|
+
"""
|
|
428
|
+
Share of each label around every vertex (by the area of the faces using it), so texels blend between
|
|
429
|
+
choices only inside the ring of faces where two choices meet.
|
|
430
|
+
|
|
431
|
+
:returns: float32 (vertices, labels), rows summing to 1.
|
|
432
|
+
"""
|
|
433
|
+
edge_one = triangles.positions[:, 1] - triangles.positions[:, 0]
|
|
434
|
+
edge_two = triangles.positions[:, 2] - triangles.positions[:, 0]
|
|
435
|
+
areas = 0.5 * np.linalg.norm(np.cross(edge_one, edge_two), axis=1) + 1e-12
|
|
436
|
+
weights = np.zeros((int(triangles.vertex_index.max()) + 1, label_count), dtype=np.float64)
|
|
437
|
+
for corner in range(3):
|
|
438
|
+
np.add.at(weights, (triangles.vertex_index[:, corner], labels), areas)
|
|
439
|
+
return (weights / np.maximum(weights.sum(axis=1, keepdims=True), 1e-20)).astype(np.float32)
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _label_weight_at(surface: TexelSurface, triangles, vertex_weights: np.ndarray, texels: np.ndarray,
|
|
443
|
+
label: int) -> np.ndarray:
|
|
444
|
+
"""A label's weight at given texels, interpolated from the vertices of their triangles."""
|
|
445
|
+
corners = triangles.vertex_index[surface.triangle_index[texels]]
|
|
446
|
+
return (surface.barycentric[texels] * vertex_weights[corners, label]).sum(axis=1)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _blend_views(samples: list, surface: TexelSurface, triangles, vertex_weights: np.ndarray) -> tuple:
|
|
450
|
+
"""
|
|
451
|
+
Combines the views by their label weights. Where a view's weight falls on a texel it cannot paint, that
|
|
452
|
+
weight goes to the source texture.
|
|
453
|
+
|
|
454
|
+
:returns: (reference color float32 (count, 3), coverage float32 (count,) = share painted by views,
|
|
455
|
+
dominant view index int16 (count,), -1 where no view paints).
|
|
456
|
+
"""
|
|
457
|
+
count = surface.texel_index.size
|
|
458
|
+
color_sum = np.zeros((count, 3), dtype=np.float32)
|
|
459
|
+
weight_sum = np.zeros(count, dtype=np.float32)
|
|
460
|
+
best_weight = np.zeros(count, dtype=np.float32)
|
|
461
|
+
dominant = np.full(count, -1, dtype=np.int16)
|
|
462
|
+
for index, view_samples in enumerate(samples):
|
|
463
|
+
if view_samples.texels.size == 0:
|
|
464
|
+
continue
|
|
465
|
+
weight = _label_weight_at(surface, triangles, vertex_weights, view_samples.texels, index + 1)
|
|
466
|
+
color_sum[view_samples.texels] += view_samples.colors * weight[:, None]
|
|
467
|
+
weight_sum[view_samples.texels] += weight
|
|
468
|
+
wins = weight > best_weight[view_samples.texels]
|
|
469
|
+
best_weight[view_samples.texels[wins]] = weight[wins]
|
|
470
|
+
dominant[view_samples.texels[wins]] = index
|
|
471
|
+
reference_colors = color_sum / np.maximum(weight_sum, 1e-12)[:, None]
|
|
472
|
+
return reference_colors, np.clip(weight_sum, 0.0, 1.0), dominant
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _face_refusals(samples: list, surface: TexelSurface, triangle_count: int, clutter: np.ndarray) -> np.ndarray:
|
|
476
|
+
"""
|
|
477
|
+
Why the view facing each face most directly could not paint it: hidden by other geometry, off its
|
|
478
|
+
subject, or (in a cluttered part) disagreeing with the model's own texture.
|
|
479
|
+
|
|
480
|
+
:returns: int8 (triangles,) refusal codes.
|
|
481
|
+
"""
|
|
482
|
+
face_texels = np.maximum(np.bincount(surface.triangle_index, minlength=triangle_count), 1).astype(np.float32)
|
|
483
|
+
facing = np.stack([view_samples.face_facing / face_texels for view_samples in samples], axis=1)
|
|
484
|
+
best = facing.argmax(axis=1)
|
|
485
|
+
face_index = np.arange(triangle_count)
|
|
486
|
+
|
|
487
|
+
def share(name: str) -> np.ndarray:
|
|
488
|
+
return np.stack([getattr(view_samples, name) for view_samples in samples], axis=1)[face_index, best] / face_texels
|
|
489
|
+
|
|
490
|
+
visible, inside, trust = share("face_visible"), share("face_inside"), share("face_trust")
|
|
491
|
+
mean_trust = trust / np.maximum(inside, 1e-6)
|
|
492
|
+
refusal = np.full(triangle_count, REFUSAL_NONE, dtype=np.int8)
|
|
493
|
+
refusal[visible < MINIMUM_SEEN_SHARE] = REFUSAL_HIDDEN
|
|
494
|
+
refusal[(refusal == REFUSAL_NONE) & (inside < MINIMUM_SEEN_SHARE)] = REFUSAL_OUTSIDE
|
|
495
|
+
refusal[(refusal == REFUSAL_NONE) & (mean_trust < 0.5) & (clutter >= 0.5)] = REFUSAL_INCONSISTENT
|
|
496
|
+
refusal[facing.max(axis=1) < 0.5] = REFUSAL_NONE
|
|
497
|
+
return refusal
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def view_color(view: str, extra_index: int) -> tuple:
|
|
501
|
+
"""Coverage-map color of a view: fixed for the named sides, from a short cycle for any other angle."""
|
|
502
|
+
return VIEW_COLORS.get(view, EXTRA_VIEW_COLORS[extra_index % len(EXTRA_VIEW_COLORS)])
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _view_palette(views: list) -> np.ndarray:
|
|
506
|
+
"""Coverage-map colors for a list of views."""
|
|
507
|
+
extra = [view for view in views if view not in VIEW_COLORS]
|
|
508
|
+
return np.array([view_color(view, extra.index(view) if view in extra else 0) for view in views],
|
|
509
|
+
dtype=np.float32).reshape(-1, 3)
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def _hex(color: tuple) -> str:
|
|
513
|
+
"""#rrggbb for a 0..1 color."""
|
|
514
|
+
return "#" + "".join(f"{int(round(channel * 255)):02x}" for channel in color)
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def coverage_image(surface: TexelSurface, views: list, coverage: np.ndarray, dominant: np.ndarray,
|
|
518
|
+
texel_refusal: np.ndarray, padding: int) -> np.ndarray:
|
|
519
|
+
"""
|
|
520
|
+
Renders where each view painted as a texture for the same UV layout: view colors where references
|
|
521
|
+
painted (brighter = fuller coverage), and for the rest why the best-facing view could not: red = hidden
|
|
522
|
+
by other geometry, pink = off its subject, black = it disagrees with the model's own texture; dark grey
|
|
523
|
+
= no view faces it closely enough, or the model's own texture simply scored higher.
|
|
524
|
+
|
|
525
|
+
:returns: float32 (size, size, 4).
|
|
526
|
+
"""
|
|
527
|
+
colors = np.tile(np.array(UNSEEN_COLOR, dtype=np.float32), (coverage.size, 1))
|
|
528
|
+
painted = (coverage >= 0.5) & (dominant >= 0)
|
|
529
|
+
colors[painted] = _view_palette(views)[dominant[painted]] * (0.45 + 0.55 * coverage[painted])[:, None]
|
|
530
|
+
for code, color in ((REFUSAL_HIDDEN, REFUSED_HIDDEN_COLOR), (REFUSAL_OUTSIDE, REFUSED_OUTSIDE_COLOR),
|
|
531
|
+
(REFUSAL_INCONSISTENT, REFUSED_INCONSISTENT_COLOR)):
|
|
532
|
+
colors[~painted & (texel_refusal == code)] = color
|
|
533
|
+
flat = np.zeros((surface.size * surface.size, 4), dtype=np.float32)
|
|
534
|
+
flat[surface.texel_index, :3] = colors
|
|
535
|
+
flat[:, 3] = 1.0
|
|
536
|
+
return image_utils.dilate_colors(flat.reshape(surface.size, surface.size, 4), surface.covered_mask(), padding)
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def clutter_image(surface: TexelSurface, texel_clutter: np.ndarray, padding: int) -> np.ndarray:
|
|
540
|
+
"""
|
|
541
|
+
Renders face_clutter as a texture for the same UV layout: blue = open surface (references paint it as
|
|
542
|
+
decals), orange = cluttered (references must agree with the model's own texture to paint it).
|
|
543
|
+
|
|
544
|
+
:returns: float32 (size, size, 4).
|
|
545
|
+
"""
|
|
546
|
+
colors = CLUTTER_OPEN_COLOR[None, :] * (1.0 - texel_clutter[:, None]) + \
|
|
547
|
+
CLUTTER_CLUTTERED_COLOR[None, :] * texel_clutter[:, None]
|
|
548
|
+
flat = np.zeros((surface.size * surface.size, 4), dtype=np.float32)
|
|
549
|
+
flat[surface.texel_index, :3] = colors
|
|
550
|
+
flat[:, 3] = 1.0
|
|
551
|
+
return image_utils.dilate_colors(flat.reshape(surface.size, surface.size, 4), surface.covered_mask(), padding)
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def coverage_summary(views: list, coverage: np.ndarray, dominant: np.ndarray, texel_refusal: np.ndarray) -> dict:
|
|
555
|
+
"""Shares of the surface by outcome, and the coverage-map legend, for the report."""
|
|
556
|
+
painted = (coverage >= 0.5) & (dominant >= 0)
|
|
557
|
+
|
|
558
|
+
def share(selection: np.ndarray) -> float:
|
|
559
|
+
return round(float(selection.mean()) * 100.0, 1)
|
|
560
|
+
|
|
561
|
+
legend = {view: _hex(tuple(color)) for view, color in zip(views, _view_palette(views).tolist())}
|
|
562
|
+
legend.update({"kept: hidden by other geometry": _hex(REFUSED_HIDDEN_COLOR),
|
|
563
|
+
"kept: off the subject": _hex(REFUSED_OUTSIDE_COLOR),
|
|
564
|
+
"kept: view disagrees with the model's texture": _hex(REFUSED_INCONSISTENT_COLOR),
|
|
565
|
+
"kept: no view faces it well enough": _hex(UNSEEN_COLOR)})
|
|
566
|
+
return {
|
|
567
|
+
"painted_percent": share(painted),
|
|
568
|
+
"kept_hidden_percent": share(~painted & (texel_refusal == REFUSAL_HIDDEN)),
|
|
569
|
+
"kept_outside_subject_percent": share(~painted & (texel_refusal == REFUSAL_OUTSIDE)),
|
|
570
|
+
"kept_inconsistent_percent": share(~painted & (texel_refusal == REFUSAL_INCONSISTENT)),
|
|
571
|
+
"kept_unseen_percent": share(~painted & (texel_refusal == REFUSAL_NONE)),
|
|
572
|
+
"legend": legend,
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def match_source_colors(source_colors: np.ndarray, reference_colors: np.ndarray, coverage: np.ndarray) -> tuple:
|
|
577
|
+
"""
|
|
578
|
+
Adjusts the baked source texture's brightness and contrast per channel so it matches the references
|
|
579
|
+
where both exist; the hand-over between reference-painted and source-only areas then does not show.
|
|
580
|
+
|
|
581
|
+
:param source_colors: float32 (count, 3) baked source colors.
|
|
582
|
+
:param reference_colors: float32 (count, 3) reference colors.
|
|
583
|
+
:param coverage: float32 (count,) 0..1 reference coverage.
|
|
584
|
+
:returns: (adjusted source colors, dict of per-channel gain and bias for the report).
|
|
585
|
+
"""
|
|
586
|
+
strong = coverage >= STRONG_COVERAGE
|
|
587
|
+
if strong.sum() < COLOR_MATCH_MINIMUM_TEXELS:
|
|
588
|
+
return source_colors, {"applied": False, "reason": "too little reference coverage to compare"}
|
|
589
|
+
source_mean = source_colors[strong].mean(axis=0)
|
|
590
|
+
source_spread = source_colors[strong].std(axis=0)
|
|
591
|
+
reference_mean = reference_colors[strong].mean(axis=0)
|
|
592
|
+
reference_spread = reference_colors[strong].std(axis=0)
|
|
593
|
+
gain = np.clip(reference_spread / np.maximum(source_spread, 1e-4), *COLOR_MATCH_GAIN_LIMITS)
|
|
594
|
+
bias = reference_mean - source_mean * gain
|
|
595
|
+
adjusted = np.clip(source_colors * gain + bias, 0.0, 1.0)
|
|
596
|
+
return adjusted, {"applied": True, "gain": np.round(gain, 3).tolist(), "bias": np.round(bias, 3).tolist()}
|