3d8825f5a9
REGISTRY rewritten around the central rule: a character folder is born only when a body ships to ariki-game (<character>_base_v<NN> = ship ordinal). lena_nude dissolves accordingly: - characters/female/lena_base_v01/ — SHIPPED 2026-08-10: AccuRig GLB carrier, T-pose/rig FBX + JSON, previews, frozen README - characters/work/lena/ — the live lane: recipes 01-47 (incl. new 36-47: refill/sheets/clay/despeckle/musculature/spin/AccuRig export/graft/pose QC), masters (athletic_v04 blend + textures, accurig blend), lane-history README - hires_claude/hires_work intermediates (blends, logs, probes) pruned Supporting docs: AGENTS.md, working-files rule, rig-graft plan addendum, originals README, prune_lane.py. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
224 lines
8.5 KiB
Python
224 lines
8.5 KiB
Python
# Stage 30: decimate the v03 sculpt to the game-body vertex budget and export a clean GLB for the
|
|
# retexture / re-atlas lane.
|
|
#
|
|
# blender --background --python 30_decimate.py -- <in.blend> <out.glb> [target_verts] [review_dir]
|
|
#
|
|
# TARGET. Jeremy picked the shipped game body's density: `lena_nude_quatskin_glb_v01.glb` is
|
|
# 31,670 v, so that is the number to hit — not a round ratio.
|
|
#
|
|
# WHY A SEARCH INSTEAD OF A RATIO. Blender's Decimate COLLAPSE ratio is a fraction of FACES, and
|
|
# the vertex count that falls out of it depends on the mesh's genus and boundary, so
|
|
# verts != faces/2 exactly. Rather than assume, this evaluates the modifier through the depsgraph
|
|
# (no destructive apply) and bisects the ratio until the vertex count lands inside tolerance. The
|
|
# modifier is applied exactly once, at the end, with the ratio the search settled on.
|
|
#
|
|
# WHAT IT DELIBERATELY DOES NOT DO. It does not try to protect the UV atlas. The consumer is the
|
|
# re-atlas work in this lane (`24_seams.py`), which throws Tripo's 5,870-chart soup away and builds
|
|
# ~14 anatomical charts from scratch, so spending decimation quality on preserving the old UVs
|
|
# would be wasted. The basecolor/normal/rm are still carried into the GLB so the mesh arrives
|
|
# textured and can be eyeballed on its own.
|
|
#
|
|
# Transforms are applied and the object is left alone in the scene, because that is what
|
|
# `24_seams.py` expects of its input.
|
|
import bpy, bmesh, sys, os, math, time
|
|
import numpy as np
|
|
from mathutils import Vector
|
|
|
|
argv = sys.argv[sys.argv.index("--") + 1:]
|
|
BLEND, OUT = argv[0], argv[1]
|
|
TARGET_V = int(argv[2]) if len(argv) > 2 else 31670
|
|
REVIEW = argv[3] if len(argv) > 3 else ""
|
|
t0 = time.time()
|
|
TOL = 0.01 # accept within 1% of the target vertex count
|
|
UNIT_MM = 1815.0
|
|
|
|
|
|
def log(m):
|
|
print(f"[dec {time.time()-t0:6.1f}s] {m}", flush=True)
|
|
|
|
|
|
bpy.ops.wm.open_mainfile(filepath=BLEND)
|
|
ob = max([o for o in bpy.data.objects if o.type == 'MESH'],
|
|
key=lambda o: len(o.data.vertices))
|
|
bpy.context.view_layer.objects.active = ob
|
|
for o in bpy.data.objects:
|
|
o.select_set(o is ob)
|
|
bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
|
|
me = ob.data
|
|
v0, f0 = len(me.vertices), len(me.polygons)
|
|
co0 = np.empty(v0 * 3)
|
|
me.vertices.foreach_get("co", co0)
|
|
co0 = co0.reshape(-1, 3)
|
|
h0 = co0[:, 2].max() - co0[:, 2].min()
|
|
log(f"in: {v0}v {f0}f height {h0:.4f} units ({h0*UNIT_MM/1000:.3f} m equiv)")
|
|
log(f"target: {TARGET_V} v (+/-{TOL*100:.0f}%)")
|
|
|
|
# ---- bisect the collapse ratio against the evaluated mesh ----
|
|
mod = ob.modifiers.new("dec", 'DECIMATE')
|
|
mod.decimate_type = 'COLLAPSE'
|
|
mod.use_collapse_triangulate = False
|
|
|
|
|
|
def verts_at(ratio):
|
|
mod.ratio = ratio
|
|
ob.update_tag()
|
|
dg = bpy.context.evaluated_depsgraph_get()
|
|
ev = ob.evaluated_get(dg)
|
|
m = ev.to_mesh()
|
|
n = len(m.vertices)
|
|
ev.to_mesh_clear()
|
|
return n
|
|
|
|
|
|
lo, hi = 0.001, 1.0
|
|
best = None
|
|
# seed from the naive verts~faces/2 relation, then bisect
|
|
guess = min(1.0, max(0.001, (TARGET_V * 2.0) / f0))
|
|
n = verts_at(guess)
|
|
log(f" seed ratio {guess:.5f} -> {n} v")
|
|
if abs(n - TARGET_V) / TARGET_V <= TOL:
|
|
best = (guess, n)
|
|
else:
|
|
if n > TARGET_V:
|
|
hi = guess
|
|
else:
|
|
lo = guess
|
|
for it in range(24):
|
|
mid = 0.5 * (lo + hi)
|
|
n = verts_at(mid)
|
|
log(f" it{it:02d} ratio {mid:.6f} -> {n} v")
|
|
if abs(n - TARGET_V) / TARGET_V <= TOL:
|
|
best = (mid, n)
|
|
break
|
|
if n > TARGET_V:
|
|
hi = mid
|
|
else:
|
|
lo = mid
|
|
if best is None:
|
|
best = (0.5 * (lo + hi), verts_at(0.5 * (lo + hi)))
|
|
log(f" search exhausted; using ratio {best[0]:.6f} -> {best[1]} v")
|
|
|
|
ratio, got = best
|
|
mod.ratio = ratio
|
|
log(f"SETTLED ratio {ratio:.6f} -> {got} v (target {TARGET_V})")
|
|
bpy.ops.object.modifier_apply(modifier=mod.name)
|
|
me = ob.data
|
|
v1, f1 = len(me.vertices), len(me.polygons)
|
|
log(f"applied: {v0}v/{f0}f -> {v1}v/{f1}f "
|
|
f"({100.0*v1/v0:.2f}% of verts, {100.0*f1/f0:.2f}% of faces)")
|
|
|
|
# ---- shape + health checks ----
|
|
co1 = np.empty(v1 * 3)
|
|
me.vertices.foreach_get("co", co1)
|
|
co1 = co1.reshape(-1, 3)
|
|
h1 = co1[:, 2].max() - co1[:, 2].min()
|
|
print(f"HEIGHT {h0:.5f} -> {h1:.5f} units (delta {(h1-h0)*UNIT_MM:+.2f} real mm)")
|
|
for ax, nm in ((0, "x"), (1, "y"), (2, "z")):
|
|
print(f" bbox {nm}: {co0[:,ax].min():+.4f}..{co0[:,ax].max():+.4f} -> "
|
|
f"{co1[:,ax].min():+.4f}..{co1[:,ax].max():+.4f}")
|
|
|
|
# smooth normals over the new topology, matching the rest of the pipeline
|
|
vn = np.empty(v1 * 3, dtype=np.float32)
|
|
me.vertices.foreach_get("normal", vn)
|
|
if me.has_custom_normals:
|
|
me.normals_split_custom_set_from_vertices(vn.reshape(-1, 3))
|
|
|
|
bm = bmesh.new()
|
|
bm.from_mesh(me)
|
|
bnd = len([e for e in bm.edges if len(e.link_faces) == 1])
|
|
nm_ = len([e for e in bm.edges if len(e.link_faces) > 2])
|
|
tri = len([f for f in bm.faces if len(f.verts) == 3])
|
|
quad = len([f for f in bm.faces if len(f.verts) == 4])
|
|
ngon = len([f for f in bm.faces if len(f.verts) > 4])
|
|
bm.free()
|
|
print(f"TOPO boundary_edges={bnd} nonmanifold_edges={nm_} tris={tri} quads={quad} ngons={ngon}")
|
|
|
|
# flipped faces, same test stage 25 used
|
|
fn = np.empty(f1 * 3)
|
|
me.polygons.foreach_get("normal", fn)
|
|
fn = fn.reshape(-1, 3)
|
|
lv = np.empty(len(me.loops), dtype=np.int32)
|
|
me.loops.foreach_get("vertex_index", lv)
|
|
ls = np.empty(f1, dtype=np.int32)
|
|
me.polygons.foreach_get("loop_start", ls)
|
|
lt = np.empty(f1, dtype=np.int32)
|
|
me.polygons.foreach_get("loop_total", lt)
|
|
vn2 = vn.reshape(-1, 3).astype(np.float64)
|
|
acc = np.zeros((f1, 3))
|
|
for k in range(int(lt.max())):
|
|
sel = lt > k
|
|
acc[sel] += vn2[lv[ls[sel] + k]]
|
|
acc /= np.maximum(np.linalg.norm(acc, axis=1, keepdims=True), 1e-12)
|
|
print(f"FLIPPED FACES: {int(((fn*acc).sum(axis=1) < 0).sum())} of {f1}")
|
|
|
|
uvl = me.uv_layers.active
|
|
print(f"UV layer: {uvl.name if uvl else None} "
|
|
f"(carried through decimation; the re-atlas rebuilds it)")
|
|
imgs = [i.name for i in bpy.data.images if i.has_data]
|
|
print(f"IMAGES carried: {imgs}")
|
|
print(f"MATERIALS: {[ms.material.name if ms.material else None for ms in ob.material_slots]}")
|
|
print(f"MODIFIERS left: {[m.type for m in ob.modifiers]}")
|
|
|
|
# ---- export ----
|
|
os.makedirs(os.path.dirname(os.path.abspath(OUT)), exist_ok=True)
|
|
bpy.ops.export_scene.gltf(
|
|
filepath=OUT,
|
|
export_format='GLB',
|
|
export_image_format='AUTO',
|
|
export_yup=True,
|
|
export_apply=False,
|
|
export_animations=False,
|
|
export_skins=False,
|
|
export_morph=False,
|
|
)
|
|
log(f"WROTE {OUT} ({os.path.getsize(OUT)/1e6:.2f} MB)")
|
|
|
|
# ---- optional review renders ----
|
|
if REVIEW:
|
|
os.makedirs(REVIEW, exist_ok=True)
|
|
scn = bpy.context.scene
|
|
wd = bpy.data.worlds.new("W")
|
|
wd.color = (0.22, 0.22, 0.24)
|
|
scn.world = wd
|
|
key = bpy.data.objects.new("Key", bpy.data.lights.new("Key", 'SUN'))
|
|
key.data.energy = 3.0
|
|
key.data.use_shadow = False
|
|
bpy.context.collection.objects.link(key)
|
|
fl = bpy.data.objects.new("Fill", bpy.data.lights.new("Fill", 'SUN'))
|
|
fl.data.energy = 1.0
|
|
fl.data.use_shadow = False
|
|
bpy.context.collection.objects.link(fl)
|
|
cam = bpy.data.objects.new("Cam", bpy.data.cameras.new("Cam"))
|
|
cam.data.lens = 85
|
|
bpy.context.collection.objects.link(cam)
|
|
scn.camera = cam
|
|
scn.render.engine = 'BLENDER_EEVEE' if bpy.app.version >= (4, 2) else 'BLENDER_EEVEE_NEXT'
|
|
scn.render.resolution_x = scn.render.resolution_y = 1000
|
|
clay = bpy.data.materials.new("Clay")
|
|
clay.use_nodes = True
|
|
nt = clay.node_tree.nodes["Principled BSDF"]
|
|
nt.inputs["Base Color"].default_value = (0.62, 0.60, 0.58, 1)
|
|
nt.inputs["Roughness"].default_value = 0.45
|
|
orig = [ms.material for ms in ob.material_slots]
|
|
|
|
def shoot(tag, ctr, span, yaw, use_clay):
|
|
for i, ms in enumerate(ob.material_slots):
|
|
ms.material = clay if use_clay else orig[i]
|
|
y = math.radians(yaw)
|
|
d = span * 3.0
|
|
cam.location = Vector(ctr) + Vector((math.sin(y) * d, -math.cos(y) * d, 0.02))
|
|
cam.rotation_euler = (Vector(ctr) - cam.location).to_track_quat('-Z', 'Y').to_euler()
|
|
key.rotation_euler = (math.radians(62), 0, math.radians(35 + yaw))
|
|
fl.rotation_euler = (math.radians(75), 0, math.radians(yaw - 110))
|
|
scn.render.filepath = os.path.abspath(os.path.join(REVIEW, f"{tag}.png"))
|
|
bpy.ops.render.render(write_still=True)
|
|
log(f"render {tag}")
|
|
|
|
shoot("full_clay_0", (0.0, 0.0, 0.50), 0.55, 0, True)
|
|
shoot("full_tex_0", (0.0, 0.0, 0.50), 0.55, 0, False)
|
|
shoot("chest_clay_0", (0.0, 0.0, 0.675), 0.22, 0, True)
|
|
shoot("chest_tex_0", (0.0, 0.0, 0.675), 0.22, 0, False)
|
|
shoot("hip_clay_0", (0.0, 0.0, 0.53), 0.22, 0, True)
|
|
|
|
print("DEC_DONE")
|