maillage 0.1.0b2__py3-none-any.whl
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.
- maillage/__init__.py +24 -0
- maillage/__main__.py +3 -0
- maillage/animate.py +29 -0
- maillage/blender/__init__.py +6 -0
- maillage/blender/drop_test.py +611 -0
- maillage/cli.py +230 -0
- maillage/fabrics.py +148 -0
- maillage/formats.py +99 -0
- maillage/generator.py +292 -0
- maillage/mesh.py +192 -0
- maillage/outline.py +204 -0
- maillage/presets.py +232 -0
- maillage/render.py +89 -0
- maillage/texture.py +163 -0
- maillage/usd_export.py +151 -0
- maillage-0.1.0b2.dist-info/METADATA +496 -0
- maillage-0.1.0b2.dist-info/RECORD +21 -0
- maillage-0.1.0b2.dist-info/WHEEL +5 -0
- maillage-0.1.0b2.dist-info/entry_points.txt +2 -0
- maillage-0.1.0b2.dist-info/licenses/LICENSE +21 -0
- maillage-0.1.0b2.dist-info/top_level.txt +1 -0
maillage/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Maillage: realistic textile assets generator for Physical AI, exporting to OpenUSD."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("maillage")
|
|
7
|
+
except PackageNotFoundError: # running from a source tree without installation
|
|
8
|
+
__version__ = "0.0.0+unknown"
|
|
9
|
+
|
|
10
|
+
from .fabrics import FABRICS # noqa: E402
|
|
11
|
+
from .generator import Piece, Scene, Variations, generate_scene, write_outputs # noqa: E402
|
|
12
|
+
from .presets import CATEGORIES, PRESETS # noqa: E402
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"CATEGORIES",
|
|
16
|
+
"FABRICS",
|
|
17
|
+
"PRESETS",
|
|
18
|
+
"Piece",
|
|
19
|
+
"Scene",
|
|
20
|
+
"Variations",
|
|
21
|
+
"__version__",
|
|
22
|
+
"generate_scene",
|
|
23
|
+
"write_outputs",
|
|
24
|
+
]
|
maillage/__main__.py
ADDED
maillage/animate.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Animated GIF from the frames rendered by the drape test (needs Pillow,
|
|
2
|
+
installed with matplotlib: pip install "maillage[render]")."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def make_gif(
|
|
10
|
+
frames_dir: str | Path, output: str | Path, fps: float = 12.0, width: int = 640, hold: float = 1.5
|
|
11
|
+
):
|
|
12
|
+
"""Assemble frames_dir/frame_*.png into a looping GIF; the last frame is held
|
|
13
|
+
`hold` seconds so the final drape can be seen."""
|
|
14
|
+
from PIL import Image
|
|
15
|
+
|
|
16
|
+
files = sorted(Path(frames_dir).glob("frame_*.png"))
|
|
17
|
+
if not files:
|
|
18
|
+
raise FileNotFoundError(f"no frame_*.png in {frames_dir}")
|
|
19
|
+
frames = []
|
|
20
|
+
for f in files:
|
|
21
|
+
im = Image.open(f).convert("RGB")
|
|
22
|
+
if im.width > width:
|
|
23
|
+
im = im.resize((width, round(im.height * width / im.width)), Image.LANCZOS)
|
|
24
|
+
frames.append(im.quantize(colors=200, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE))
|
|
25
|
+
durations = [round(1000 / fps)] * len(frames)
|
|
26
|
+
durations[-1] = round(1000 * hold)
|
|
27
|
+
output = Path(output)
|
|
28
|
+
frames[0].save(output, save_all=True, append_images=frames[1:], duration=durations, loop=0, optimize=True)
|
|
29
|
+
return output
|
|
@@ -0,0 +1,611 @@
|
|
|
1
|
+
"""Blender drop test for Maillage pieces.
|
|
2
|
+
|
|
3
|
+
Runs inside Blender (it does not import maillage, so Blender's own Python
|
|
4
|
+
needs nothing installed):
|
|
5
|
+
|
|
6
|
+
blender -b -P drop_test.py -- output/tea_towel [--pieces 4] [--frames 120] [--render]
|
|
7
|
+
|
|
8
|
+
or, when the `bpy` module is installed (pip install "maillage[blender]"):
|
|
9
|
+
|
|
10
|
+
maillage drop-test output/tea_towel --render
|
|
11
|
+
|
|
12
|
+
For each of the first pieces of a generated scene, it:
|
|
13
|
+
|
|
14
|
+
1. imports the OpenUSD scene with Blender's USD importer (geometry, UVs,
|
|
15
|
+
textured material, `hem` and `pin` primvars);
|
|
16
|
+
2. reads the `maillage:*` attributes (mass, thickness, friction, Blender cloth
|
|
17
|
+
stiffness) with the OpenUSD Python bindings shipped with Blender;
|
|
18
|
+
3. sets up Blender's cloth solver: stiffness from the fabric, rescaled to
|
|
19
|
+
the mesh resolution and the piece's real mass, stiffer bending on the hem, pinned vertices,
|
|
20
|
+
collisions and self-collisions;
|
|
21
|
+
4. lays the piece flat on a round pedestal, its centre clamped as in a
|
|
22
|
+
Cusick drape tester, and lets the rest fall (or hangs a piece by its
|
|
23
|
+
pinned vertices), then simulates it;
|
|
24
|
+
5. checks the result: no invalid coordinates, limited stretch of the edges,
|
|
25
|
+
no penetration of the pedestal or the floor, at rest at the end (draped
|
|
26
|
+
pieces); it also measures how much the piece drapes (Cusick drape
|
|
27
|
+
coefficient);
|
|
28
|
+
6. writes drop_test.json, the draped meshes as draped.usdc (with the
|
|
29
|
+
maillage:* attributes copied back) and, with --render, a Cycles image.
|
|
30
|
+
|
|
31
|
+
Exit code 0 when every piece passes, 1 otherwise.
|
|
32
|
+
|
|
33
|
+
The cloth parameters are starting values, not calibrated: passing this test
|
|
34
|
+
means the asset imports and simulates sanely in Blender, not that it drapes
|
|
35
|
+
like the real fabric.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
from __future__ import annotations
|
|
39
|
+
|
|
40
|
+
import argparse
|
|
41
|
+
import json
|
|
42
|
+
import math
|
|
43
|
+
import random
|
|
44
|
+
import sys
|
|
45
|
+
from pathlib import Path
|
|
46
|
+
|
|
47
|
+
import bpy
|
|
48
|
+
import numpy as np
|
|
49
|
+
from mathutils import Euler, Matrix, Vector
|
|
50
|
+
from pxr import Usd, UsdGeom
|
|
51
|
+
|
|
52
|
+
PEDESTAL_HEIGHT = 0.75
|
|
53
|
+
BLENDER_VERTEX_MASS = 0.3 # kg, Blender's default cloth vertex mass
|
|
54
|
+
PEDESTAL_FRACTION = 0.6 # pedestal diameter / shorter side of the piece (Cusick tester: 18 / 30 cm)
|
|
55
|
+
STRETCH_P99_MAX = 1.10 # 99 % of the edges stretched by less than 10 %
|
|
56
|
+
STRETCH_MAX = 1.6
|
|
57
|
+
PENETRATION_MAX = 0.005 # fraction of vertices allowed inside an obstacle
|
|
58
|
+
REST_SPEED_MAX = 0.1 # m/s, fastest vertex over the last frame
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# ----------------------------------------------------------------- inputs
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def find_usd(path: Path) -> Path:
|
|
65
|
+
if path.is_dir():
|
|
66
|
+
found = sorted(path.glob("maillage_*.usd*"))
|
|
67
|
+
if not found:
|
|
68
|
+
raise SystemExit(f"no maillage_*.usd* file in {path}")
|
|
69
|
+
return found[0]
|
|
70
|
+
return path
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def read_pieces(usd_path: Path) -> dict:
|
|
74
|
+
"""maillage:* attributes of every cloth mesh, by prim name."""
|
|
75
|
+
stage = Usd.Stage.Open(str(usd_path))
|
|
76
|
+
out = {}
|
|
77
|
+
cloths = stage.GetPrimAtPath("/World/Cloths")
|
|
78
|
+
for prim in cloths.GetChildren() if cloths else []:
|
|
79
|
+
if not prim.IsA(UsdGeom.Mesh):
|
|
80
|
+
continue
|
|
81
|
+
attrs = {}
|
|
82
|
+
for a in prim.GetAttributes():
|
|
83
|
+
name = a.GetName()
|
|
84
|
+
if name.startswith("maillage:"):
|
|
85
|
+
v = a.Get()
|
|
86
|
+
attrs[name[len("maillage:") :]] = (
|
|
87
|
+
tuple(v) if hasattr(v, "__len__") and not isinstance(v, str) else v
|
|
88
|
+
)
|
|
89
|
+
out[prim.GetName()] = attrs
|
|
90
|
+
return out
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# -------------------------------------------------------------- the scene
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _material(name, rgb, roughness=0.6):
|
|
97
|
+
m = bpy.data.materials.new(name)
|
|
98
|
+
if m.node_tree is None: # Blender < 5: node trees are opt-in
|
|
99
|
+
m.use_nodes = True
|
|
100
|
+
bsdf = m.node_tree.nodes.get("Principled BSDF")
|
|
101
|
+
bsdf.inputs["Base Color"].default_value = (*rgb, 1.0)
|
|
102
|
+
bsdf.inputs["Roughness"].default_value = roughness
|
|
103
|
+
return m
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _pedestal(name, xy, radius, material):
|
|
107
|
+
bpy.ops.mesh.primitive_cylinder_add(
|
|
108
|
+
vertices=96, radius=radius, depth=PEDESTAL_HEIGHT, location=(xy[0], xy[1], PEDESTAL_HEIGHT / 2)
|
|
109
|
+
)
|
|
110
|
+
o = bpy.context.object
|
|
111
|
+
o.name = name
|
|
112
|
+
o.data.materials.append(material)
|
|
113
|
+
bpy.ops.object.shade_smooth()
|
|
114
|
+
return o
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _collider(o, friction):
|
|
118
|
+
o.modifiers.new("Collision", "COLLISION")
|
|
119
|
+
o.collision.thickness_outer = 0.002
|
|
120
|
+
o.collision.cloth_friction = friction
|
|
121
|
+
o.collision.damping = 0.1
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _vertex_group(o, attr_name):
|
|
125
|
+
a = o.data.attributes.get(attr_name)
|
|
126
|
+
if a is None:
|
|
127
|
+
return None
|
|
128
|
+
w = np.zeros(len(o.data.vertices), np.float32)
|
|
129
|
+
a.data.foreach_get("value", w)
|
|
130
|
+
idx = np.nonzero(w > 0)[0]
|
|
131
|
+
if len(idx) == 0:
|
|
132
|
+
return None
|
|
133
|
+
g = o.vertex_groups.new(name=attr_name)
|
|
134
|
+
for i in idx:
|
|
135
|
+
g.add([int(i)], float(w[i]), "REPLACE")
|
|
136
|
+
return g.name
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def pedestal_radius(props):
|
|
140
|
+
L, W = props.get("size", (1.0, 1.0))
|
|
141
|
+
return PEDESTAL_FRACTION * min(L, W) / 2
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _clamp_group(o, radius):
|
|
145
|
+
co = rest_points(o)
|
|
146
|
+
idx = np.nonzero(np.linalg.norm(co[:, :2], axis=1) < 0.98 * radius)[0]
|
|
147
|
+
g = o.vertex_groups.new(name="clamp")
|
|
148
|
+
g.add([int(i) for i in idx], 1.0, "REPLACE")
|
|
149
|
+
return g.name
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def setup_cloth(o, props, frames, self_collision, quality=10):
|
|
153
|
+
nverts = len(o.data.vertices)
|
|
154
|
+
mod = o.modifiers.new("Cloth", "CLOTH")
|
|
155
|
+
s, c = mod.settings, mod.collision_settings
|
|
156
|
+
s.quality = quality
|
|
157
|
+
# Stiffness is given for 1 cm edges and the real vertex mass, rescaled to
|
|
158
|
+
# this mesh so the behaviour does not depend on the resolution (see
|
|
159
|
+
# fabrics.py). The solver then runs with Blender's usual 0.3 kg vertex mass
|
|
160
|
+
# and every stiffness and damping multiplied by the same factor: the
|
|
161
|
+
# accelerations, hence the motion, are unchanged, and Blender's solver
|
|
162
|
+
# tolerances (tuned for that mass range) stay effective; with the real,
|
|
163
|
+
# much smaller mass, stiff fabrics vibrate instead of coming to rest.
|
|
164
|
+
real_mass = float(props.get("mass", 0.1)) / nverts
|
|
165
|
+
lam = BLENDER_VERTEX_MASS / real_mass
|
|
166
|
+
o["maillage_mass_scale"] = lam # external forces (wind) must be scaled too
|
|
167
|
+
e = edges(o)
|
|
168
|
+
rest = rest_points(o)
|
|
169
|
+
h = float(np.mean(np.linalg.norm(rest[e[:, 0]] - rest[e[:, 1]], axis=1)))
|
|
170
|
+
r = h / float(props.get("blender:referenceEdge", 0.01))
|
|
171
|
+
s.mass = BLENDER_VERTEX_MASS
|
|
172
|
+
s.tension_stiffness = lam * r * props["blender:tensionStiffness"]
|
|
173
|
+
s.compression_stiffness = lam * r * props["blender:compressionStiffness"]
|
|
174
|
+
s.shear_stiffness = lam * r * props["blender:shearStiffness"]
|
|
175
|
+
s.bending_stiffness = lam * props["blender:bendingStiffness"]
|
|
176
|
+
s.air_damping = lam * r * r * props["blender:airDamping"]
|
|
177
|
+
|
|
178
|
+
# spring damping: same damping ratio c / sqrt(k m) as Blender's defaults
|
|
179
|
+
# (vertex mass 0.3; tension 15 / 5, shear 5 / 5, bending 0.5 / 0.5)
|
|
180
|
+
def damping(k, k0, c0):
|
|
181
|
+
return c0 * math.sqrt(k / k0)
|
|
182
|
+
|
|
183
|
+
s.tension_damping = damping(s.tension_stiffness, 15.0, 5.0)
|
|
184
|
+
s.compression_damping = damping(s.compression_stiffness, 15.0, 5.0)
|
|
185
|
+
s.shear_damping = damping(s.shear_stiffness, 5.0, 5.0)
|
|
186
|
+
s.bending_damping = damping(s.bending_stiffness, 0.5, 0.5)
|
|
187
|
+
s.bending_model = "ANGULAR"
|
|
188
|
+
hem = _vertex_group(o, "hem")
|
|
189
|
+
if hem:
|
|
190
|
+
s.vertex_group_bending = hem
|
|
191
|
+
s.bending_stiffness_max = s.bending_stiffness * props.get("hemBendingFactor", 3.0)
|
|
192
|
+
pin = _vertex_group(o, "pin")
|
|
193
|
+
pinned = bool(pin)
|
|
194
|
+
if not pinned:
|
|
195
|
+
# drape test: the centre is clamped on the pedestal, as between the two
|
|
196
|
+
# discs of a Cusick drape tester
|
|
197
|
+
pin = _clamp_group(o, pedestal_radius(props))
|
|
198
|
+
s.vertex_group_mass = pin
|
|
199
|
+
s.pin_stiffness = 50.0 # maximum: a firm clamp / hoist
|
|
200
|
+
thickness = float(props.get("thickness", 0.5e-3))
|
|
201
|
+
c.collision_quality = 3
|
|
202
|
+
c.distance_min = max(0.004, thickness)
|
|
203
|
+
c.use_self_collision = self_collision
|
|
204
|
+
c.self_distance_min = max(0.003, 0.75 * thickness)
|
|
205
|
+
c.self_friction = 5.0
|
|
206
|
+
mod.point_cache.frame_start = 1
|
|
207
|
+
mod.point_cache.frame_end = frames
|
|
208
|
+
return mod, pinned
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def place(o, props, origin, rng, pinned, clearance):
|
|
212
|
+
"""Flat on the pedestal (drape test), or hanging for pinned pieces."""
|
|
213
|
+
L, W = props.get("size", (1.0, 1.0))
|
|
214
|
+
if pinned:
|
|
215
|
+
# vertical, hoist (x = -L/2) at the pole, top edge at 2.4 m
|
|
216
|
+
rot = Euler((math.pi / 2, 0.0, 0.0))
|
|
217
|
+
loc = Vector((origin[0] + L / 2, origin[1], 2.4 - W / 2))
|
|
218
|
+
else:
|
|
219
|
+
# flat on the pedestal, clamped at the centre; random turn about z
|
|
220
|
+
rot = Euler((0.0, 0.0, math.radians(rng.uniform(-45, 45))))
|
|
221
|
+
loc = Vector((origin[0], origin[1], PEDESTAL_HEIGHT + clearance))
|
|
222
|
+
o.parent = None
|
|
223
|
+
o.matrix_world = Matrix.Translation(loc) @ rot.to_matrix().to_4x4()
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
# ------------------------------------------------------------ measurement
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def world_points(o, depsgraph):
|
|
230
|
+
ev = o.evaluated_get(depsgraph)
|
|
231
|
+
me = ev.data
|
|
232
|
+
co = np.empty(len(me.vertices) * 3, np.float64)
|
|
233
|
+
me.vertices.foreach_get("co", co)
|
|
234
|
+
co = co.reshape(-1, 3)
|
|
235
|
+
m = np.array(ev.matrix_world)
|
|
236
|
+
return co @ m[:3, :3].T + m[:3, 3]
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def rest_points(o):
|
|
240
|
+
co = np.empty(len(o.data.vertices) * 3, np.float64)
|
|
241
|
+
o.data.vertices.foreach_get("co", co)
|
|
242
|
+
return co.reshape(-1, 3)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def edges(o):
|
|
246
|
+
e = np.empty(len(o.data.edges) * 2, np.int64)
|
|
247
|
+
o.data.edges.foreach_get("vertices", e)
|
|
248
|
+
return e.reshape(-1, 2)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def hull_area(xy):
|
|
252
|
+
"""Area of the convex hull of 2-D points (monotone chain)."""
|
|
253
|
+
pts = np.unique(np.round(xy, 9), axis=0)
|
|
254
|
+
if len(pts) < 3:
|
|
255
|
+
return 0.0
|
|
256
|
+
pts = pts[np.lexsort((pts[:, 1], pts[:, 0]))]
|
|
257
|
+
|
|
258
|
+
def cross(o, a, b):
|
|
259
|
+
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
|
|
260
|
+
|
|
261
|
+
def half(ps):
|
|
262
|
+
h = []
|
|
263
|
+
for p in ps:
|
|
264
|
+
while len(h) >= 2 and cross(h[-2], h[-1], p) <= 0:
|
|
265
|
+
h.pop()
|
|
266
|
+
h.append(p)
|
|
267
|
+
return h
|
|
268
|
+
|
|
269
|
+
hull = np.array(half(pts)[:-1] + half(pts[::-1])[:-1])
|
|
270
|
+
x, y = hull[:, 0], hull[:, 1]
|
|
271
|
+
return 0.5 * abs(float(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1))))
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def flat_area(o):
|
|
275
|
+
p = rest_points(o)[:, :2]
|
|
276
|
+
area = 0.0
|
|
277
|
+
for poly in o.data.polygons:
|
|
278
|
+
q = p[list(poly.vertices)]
|
|
279
|
+
area += 0.5 * (np.dot(q[:, 0], np.roll(q[:, 1], -1)) - np.dot(q[:, 1], np.roll(q[:, 0], -1)))
|
|
280
|
+
return abs(area)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
# ------------------------------------------------------------- outputs
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def copy_attributes(src_usd: Path, dst_usd: Path, names):
|
|
287
|
+
"""Copy the maillage:* attributes onto the meshes of the draped export."""
|
|
288
|
+
src = Usd.Stage.Open(str(src_usd))
|
|
289
|
+
dst = Usd.Stage.Open(str(dst_usd))
|
|
290
|
+
for prim in dst.Traverse():
|
|
291
|
+
if not prim.IsA(UsdGeom.Mesh) or prim.GetName() not in names:
|
|
292
|
+
continue
|
|
293
|
+
sp = src.GetPrimAtPath(f"/World/Cloths/{prim.GetName()}")
|
|
294
|
+
if not sp:
|
|
295
|
+
continue
|
|
296
|
+
for a in sp.GetAttributes():
|
|
297
|
+
if a.GetName().startswith("maillage:"):
|
|
298
|
+
prim.CreateAttribute(a.GetName(), a.GetTypeName(), custom=True).Set(a.Get())
|
|
299
|
+
dst.GetRootLayer().Save()
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def setup_render(objects, out_png: Path, samples: int):
|
|
303
|
+
sc = bpy.context.scene
|
|
304
|
+
pts = np.vstack([np.array([o.matrix_world @ Vector(c) for c in o.bound_box]) for o in objects])
|
|
305
|
+
lo, hi = pts.min(axis=0), pts.max(axis=0)
|
|
306
|
+
radius = float(np.linalg.norm(hi - lo)) / 2
|
|
307
|
+
# framed on the cloths, a little below their start: they fall and drape
|
|
308
|
+
center = Vector(((lo + hi) / 2).tolist()) - Vector((0.0, 0.0, 0.12 * radius))
|
|
309
|
+
cam_data = bpy.data.cameras.new("Camera")
|
|
310
|
+
cam_data.lens = 40
|
|
311
|
+
cam = bpy.data.objects.new("Camera", cam_data)
|
|
312
|
+
sc.collection.objects.link(cam)
|
|
313
|
+
cam.location = center + Vector((0.35 * radius, -2.2 * radius, 1.2 * radius))
|
|
314
|
+
cam.rotation_euler = (center - cam.location).to_track_quat("-Z", "Y").to_euler()
|
|
315
|
+
sc.camera = cam
|
|
316
|
+
sun = bpy.data.objects.new("Sun", bpy.data.lights.new("Sun", "SUN"))
|
|
317
|
+
sun.data.energy = 3.5
|
|
318
|
+
sun.data.angle = math.radians(8)
|
|
319
|
+
sun.rotation_euler = Euler((math.radians(40), math.radians(15), math.radians(30)))
|
|
320
|
+
sc.collection.objects.link(sun)
|
|
321
|
+
world = bpy.data.worlds.new("World")
|
|
322
|
+
if world.node_tree is None: # Blender < 5
|
|
323
|
+
world.use_nodes = True
|
|
324
|
+
bg = world.node_tree.nodes.get("Background")
|
|
325
|
+
bg.inputs["Color"].default_value = (0.75, 0.78, 0.82, 1.0)
|
|
326
|
+
bg.inputs["Strength"].default_value = 0.6
|
|
327
|
+
sc.world = world
|
|
328
|
+
sc.render.engine = "CYCLES"
|
|
329
|
+
sc.cycles.device = "CPU"
|
|
330
|
+
sc.cycles.samples = samples
|
|
331
|
+
try:
|
|
332
|
+
sc.cycles.use_denoising = True
|
|
333
|
+
sc.cycles.denoiser = "OPENIMAGEDENOISE"
|
|
334
|
+
except (AttributeError, TypeError):
|
|
335
|
+
sc.cycles.use_denoising = False
|
|
336
|
+
sc.render.resolution_x, sc.render.resolution_y = 1600, 900
|
|
337
|
+
sc.render.filepath = str(out_png)
|
|
338
|
+
sc.render.image_settings.file_format = "PNG"
|
|
339
|
+
sc.view_settings.view_transform = "AgX"
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
# ------------------------------------------------------------------ main
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def run(
|
|
346
|
+
target,
|
|
347
|
+
out_dir=None,
|
|
348
|
+
pieces=4,
|
|
349
|
+
frames=120,
|
|
350
|
+
seed=1,
|
|
351
|
+
render=False,
|
|
352
|
+
samples=32,
|
|
353
|
+
wind=0.0,
|
|
354
|
+
self_collision=True,
|
|
355
|
+
quality=10,
|
|
356
|
+
animate=0,
|
|
357
|
+
) -> dict:
|
|
358
|
+
usd_path = find_usd(Path(target))
|
|
359
|
+
out = Path(out_dir) if out_dir else usd_path.parent / "drop_test"
|
|
360
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
361
|
+
rng = random.Random(seed)
|
|
362
|
+
props = read_pieces(usd_path)
|
|
363
|
+
|
|
364
|
+
bpy.ops.wm.read_factory_settings(use_empty=True)
|
|
365
|
+
bpy.ops.wm.usd_import(filepath=str(usd_path), read_mesh_attributes=True)
|
|
366
|
+
sc = bpy.context.scene
|
|
367
|
+
sc.frame_start, sc.frame_end = 1, frames
|
|
368
|
+
sc.render.fps = 24
|
|
369
|
+
|
|
370
|
+
names = [n for n in props if n in bpy.data.objects][:pieces]
|
|
371
|
+
for o in list(bpy.data.objects): # keep only the tested pieces
|
|
372
|
+
if o.name not in names:
|
|
373
|
+
bpy.data.objects.remove(o, do_unlink=True)
|
|
374
|
+
|
|
375
|
+
wood = _material("Pedestal", (0.42, 0.30, 0.20), 0.5)
|
|
376
|
+
floor = _material("Floor", (0.30, 0.30, 0.30), 0.8)
|
|
377
|
+
steel = _material("Pole", (0.6, 0.6, 0.62), 0.3)
|
|
378
|
+
spacing = 1.7 * max(max(props[n].get("size", (1, 1))) for n in names)
|
|
379
|
+
objs, pedestals, pinned_any = [], {}, False
|
|
380
|
+
for i, name in enumerate(names):
|
|
381
|
+
o = bpy.data.objects[name]
|
|
382
|
+
p = props[name]
|
|
383
|
+
L, W = p.get("size", (1.0, 1.0))
|
|
384
|
+
origin = (i * spacing, 0.0)
|
|
385
|
+
mod, pinned = setup_cloth(o, p, frames, self_collision, quality)
|
|
386
|
+
mu = float(p.get("friction", 0.5))
|
|
387
|
+
if pinned:
|
|
388
|
+
pinned_any = True
|
|
389
|
+
bpy.ops.mesh.primitive_cylinder_add(radius=0.015, depth=2.6, location=(origin[0], 0.0, 1.3))
|
|
390
|
+
bpy.context.object.data.materials.append(steel)
|
|
391
|
+
bpy.context.object.name = f"{name}_pole"
|
|
392
|
+
mod.settings.effector_weights.wind = 1.0
|
|
393
|
+
else:
|
|
394
|
+
t = _pedestal(f"{name}_pedestal", origin, pedestal_radius(p), wood)
|
|
395
|
+
_collider(t, 10.0 * mu)
|
|
396
|
+
pedestals[name] = t
|
|
397
|
+
mod.settings.effector_weights.wind = 0.0
|
|
398
|
+
place(o, p, origin, rng, pinned, mod.collision_settings.distance_min + 0.001)
|
|
399
|
+
objs.append(o)
|
|
400
|
+
|
|
401
|
+
ground_size = spacing * (len(names) + 2) + 6.0
|
|
402
|
+
bpy.ops.mesh.primitive_plane_add(size=ground_size, location=((len(names) - 1) * spacing / 2, 0.0, 0.0))
|
|
403
|
+
ground = bpy.context.object
|
|
404
|
+
ground.name = "Floor"
|
|
405
|
+
ground.data.materials.append(floor)
|
|
406
|
+
_collider(ground, 5.0)
|
|
407
|
+
|
|
408
|
+
if wind > 0 and pinned_any:
|
|
409
|
+
bpy.ops.object.effector_add(type="WIND", location=(-2.0, -0.5, 1.8))
|
|
410
|
+
w = bpy.context.object
|
|
411
|
+
w.rotation_euler = Euler((0.0, math.radians(90), math.radians(-10)))
|
|
412
|
+
# Blender's wind is a force: with the vertex mass scaled up by lam, the
|
|
413
|
+
# force is scaled by lam too, per piece through its effector weight
|
|
414
|
+
hung = [o for o in objs if o.modifiers["Cloth"].settings.effector_weights.wind > 0]
|
|
415
|
+
lam_max = max(o["maillage_mass_scale"] for o in hung)
|
|
416
|
+
for o in hung:
|
|
417
|
+
o.modifiers["Cloth"].settings.effector_weights.wind = o["maillage_mass_scale"] / lam_max
|
|
418
|
+
w.field.strength = wind * lam_max
|
|
419
|
+
w.field.noise = 0.6 * wind
|
|
420
|
+
w.field.seed = seed
|
|
421
|
+
|
|
422
|
+
frames_dir = None
|
|
423
|
+
if animate:
|
|
424
|
+
# small Cycles renders of every `animate`-th frame, for an animated GIF
|
|
425
|
+
frames_dir = out / "frames"
|
|
426
|
+
frames_dir.mkdir(exist_ok=True)
|
|
427
|
+
for old in frames_dir.glob("frame_*.png"):
|
|
428
|
+
old.unlink()
|
|
429
|
+
setup_render(objs, out / "drop_test.png", samples)
|
|
430
|
+
sc.render.resolution_x, sc.render.resolution_y = 800, 450
|
|
431
|
+
|
|
432
|
+
# simulate frame by frame (the cloth cache needs every frame in order)
|
|
433
|
+
rest = {o.name: rest_points(o) for o in objs}
|
|
434
|
+
prev = None
|
|
435
|
+
for f in range(1, frames + 1):
|
|
436
|
+
sc.frame_set(f)
|
|
437
|
+
if frames_dir is not None and (f == 1 or f % animate == 0):
|
|
438
|
+
sc.render.filepath = str(frames_dir / f"frame_{f:04d}.png")
|
|
439
|
+
bpy.ops.render.render(write_still=True)
|
|
440
|
+
if f >= frames - 1:
|
|
441
|
+
dg = bpy.context.evaluated_depsgraph_get()
|
|
442
|
+
cur = {o.name: world_points(o, dg) for o in objs}
|
|
443
|
+
if f == frames:
|
|
444
|
+
last, before = cur, prev
|
|
445
|
+
prev = cur
|
|
446
|
+
|
|
447
|
+
report = {
|
|
448
|
+
"usd": str(usd_path),
|
|
449
|
+
"frames": frames,
|
|
450
|
+
"fps": sc.render.fps,
|
|
451
|
+
"blender": bpy.app.version_string,
|
|
452
|
+
"criteria": {
|
|
453
|
+
"stretch_p99_max": STRETCH_P99_MAX,
|
|
454
|
+
"stretch_max": STRETCH_MAX,
|
|
455
|
+
"penetration_max": PENETRATION_MAX,
|
|
456
|
+
"rest_speed_max_m_s": REST_SPEED_MAX,
|
|
457
|
+
},
|
|
458
|
+
"pieces": [],
|
|
459
|
+
}
|
|
460
|
+
for o in objs:
|
|
461
|
+
p = props[o.name]
|
|
462
|
+
pts = last[o.name]
|
|
463
|
+
e = edges(o)
|
|
464
|
+
r0 = np.linalg.norm(rest[o.name][e[:, 0]] - rest[o.name][e[:, 1]], axis=1)
|
|
465
|
+
r1 = np.linalg.norm(pts[e[:, 0]] - pts[e[:, 1]], axis=1)
|
|
466
|
+
ratio = r1 / np.maximum(r0, 1e-9)
|
|
467
|
+
speed = float(np.max(np.linalg.norm(pts - before[o.name], axis=1))) * sc.render.fps
|
|
468
|
+
tol = 0.002
|
|
469
|
+
inside = pts[:, 2] < -tol
|
|
470
|
+
t = pedestals.get(o.name)
|
|
471
|
+
drape = None
|
|
472
|
+
if t is not None:
|
|
473
|
+
r = t.dimensions.x / 2
|
|
474
|
+
c = np.array(t.location)
|
|
475
|
+
radial = np.linalg.norm(pts[:, :2] - c[:2], axis=1)
|
|
476
|
+
inside |= (radial < r - tol) & (pts[:, 2] < PEDESTAL_HEIGHT - tol)
|
|
477
|
+
# Cusick drape coefficient: 1 = stays flat, 0 = hangs straight down
|
|
478
|
+
disc, flat = math.pi * r * r, flat_area(o)
|
|
479
|
+
drape = (hull_area(pts[:, :2]) - disc) / (flat - disc)
|
|
480
|
+
pinned = any(g.name == "pin" for g in o.vertex_groups)
|
|
481
|
+
finite = bool(np.all(np.isfinite(pts)))
|
|
482
|
+
res = {
|
|
483
|
+
"name": o.name,
|
|
484
|
+
"fabric": p.get("fabric"),
|
|
485
|
+
"pattern": p.get("pattern"),
|
|
486
|
+
"scenario": "hang" if pinned else "drape",
|
|
487
|
+
"vertices": len(pts),
|
|
488
|
+
"mass_kg": round(float(p.get("mass", 0.0)), 5),
|
|
489
|
+
"finite": finite,
|
|
490
|
+
"stretch_p99": round(float(np.percentile(ratio, 99)), 4),
|
|
491
|
+
"stretch_max": round(float(ratio.max()), 4),
|
|
492
|
+
"compression_p01": round(float(np.percentile(ratio, 1)), 4),
|
|
493
|
+
"penetration": round(float(inside.mean()), 5),
|
|
494
|
+
"max_speed_m_s": round(speed, 4),
|
|
495
|
+
"drape_coefficient": None if drape is None else round(float(drape), 4),
|
|
496
|
+
"lowest_point_m": round(float(pts[:, 2].min()), 4),
|
|
497
|
+
}
|
|
498
|
+
checks = {
|
|
499
|
+
"finite": finite,
|
|
500
|
+
"stretch": res["stretch_p99"] <= STRETCH_P99_MAX and res["stretch_max"] <= STRETCH_MAX,
|
|
501
|
+
"penetration": res["penetration"] <= PENETRATION_MAX,
|
|
502
|
+
"at_rest": pinned or speed <= REST_SPEED_MAX,
|
|
503
|
+
}
|
|
504
|
+
res["checks"] = checks
|
|
505
|
+
res["passed"] = all(checks.values())
|
|
506
|
+
report["pieces"].append(res)
|
|
507
|
+
report["passed"] = all(r["passed"] for r in report["pieces"])
|
|
508
|
+
|
|
509
|
+
# draped meshes, with the physical attributes copied back
|
|
510
|
+
bpy.ops.object.select_all(action="DESELECT")
|
|
511
|
+
for o in objs:
|
|
512
|
+
o.select_set(True)
|
|
513
|
+
draped = out / "draped.usdc"
|
|
514
|
+
bpy.ops.wm.usd_export(
|
|
515
|
+
filepath=str(draped),
|
|
516
|
+
selected_objects_only=True,
|
|
517
|
+
export_animation=False,
|
|
518
|
+
export_materials=True,
|
|
519
|
+
relative_paths=True,
|
|
520
|
+
)
|
|
521
|
+
copy_attributes(usd_path, draped, set(names))
|
|
522
|
+
report["draped_usd"] = str(draped)
|
|
523
|
+
|
|
524
|
+
if render:
|
|
525
|
+
for o in objs:
|
|
526
|
+
sol = o.modifiers.new("Thickness", "SOLIDIFY")
|
|
527
|
+
sol.thickness = max(0.001, float(props[o.name].get("thickness", 0.5e-3)))
|
|
528
|
+
sol.offset = 0.0
|
|
529
|
+
if sc.camera is None:
|
|
530
|
+
setup_render(objs, out / "drop_test.png", samples)
|
|
531
|
+
sc.render.resolution_x, sc.render.resolution_y = 1600, 900
|
|
532
|
+
sc.render.filepath = str(out / "drop_test.png")
|
|
533
|
+
bpy.ops.render.render(write_still=True)
|
|
534
|
+
report["render"] = str(out / "drop_test.png")
|
|
535
|
+
|
|
536
|
+
if frames_dir is not None:
|
|
537
|
+
report["frames_dir"] = str(frames_dir)
|
|
538
|
+
(out / "drop_test.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
|
539
|
+
report["report"] = str(out / "drop_test.json")
|
|
540
|
+
return report
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def build_parser():
|
|
544
|
+
ap = argparse.ArgumentParser(prog="drop_test.py", description="Blender cloth drop test for Maillage")
|
|
545
|
+
ap.add_argument("target", help="a generated folder (output/<preset>) or a maillage_*.usdc file")
|
|
546
|
+
ap.add_argument("--out", default=None, help="output folder (default: <folder>/drop_test)")
|
|
547
|
+
ap.add_argument("--pieces", type=int, default=4, help="number of pieces tested (default: 4)")
|
|
548
|
+
ap.add_argument("--frames", type=int, default=120, help="frames simulated at 24 fps (default: 120)")
|
|
549
|
+
ap.add_argument("--seed", type=int, default=1, help="random drop poses (default: 1)")
|
|
550
|
+
ap.add_argument("--render", action="store_true", help="render a Cycles image of the result")
|
|
551
|
+
ap.add_argument("--samples", type=int, default=32, help="Cycles samples (default: 32)")
|
|
552
|
+
ap.add_argument("--wind", type=float, default=0.0, help="wind strength on hung pieces (default: 0)")
|
|
553
|
+
ap.add_argument(
|
|
554
|
+
"--animate",
|
|
555
|
+
type=int,
|
|
556
|
+
default=0,
|
|
557
|
+
help="render every N-th frame to frames/ for a GIF (default: 0, off)",
|
|
558
|
+
)
|
|
559
|
+
ap.add_argument("--quality", type=int, default=10, help="cloth solver steps per frame (default: 10)")
|
|
560
|
+
ap.add_argument(
|
|
561
|
+
"--self-collision",
|
|
562
|
+
action=argparse.BooleanOptionalAction,
|
|
563
|
+
default=True,
|
|
564
|
+
help="cloth self-collisions (slower, more realistic folds)",
|
|
565
|
+
)
|
|
566
|
+
return ap
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def summary_lines(report):
|
|
570
|
+
lines = []
|
|
571
|
+
for r in report["pieces"]:
|
|
572
|
+
status = "PASS" if r["passed"] else "FAIL " + ",".join(k for k, v in r["checks"].items() if not v)
|
|
573
|
+
lines.append(
|
|
574
|
+
f"{r['name']:<22} {r['scenario']:<6} stretch p99 {r['stretch_p99']:.3f} "
|
|
575
|
+
f"penetration {r['penetration']:.2%} speed {r['max_speed_m_s']:.3f} m/s "
|
|
576
|
+
+ (f"drape {r['drape_coefficient']:.2f} " if r["drape_coefficient"] is not None else "")
|
|
577
|
+
+ status
|
|
578
|
+
)
|
|
579
|
+
return lines
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def main(argv=None):
|
|
583
|
+
if argv is None:
|
|
584
|
+
if "--" in sys.argv: # blender -b -P drop_test.py -- ...
|
|
585
|
+
argv = sys.argv[sys.argv.index("--") + 1 :]
|
|
586
|
+
elif Path(sys.argv[0]).name == Path(__file__).name: # python drop_test.py ... (bpy module)
|
|
587
|
+
argv = sys.argv[1:]
|
|
588
|
+
else:
|
|
589
|
+
argv = []
|
|
590
|
+
args = build_parser().parse_args(argv)
|
|
591
|
+
report = run(
|
|
592
|
+
args.target,
|
|
593
|
+
args.out,
|
|
594
|
+
args.pieces,
|
|
595
|
+
args.frames,
|
|
596
|
+
args.seed,
|
|
597
|
+
args.render,
|
|
598
|
+
args.samples,
|
|
599
|
+
args.wind,
|
|
600
|
+
args.self_collision,
|
|
601
|
+
args.quality,
|
|
602
|
+
args.animate,
|
|
603
|
+
)
|
|
604
|
+
for line in summary_lines(report):
|
|
605
|
+
print(line)
|
|
606
|
+
print(f"report: {report['report']}")
|
|
607
|
+
return 0 if report["passed"] else 1
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
if __name__ == "__main__":
|
|
611
|
+
sys.exit(main())
|