Files
ComfyGen/mesh_prep.py

274 lines
12 KiB
Python
Raw Permalink Normal View History

"""Turns a generated GLB into something this game can actually draw.
py -3.12 mesh_prep.py <in.glb> <out.glb> [--faces=2500] [--height=3.6]
[--paint=balloon] [--flame]
Hunyuan3D gives shape and nothing else: a quarter of a million triangles, no
normals, no colours, no material. This game draws flat-faceted, brightly
coloured, low-poly meshes at two hundred triangles apiece. So the raw output
needs three things doing to it before it is a prop:
* **Fewer triangles.** By vertex clustering - snap every vertex to a grid,
merge, throw away the triangles that collapse. Cheap, needs nothing but
numpy, and its failure mode is *more* faceted, which is this game's look.
* **Flat normals.** Every triangle gets its own three vertices and its own
face normal, exactly as MeshBuilder does for the hand-built props.
* **Colour.** The one thing a generated mesh cannot have and the one thing
this game's art is made of. Painted here from the shape itself: see
`paint_balloon` - height says basket, ropes or envelope, and the angle round
the middle says which gore.
The result is a GLB with POSITION, NORMAL and COLOR_0, which is what
Engine/Renderer/GltfMesh.cpp reads.
"""
import math
import sys
import numpy as np
import trimesh
# The palette the hand-built balloon uses (Engine/Renderer/MeshPrimitives.cpp),
# so a generated one sits beside the rest of the village rather than beside
# nothing.
CLOTH = (0.86, 0.32, 0.26)
CLOTH_ALT = (0.94, 0.82, 0.42)
WICKER = (0.62, 0.45, 0.24)
ROPE = (0.74, 0.68, 0.52)
FLAME = (0.96, 0.55, 0.15)
FLAME_HEART = (1.00, 0.90, 0.52)
WALL = (0.90, 0.85, 0.72)
ROOF = (0.72, 0.26, 0.22)
THATCH = (0.86, 0.72, 0.34)
STONE = (0.55, 0.55, 0.58)
WOOD = (0.55, 0.38, 0.24)
SAIL = (0.86, 0.82, 0.70)
def cluster(vertices, faces, cells):
"""Vertex-cluster decimation on a `cells`-per-side grid."""
low = vertices.min(axis=0)
high = vertices.max(axis=0)
span = np.maximum(high - low, 1e-6)
keys = np.floor((vertices - low) / span * (cells - 1) + 0.5).astype(np.int64)
flat = (keys[:, 0] * cells + keys[:, 1]) * cells + keys[:, 2]
unique, inverse = np.unique(flat, return_inverse=True)
# Each cell keeps the average of what landed in it, which rounds corners
# far less than keeping the first vertex would.
merged = np.zeros((len(unique), 3), dtype=np.float64)
counts = np.zeros(len(unique), dtype=np.int64)
np.add.at(merged, inverse, vertices)
np.add.at(counts, inverse, 1)
merged /= counts[:, None]
remapped = inverse[faces]
# Anything that collapsed to a line or a point is gone.
keep = ((remapped[:, 0] != remapped[:, 1]) &
(remapped[:, 1] != remapped[:, 2]) &
(remapped[:, 2] != remapped[:, 0]))
return merged, remapped[keep]
def decimate_to(mesh, target_faces):
"""Clusters at whatever grid gets nearest to `target_faces` from below."""
vertices = np.asarray(mesh.vertices, dtype=np.float64)
faces = np.asarray(mesh.faces, dtype=np.int64)
best = (vertices, faces)
for cells in range(8, 129, 2):
merged, kept = cluster(vertices, faces, cells)
if len(kept) == 0:
continue
best = (merged, kept)
if len(kept) >= target_faces:
break
return best
def paint_balloon(points):
"""A colour per vertex, from where the vertex is on the balloon.
The shape is known even though the mesh is not: a basket at the bottom, a
thin waist of ropes and burner above it, and an envelope over that. Height
picks the part; the angle round the middle cuts the envelope into gores.
"""
low = points[:, 1].min()
high = points[:, 1].max()
t = (points[:, 1] - low) / max(high - low, 1e-6)
angle = np.arctan2(points[:, 2], points[:, 0])
gore = np.floor((angle + math.pi) / (2.0 * math.pi) * 8.0).astype(np.int64) % 2
colours = np.zeros((len(points), 3), dtype=np.float32)
colours[:] = CLOTH
colours[gore == 1] = CLOTH_ALT
colours[t < 0.42] = ROPE
colours[t < 0.30] = WICKER
return colours
def paint_building(points, faces, roof, wall, base=STONE, sails=None, roof_at=1.01,
slope=0.25):
"""A colour per *face*, from which way the face points.
Height alone is the obvious rule and it is wrong on the first building that
has a tower: everything above the eaves goes roof-coloured, including the
tower's walls. What actually separates a roof from a wall is that one is
sloped and the other is upright, so that is what this asks - the normal
decides the material and the height only breaks ties.
`sails` paints whatever sticks out sideways high up, which is a windmill's
arms and nothing else on a building.
"""
corners = points[faces]
normals = np.cross(corners[:, 1] - corners[:, 0], corners[:, 2] - corners[:, 0])
normals /= np.maximum(np.linalg.norm(normals, axis=1, keepdims=True), 1e-9)
middles = corners.mean(axis=1)
low = points[:, 1].min()
high = points[:, 1].max()
t = (middles[:, 1] - low) / max(high - low, 1e-6)
# The absolute value, not the signed one.
#
# A generated mesh has no consistent winding - surface net gives whichever
# way round each quad came out - so "points upwards" is a coin toss and
# painting on it speckled the walls with roof. What is actually being
# asked is "is this face flat or upright", and that question has the same
# answer either way round.
colours = np.tile(np.asarray(wall, dtype=np.float32), (len(faces), 1))
# Two ways to be a roof, because one is not enough.
#
# The slope test is the honest one and it is not sufficient: these gables
# are steep enough that their normals barely tilt off the horizontal, so
# anything strict enough to exclude a wall also excludes the roof. `roof_at`
# is the blunt half - above this height it is roof whatever it points at -
# and it is set per building from what the thing actually looks like.
colours[(np.abs(normals[:, 1]) > slope) & (t > 0.34)] = roof
colours[t > roof_at] = roof
colours[t < 0.09] = base
if sails is not None:
radius = np.linalg.norm(middles[:, [0, 2]], axis=1)
reach = np.linalg.norm(points[:, [0, 2]], axis=1).max()
colours[(radius > reach * 0.56) & (t > 0.42)] = sails
return colours
def flame(at_y, radius, height, colour, segments=7):
"""A cone, as a mesh, for the burner under the mouth."""
cone = trimesh.creation.cone(radius=radius, height=height, sections=segments)
cone.apply_translation((0.0, 0.0, 0.0))
# trimesh cones stand along +Z; this game is Y-up.
cone.apply_transform(trimesh.transformations.rotation_matrix(-math.pi / 2.0, (1, 0, 0)))
cone.apply_translation((0.0, at_y, 0.0))
return cone, np.tile(np.asarray(colour, dtype=np.float32), (len(cone.vertices), 1))
def main():
args = [a for a in sys.argv[1:] if not a.startswith("--")]
flags = {a.split("=", 1)[0]: (a.split("=", 1)[1] if "=" in a else True)
for a in sys.argv[1:] if a.startswith("--")}
if len(args) < 2:
print(__doc__)
return 1
target = int(flags.get("--faces", 2500))
height = float(flags.get("--height", 3.6))
paint = flags.get("--paint", "balloon")
mesh = trimesh.load(args[0], force="mesh")
print(f"in : {len(mesh.vertices)} vertices, {len(mesh.faces)} faces")
points, faces = decimate_to(mesh, target)
print(f"cut : {len(points)} vertices, {len(faces)} faces")
# Winding, made consistent and turned outwards.
#
# Surface net hands back each quad in whichever order it came out, so half
# the face normals point into the model. Nothing notices until the mesh is
# flat-shaded and lit: then half the faces are lit as though the sun were
# underground, and the prop reads as a blotchy mess whatever it is painted.
# trimesh knows how to do this; doing it here means the game's loader never
# has to care.
fixed = trimesh.Trimesh(vertices=points, faces=faces, process=False)
trimesh.repair.fix_winding(fixed)
trimesh.repair.fix_inversion(fixed, multibody=True)
points = np.asarray(fixed.vertices, dtype=np.float64)
faces = np.asarray(fixed.faces, dtype=np.int64)
# Stood on the ground and scaled to the size the rest of the village is
# built at. The generator works in a unit box; this game works in metres.
points = points - np.array([
(points[:, 0].min() + points[:, 0].max()) * 0.5,
points[:, 1].min(),
(points[:, 2].min() + points[:, 2].max()) * 0.5,
])
scale = height / max(points[:, 1].max(), 1e-6)
points *= scale
# Two kinds of painter. The balloon's is per vertex, because a gore is a
# wedge of the shape rather than a set of faces; a building's is per face,
# because a roof is a face that points upwards.
face_colours = None
colours = None
if paint == "balloon":
colours = paint_balloon(points)
elif paint == "hall":
# The eaves sit low on a hall this steep: nearly half of it is roof.
face_colours = paint_building(points, faces, roof=THATCH, wall=WALL, roof_at=0.46)
elif paint == "mill":
# Height only, and high. A mill tower tapers, so its walls are sloped
# too and the slope test cannot tell them from the cap - it painted two
# thirds of the tower red. The cap is simply the top fifth.
face_colours = paint_building(points, faces, roof=ROOF, wall=WALL, sails=WOOD,
roof_at=0.79, slope=2.0)
else:
colours = np.tile(np.asarray(WALL, dtype=np.float32), (len(points), 1))
if flags.get("--flame") and colours is not None:
# The burner, in finished units - this runs after the scaling above, so
# a flame written as "a tenth of the balloon" stays a tenth of it
# whatever the model came out as. It was written before the scaling
# once, in generator units multiplied by the scale, and produced a cone
# taller than the envelope.
tall = points[:, 1].max()
mouth = tall * 0.37
for radius, length, colour in ((tall * 0.080, tall * 0.17, FLAME),
(tall * 0.045, tall * 0.11, FLAME_HEART)):
cone, cone_colours = flame(mouth, radius, length, colour)
offset = len(points)
points = np.vstack([points, np.asarray(cone.vertices)])
colours = np.vstack([colours, cone_colours])
faces = np.vstack([faces, np.asarray(cone.faces) + offset])
print(f"lit : {len(points)} vertices, {len(faces)} faces")
# Flat shading: one triangle, three vertices of its own, one normal.
corners = points[faces]
normals = np.cross(corners[:, 1] - corners[:, 0], corners[:, 2] - corners[:, 0])
lengths = np.linalg.norm(normals, axis=1, keepdims=True)
normals = np.divide(normals, np.maximum(lengths, 1e-9))
flat_points = corners.reshape(-1, 3).astype(np.float32)
flat_normals = np.repeat(normals, 3, axis=0).astype(np.float32)
flat_colours = (np.repeat(face_colours, 3, axis=0) if face_colours is not None
else colours[faces].reshape(-1, 3)).astype(np.float32)
flat_faces = np.arange(len(flat_points), dtype=np.uint32).reshape(-1, 3)
out = trimesh.Trimesh(vertices=flat_points, faces=flat_faces, process=False)
out.visual = trimesh.visual.ColorVisuals(
mesh=out, vertex_colors=(np.clip(flat_colours, 0.0, 1.0) * 255).astype(np.uint8))
out.vertex_normals = flat_normals
with open(args[1], "wb") as handle:
handle.write(trimesh.exchange.gltf.export_glb(out, include_normals=True))
print(f"out : {len(flat_points)} vertices, {len(flat_faces)} faces -> {args[1]}")
return 0
if __name__ == "__main__":
raise SystemExit(main())