@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,605 @@
|
|
|
1
|
+
"""
|
|
2
|
+
New UV layouts for bt-unwrap.
|
|
3
|
+
|
|
4
|
+
The default 'views' method lays every face out flat as seen from the camera direction it faces most:
|
|
5
|
+
front, rear, left, right, top or bottom (optionally diagonals too). Faces that share a direction form large
|
|
6
|
+
islands, seams fall where the facing direction changes, and every island is an undistorted orthographic
|
|
7
|
+
picture of its surface — text stays upright and is never mirrored, and reference images taken from the same
|
|
8
|
+
directions line up with it directly.
|
|
9
|
+
|
|
10
|
+
The model must already face Blender -Y with +Z up (the pipeline orients it first): front = -Y, rear = +Y,
|
|
11
|
+
left = +X, right = -X, top = +Z, bottom = -Z.
|
|
12
|
+
"""
|
|
13
|
+
import math
|
|
14
|
+
from contextlib import contextmanager
|
|
15
|
+
|
|
16
|
+
import bpy
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
import mesh_tools
|
|
20
|
+
import rasterizer
|
|
21
|
+
|
|
22
|
+
NEW_UV_LAYER = "UVMap_bt"
|
|
23
|
+
FINAL_UV_LAYER = "UVMap"
|
|
24
|
+
|
|
25
|
+
# Outward direction of every named view in the oriented model frame.
|
|
26
|
+
VIEW_DIRECTIONS = {
|
|
27
|
+
"front": (0.0, -1.0, 0.0),
|
|
28
|
+
"rear": (0.0, 1.0, 0.0),
|
|
29
|
+
"left": (1.0, 0.0, 0.0),
|
|
30
|
+
"right": (-1.0, 0.0, 0.0),
|
|
31
|
+
"top": (0.0, 0.0, 1.0),
|
|
32
|
+
"bottom": (0.0, 0.0, -1.0),
|
|
33
|
+
}
|
|
34
|
+
HORIZONTAL_DIAGONALS = {
|
|
35
|
+
"front_left": (1.0, -1.0, 0.0),
|
|
36
|
+
"front_right": (-1.0, -1.0, 0.0),
|
|
37
|
+
"rear_left": (1.0, 1.0, 0.0),
|
|
38
|
+
"rear_right": (-1.0, 1.0, 0.0),
|
|
39
|
+
}
|
|
40
|
+
CORNER_DIAGONALS = {
|
|
41
|
+
"top_front_left": (1.0, -1.0, 1.0), "top_front_right": (-1.0, -1.0, 1.0),
|
|
42
|
+
"top_rear_left": (1.0, 1.0, 1.0), "top_rear_right": (-1.0, 1.0, 1.0),
|
|
43
|
+
"bottom_front_left": (1.0, -1.0, -1.0), "bottom_front_right": (-1.0, -1.0, -1.0),
|
|
44
|
+
"bottom_rear_left": (1.0, 1.0, -1.0), "bottom_rear_right": (-1.0, 1.0, -1.0),
|
|
45
|
+
}
|
|
46
|
+
FORWARD = np.array((0.0, -1.0, 0.0))
|
|
47
|
+
UP = np.array((0.0, 0.0, 1.0))
|
|
48
|
+
|
|
49
|
+
# A neighbour's vote counts this much less than the face's own label, so labels settle instead of flickering.
|
|
50
|
+
SELF_VOTE_WEIGHT = 1.5
|
|
51
|
+
SMALL_ISLAND_PASSES = 16
|
|
52
|
+
# Tiny islands may join any neighbouring view the face does not point away from (about 87 degrees): on
|
|
53
|
+
# small parts a little stretch costs far less than a scatter of fragments.
|
|
54
|
+
SMALL_ISLAND_MINIMUM_FACING = 0.05
|
|
55
|
+
OVERLAP_CHECK_RESOLUTION = 1024
|
|
56
|
+
SELF_OVERLAP_RESOLUTION = 256 # smallest fold-check raster per island, within its own bounds
|
|
57
|
+
MAXIMUM_FOLD_CHECK_RESOLUTION = 1024
|
|
58
|
+
FOLD_CHECK_TEXTURE_SIZE = 2400 # an island covering the whole surface is checked at about this size
|
|
59
|
+
MINIMUM_FOLD_TRIANGLES = 3 # one or two triangles cannot fold over themselves in a meaningful way
|
|
60
|
+
FOLD_GRAZING_FACING = (0.4, 0.6, 0.6) # per pass: folded faces facing their view less than this are moved
|
|
61
|
+
FOLD_SPLIT_PASSES = len(FOLD_GRAZING_FACING)
|
|
62
|
+
PACK_ROTATION = {"none": (False, "ANY"), "cardinal": (True, "CARDINAL"), "any": (True, "ANY")}
|
|
63
|
+
# Texel density by visibility: every face is tested from the 26 directions around a cube (sides, edges and
|
|
64
|
+
# corners). Islands seen from none of them (inside the body, under covers) shrink to --hidden-density.
|
|
65
|
+
VISIBILITY_RASTER_SIZE = 640 # depth raster per direction for dense meshes...
|
|
66
|
+
VISIBILITY_RASTER_PER_TRIANGLE_ROOT = 4 # ...smaller for low-poly ones, whose big faces need no fine raster
|
|
67
|
+
VISIBILITY_MINIMUM_RASTER = 96
|
|
68
|
+
VISIBILITY_FACING = 0.1 # a face must turn at least this much toward a direction to be seen from it
|
|
69
|
+
VISIBILITY_DEPTH_TOLERANCE = 0.004 # of the model diagonal
|
|
70
|
+
VISIBILITY_FULL_DIRECTIONS = 2 # seen from this many directions counts as fully visible
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def projection_directions(projection_count: int) -> dict:
|
|
74
|
+
"""
|
|
75
|
+
Chooses the set of view directions faces are sorted into.
|
|
76
|
+
|
|
77
|
+
:param projection_count: 6 (box), 10 (box + horizontal diagonals) or 14 (box + corners).
|
|
78
|
+
:returns: Ordered dict of view name -> unit direction (numpy 3-vector).
|
|
79
|
+
"""
|
|
80
|
+
directions = dict(VIEW_DIRECTIONS)
|
|
81
|
+
if projection_count == 10:
|
|
82
|
+
directions.update(HORIZONTAL_DIAGONALS)
|
|
83
|
+
elif projection_count == 14:
|
|
84
|
+
directions.update(CORNER_DIAGONALS)
|
|
85
|
+
return {name: np.array(vector) / np.linalg.norm(vector) for name, vector in directions.items()}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def view_axes(direction: np.ndarray) -> tuple:
|
|
89
|
+
"""
|
|
90
|
+
Image axes of an orthographic camera that sits on the given side of the model and looks back at it.
|
|
91
|
+
Side views keep +Z up; the top and bottom views put the model's front at the top of the image.
|
|
92
|
+
|
|
93
|
+
:param direction: Unit vector from the model toward the camera.
|
|
94
|
+
:returns: (right, up) unit vectors in world space.
|
|
95
|
+
"""
|
|
96
|
+
view_direction = -direction
|
|
97
|
+
up_hint = UP if abs(direction[2]) < 0.9 else FORWARD
|
|
98
|
+
right = np.cross(view_direction, up_hint)
|
|
99
|
+
right /= np.linalg.norm(right)
|
|
100
|
+
up = np.cross(right, view_direction)
|
|
101
|
+
return right, up / np.linalg.norm(up)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@contextmanager
|
|
105
|
+
def edit_mode(objects: list):
|
|
106
|
+
"""
|
|
107
|
+
Puts the given mesh objects into edit mode together and returns them to object mode afterwards.
|
|
108
|
+
|
|
109
|
+
:param objects: Mesh objects to edit.
|
|
110
|
+
"""
|
|
111
|
+
bpy.ops.object.select_all(action="DESELECT")
|
|
112
|
+
for obj in objects:
|
|
113
|
+
obj.select_set(True)
|
|
114
|
+
bpy.context.view_layer.objects.active = objects[0]
|
|
115
|
+
bpy.ops.object.mode_set(mode="EDIT")
|
|
116
|
+
try:
|
|
117
|
+
yield
|
|
118
|
+
finally:
|
|
119
|
+
bpy.ops.object.mode_set(mode="OBJECT")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def ensure_new_uv_layer(obj: bpy.types.Object) -> bpy.types.MeshUVLoopLayer:
|
|
123
|
+
"""
|
|
124
|
+
Adds (or reuses) the working UV layer and makes it the active and render layer.
|
|
125
|
+
|
|
126
|
+
:param obj: A mesh object.
|
|
127
|
+
:returns: The working UV layer.
|
|
128
|
+
"""
|
|
129
|
+
layers = obj.data.uv_layers
|
|
130
|
+
layer = layers.get(NEW_UV_LAYER) or layers.new(name=NEW_UV_LAYER)
|
|
131
|
+
layers.active = layer
|
|
132
|
+
layer.active_render = True
|
|
133
|
+
return layer
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def unwrap_by_views(objects: list, options) -> dict:
|
|
137
|
+
"""
|
|
138
|
+
Lays every face out from the view direction it faces most, then repairs overlaps and packs.
|
|
139
|
+
|
|
140
|
+
:param objects: Mesh objects of the oriented model.
|
|
141
|
+
:param options: Parsed command-line options (projections, label_smoothing, min_island_faces,
|
|
142
|
+
max_facing_angle, view_density, padding, texture_size, pack_rotate, fix_overlaps).
|
|
143
|
+
:returns: Statistics: island count per view, faces per view, overlap repairs and packing efficiency.
|
|
144
|
+
"""
|
|
145
|
+
directions = projection_directions(options.projections)
|
|
146
|
+
names = list(directions)
|
|
147
|
+
direction_matrix = np.stack([directions[name] for name in names])
|
|
148
|
+
axes = [view_axes(directions[name]) for name in names]
|
|
149
|
+
density = np.array([options.view_density.get(name, 1.0) for name in names])
|
|
150
|
+
minimum_facing = math.cos(math.radians(options.max_facing_angle))
|
|
151
|
+
|
|
152
|
+
meshes = mesh_tools.mesh_objects(objects)
|
|
153
|
+
labels_per_object = []
|
|
154
|
+
for obj in meshes:
|
|
155
|
+
labels = _label_faces(obj, direction_matrix, minimum_facing, options)
|
|
156
|
+
_write_projected_uvs(obj, labels, axes)
|
|
157
|
+
labels_per_object.append(labels)
|
|
158
|
+
|
|
159
|
+
fold_repair = {"passes": 0, "faces_moved": 0}
|
|
160
|
+
if options.fix_overlaps:
|
|
161
|
+
fold_repair = _split_folds(meshes, labels_per_object, direction_matrix, axes)
|
|
162
|
+
faces_per_view = sum(np.bincount(labels, minlength=len(names)) for labels in labels_per_object)
|
|
163
|
+
_average_island_scale(meshes)
|
|
164
|
+
if np.any(density != 1.0):
|
|
165
|
+
for obj, labels in zip(meshes, labels_per_object):
|
|
166
|
+
_scale_islands_by_view(obj, labels, density)
|
|
167
|
+
visibility = scale_islands_by_visibility(meshes, options.hidden_density)
|
|
168
|
+
_pack(meshes, options)
|
|
169
|
+
statistics = layout_statistics(objects)
|
|
170
|
+
statistics.update({
|
|
171
|
+
"method": "views",
|
|
172
|
+
"projections": names,
|
|
173
|
+
"faces_per_view": {name: int(count) for name, count in zip(names, faces_per_view)},
|
|
174
|
+
"fold_repair": fold_repair,
|
|
175
|
+
"visibility": visibility,
|
|
176
|
+
})
|
|
177
|
+
return statistics
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _label_faces(obj, direction_matrix, minimum_facing, options) -> np.ndarray:
|
|
181
|
+
"""Sorts one object's faces into view directions, smooths the result and absorbs tiny islands; marks
|
|
182
|
+
seams where the view changes. Returns the view index per polygon."""
|
|
183
|
+
mesh = obj.data
|
|
184
|
+
polygon_count = len(mesh.polygons)
|
|
185
|
+
normals = np.empty(polygon_count * 3, dtype=np.float64)
|
|
186
|
+
mesh.polygons.foreach_get("normal", normals)
|
|
187
|
+
normal_matrix = np.array(obj.matrix_world.to_3x3().inverted_safe().transposed(), dtype=np.float64)
|
|
188
|
+
normals = normals.reshape(-1, 3) @ normal_matrix.T
|
|
189
|
+
normals /= np.maximum(np.linalg.norm(normals, axis=1, keepdims=True), 1e-20)
|
|
190
|
+
areas = np.empty(polygon_count, dtype=np.float64)
|
|
191
|
+
mesh.polygons.foreach_get("area", areas)
|
|
192
|
+
|
|
193
|
+
facing = normals @ direction_matrix.T
|
|
194
|
+
labels = facing.argmax(axis=1)
|
|
195
|
+
allowed = facing >= minimum_facing
|
|
196
|
+
allowed[np.arange(polygon_count), labels] = True
|
|
197
|
+
allowed_for_small = facing >= SMALL_ISLAND_MINIMUM_FACING
|
|
198
|
+
allowed_for_small[np.arange(polygon_count), labels] = True
|
|
199
|
+
pairs, edge_index = mesh_tools.polygon_adjacency_with_edges(mesh)
|
|
200
|
+
|
|
201
|
+
for _ in range(options.label_smoothing):
|
|
202
|
+
votes = np.zeros_like(facing)
|
|
203
|
+
np.add.at(votes, (np.arange(polygon_count), labels), areas * SELF_VOTE_WEIGHT)
|
|
204
|
+
np.add.at(votes, (pairs[:, 0], labels[pairs[:, 1]]), areas[pairs[:, 1]])
|
|
205
|
+
np.add.at(votes, (pairs[:, 1], labels[pairs[:, 0]]), areas[pairs[:, 0]])
|
|
206
|
+
votes[~allowed] = -1.0
|
|
207
|
+
labels = votes.argmax(axis=1)
|
|
208
|
+
|
|
209
|
+
for _ in range(SMALL_ISLAND_PASSES):
|
|
210
|
+
components = _same_label_components(polygon_count, pairs, labels)
|
|
211
|
+
_, inverse, sizes = np.unique(components, return_inverse=True, return_counts=True)
|
|
212
|
+
island_size = sizes[inverse]
|
|
213
|
+
is_small = island_size < options.min_island_faces
|
|
214
|
+
if not is_small.any():
|
|
215
|
+
break
|
|
216
|
+
# A small island is absorbed by its neighbours, the bigger the neighbouring island the stronger its
|
|
217
|
+
# pull; only strictly bigger islands may absorb, so two small islands never trade faces back and forth.
|
|
218
|
+
votes = np.zeros_like(facing)
|
|
219
|
+
for receiver, giver in ((pairs[:, 0], pairs[:, 1]), (pairs[:, 1], pairs[:, 0])):
|
|
220
|
+
absorbs = is_small[receiver] & (island_size[giver] > island_size[receiver])
|
|
221
|
+
np.add.at(votes, (receiver[absorbs], labels[giver[absorbs]]),
|
|
222
|
+
areas[giver[absorbs]] * island_size[giver[absorbs]])
|
|
223
|
+
votes[~allowed_for_small] = 0.0
|
|
224
|
+
has_vote = votes.max(axis=1) > 0
|
|
225
|
+
if not has_vote.any():
|
|
226
|
+
break
|
|
227
|
+
labels[has_vote] = votes[has_vote].argmax(axis=1)
|
|
228
|
+
|
|
229
|
+
_mark_seams(mesh, pairs, edge_index, labels)
|
|
230
|
+
return labels
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _same_label_components(polygon_count, pairs, labels) -> np.ndarray:
|
|
234
|
+
"""Connected groups of faces that share a view label — the future UV islands."""
|
|
235
|
+
same = labels[pairs[:, 0]] == labels[pairs[:, 1]]
|
|
236
|
+
return mesh_tools.connected_components(polygon_count, pairs[same])
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _mark_seams(mesh, pairs, edge_index, labels) -> None:
|
|
240
|
+
"""Marks a UV seam on every edge where the view label changes, and clears all other seams."""
|
|
241
|
+
seams = np.zeros(len(mesh.edges), dtype=bool)
|
|
242
|
+
seams[edge_index[labels[pairs[:, 0]] != labels[pairs[:, 1]]]] = True
|
|
243
|
+
mesh.edges.foreach_set("use_seam", seams)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _write_projected_uvs(obj, labels, axes) -> None:
|
|
247
|
+
"""Writes each corner's UV as its world position seen along its face's view (meters, before packing)."""
|
|
248
|
+
mesh = obj.data
|
|
249
|
+
layer = ensure_new_uv_layer(obj)
|
|
250
|
+
loop_vertex = np.empty(len(mesh.loops), dtype=np.int64)
|
|
251
|
+
mesh.loops.foreach_get("vertex_index", loop_vertex)
|
|
252
|
+
loop_totals = np.empty(len(mesh.polygons), dtype=np.int64)
|
|
253
|
+
mesh.polygons.foreach_get("loop_total", loop_totals)
|
|
254
|
+
loop_label = np.repeat(labels, loop_totals)
|
|
255
|
+
|
|
256
|
+
coordinates = np.empty(len(mesh.vertices) * 3, dtype=np.float64)
|
|
257
|
+
mesh.vertices.foreach_get("co", coordinates)
|
|
258
|
+
world_matrix = np.array(obj.matrix_world, dtype=np.float64)
|
|
259
|
+
world = coordinates.reshape(-1, 3) @ world_matrix[:3, :3].T + world_matrix[:3, 3]
|
|
260
|
+
loop_position = world[loop_vertex]
|
|
261
|
+
|
|
262
|
+
right_axes = np.stack([axis[0] for axis in axes])
|
|
263
|
+
up_axes = np.stack([axis[1] for axis in axes])
|
|
264
|
+
corner_uvs = np.stack((
|
|
265
|
+
(loop_position * right_axes[loop_label]).sum(axis=1),
|
|
266
|
+
(loop_position * up_axes[loop_label]).sum(axis=1),
|
|
267
|
+
), axis=1).astype(np.float32)
|
|
268
|
+
layer.data.foreach_set("uv", corner_uvs.ravel())
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _scale_islands_by_view(obj, labels, density) -> None:
|
|
272
|
+
"""
|
|
273
|
+
Enlarges (or shrinks) the islands of chosen views so they get more (or less) of the texture, e.g. the
|
|
274
|
+
side panels that carry a livery. Every island holds one view, so scaling about the origin keeps islands
|
|
275
|
+
whole; packing moves them into place afterwards.
|
|
276
|
+
"""
|
|
277
|
+
mesh = obj.data
|
|
278
|
+
layer = mesh.uv_layers[NEW_UV_LAYER]
|
|
279
|
+
loop_totals = np.empty(len(mesh.polygons), dtype=np.int64)
|
|
280
|
+
mesh.polygons.foreach_get("loop_total", loop_totals)
|
|
281
|
+
corner_uvs = np.empty(len(mesh.loops) * 2, dtype=np.float32)
|
|
282
|
+
layer.data.foreach_get("uv", corner_uvs)
|
|
283
|
+
corner_uvs = corner_uvs.reshape(-1, 2) * density[np.repeat(labels, loop_totals)][:, None].astype(np.float32)
|
|
284
|
+
layer.data.foreach_set("uv", corner_uvs.ravel())
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _folded_triangles(triangles, triangle_island) -> np.ndarray:
|
|
288
|
+
"""
|
|
289
|
+
Finds triangles that take part in a fold: places where an island's own triangles cover the same UV area
|
|
290
|
+
twice. Each island is checked in its own bounding box, so small islands are checked as finely as large
|
|
291
|
+
ones.
|
|
292
|
+
|
|
293
|
+
:param triangles: TriangleSet with the working UV layer.
|
|
294
|
+
:param triangle_island: Island id per triangle.
|
|
295
|
+
:returns: Boolean mask over triangles.
|
|
296
|
+
"""
|
|
297
|
+
uvs = triangles.uvs[NEW_UV_LAYER].astype(np.float64)
|
|
298
|
+
edges_one = triangles.positions[:, 1] - triangles.positions[:, 0]
|
|
299
|
+
edges_two = triangles.positions[:, 2] - triangles.positions[:, 0]
|
|
300
|
+
surface_area = 0.5 * np.linalg.norm(np.cross(edges_one, edges_two), axis=1)
|
|
301
|
+
total_area = max(float(surface_area.sum()), 1e-12)
|
|
302
|
+
folded = np.zeros(triangles.count, dtype=bool)
|
|
303
|
+
order = np.argsort(triangle_island, kind="stable")
|
|
304
|
+
_, starts = np.unique(triangle_island[order], return_index=True)
|
|
305
|
+
ends = np.r_[starts[1:], order.size]
|
|
306
|
+
for start, end in zip(starts, ends):
|
|
307
|
+
if end - start < MINIMUM_FOLD_TRIANGLES:
|
|
308
|
+
continue
|
|
309
|
+
members = order[start:end]
|
|
310
|
+
island_uvs = uvs[members]
|
|
311
|
+
flat = island_uvs.reshape(-1, 2)
|
|
312
|
+
minimum = flat.min(axis=0)
|
|
313
|
+
extent = max(float((flat.max(axis=0) - minimum).max()), 1e-12)
|
|
314
|
+
# Check each island about as finely as it will appear in the final texture.
|
|
315
|
+
share = float(surface_area[members].sum()) / total_area
|
|
316
|
+
resolution = int(np.clip(FOLD_CHECK_TEXTURE_SIZE * np.sqrt(share), SELF_OVERLAP_RESOLUTION,
|
|
317
|
+
MAXIMUM_FOLD_CHECK_RESOLUTION))
|
|
318
|
+
pixels = (island_uvs - minimum) / extent * resolution
|
|
319
|
+
count, _ = rasterizer.rasterize_coverage_count(pixels, resolution, resolution)
|
|
320
|
+
doubled = count > 1
|
|
321
|
+
if not doubled.any():
|
|
322
|
+
continue
|
|
323
|
+
for fragments in rasterizer.rasterize(pixels, resolution, resolution, edge_tolerance=-1e-3):
|
|
324
|
+
involved = np.unique(fragments.triangle_index[doubled[fragments.pixel_index]])
|
|
325
|
+
folded[members[involved]] = True
|
|
326
|
+
return folded
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _split_folds(meshes, labels_per_object, direction_matrix, axes) -> dict:
|
|
330
|
+
"""
|
|
331
|
+
Removes folds by moving the folded faces that face their island's view only at a grazing angle (the part
|
|
332
|
+
of the surface that doubles back) to their next-best view, where they form their own small island
|
|
333
|
+
projected without a fold. Repeats a few passes, since a move can expose a smaller fold.
|
|
334
|
+
|
|
335
|
+
:returns: {"passes": passes run, "faces_moved": faces given another view}.
|
|
336
|
+
"""
|
|
337
|
+
moved_total = 0
|
|
338
|
+
passes = 0
|
|
339
|
+
for passes in range(1, FOLD_SPLIT_PASSES + 1):
|
|
340
|
+
triangles = mesh_tools.collect_triangles(meshes, (NEW_UV_LAYER,))
|
|
341
|
+
island_per_object = [_same_label_components(len(obj.data.polygons), mesh_tools.polygon_adjacency(obj.data), labels)
|
|
342
|
+
for obj, labels in zip(meshes, labels_per_object)]
|
|
343
|
+
offsets = np.cumsum([0] + [len(obj.data.polygons) for obj in meshes])[:-1]
|
|
344
|
+
polygon_island = np.concatenate([islands + offset for islands, offset in zip(island_per_object, offsets)])
|
|
345
|
+
triangle_polygon = offsets[triangles.object_index] + triangles.polygon_index
|
|
346
|
+
folded = _folded_triangles(triangles, polygon_island[triangle_polygon])
|
|
347
|
+
if not folded.any():
|
|
348
|
+
break
|
|
349
|
+
moved_this_pass = 0
|
|
350
|
+
for object_number, (obj, labels) in enumerate(zip(meshes, labels_per_object)):
|
|
351
|
+
folded_polygons = np.unique(triangles.polygon_index[folded & (triangles.object_index == object_number)])
|
|
352
|
+
if folded_polygons.size == 0:
|
|
353
|
+
continue
|
|
354
|
+
facing = _polygon_facing(obj, direction_matrix)
|
|
355
|
+
own_facing = facing[folded_polygons, labels[folded_polygons]]
|
|
356
|
+
# Only the part that doubles back moves; the head-on part keeps its island intact. Later passes
|
|
357
|
+
# accept less grazing faces for folds the first pass could not resolve.
|
|
358
|
+
to_move = folded_polygons[own_facing < FOLD_GRAZING_FACING[passes - 1]]
|
|
359
|
+
if to_move.size == 0:
|
|
360
|
+
continue
|
|
361
|
+
alternatives = facing[to_move].copy()
|
|
362
|
+
alternatives[np.arange(to_move.size), labels[to_move]] = -np.inf
|
|
363
|
+
best = alternatives.argmax(axis=1)
|
|
364
|
+
movable = alternatives[np.arange(to_move.size), best] >= SMALL_ISLAND_MINIMUM_FACING
|
|
365
|
+
labels[to_move[movable]] = best[movable]
|
|
366
|
+
moved_this_pass += int(movable.sum())
|
|
367
|
+
pairs, edge_index = mesh_tools.polygon_adjacency_with_edges(obj.data)
|
|
368
|
+
_mark_seams(obj.data, pairs, edge_index, labels)
|
|
369
|
+
_write_projected_uvs(obj, labels, axes)
|
|
370
|
+
moved_total += moved_this_pass
|
|
371
|
+
if moved_this_pass == 0:
|
|
372
|
+
break
|
|
373
|
+
return {"passes": passes, "faces_moved": moved_total}
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _polygon_facing(obj, direction_matrix) -> np.ndarray:
|
|
377
|
+
"""How directly every polygon faces every view: (polygon_count, view_count) dot products."""
|
|
378
|
+
normals = np.empty(len(obj.data.polygons) * 3, dtype=np.float64)
|
|
379
|
+
obj.data.polygons.foreach_get("normal", normals)
|
|
380
|
+
normal_matrix = np.array(obj.matrix_world.to_3x3().inverted_safe().transposed(), dtype=np.float64)
|
|
381
|
+
normals = normals.reshape(-1, 3) @ normal_matrix.T
|
|
382
|
+
normals /= np.maximum(np.linalg.norm(normals, axis=1, keepdims=True), 1e-20)
|
|
383
|
+
return normals @ direction_matrix.T
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def scale_islands_by_visibility(meshes: list, hidden_density: float) -> dict:
|
|
387
|
+
"""
|
|
388
|
+
Gives surfaces nobody can see less of the texture: each face is tested from the 26 directions around
|
|
389
|
+
the model, and every UV island is scaled by how visible its faces are, from 1 (seen from at least
|
|
390
|
+
VISIBILITY_FULL_DIRECTIONS directions) down to `hidden_density` (seen from none). Packing then hands the
|
|
391
|
+
freed space to the visible islands, so they get more texels for the same texture size.
|
|
392
|
+
|
|
393
|
+
:param meshes: Mesh objects with the working UV layer, islands already at equal texel density.
|
|
394
|
+
:param hidden_density: Texel density of fully hidden surface relative to visible surface (1 = off).
|
|
395
|
+
:returns: Statistics: hidden_surface_percent and the hidden_density used.
|
|
396
|
+
"""
|
|
397
|
+
if hidden_density >= 1.0:
|
|
398
|
+
return {"hidden_density": 1.0}
|
|
399
|
+
triangles = mesh_tools.collect_triangles(meshes)
|
|
400
|
+
seen_from = _directions_seeing_each_triangle(triangles)
|
|
401
|
+
edge_one = triangles.positions[:, 1] - triangles.positions[:, 0]
|
|
402
|
+
edge_two = triangles.positions[:, 2] - triangles.positions[:, 0]
|
|
403
|
+
areas = 0.5 * np.linalg.norm(np.cross(edge_one, edge_two), axis=1)
|
|
404
|
+
visible_share = np.clip(seen_from / VISIBILITY_FULL_DIRECTIONS, 0.0, 1.0)
|
|
405
|
+
for object_number, obj in enumerate(meshes):
|
|
406
|
+
mine = triangles.object_index == object_number
|
|
407
|
+
if not mine.any():
|
|
408
|
+
continue
|
|
409
|
+
polygon_count = len(obj.data.polygons)
|
|
410
|
+
polygon_area = np.bincount(triangles.polygon_index[mine], weights=areas[mine], minlength=polygon_count)
|
|
411
|
+
polygon_visible = np.bincount(triangles.polygon_index[mine], weights=areas[mine] * visible_share[mine],
|
|
412
|
+
minlength=polygon_count)
|
|
413
|
+
islands = uv_islands(obj)
|
|
414
|
+
island_area = np.bincount(islands, weights=polygon_area)
|
|
415
|
+
island_visible = np.bincount(islands, weights=polygon_visible) / np.maximum(island_area, 1e-20)
|
|
416
|
+
island_scale = hidden_density + (1.0 - hidden_density) * island_visible
|
|
417
|
+
_scale_polygon_uvs(obj, island_scale[islands])
|
|
418
|
+
hidden = float((areas * (seen_from == 0)).sum() / max(areas.sum(), 1e-20))
|
|
419
|
+
return {"hidden_density": hidden_density, "hidden_surface_percent": round(hidden * 100.0, 1)}
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _directions_seeing_each_triangle(triangles) -> np.ndarray:
|
|
423
|
+
"""Counts, per triangle, how many of the 26 cube directions see its center unobstructed."""
|
|
424
|
+
directions = [np.array((x, y, z), dtype=np.float64) for x in (-1, 0, 1) for y in (-1, 0, 1) for z in (-1, 0, 1)
|
|
425
|
+
if (x, y, z) != (0, 0, 0)]
|
|
426
|
+
centers = triangles.positions.mean(axis=1)
|
|
427
|
+
face_normals = triangles.face_normals.astype(np.float64)
|
|
428
|
+
flat = triangles.positions.reshape(-1, 3)
|
|
429
|
+
diagonal = float(np.linalg.norm(flat.max(axis=0) - flat.min(axis=0)))
|
|
430
|
+
tolerance = VISIBILITY_DEPTH_TOLERANCE * diagonal
|
|
431
|
+
raster_size = int(np.clip(VISIBILITY_RASTER_PER_TRIANGLE_ROOT * np.sqrt(triangles.count), VISIBILITY_MINIMUM_RASTER,
|
|
432
|
+
VISIBILITY_RASTER_SIZE))
|
|
433
|
+
seen_from = np.zeros(triangles.count, dtype=np.int32)
|
|
434
|
+
for direction in directions:
|
|
435
|
+
direction /= np.linalg.norm(direction)
|
|
436
|
+
right, up = view_axes(direction)
|
|
437
|
+
plane = np.stack((flat @ right, flat @ up), axis=1)
|
|
438
|
+
minimum = plane.min(axis=0)
|
|
439
|
+
scale = (raster_size - 2) / max(float((plane.max(axis=0) - minimum).max()), 1e-12)
|
|
440
|
+
pixel_points = ((plane - minimum) * scale + 1.0).reshape(-1, 3, 2)
|
|
441
|
+
depth = rasterizer.rasterize_depth(pixel_points, triangles.positions @ direction, raster_size, raster_size)
|
|
442
|
+
center_pixels = (np.stack((centers @ right, centers @ up), axis=1) - minimum) * scale + 1.0
|
|
443
|
+
nearest = depth[np.clip(center_pixels[:, 1].astype(np.int64), 0, raster_size - 1),
|
|
444
|
+
np.clip(center_pixels[:, 0].astype(np.int64), 0, raster_size - 1)]
|
|
445
|
+
facing = face_normals @ direction >= VISIBILITY_FACING
|
|
446
|
+
seen_from += (facing & (centers @ direction >= nearest - tolerance)).astype(np.int32)
|
|
447
|
+
return seen_from
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def uv_islands(obj) -> np.ndarray:
|
|
451
|
+
"""
|
|
452
|
+
Island number of every polygon in the working UV layer: faces joined by edges whose two sides have
|
|
453
|
+
identical UVs.
|
|
454
|
+
|
|
455
|
+
:param obj: A mesh object with the working UV layer.
|
|
456
|
+
:returns: int64 array (polygon_count,) of island numbers 0..n-1.
|
|
457
|
+
"""
|
|
458
|
+
mesh = obj.data
|
|
459
|
+
corner_uvs = np.empty(len(mesh.loops) * 2, dtype=np.float32)
|
|
460
|
+
mesh.uv_layers[NEW_UV_LAYER].data.foreach_get("uv", corner_uvs)
|
|
461
|
+
corner_uvs = corner_uvs.reshape(-1, 2)
|
|
462
|
+
loop_vertex = np.empty(len(mesh.loops), dtype=np.int64)
|
|
463
|
+
mesh.loops.foreach_get("vertex_index", loop_vertex)
|
|
464
|
+
loop_totals = np.empty(len(mesh.polygons), dtype=np.int64)
|
|
465
|
+
mesh.polygons.foreach_get("loop_total", loop_totals)
|
|
466
|
+
polygon_of_loop = np.repeat(np.arange(len(mesh.polygons)), loop_totals)
|
|
467
|
+
# Two faces are UV-connected when they share a vertex at exactly the same UV coordinate.
|
|
468
|
+
quantized = np.round(corner_uvs * 1e6).astype(np.int64)
|
|
469
|
+
keys = np.stack((loop_vertex, quantized[:, 0], quantized[:, 1]), axis=1)
|
|
470
|
+
_, key_id = np.unique(keys, axis=0, return_inverse=True)
|
|
471
|
+
key_id = key_id.ravel()
|
|
472
|
+
order = np.argsort(key_id, kind="stable")
|
|
473
|
+
same = key_id[order][1:] == key_id[order][:-1]
|
|
474
|
+
pairs = np.stack((polygon_of_loop[order][:-1][same], polygon_of_loop[order][1:][same]), axis=1)
|
|
475
|
+
components = mesh_tools.connected_components(len(mesh.polygons), pairs)
|
|
476
|
+
return np.unique(components, return_inverse=True)[1].ravel()
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def _scale_polygon_uvs(obj, polygon_scale: np.ndarray) -> None:
|
|
480
|
+
"""Scales every polygon's UVs about the origin by its factor (whole islands share one factor)."""
|
|
481
|
+
mesh = obj.data
|
|
482
|
+
layer = mesh.uv_layers[NEW_UV_LAYER]
|
|
483
|
+
loop_totals = np.empty(len(mesh.polygons), dtype=np.int64)
|
|
484
|
+
mesh.polygons.foreach_get("loop_total", loop_totals)
|
|
485
|
+
corner_uvs = np.empty(len(mesh.loops) * 2, dtype=np.float32)
|
|
486
|
+
layer.data.foreach_get("uv", corner_uvs)
|
|
487
|
+
corner_uvs = corner_uvs.reshape(-1, 2) * np.repeat(polygon_scale, loop_totals)[:, None].astype(np.float32)
|
|
488
|
+
layer.data.foreach_set("uv", corner_uvs.ravel())
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def _average_island_scale(meshes) -> None:
|
|
492
|
+
"""Scales every island so texels per meter are the same everywhere (undoes projection foreshortening)."""
|
|
493
|
+
with edit_mode(meshes):
|
|
494
|
+
bpy.ops.mesh.select_all(action="SELECT")
|
|
495
|
+
bpy.ops.uv.select_all(action="SELECT")
|
|
496
|
+
bpy.ops.uv.average_islands_scale()
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _pack(meshes, options) -> None:
|
|
500
|
+
"""Packs every island into the 0..1 texture square with the padding gap between them."""
|
|
501
|
+
rotate, rotate_method = PACK_ROTATION[options.pack_rotate]
|
|
502
|
+
margin = options.padding / float(options.texture_size)
|
|
503
|
+
# Concave outlines pack tightest, but Blender's concave search slows down by an order of magnitude when
|
|
504
|
+
# several objects are packed together (minutes for a dozen islands); convex outlines pack those as well.
|
|
505
|
+
shape_method = "CONCAVE" if len(meshes) == 1 else "CONVEX"
|
|
506
|
+
with edit_mode(meshes):
|
|
507
|
+
bpy.ops.mesh.select_all(action="SELECT")
|
|
508
|
+
bpy.ops.uv.select_all(action="SELECT")
|
|
509
|
+
bpy.ops.uv.pack_islands(rotate=rotate, rotate_method=rotate_method, scale=True,
|
|
510
|
+
margin_method="FRACTION", margin=margin, shape_method=shape_method,
|
|
511
|
+
merge_overlap=False)
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def unwrap_smart(objects: list, options) -> dict:
|
|
515
|
+
"""
|
|
516
|
+
Unwraps with Blender's Smart UV Project, then packs. Better than 'views' for organic shapes
|
|
517
|
+
(characters, creatures, rocks) that have no meaningful front / side / top.
|
|
518
|
+
|
|
519
|
+
:param objects: Mesh objects.
|
|
520
|
+
:param options: Parsed options (smart_angle, padding, texture_size, pack_rotate).
|
|
521
|
+
:returns: Layout statistics.
|
|
522
|
+
"""
|
|
523
|
+
meshes = mesh_tools.mesh_objects(objects)
|
|
524
|
+
for obj in meshes:
|
|
525
|
+
ensure_new_uv_layer(obj)
|
|
526
|
+
with edit_mode(meshes):
|
|
527
|
+
bpy.ops.mesh.select_all(action="SELECT")
|
|
528
|
+
bpy.ops.uv.smart_project(angle_limit=math.radians(options.smart_angle), island_margin=0.0,
|
|
529
|
+
area_weight=0.0, correct_aspect=True, scale_to_bounds=False)
|
|
530
|
+
_average_island_scale(meshes)
|
|
531
|
+
visibility = scale_islands_by_visibility(meshes, options.hidden_density)
|
|
532
|
+
_pack(meshes, options)
|
|
533
|
+
statistics = layout_statistics(objects)
|
|
534
|
+
statistics["method"] = "smart"
|
|
535
|
+
statistics["visibility"] = visibility
|
|
536
|
+
return statistics
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def keep_existing_layout(objects: list) -> dict:
|
|
540
|
+
"""
|
|
541
|
+
Copies the current render UV layer into the working layer so later steps treat it like a new layout.
|
|
542
|
+
|
|
543
|
+
:param objects: Mesh objects.
|
|
544
|
+
:returns: Layout statistics.
|
|
545
|
+
:raises RuntimeError: when a mesh has no UV layer to keep.
|
|
546
|
+
"""
|
|
547
|
+
for obj in mesh_tools.mesh_objects(objects):
|
|
548
|
+
layers = obj.data.uv_layers
|
|
549
|
+
source = next((layer for layer in layers if layer.active_render), None) or layers.active
|
|
550
|
+
if source is None:
|
|
551
|
+
raise RuntimeError(f"'{obj.name}' has no UV layer; --unwrap keep needs one (use views or smart)")
|
|
552
|
+
corner_uvs = np.empty(len(obj.data.loops) * 2, dtype=np.float32)
|
|
553
|
+
source.data.foreach_get("uv", corner_uvs)
|
|
554
|
+
ensure_new_uv_layer(obj).data.foreach_set("uv", corner_uvs)
|
|
555
|
+
statistics = layout_statistics(objects)
|
|
556
|
+
statistics["method"] = "keep"
|
|
557
|
+
return statistics
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def layout_statistics(objects: list) -> dict:
|
|
561
|
+
"""
|
|
562
|
+
Measures the working layout: island count and how much of the texture square islands cover.
|
|
563
|
+
|
|
564
|
+
:param objects: Mesh objects with the working UV layer.
|
|
565
|
+
:returns: {islands, uv_coverage_percent, overlap_percent}.
|
|
566
|
+
"""
|
|
567
|
+
meshes = mesh_tools.mesh_objects(objects)
|
|
568
|
+
triangles = mesh_tools.collect_triangles(meshes, (NEW_UV_LAYER,))
|
|
569
|
+
pixels = triangles.uvs[NEW_UV_LAYER].astype(np.float64) * OVERLAP_CHECK_RESOLUTION
|
|
570
|
+
count, _ = rasterizer.rasterize_coverage_count(pixels, OVERLAP_CHECK_RESOLUTION, OVERLAP_CHECK_RESOLUTION)
|
|
571
|
+
covered = rasterizer.rasterize_mask(pixels, OVERLAP_CHECK_RESOLUTION, OVERLAP_CHECK_RESOLUTION).ravel()
|
|
572
|
+
island_total = 0
|
|
573
|
+
for obj in meshes:
|
|
574
|
+
island_total += _uv_island_count(obj)
|
|
575
|
+
return {
|
|
576
|
+
"islands": island_total,
|
|
577
|
+
"uv_coverage_percent": round(100.0 * covered.mean(), 1),
|
|
578
|
+
"overlap_percent": round(100.0 * (count > 1).sum() / max(covered.sum(), 1), 2),
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def _uv_island_count(obj) -> int:
|
|
583
|
+
"""Counts the UV islands of the working layer."""
|
|
584
|
+
mesh = obj.data
|
|
585
|
+
if mesh.uv_layers.get(NEW_UV_LAYER) is None or len(mesh.polygons) == 0:
|
|
586
|
+
return 0
|
|
587
|
+
return int(uv_islands(obj).max()) + 1
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def finalize_uv_layers(objects: list) -> None:
|
|
591
|
+
"""
|
|
592
|
+
Removes every UV layer except the new one and renames it to the standard name, so exporters write a
|
|
593
|
+
single TEXCOORD_0.
|
|
594
|
+
|
|
595
|
+
:param objects: Mesh objects.
|
|
596
|
+
"""
|
|
597
|
+
for obj in mesh_tools.mesh_objects(objects):
|
|
598
|
+
layers = obj.data.uv_layers
|
|
599
|
+
for layer in [layer for layer in layers if layer.name != NEW_UV_LAYER]:
|
|
600
|
+
layers.remove(layer)
|
|
601
|
+
new_layer = layers.get(NEW_UV_LAYER)
|
|
602
|
+
if new_layer is not None:
|
|
603
|
+
new_layer.name = FINAL_UV_LAYER
|
|
604
|
+
layers.active = new_layer
|
|
605
|
+
new_layer.active_render = True
|