Spaces:
Paused
Paused
Complete isolated repair feedback, learned rig transfer and audited animation workflow
Browse filesFiles changed (14)
- README.md+30-18
- app.py+1-1
- scripts/audit_character_collisions.py+38
- scripts/project_reference_texture.pyAdded+130
- scripts/retarget_character.py+142-14
- scripts/transfer_learned_rig.py+13
- studio/animation.py+5-1
- studio/contracts.py+3
- studio/motion.py+10-6
- studio/native.py+2-2
- studio/pipeline.py+8-2
- studio/refine.py+112-25
- studio/rigging.py+55-22
- studio/texture_repair.pyAdded+74
13 unmodified lines1415161718193 unmodified lines2324252627282930313233345 unmodified lines4041424344454647484950515214 unmodified lines676869707172737475767715 unmodified lines9394959697989910010110213 unmodified linesA new Gradio + uv pipeline targeting Hugging Face ZeroGPU. It accepts an image,a prompt, or both and produces a textured GLB with individually editable components.## Inputs3 unmodified lines| Prompt only | “A brass desk lamp with a green glass shade” | Generate a reference with FLUX.2 Klein, then reconstruct it || Both | Stool image + “Walnut seat and black metal legs; keep the shape” | Edit the image with FLUX.2 Klein, then reconstruct the edited reference |## Six stages1. Validate inputs and prepare a reference. Images keep EXIF orientation and alpha.2. TRELLIS.2 generates geometry at its 1024 cascade setting and a 512px PBR atlas. Texture samplinguses four steps. Reducing both the texture sampling budget and atlas size saves work;a smaller exported PNG alone would not reduce the diffusion cost.3. PartField predicts learned 3D features. Cluster those features into the requested numberof parts, partition the original faces, crop component texture bounds and remap UVs.This is learned part segmentation, not merely splitting disconnected islands. The5 unmodified linesCUDA OOM halves concurrency and then tile size. GPU leases and requests are serialized;component workers run concurrently within the lease. Alpha is interpolated separately.Normal, metallic, roughness, occlusion and emission maps preserve their data and UVs.5. Ling 3.0 Flash VL inspects reference and rendered views. The same model runs throughfx with TheOrcDev's pinned game-model-cleanup skill and workflow to produce a typedrepair plan. Apply identity-preserving mesh cleanup, part names and bounded material/color corrections. Render again and retain the prior version if Ling detects regression.Unsupported reconstruction/rigging/seam painting is recorded as unresolved.6. Reopen the final GLB to verify components and textures. Present the asset, views, and aZIP containing individual GLBs, textures, source lineage, repair plan and stage log.## Local development14 unmodified lines`studio/`, `scripts/`, and `assets/`. Do not upload `.runtime/`, credentials, or old outputs.Add `OPENROUTER_API_KEY` as a Space secret. Add `HF_TOKEN` from an account with access to TRELLIS’s gated DINOv3 and BRIARMBG-2.0 dependencies. Obtain that access on the model pages before startup; setupdoes not accept model terms for you. The exact `inclusionai/ling-3.0-flash-vl:free` route is used; its availabilityand rate limits are controlled by OpenRouter, and there is no paid-model fallback.HF installs the CUDA dependencies and Blender at build time. On startup `app.py` detects`SPACE_ID`, downloads pinned source/models and builds fx with Zig 0.16, then loads models before handlingrequests. GPU stages use `@spaces.GPU`; CPU exports, rendering and fx run outside leases.Only CPU inputs/results cross worker queues. Upscaled textures are returned explicitlyto the parent process; models and UI callbacks are never serialized as worker arguments.15 unmodified linesstorage and RAM; downloads are cached. ZeroGPU quota expiry, unavailable models and memoryfailures are surfaced with retained intermediate files, never reported as completed runs.The first `prepare_runtime.py` invocation adds a named `component-studio` connection to`~/.fx/settings.json`, preserving other settings. Its dedicated workspace denies all tools and limits agent steps;fx returns a plan, and the Python pipeline applies allowed operations. Keys stay in environment variables.Upstream source and the exact skill are downloaded to `.runtime/`, not installed globally.## Model choices and known limits13 unmodified lines14151617181920212223243 unmodified lines28293031323334353637385 unmodified lines4445464748495051525354555657585960616214 unmodified lines77787980818283848586878815 unmodified lines10410510610710810911011111211311413 unmodified linesA new Gradio + uv pipeline targeting Hugging Face ZeroGPU. It accepts an image,a prompt, or both and produces a textured GLB with individually editable components.Add an animation prompt to run learned humanoid rigging, NVIDIA Kimodo motion generation,retargeting, video export, full-frame collision checks and Astra visual review.The animated workflow is under production verification. A completed export is not a qualitypass: rejected models or animations retain their artifacts with `needs_review` status.## Inputs3 unmodified lines| Prompt only | “A brass desk lamp with a green glass shade” | Generate a reference with FLUX.2 Klein, then reconstruct it || Both | Stool image + “Walnut seat and black metal legs; keep the shape” | Edit the image with FLUX.2 Klein, then reconstruct the edited reference |## Pipeline stages1. Validate inputs and prepare a reference. Images keep EXIF orientation and alpha.2. TRELLIS.2 generates geometry at its 1024 cascade setting and a 1024px PBR atlas. Texture samplinguses twelve steps before component upscaling, giving refinement more source detail.3. PartField predicts learned 3D features. Cluster those features into the requested numberof parts, partition the original faces, crop component texture bounds and remap UVs.This is learned part segmentation, not merely splitting disconnected islands. The5 unmodified linesCUDA OOM halves concurrency and then tile size. GPU leases and requests are serialized;component workers run concurrently within the lease. Alpha is interpolated separately.Normal, metallic, roughness, occlusion and emission maps preserve their data and UVs.5. Astra (`openai/gpt-6-astra`) reviews the reference and rendered views. An embedded fxagent inspects per-run evidence inside a fresh just-bash virtual filesystem and returnsa validated repair plan. Its tools cannot access the host filesystem, shell or network.The host applies bounded repairs, renders again and preserves the original on regression.Quality acceptance is a separate decision from non-regression.6. For an animation prompt, learn the humanoid skeleton and weights, transfer them ontothe original textured components, and generate the requested motion with pinned nativeNVIDIA Kimodo. Retarget it in Blender and export the actual animated GLB and MP4.7. Measure every exported frame for new triangle intersections and ground penetration;render chronological front/side evidence and ask Astra to judge the requested action,deformation, texture fidelity and contacts. A failing review remains `needs_review`.8. Package the original inputs, candidate meshes, textures, rig, source motion, GLB,video, audit evidence and provenance. Downloads belong to one unique run directory.## Local development14 unmodified lines`studio/`, `scripts/`, and `assets/`. Do not upload `.runtime/`, credentials, or old outputs.Add `OPENROUTER_API_KEY` as a Space secret. Add `HF_TOKEN` from an account with access to TRELLIS’s gated DINOv3 and BRIARMBG-2.0 dependencies. Obtain that access on the model pages before startup; setupdoes not accept model terms for you. The exact `openai/gpt-6-astra` route is used for review and fx repair planning.OpenRouter billing and availability apply; no substitute review model is selected.Native Kimodo also requires access to `meta-llama/Meta-Llama-3-8B-Instruct`.HF installs the CUDA dependencies and Blender at build time. On startup `app.py` detects`SPACE_ID`, downloads pinned source/models and installs the pinned embedded fx/Node runtime, then loads models before handlingrequests. GPU stages use `@spaces.GPU`; CPU exports, rendering and fx run outside leases.Only CPU inputs/results cross worker queues. Upscaled textures are returned explicitlyto the parent process; models and UI callbacks are never serialized as worker arguments.15 unmodified linesstorage and RAM; downloads are cached. ZeroGPU quota expiry, unavailable models and memoryfailures are surfaced with retained intermediate files, never reported as completed runs.Refinement uses `libfx` with an explicit host-owned OpenRouter transport and a freshin-memory just-bash filesystem for each attempt. Only the run's review evidence is mounted;credentials remain outside tools. Tool calls, model calls, memory, output size and elapsedtime are bounded. Runtime dependencies and the upstream cleanup skill are pinned.## Model choices and known limits
69 unmodified lines7071727374757669 unmodified linesanimation_seconds = gr.Slider(2, 12, value=6, step=1, label="Animation duration (seconds)")parts = gr.Slider(2, 32, value=8, step=1, label="Target components")seed = gr.Number(value=0, precision=0, label="Seed")gr.Markdown("512px initial textures · 4× base-color upscale · 10% memory reserve")button = gr.Button("Create asset", variant="primary")with gr.Accordion("Continue an existing textured mesh", open=False):source_mesh = gr.File(label="Source GLB", file_types=[".glb"], type="filepath")69 unmodified lines7071727374757669 unmodified linesanimation_seconds = gr.Slider(2, 12, value=6, step=1, label="Animation duration (seconds)")parts = gr.Slider(2, 32, value=8, step=1, label="Target components")seed = gr.Number(value=0, precision=0, label="Seed")gr.Markdown("1024px initial textures · 4× base-color upscale · 10% memory reserve")button = gr.Button("Create asset", variant="primary")with gr.Accordion("Continue an existing textured mesh", open=False):source_mesh = gr.File(label="Source GLB", file_types=[".glb"], type="filepath")
57 unmodified lines58596061626377 unmodified lines14114214314414514627 unmodified lines17417517617717817933 unmodified lines21321421521621721857 unmodified linesm.rest_source = "ORCO"rig = next(o for o in bpy.context.scene.objects if o.type == "ARMATURE")rig.data.pose_position = "REST"bpy.context.view_layer.update()77 unmodified linesreturn {int(i) * len(faces) + int(j) for i, j in pairs}, dict(groups)baseline, baseline_groups = intersections(rest)print("REST", len(baseline), baseline_groups, flush=True)rig.data.pose_position = "POSE"27 unmodified lines"groups": groups,"new_groups": dict(newgroups),"lowest_foot_z": feet,}rows.append(row)joint_tracks.append(33 unmodified lines"total_new_pair_frames": sum(r["new_pairs_vs_rest"] for r in rows),"worst_frame": worst,"ground_min_z": min(min(r["lowest_foot_z"].values()) for r in rows),"method": "Deformed full-resolution triangles; BVH broad phase and triangle separating-axis narrow phase. Shared welded-vertex pairs excluded. Requires triangle-plane crossings deeper than 1e-6 model units; coplanar contact is excluded. Existing rest-pose intersections reported separately. Discrete 30 fps samples, not continuous collision detection.",}(out / "audit.json").write_text(57 unmodified lines5859606162636465666777 unmodified lines14514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517627 unmodified lines20420520620720820921021133 unmodified lines24524624724824925025125225325425525657 unmodified linesm.rest_source = "ORCO"rig = next(o for o in bpy.context.scene.objects if o.type == "ARMATURE")rig.data.pose_position = "REST"for obj in objects:if obj.data.shape_keys:for key in obj.data.shape_keys.key_blocks:key.value = 0.0bpy.context.view_layer.update()77 unmodified linesreturn {int(i) * len(faces) + int(j) for i, j in pairs}, dict(groups)def crossing_severity(vertices, encoded_pairs):if not encoded_pairs:return {"max_triangle_plane_depth": 0.0,"p95_triangle_plane_depth": 0.0,"affected_surface_area": 0.0,"affected_surface_fraction": 0.0,}pairs = np.array([(key // len(faces), key % len(faces)) for key in encoded_pairs], dtype=int)triangles = vertices[faces]normals = np.cross(triangles[:, 1] - triangles[:, 0], triangles[:, 2] - triangles[:, 0])lengths = np.linalg.norm(normals, axis=1)unit = normals / np.maximum(lengths[:, None], 1e-20)first, second = pairs.Tda = np.einsum("nti,ni->nt", triangles[first] - triangles[second, 0, None], unit[second])db = np.einsum("nti,ni->nt", triangles[second] - triangles[first, 0, None], unit[first])depth = np.minimum.reduce([da.max(1), -da.min(1), db.max(1), -db.min(1)])affected = float(lengths[np.unique(pairs)].sum() * 0.5)return {"max_triangle_plane_depth": float(depth.max()),"p95_triangle_plane_depth": float(np.quantile(depth, 0.95)),"affected_surface_area": affected,"affected_surface_fraction": affected / max(float(lengths.sum() * 0.5), 1e-20),}baseline, baseline_groups = intersections(rest)print("REST", len(baseline), baseline_groups, flush=True)rig.data.pose_position = "POSE"27 unmodified lines"groups": groups,"new_groups": dict(newgroups),"lowest_foot_z": feet,"lowest_vertex_z": float(vertices[:, 2].min()),"new_collision_severity": crossing_severity(vertices, new),}rows.append(row)joint_tracks.append(33 unmodified lines"total_new_pair_frames": sum(r["new_pairs_vs_rest"] for r in rows),"worst_frame": worst,"ground_min_z": min(min(r["lowest_foot_z"].values()) for r in rows),"ground_min_all_vertices_z": min(r["lowest_vertex_z"] for r in rows),"peak_triangle_plane_depth": max(r["new_collision_severity"]["max_triangle_plane_depth"] for r in rows),"peak_affected_surface_fraction": max(r["new_collision_severity"]["affected_surface_fraction"] for r in rows),"severity_method": "For each crossing triangle pair, minimum of both positive and negative vertex distances to the opposite triangle plane. This is a local crossing-depth estimate, not volumetric penetration. Affected area counts unique triangles once; dimensions use model units.","method": "Deformed full-resolution triangles; BVH broad phase and triangle separating-axis narrow phase. Shared welded-vertex pairs excluded. Requires triangle-plane crossings deeper than 1e-6 model units; coplanar contact is excluded. Existing rest-pose intersections reported separately. Discrete 30 fps samples, not continuous collision detection.",}(out / "audit.json").write_text(
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""Project a reference onto visible UV texels; retain occluded and shared-backside texels."""import argparseimport jsonfrom pathlib import Pathimport sys
import bpyimport numpy as npfrom mathutils import Vectorfrom mathutils.bvhtree import BVHTree
p = argparse.ArgumentParser()p.add_argument('--folder', required=True)p.add_argument('--front-axis', choices=['-Y', '+Y', '-X', '+X'], default='-Y')p.add_argument('--strength', type=float, default=.9)a = p.parse_args(sys.argv[sys.argv.index('--') + 1:])folder = Path(a.folder)bpy.ops.object.select_all(action='SELECT')bpy.ops.object.delete(use_global=False)bpy.ops.import_scene.gltf(filepath=str(folder / 'source.glb'))objects = [o for o in bpy.context.scene.objects if o.type == 'MESH']front = np.array({'-Y': [0, -1, 0], '+Y': [0, 1, 0], '-X': [-1, 0, 0], '+X': [1, 0, 0]}[a.front_axis], dtype=float)right = np.cross(front, [0, 0, 1]) * -1vertices, triangles, records = [], [], []offset = 0for obj in objects: mesh = obj.data mesh.calc_loop_triangles() world = np.array([obj.matrix_world @ v.co for v in mesh.vertices]) normals = np.array([obj.matrix_world.to_3x3().inverted().transposed() @ v.normal for v in mesh.vertices]) normals /= np.maximum(np.linalg.norm(normals, axis=1, keepdims=True), 1e-12) vertices.extend(world.tolist()) triangles.extend(tuple(offset + i for i in t.vertices) for t in mesh.loop_triangles) records.append((obj, world, normals)) offset += len(world)vertices = np.array(vertices)bvh = BVHTree.FromPolygons(vertices.tolist(), triangles, all_triangles=True)height = np.ptp(vertices[:, 2])horizontal = vertices @ rightspan = np.ptp(horizontal)horizontal_min = horizontal.min()vertical_min = vertices[:, 2].min()if height <= 0 or span <= 0: raise ValueError('Degenerate projection bounds')reference = np.load(folder / 'reference.npz')rgba, mask, bounds = reference['rgba'], reference['mask'], reference['bounds']ref_h, ref_w = mask.shapex0, y0, x1, y1 = boundsmetrics = {'front_axis': a.front_axis, 'strength': a.strength, 'method': 'per-texel UV projection with BVH occlusion, normal falloff and shared-UV protection', 'material_color_boundaries_protected': True, 'geometry_unchanged': True, 'uv_unchanged': True, 'pbr_channels_preserved': True, 'parts': []}inputs = json.loads((folder / 'inputs.json').read_text())for item in inputs: matches = [r for r in records if r[0].name == item['part_id'] or r[0].name.startswith(item['part_id'] + ' ')] if len(matches) != 1: raise ValueError(f"Cannot identify unique component {item['part_id']}") obj, world, normals = matches[0] source = np.load(folder / item['file']) h, w = source.shape[:2] weights = np.zeros((h, w), dtype=np.float32) colors = np.zeros((h, w, 3), dtype=np.uint8) blocked = np.zeros((h, w), dtype=bool) uv_data = obj.data.uv_layers.active.data for triangle in obj.data.loop_triangles: uv = np.array([uv_data[i].uv for i in triangle.loops]) if np.any(uv < -1e-6) or np.any(uv > 1 + 1e-6): raise ValueError('Tiled UVs are unsupported for reference projection; source retained.') pixel = uv * [w, -h] + [0, h] low = np.maximum(np.floor(pixel.min(0)).astype(int), 0) high = np.minimum(np.ceil(pixel.max(0)).astype(int), [w - 1, h - 1]) if np.any(high < low): continue yy, xx = np.mgrid[low[1]:high[1] + 1, low[0]:high[0] + 1] points = np.stack([xx.ravel() + .5, yy.ravel() + .5], axis=1) v0, v1 = pixel[1] - pixel[0], pixel[2] - pixel[0] determinant = v0[0] * v1[1] - v0[1] * v1[0] if abs(determinant) < 1e-10: continue delta = points - pixel[0] b1 = (delta[:, 0] * v1[1] - delta[:, 1] * v1[0]) / determinant b2 = (v0[0] * delta[:, 1] - v0[1] * delta[:, 0]) / determinant bary = np.stack([1 - b1 - b2, b1, b2], axis=1) inside = np.all(bary >= -1e-7, axis=1) if not inside.any(): continue bary = bary[inside] xx, yy = xx.ravel()[inside], yy.ravel()[inside] ids = list(triangle.vertices) xyz = bary @ world[ids] n = bary @ normals[ids] facing = np.clip((n @ front - .35) / .55, 0, 1) facing = facing * facing * (3 - 2 * facing) rx = np.clip(np.rint(x0 + (xyz @ right - horizontal_min) / span * (x1 - x0)).astype(int), 0, ref_w - 1) ry = np.clip(np.rint(y1 - (xyz[:, 2] - vertical_min) / height * (y1 - y0)).astype(int), 0, ref_h - 1) eligible = (facing > 0) & mask[ry, rx] visible = np.zeros(len(xyz), dtype=bool) for index in np.flatnonzero(eligible): point = xyz[index] hit, _, _, _ = bvh.ray_cast(Vector(point + front * height * 2), Vector(-front)) visible[index] = hit is not None and np.linalg.norm(np.array(hit) - point) < height * 1e-4 original_rgb = source[yy, xx, :3].astype(float) / 255 target_rgb = rgba[ry, rx, :3].astype(float) / 255 original_sat = np.ptp(original_rgb, axis=1) / np.maximum(original_rgb.max(1), 1e-6) target_sat = np.ptp(target_rgb, axis=1) / np.maximum(target_rgb.max(1), 1e-6) colored = np.clip((original_sat - .35) / .15, 0, 1) washed_out = np.clip((.45 - target_sat) / .15, 0, 1) color_agreement = 1 - colored * washed_out source_chroma = original_rgb - original_rgb.mean(1, keepdims=True) target_chroma = target_rgb - target_rgb.mean(1, keepdims=True) cosine = np.sum(source_chroma * target_chroma, axis=1) / np.maximum( np.linalg.norm(source_chroma, axis=1) * np.linalg.norm(target_chroma, axis=1), 1e-6) changed_hue = colored * np.clip((target_sat - .35) / .15, 0, 1) color_agreement *= 1 - changed_hue * (1 - np.clip((cosine - .3) / .5, 0, 1)) weight = facing * visible * color_agreement * a.strength blocked[yy[weight == 0], xx[weight == 0]] = True keep = weight > weights[yy, xx] weights[yy[keep], xx[keep]] = weight[keep] colors[yy[keep], xx[keep]] = rgba[ry[keep], rx[keep], :3] weights[blocked] = 0 changed = weights > 0 result = source.copy() result[:, :, :3] = np.rint(source[:, :, :3] * (1 - weights[:, :, None]) + colors * weights[:, :, None]).astype(np.uint8) np.save(folder / ('projected-' + item['file']), result) assert np.array_equal(source[~changed], result[~changed]) assert np.array_equal(source[:, :, 3], result[:, :, 3]) metrics['parts'].append({'part_id': item['part_id'], 'changed_texels': int(changed.sum()), 'total_texels': int(h * w), 'protected_texels_unchanged': True, 'alpha_unchanged': True})(folder / 'projection.json').write_text(json.dumps(metrics, indent=2))print(json.dumps(metrics), flush=True)12 unmodified lines13141516171811 unmodified lines30313233343515 unmodified lines51525354555657585960616263646566676869707121 unmodified lines939495969798991001011021032 unmodified lines1061071081091101111121131141156 unmodified lines1221231241251261271281291301311321332 unmodified lines13613713813914014121 unmodified lines16316416516616716812 unmodified linesp = argparse.ArgumentParser()for name in ["input", "motion", "bvh", "output"]:p.add_argument("--" + name, required=True)a = p.parse_args(sys.argv[sys.argv.index("--") + 1 :])out = Path(a.output)out.mkdir(parents=True, exist_ok=True)11 unmodified linesif o.type == "MESH" and any(m.type == "ARMATURE" and m.object == rig for m in o.modifiers)]rig.animation_data_clear()for action in list(bpy.data.actions):bpy.data.actions.remove(action)# Normalize the whole hierarchy together, retaining bind matrices and textured geometry.15 unmodified linesrename[side + "UpLeg"] = side + "Leg"rename[side + "Leg"] = side + "Shin"original = [(b, b.name, b.name.split(":")[-1]) for b in rig.data.bones]for b, old, short in original:b.name = "__retarget_" + shortfor b, old, short in original:new = rename.get(short, short)b.name = newfor obj in meshes:group = obj.vertex_groups.get(old)if group:group.name = newsource_names = re.findall(r"JOINT (\S+)", Path(a.bvh).read_text())idx = {name: i for i, name in enumerate(source_names)}with np.load(a.motion, allow_pickle=False) as data:pos = data["posed_joints"].copy()C = np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]])pos = pos @ C.Tif pos.shape[1] != len(source_names):raise ValueError("Motion NPZ and BVH skeleton disagree.")tips = {21 unmodified linesbones = list(rig.data.bones)heads = {b.name: np.array(b.head_local) for b in bones}rest = {b.name: b.matrix_local.to_3x3() for b in bones}source_height = np.median(pos[:, idx["HeadEnd"], 2] - np.minimum(pos[:, idx["LeftFoot"], 2], pos[:, idx["RightFoot"], 2]))target_height = (rig.data.bones["Head"].head_local - rig.data.bones["LeftFoot"].head_local).lengthscale = target_height / max(source_height, 1e-6)scene.frame_start = 1scene.frame_end = len(pos)for f in range(len(pos)):2 unmodified linesfor bone in bones:name = bone.nameparent = bone.parent.name if bone.parent else Noneif name in tips and name in idx and tips[name] in idx:direction = rig.matrix_world.to_3x3().inverted() @ Vector(pos[f, idx[tips[name]]] - pos[f, idx[name]])rotation = ((Vector(heads[tips[name]] - heads[name])6 unmodified lineselse:rotation = rotations[parent] if parent else Matrix.Identity(3)rotations[name] = rotationif parent:targets[name] = targets[parent] + np.array(rotations[parent]) @ (heads[name] - heads[parent])else:delta = pos[f, idx["Hips"]] - pos[0, idx["Hips"]]delta[:2] = 0targets[name] = heads[name] + delta * scalematrix = (rotation @ rest[name]).to_4x4()matrix.translation = Vector(targets[name])pb = rig.pose.bones[name]2 unmodified linesbpy.context.view_layer.update()for channel in ["location", "rotation_quaternion", "scale"]:pb.keyframe_insert(channel, frame=f + 1)rig.animation_data.action.name = "Generated_Motion"scene.frame_set(1)bpy.ops.object.select_all(action="DESELECT")21 unmodified lines"Self intersections require audit review",],"root_translation": "vertical only; in-place preview",},indent=2,)12 unmodified lines13141516171819202111 unmodified lines33343536373839404115 unmodified lines5758596061626364656667686970717273747576777879808182838485868721 unmodified lines1091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571582 unmodified lines1611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112126 unmodified lines2192202212222232242 unmodified lines22722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626721 unmodified lines28929029129229329429529612 unmodified linesp = argparse.ArgumentParser()for name in ["input", "motion", "bvh", "output"]:p.add_argument("--" + name, required=True)p.add_argument("--body-clearance", action="store_true")p.add_argument("--smooth-joints", action="store_true")p.add_argument("--arm-blend-band", type=float, default=0.55)a = p.parse_args(sys.argv[sys.argv.index("--") + 1 :])out = Path(a.output)out.mkdir(parents=True, exist_ok=True)11 unmodified linesif o.type == "MESH" and any(m.type == "ARMATURE" and m.object == rig for m in o.modifiers)]rig.animation_data_clear()for bone in rig.pose.bones:bone.matrix_basis.identity()bpy.context.view_layer.update()for action in list(bpy.data.actions):bpy.data.actions.remove(action)# Normalize the whole hierarchy together, retaining bind matrices and textured geometry.15 unmodified linesrename[side + "UpLeg"] = side + "Leg"rename[side + "Leg"] = side + "Shin"original = [(b, b.name, b.name.split(":")[-1]) for b in rig.data.bones]groups_by_bone = {old: [obj.vertex_groups.get(old) for obj in meshes] for bone, old, short in original}for bone, old, short in original:staged = "__retarget_" + shortbone.name = stagedfor group in groups_by_bone[old]:if group is not None and group.name != staged:group.name = stagedfor bone, old, short in original:new = rename.get(short, short)bone.name = newfor group in groups_by_bone[old]:if group is not None and group.name != new:group.name = newfor obj in meshes:if any(group.name not in rig.data.bones for group in obj.vertex_groups):raise ValueError("Skin groups do not match retargeted skeleton bone names.")source_names = re.findall(r"JOINT (\S+)", Path(a.bvh).read_text())idx = {name: i for i, name in enumerate(source_names)}with np.load(a.motion, allow_pickle=False) as data:pos = data["posed_joints"].copy()source_rotations = data["global_rot_mats"].copy()contacts = data["foot_contacts"].reshape(len(pos), 2, -1).max(axis=2) > 0.5C = np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]])pos = pos @ C.Tsource_rotations = C @ source_rotations @ C.Tif pos.shape[1] != len(source_names):raise ValueError("Motion NPZ and BVH skeleton disagree.")tips = {21 unmodified linesbones = list(rig.data.bones)heads = {b.name: np.array(b.head_local) for b in bones}rest = {b.name: b.matrix_local.to_3x3() for b in bones}if a.smooth_joints:for side in ["Left", "Right"]:for upper, lower in [(side + "Arm", side + "ForeArm"), (side + "Leg", side + "Shin")]:pivot = heads[lower]direction = Vector(heads[lower] - heads[upper]).normalized()length = np.linalg.norm(heads[lower] - heads[upper])band = length * (a.arm_blend_band if upper.endswith("Arm") else 0.55)for obj in meshes:matrix = rig.matrix_world.inverted() @ obj.matrix_worldgroups = {group.index: group.name for group in obj.vertex_groups}for vertex in obj.data.vertices:total = sum(group.weight for group in vertex.groups if groups[group.group] in {upper, lower})if total < 1e-6:continuepoint = matrix @ vertex.cot = float(np.clip((np.dot(np.array(point) - pivot, direction) + band) / (2 * band), 0, 1))t = t * t * (3 - 2 * t)obj.vertex_groups[upper].add([vertex.index], total * (1 - t), "REPLACE")obj.vertex_groups[lower].add([vertex.index], total * t, "REPLACE")source_height = np.median(pos[:, idx["HeadEnd"], 2] - np.minimum(pos[:, idx["LeftFoot"], 2], pos[:, idx["RightFoot"], 2]))target_height = (rig.data.bones["Head"].head_local - rig.data.bones["LeftFoot"].head_local).lengthscale = target_height / max(source_height, 1e-6)torso_points = []for obj in meshes:lookup = {group.index: group.name for group in obj.vertex_groups}matrix = rig.matrix_world.inverted() @ obj.matrix_worldfor vertex in obj.data.vertices:torso_weight = sum(group.weightfor group in vertex.groupsif lookup[group.group] in {"Hips", "Spine1", "Spine2", "Chest"})if torso_weight > 0.7:torso_points.append(tuple(matrix @ vertex.co))if not torso_points:raise ValueError("Learned skin has no torso region.")torso_points = np.array(torso_points)body_low, body_high = np.quantile(torso_points, [0.01, 0.99], axis=0)clearance_radius = target_height * 0.10clearance_changes = 0scene.frame_start = 1scene.frame_end = len(pos)for f in range(len(pos)):2 unmodified linesfor bone in bones:name = bone.nameparent = bone.parent.name if bone.parent else Noneif parent:targets[name] = targets[parent] + np.array(rotations[parent]) @ (heads[name] - heads[parent])else:delta = pos[f, idx["Hips"]] - pos[0, idx["Hips"]]delta[:2] = 0targets[name] = heads[name] + delta * scaleif name == "Head" or name.endswith("Hand"):source_parent = "Neck1" if name == "Head" else name.replace("Hand", "ForeArm")relative = source_rotations[f, idx[source_parent]].T @ source_rotations[f, idx[name]]initial = source_rotations[0, idx[source_parent]].T @ source_rotations[0, idx[name]]delta_rotation = Matrix((relative @ initial.T).tolist())rotation = rotations[parent] @ delta_rotationelif name in tips and name in idx and tips[name] in idx:direction = rig.matrix_world.to_3x3().inverted() @ Vector(pos[f, idx[tips[name]]] - pos[f, idx[name]])if a.body_clearance and name.endswith(("Arm", "ForeArm")):rest_direction = heads[tips[name]] - heads[name]length = np.linalg.norm(rest_direction)unit = np.array(direction.normalized())end = targets[name] + unit * lengthpad = clearance_radiusif (body_low[1] - pad < end[1] < body_high[1] + padand body_low[2] - pad < end[2] < body_high[2] + pad):sign = 1 if name.startswith("Left") else -1bound = body_high[0] + pad if sign > 0 else body_low[0] - paddesired_x = (bound - targets[name][0]) / max(length, 1e-8)if unit[0] * sign < desired_x * sign:desired_x = float(np.clip(desired_x, -0.8, 0.8))yz = unit[1:] / max(np.linalg.norm(unit[1:]), 1e-8)direction = Vector((desired_x, *(yz * np.sqrt(1 - desired_x**2))))clearance_changes += 1if a.body_clearance and name.endswith(("Leg", "Shin")):length = np.linalg.norm(heads[tips[name]] - heads[name])unit = np.array(direction.normalized())endpoint = targets[name] + unit * lengthsign = 1 if name.startswith("Left") else -1hip_x = targets["Hips"][0]stance_x = hip_x + (heads[tips[name]][0] - heads["Hips"][0])if (endpoint[0] - stance_x) * sign < 0:desired_x = float(np.clip((stance_x - targets[name][0]) / max(length, 1e-8), -0.8, 0.8))yz = unit[1:] / max(np.linalg.norm(unit[1:]), 1e-8)direction = Vector((desired_x, *(yz * np.sqrt(1 - desired_x**2))))clearance_changes += 1rotation = ((Vector(heads[tips[name]] - heads[name])6 unmodified lineselse:rotation = rotations[parent] if parent else Matrix.Identity(3)rotations[name] = rotationmatrix = (rotation @ rest[name]).to_4x4()matrix.translation = Vector(targets[name])pb = rig.pose.bones[name]2 unmodified linesbpy.context.view_layer.update()for channel in ["location", "rotation_quaternion", "scale"]:pb.keyframe_insert(channel, frame=f + 1)# Preserve generated airborne phases while aligning source support contacts with the floor.foot_ids = {}for side, sign in [("Left", 1), ("Right", -1)]:foot_ids[side] = []for obj in meshes:points = np.array([tuple(obj.matrix_world @ vertex.co) for vertex in obj.data.vertices])foot_ids[side].append(np.where((points[:, 2] < 0.12) & (points[:, 0] * sign > 0))[0])foot_minima = []for frame in range(1, len(pos) + 1):scene.frame_set(frame)depsgraph = bpy.context.evaluated_depsgraph_get()pair = []for side in ["Left", "Right"]:values = []for obj, indices in zip(meshes, foot_ids[side]):evaluated = obj.evaluated_get(depsgraph)mesh = evaluated.to_mesh()values.extend((evaluated.matrix_world @ mesh.vertices[int(i)].co).z for i in indices)evaluated.to_mesh_clear()if not values:raise ValueError("Learned rig has no usable foot geometry for ground contact correction.")pair.append(min(values))foot_minima.append(pair)foot_minima = np.array(foot_minima)support = np.where(contacts, foot_minima, np.inf).min(axis=1)support_frames = np.where(np.isfinite(support))[0]if len(support_frames):correction = np.interp(np.arange(len(pos)), support_frames, -support[support_frames])else:correction = np.zeros(len(pos))correction = np.maximum(correction, -foot_minima.min(axis=1))base_z = rig.location.zfor frame, offset in enumerate(correction, 1):rig.location.z = base_z + float(offset)rig.keyframe_insert("location", frame=frame)rig.animation_data.action.name = "Generated_Motion"scene.frame_set(1)bpy.ops.object.select_all(action="DESELECT")21 unmodified lines"Self intersections require audit review",],"root_translation": "vertical only; in-place preview","ground_correction": correction.tolist(),"body_clearance_adjustments": clearance_changes,},indent=2,)
5 unmodified lines678910112 unmodified lines1415161718198 unmodified lines2829303132335 unmodified linesfrom pathlib import Pathimport bpyfrom mathutils.kdtree import KDTree2 unmodified linesparser.add_argument("--source", required=True)parser.add_argument("--rig", required=True)parser.add_argument("--output", required=True)args = parser.parse_args(sys.argv[sys.argv.index("--") + 1 :])bpy.ops.wm.read_factory_settings(use_empty=True)if Path(args.rig).suffix.lower() == ".fbx":8 unmodified linesfor bone in rig.pose.bones:bone.matrix_basis.identity()donors = [o for o in bpy.context.scene.objects if o.type == "MESH"]points = []weights = []for donor in donors:5 unmodified lines67891011122 unmodified lines151617181920218 unmodified lines30313233343536373839404142434445465 unmodified linesfrom pathlib import Pathimport bpyfrom mathutils import Matrixfrom mathutils.kdtree import KDTree2 unmodified linesparser.add_argument("--source", required=True)parser.add_argument("--rig", required=True)parser.add_argument("--output", required=True)parser.add_argument("--normalization")args = parser.parse_args(sys.argv[sys.argv.index("--") + 1 :])bpy.ops.wm.read_factory_settings(use_empty=True)if Path(args.rig).suffix.lower() == ".fbx":8 unmodified linesfor bone in rig.pose.bones:bone.matrix_basis.identity()donors = [o for o in bpy.context.scene.objects if o.type == "MESH"]if args.normalization:correction = json.loads(Path(args.normalization).read_text())donor_coords = [o.matrix_world @ v.co for o in donors for v in o.data.vertices]span = max(v.z for v in donor_coords) - min(v.z for v in donor_coords)scale = span / correction["normalized_height"]matrix = Matrix(correction["inverse_blender"]) @ Matrix.Diagonal((1 / scale, 1 / scale, 1 / scale, 1))worlds = {o: o.matrix_world.copy() for o in [rig, *donors]}rig.matrix_world = matrix @ worlds[rig]for obj in donors:obj.matrix_world = matrix @ worlds[obj]bpy.context.view_layer.update()points = []weights = []for donor in donors:
16 unmodified lines1718192021222340 unmodified lines64656667686969 unmodified lines13914014114214314412 unmodified lines15715815916016116216316416 unmodified linesraise RuntimeError(f"Animation stage failed ({result.returncode}): {tail}")def animate_character(rigged_glb, motion_npz, motion_bvh, output_dir):"""Retarget real Kimodo motion to a learned Mixamo rig; never substitutes a canned clip."""import numpy as np40 unmodified linesPath(motion_bvh).resolve(),"--output",out,],"retarget",)69 unmodified lines"animated_glb": str(glb),"video": str(video),"blend": str(out / "animation.blend"),"contact_sheet": str(out / "contact-sheet.jpg"),"contact_sheets": [str(out / "contact-sheet.jpg"), str(out / "side-contact-sheet.jpg")],"technical_pass": technical_pass,12 unmodified linessummary = audit["summary"]technical_pass = bool(summary["frames"] == framesand summary["peak_new_pairs"] == 0and summary["ground_min_z"] >= -1e-5and np.isfinite(tracks).all()and movement > 0.01)16 unmodified lines1718192021222340 unmodified lines6465666768697069 unmodified lines14014114214314414514612 unmodified lines15916016116216316416516616716816 unmodified linesraise RuntimeError(f"Animation stage failed ({result.returncode}): {tail}")def animate_character(rigged_glb, motion_npz, motion_bvh, output_dir, *, body_clearance=True):"""Retarget real Kimodo motion to a learned Mixamo rig; never substitutes a canned clip."""import numpy as np40 unmodified linesPath(motion_bvh).resolve(),"--output",out,*(["--body-clearance"] if body_clearance else []),],"retarget",)69 unmodified lines"animated_glb": str(glb),"video": str(video),"blend": str(out / "animation.blend"),"retargeting": str(out / "retargeting.json"),"contact_sheet": str(out / "contact-sheet.jpg"),"contact_sheets": [str(out / "contact-sheet.jpg"), str(out / "side-contact-sheet.jpg")],"technical_pass": technical_pass,12 unmodified linessummary = audit["summary"]technical_pass = bool(summary["frames"] == framesand len(tracks) == framesand summary["peak_new_pairs"] == 0and summary["ground_min_z"] >= -1e-5and summary.get("ground_min_all_vertices_z", summary["ground_min_z"]) >= -1e-5and np.isfinite(tracks).all()and movement > 0.01)
38 unmodified lines39404142434438 unmodified linesmodel_config = ConfigDict(extra="forbid")summary: str = Field(max_length=4000)parts: list[PartEdit] = Field(default_factory=list, max_length=32)remove_degenerate_faces: bool = Trueremove_duplicate_faces: bool = Trueunresolved: list[str] = Field(default_factory=list, max_length=32)38 unmodified lines39404142434445464738 unmodified linesmodel_config = ConfigDict(extra="forbid")summary: str = Field(max_length=4000)parts: list[PartEdit] = Field(default_factory=list, max_length=32)project_reference_texture: bool = Falsereference_front_axis: Literal["-Y", "+Y", "-X", "+X"] = "-Y"projection_strength: float = Field(default=0.9, ge=0, le=1)remove_degenerate_faces: bool = Trueremove_duplicate_faces: bool = Trueunresolved: list[str] = Field(default_factory=list, max_length=32)
17 unmodified lines1819202122232425264 unmodified lines3132333435363738394041424317 unmodified lines"""Load once at Space startup, before ZeroGPU forks its inference worker."""from kimodo.model import LLM2VecEncoderfrom kimodo.model.llm2vec.llm2vec import LLM2Vecfrom kimodo.model.loading import instantiate_from_dictfrom omegaconf import OmegaConffrom peft import PeftModelimport torchglobal _MODEL, _REVISIONS4 unmodified linesbase = json.loads((mntp / "adapter_config.json").read_text())["base_model_name_or_path"]# Transformers 5 no longer treats an adapter directory as base weights.# Merge MNTP into the base before attaching the supervised adapter.self.model = LLM2Vec.from_pretrained(base_model_name_or_path=base, peft_model_name_or_path=str(mntp),merge_peft=True, torch_dtype=torch.bfloat16,)self.model.model = PeftModel.from_pretrained(self.model.model, str(runtime / "kimodo-text/supervised"),)# LLM2Vec uses this canonical identity for Llama's instruction template.self.model.model.config._name_or_path = "meta-llama/Meta-Llama-3-8B-Instruct"self.llm_dim = 409617 unmodified lines18192021222324252627284 unmodified lines33343536373839404142434445464717 unmodified lines"""Load once at Space startup, before ZeroGPU forks its inference worker."""from kimodo.model import LLM2VecEncoderfrom kimodo.model.llm2vec.llm2vec import LLM2Vecfrom kimodo.model.llm2vec.models.bidirectional_llama import LlamaBiModelfrom kimodo.model.loading import instantiate_from_dictfrom omegaconf import OmegaConffrom peft import PeftModelfrom transformers import AutoTokenizerimport torchglobal _MODEL, _REVISIONS4 unmodified linesbase = json.loads((mntp / "adapter_config.json").read_text())["base_model_name_or_path"]# Transformers 5 no longer treats an adapter directory as base weights.# Merge MNTP into the base before attaching the supervised adapter.model = LlamaBiModel.from_pretrained(base, dtype=torch.bfloat16)model = PeftModel.from_pretrained(model, str(mntp), torch_device="cpu").merge_and_unload()model = PeftModel.from_pretrained(model, str(runtime / "kimodo-text/supervised"), torch_device="cpu",)tokenizer = AutoTokenizer.from_pretrained(base)tokenizer.pad_token = tokenizer.eos_tokentokenizer.padding_side = "left"self.model = LLM2Vec(model=model, tokenizer=tokenizer)# LLM2Vec uses this canonical identity for Llama's instruction template.self.model.model.config._name_or_path = "meta-llama/Meta-Llama-3-8B-Instruct"self.llm_dim = 4096
32 unmodified lines333435363738394041424344454632 unmodified linesmeshes, latents = pipeline.run(image, seed=seed, pipeline_type="1024_cascade", return_latent=True,sparse_structure_sampler_params={"steps": 12},shape_slat_sampler_params={"steps": 12}, tex_slat_sampler_params={"steps": 4})mesh = meshes[0]mesh.simplify(16777216)glb = o_voxel.postprocess.to_glb(vertices=mesh.vertices, faces=mesh.faces, attr_volume=mesh.attrs, coords=mesh.coords,attr_layout=pipeline.pbr_attr_layout, grid_size=latents[2],aabb=[[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]], decimation_target=50000,texture_size=512, remesh=True, remesh_band=1, remesh_project=0, use_tqdm=False)glb.export(output)return output32 unmodified lines333435363738394041424344454632 unmodified linesmeshes, latents = pipeline.run(image, seed=seed, pipeline_type="1024_cascade", return_latent=True,sparse_structure_sampler_params={"steps": 12},shape_slat_sampler_params={"steps": 12}, tex_slat_sampler_params={"steps": 12})mesh = meshes[0]mesh.simplify(16777216)glb = o_voxel.postprocess.to_glb(vertices=mesh.vertices, faces=mesh.faces, attr_volume=mesh.attrs, coords=mesh.coords,attr_layout=pipeline.pbr_attr_layout, grid_size=latents[2],aabb=[[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]], decimation_target=50000,texture_size=1024, remesh=True, remesh_band=1, remesh_project=0, use_tqdm=False)glb.export(output)return output
42 unmodified lines434445464748495051525354555642 unmodified linesimage.thumbnail((2048, 2048), Image.Resampling.LANCZOS)image.save(run.path / "input.png")if request.prompt and source_mesh is None:image = models.reference(image, request.prompt, request.seed)if image is None:raise ValueError("A reference image is required when continuing a source mesh")image.save(run.path / "reference.png")done("Reference image preserved" if source_mesh is not None or not request.promptelse "Conditioned reference generated")start("geometry", "Generating geometry with a 512px PBR atlas and four texture sampling steps")if source_mesh is None:models.geometry(image, request.seed, run.path / "source.glb")else:42 unmodified lines434445464748495051525354555657585960616242 unmodified linesimage.thumbnail((2048, 2048), Image.Resampling.LANCZOS)image.save(run.path / "input.png")if request.prompt and source_mesh is None:reference_prompt = request.promptif request.animation_prompt:reference_prompt += (". Prepare a complete upright humanoid character for rigging: ""front view, neutral relaxed A-pose, straight legs, both feet ""and hands visible, arms separated from torso, no props covering joints. ""Preserve the requested character identity and materials.")image = models.reference(image, reference_prompt, request.seed)if image is None:raise ValueError("A reference image is required when continuing a source mesh")image.save(run.path / "reference.png")done("Reference image preserved" if source_mesh is not None or not request.promptelse "Conditioned reference generated")start("geometry", "Generating geometry with a 1024px PBR atlas and twelve texture sampling steps")if source_mesh is None:models.geometry(image, request.seed, run.path / "source.glb")else:
62 unmodified lines636465666768691 unmodified line71727374757677787980815 unmodified lines87888990919228 unmodified lines12112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515662 unmodified linesreturn json.loads(text)def plan_with_fx(brief, parts, assessment, folder, images=()):skill = RUNTIME / "orc-skills/game-dev/game-model-cleanup"instructions = (skill / "SKILL.md").read_text() + "\n" + (skill / "WORKFLOW.md").read_text()prompt = f"""Apply the game-model-cleanup skill below to this asset. This application's contract replaces the1 unmodified lineInspect /work/parts.json, /work/assessment.txt, /work/schema.json and the cleanup skill using the virtualbash tool. Reference and before renders are attached. Return only a JSON repair plan matching the schema.Do not invent missing anatomy or features. All commands execute only in this run's in-memory filesystem.Only rename existing parts, remove duplicate/degenerate faces, and propose small PBR/color corrections.Color gains are multiplicative RGB gains, each between 0.75 and 1.25 inclusive, not target RGB colors.Use [1, 1, 1] to preserve the original color.Preserve UVs, normals, geometry identity, scale and all components. Put unsupported geometry reconstruction,seam repainting or rigging needs in unresolved. Empty edits are appropriate when evidence supports no change.Brief: {brief}Parts: {json.dumps(describe(parts))}Astra visual inspection: {assessment}5 unmodified lines"/work/assessment.txt": assessment,"/work/schema.json": json.dumps(Refinement.model_json_schema()),"/work/cleanup-skill.md": instructions}encoded_images = [image_data_url(p) for p in images]feedback = ""for attempt in range(1, 4):28 unmodified linesraise AssertionError("Unreachable refinement retry state")def refine(parts, brief, reference, folder):before = folder / "upscaled.glb"export(parts, before)before_views = render(before, folder / "before", components=True)assessment = vision("Inspect this generated asset against the brief. First image is its reference; second is ""a labeled contact sheet of the assembled asset and components. Identify only visible ""defects and name the affected part IDs. Preserve identity and texture channel meaning. "f"Brief: {brief}", [reference, before_views])(folder / "visual-review.txt").write_text(assessment)plan = plan_with_fx(brief, parts, assessment, folder, images=[reference, before_views])candidate = apply_refinement(parts, plan)export(candidate, folder / "candidate.glb")after_views = render(folder / "candidate.glb", folder / "after")verdict = json_object(vision("Compare before and after against the reference and brief. Image order: reference, before contact ""sheet with individual component previews, after assembled views. Judge only matched assembled views. ""Return JSON only with accept (boolean), quality_passed (boolean), unresolved (list of strings), ""and reason (string). Accept if the after asset has no visible regression in identity, silhouette, ""texture fidelity or materials. Independently set quality_passed only if the final asset is usable ""and faithful to the reference, with no material visible defects. A no-change or non-regressing result ""can still fail quality. Name remaining visible defects in unresolved. Do not reward change for its own sake. "f"Brief: {brief}", [reference, before_views, after_views]))if (type(verdict.get("accept")) is not bool or type(verdict.get("quality_passed")) is not boolor not isinstance(verdict.get("reason"), str)or not isinstance(verdict.get("unresolved"), list)or any(not isinstance(item, str) for item in verdict["unresolved"])):raise ValueError("Astra returned an invalid post-refinement verdict.")verdict["model"] = MODELverdict["unresolved"] = list(dict.fromkeys([*plan.unresolved, *verdict["unresolved"]]))verdict["quality_passed"] = verdict["accept"] and verdict["quality_passed"] and not verdict["unresolved"]verdict["source_retained"] = not verdict["accept"](folder / "verdict.json").write_text(json.dumps(verdict, indent=2))return (candidate if verdict["accept"] else parts), plan, verdict62 unmodified lines636465666768691 unmodified line7172737475767778798081828384858687885 unmodified lines94959697989910010110210310410510610710828 unmodified lines13713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224362 unmodified linesreturn json.loads(text)def plan_with_fx(brief, parts, assessment, folder, images=(), previous=None):skill = RUNTIME / "orc-skills/game-dev/game-model-cleanup"instructions = (skill / "SKILL.md").read_text() + "\n" + (skill / "WORKFLOW.md").read_text()prompt = f"""Apply the game-model-cleanup skill below to this asset. This application's contract replaces the1 unmodified lineInspect /work/parts.json, /work/assessment.txt, /work/schema.json and the cleanup skill using the virtualbash tool. Reference and before renders are attached. Return only a JSON repair plan matching the schema.Do not invent missing anatomy or features. All commands execute only in this run's in-memory filesystem.You may rename existing parts, remove duplicate/degenerate faces, propose small PBR/color corrections,and set project_reference_texture=true for evidence-supported reference texture transfer. This operatorprojects only visible foreground reference pixels, retains occluded/back-facing texels and all PBR channels,and never changes geometry or UVs. Use it for visible front texture mismatch when reference pose and modelsilhouette align. Do not use projection for different poses or to repair geometry. reference_front_axis isthe outward viewing direction AFTER Blender glTF import, with Z up; canonical front is -Y. It is NOT thesource glTF Y-up frame. Choose +Y/-X/+X only if the rendered orientation establishes that front.Use projection_strength between 0 and 1; 0.9 is appropriate for strong matching-reference correction.Color gains are multiplicative RGB gains, each between 0.75 and 1.25 inclusive, not target RGB colors.Use [1, 1, 1] to preserve the original color.Preserve UVs, normals, geometry identity, scale and all components. Put unsupported geometry reconstruction,unseen-surface repainting or rigging needs in unresolved. Do not mark supported projection as unsupported. Empty edits are appropriate when evidence supports no change.Brief: {brief}Parts: {json.dumps(describe(parts))}Astra visual inspection: {assessment}5 unmodified lines"/work/assessment.txt": assessment,"/work/schema.json": json.dumps(Refinement.model_json_schema()),"/work/cleanup-skill.md": instructions}if previous is not None:files["/work/previous-plan.json"] = json.dumps(previous["plan"])files["/work/previous-verdict.json"] = json.dumps(previous["verdict"])prompt += ("\nThis is a repair retry. Read /work/previous-plan.json and /work/previous-verdict.json. ""Image order is reference, immutable original views, previous rejected candidate views. ""The actual reviewer verdict explains the failure. Produce materially different supported ""edits that address it, not the same plan with rewritten prose. All edits start from the ""ORIGINAL parts, never cumulatively from the rejected candidate. If the defect requires ""unsupported reconstruction, preserve source and explain it in unresolved.")encoded_images = [image_data_url(p) for p in images]feedback = ""for attempt in range(1, 4):28 unmodified linesraise AssertionError("Unreachable refinement retry state")def review_candidate(brief, reference, before_views, after_views, plan):verdict = json_object(vision("Compare before and after against the reference and brief. Image order: reference, before contact ""sheet with individual component previews, after assembled views. Judge only matched assembled views. ""Return JSON only with accept (boolean), quality_passed (boolean), unresolved (list of strings), ""blocking_issues (list of strings), repairable_with_supported_tools (boolean), and reason (string). ""Accept if the after asset has no visible regression in identity, silhouette, texture fidelity or ""materials. Independently set quality_passed only if the final asset is usable and faithful to the ""reference, with no blocking defects: broken anatomy, major identity loss, obvious texture corruption ""or seams. Minor stylization differences may remain unresolved without blocking. Do not excuse visible ""bad textures. A no-change or non-regressing result can still fail quality. Name remaining defects. ""Supported repair tools are bounded per-part RGB gains, roughness/metallic adjustment, duplicate or ""degenerate face cleanup, and visibility-aware front reference texture projection. Set ""repairable_with_supported_tools=true only when a different supported plan could address the actual ""failure. Missing or broken anatomy, substantial geometry reconstruction, unseen texture repainting ""and different reference pose are NOT repairable with these tools. Do not reward changes for their own sake. "f"Applied plan: {plan.model_dump_json()} Brief: {brief}", [reference, before_views, after_views]))if (type(verdict.get("accept")) is not bool or type(verdict.get("quality_passed")) is not boolor type(verdict.get("repairable_with_supported_tools")) is not boolor not isinstance(verdict.get("reason"), str)or not isinstance(verdict.get("unresolved"), list)or any(not isinstance(item, str) for item in verdict["unresolved"])or not isinstance(verdict.get("blocking_issues"), list)or any(not isinstance(item, str) for item in verdict["blocking_issues"])):raise ValueError("Astra returned an invalid post-refinement verdict.")verdict["model"] = MODELverdict["unresolved"] = list(dict.fromkeys([*plan.unresolved, *verdict["unresolved"]]))verdict["quality_passed"] = verdict["accept"] and verdict["quality_passed"] and not verdict["blocking_issues"]verdict["source_retained"] = not verdict["quality_passed"]return verdictdef effective_edits(plan):data = plan.model_dump(exclude={"summary", "unresolved"})data["parts"] = sorted([{key: value for key, value in edit.items() if key != "name"}for edit in data["parts"]], key=lambda edit: edit["part_id"])if not data["project_reference_texture"]:data.pop("reference_front_axis")data.pop("projection_strength")return datadef refine(parts, brief, reference, folder):folder = Path(folder)folder.mkdir(parents=True, exist_ok=True)before = folder / "upscaled.glb"export(parts, before)before_views = render(before, folder / "before", components=True)assessment = vision("Inspect this generated asset against the brief. First image is its reference; second is ""a labeled contact sheet of the assembled asset and components. Identify only visible ""defects and name the affected part IDs. Preserve identity and texture channel meaning. "f"Brief: {brief}", [reference, before_views])(folder / "visual-review.txt").write_text(assessment)previous = Noneprevious_views = Noneprevious_edits = Noneselected_parts = partsselected_views = before_viewsselected_attempt = Nonefor number in range(1, 3):attempt = folder / f"repair-attempt-{number}"attempt.mkdir()images = [reference, before_views] + ([previous_views] if previous_views else [])plan = plan_with_fx(brief, parts, assessment, attempt, images=images, previous=previous)(attempt / "refinement.json").write_text(plan.model_dump_json(indent=2))edits = effective_edits(plan)if previous is not None and edits == previous_edits:verdict = dict(previous["verdict"], accept=False, quality_passed=False, source_retained=True,reason="The retry repeated the rejected edits; source retained for review.",stop_reason="identical_plan")(attempt / "verdict.json").write_text(json.dumps(verdict, indent=2))breakcandidate = apply_refinement(parts, plan)if plan.project_reference_texture:from .texture_repair import project_referencecandidate, projection = project_reference(candidate, reference, attempt / "texture-projection",front_axis=plan.reference_front_axis, strength=plan.projection_strength)(attempt / "texture-projection.json").write_text(json.dumps(projection, indent=2))export(candidate, attempt / "candidate.glb")after_views = render(attempt / "candidate.glb", attempt / "after")verdict = review_candidate(brief, reference, before_views, after_views, plan)(attempt / "verdict.json").write_text(json.dumps(verdict, indent=2))if verdict["quality_passed"]:selected_parts, selected_views, selected_attempt = candidate, after_views, numberbreakif not verdict["repairable_with_supported_tools"]:verdict["stop_reason"] = "unsupported_repairs"breakprevious = {"plan": plan.model_dump(), "verdict": verdict}previous_views, previous_edits = after_views, editsverdict = dict(verdict, attempts=number, selected_attempt=selected_attempt,status="accepted" if selected_attempt else "needs_review",candidate_accept=verdict["accept"], accept=selected_attempt is not None,source_retained=selected_attempt is None)if not selected_attempt:verdict["quality_passed"] = Falseverdict.setdefault("stop_reason", "repair_limit")(folder / "refinement.json").write_text(plan.model_dump_json(indent=2))(folder / "verdict.json").write_text(json.dumps(verdict, indent=2))export(selected_parts, folder / "candidate.glb")if selected_views.is_file():shutil.copytree(selected_views.parent, folder / "after", dirs_exist_ok=True)return selected_parts, plan, verdict
19 unmodified lines202122232425262728293031323334353637383940414243444546474849505152535455565758596012 unmodified lines737475767778798081826 unmodified lines8990919293949 unmodified lines10410510610710810915 unmodified lines12512612719 unmodified linesdef rig_character(mesh: Path, output_dir: Path, notify=None) -> RigResult:from gradio_client import Client, handle_filefrom huggingface_hub import get_tokenoutput_dir.mkdir(parents=True, exist_ok=True)space = os.environ.get("STUDIO_RIG_SPACE", "jasongzy/Make-It-Animatable-v2")client = Client(space,token=os.environ.get("HF_TOKEN") or get_token(),download_files=output_dir / "provider",verbose=False,)# Keep input rest geometry and world transforms. Do not use the demo's default run clip.job = client.submit(handle_file(str(mesh.resolve())),False,"No",[],False,0.01,True,True,True,"LeftArm",False,None,True,True,api_name="/pipeline",)receipt = {"provider": space,"endpoint": "/pipeline","source_sha256": digest(mesh),"started": time.time(),"status": "running","restore_global": True,"reset_to_rest": False,"animation_file": None,}12 unmodified lines# last concrete downloadable FBX among all yielded outputs.candidates = [results, *job.outputs()]fbx = Nonefor result in candidates:for value in result if isinstance(result, (tuple, list)) else [result]:if isinstance(value, str) and value.lower().endswith(".fbx") and Path(value).is_file():fbx = Path(value)if fbx is None:raise RuntimeError("Learned rig service did not return an FBX skin")source_fbx = output_dir / "learned-rig.fbx"6 unmodified linesraise RuntimeError("Blender is required to preserve production textures during rig transfer")rigged = output_dir / "rigged.glb"script = Path(__file__).resolve().parents[1] / "scripts/transfer_learned_rig.py"completed = subprocess.run([blender,9 unmodified linesstr(source_fbx.resolve()),"--output",str(rigged.resolve()),],capture_output=True,text=True,15 unmodified linesraisefinally:receipt_path.write_text(json.dumps(receipt, indent=2))19 unmodified lines20212223242526272829303132333435363738394041424344454647484950515212 unmodified lines65666768697071727374757677787980816 unmodified lines8889909192939495969798991009 unmodified lines11011111211311411511615 unmodified lines13213313413513613713813914014114214314414514614714814915015115215315415515615715815916019 unmodified linesdef rig_character(mesh: Path, output_dir: Path, notify=None) -> RigResult:from gradio_client import Client, handle_filefrom huggingface_hub import HfApi, get_tokenoutput_dir.mkdir(parents=True, exist_ok=True)space = os.environ.get("STUDIO_RIG_SPACE", "jasongzy/Make-It-Animatable")token = os.environ.get("HF_TOKEN") or get_token()revision = HfApi(token=token).space_info(space).shaclient = Client(space,token=token,download_files=output_dir / "provider",verbose=False,)endpoint = client.view_api(return_format="dict", print_info=False)["named_endpoints"]["/pipeline"]restore_global = any(p["label"] == "Restore Global Transform" for p in endpoint["parameters"])arguments = [handle_file(str(mesh.resolve())), False, "No", [], False, 0.01]if restore_global:arguments.append(True)arguments.extend([restore_global, True, "LeftArm", False, None, True, True])job = client.submit(*arguments, api_name="/pipeline")receipt = {"provider": space,"provider_revision": revision,"endpoint": "/pipeline","source_sha256": digest(mesh),"started": time.time(),"status": "running","restore_global": restore_global,"reset_to_rest": False,"animation_file": None,}12 unmodified lines# last concrete downloadable FBX among all yielded outputs.candidates = [results, *job.outputs()]fbx = Nonenormalized = Nonefor result in candidates:for value in result if isinstance(result, (tuple, list)) else [result]:if isinstance(value, dict):value = value.get("value", value.get("path"))if isinstance(value, dict):value = value.get("path")if isinstance(value, str) and value.lower().endswith(".fbx") and Path(value).is_file():fbx = Path(value)if isinstance(value, str) and Path(value).name == "normed.glb" and Path(value).is_file():normalized = Path(value)if fbx is None:raise RuntimeError("Learned rig service did not return an FBX skin")source_fbx = output_dir / "learned-rig.fbx"6 unmodified linesraise RuntimeError("Blender is required to preserve production textures during rig transfer")rigged = output_dir / "rigged.glb"script = Path(__file__).resolve().parents[1] / "scripts/transfer_learned_rig.py"normalization_args = []if not restore_global:if normalized is None:raise RuntimeError("Rig service omitted the normalization mesh needed to restore coordinates")normalization = output_dir / "normalization.json"normalization.write_text(json.dumps(recover_normalization(mesh, normalized), indent=2))normalization_args = ["--normalization", str(normalization.resolve())]completed = subprocess.run([blender,9 unmodified linesstr(source_fbx.resolve()),"--output",str(rigged.resolve()),*normalization_args,],capture_output=True,text=True,15 unmodified linesraisefinally:receipt_path.write_text(json.dumps(receipt, indent=2))def recover_normalization(source: Path, normalized: Path) -> dict:"""Recover the provider normalization using preserved indexed mesh topology."""import numpy as npimport trimeshoriginal = trimesh.load(source, force="mesh")canonical = trimesh.load(normalized, force="mesh")if original.vertices.shape != canonical.vertices.shape or not np.array_equal(original.faces, canonical.faces):raise RuntimeError("Rig normalization changed topology; cannot safely restore original coordinates")homogeneous = np.column_stack((original.vertices, np.ones(len(original.vertices))))transform = np.linalg.lstsq(homogeneous, canonical.vertices, rcond=None)[0]residual = float(np.max(np.linalg.norm(homogeneous @ transform - canonical.vertices, axis=1)))if residual > float(np.max(canonical.extents)) * 1e-5:raise RuntimeError("Rig normalization is not an affine transform of the production mesh")matrix = np.eye(4)matrix[:3] = transform.Tconversion = np.array([[1, 0, 0, 0], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])return {"inverse_blender": (conversion @ np.linalg.inv(matrix) @ np.linalg.inv(conversion)).tolist(),"normalized_height": float(np.ptp(canonical.vertices[:, 1])),"fit_residual": residual,}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374"""Reference projection changes only visible base-color texels on immutable source geometry."""import copyimport jsonfrom pathlib import Pathimport subprocess
import numpy as npfrom PIL import Image, ImageFilter
from .mesh import exportfrom .render import blender
ROOT = Path(__file__).resolve().parents[1]
def foreground(image): rgba = np.asarray(image.convert('RGBA')) if np.any(rgba[:, :, 3] < 250): mask = rgba[:, :, 3] > 240 method = 'reference alpha' else: rgb = rgba[:, :, :3].astype(float) border = np.concatenate([rgb[0], rgb[-1], rgb[:, 0], rgb[:, -1]]) background = np.median(border, axis=0) if np.percentile(np.linalg.norm(border - background, axis=1), 90) > 35: raise ValueError('Reference projection needs a transparent or uniform-background reference.') mask = np.linalg.norm(rgb - background, axis=2) > 28 method = 'uniform border background' yy, xx = np.where(mask) if len(xx) < 100: raise ValueError('Reference foreground is empty or too small for projection.') bounds = [int(xx.min()), int(yy.min()), int(xx.max()), int(yy.max())] # Avoid copying anti-aliased background pixels onto the silhouette. eroded = Image.fromarray(mask.astype(np.uint8) * 255).filter(ImageFilter.MinFilter(5)) return np.asarray(eroded) > 0, bounds, method
def project_reference(parts, reference, folder, *, front_axis='-Y', strength=0.9): if front_axis not in {'-Y', '+Y', '-X', '+X'} or not 0 <= strength <= 1: raise ValueError('Invalid reference projection parameters.') folder = Path(folder).resolve() folder.mkdir(parents=True, exist_ok=True) source = folder / 'source.glb' export(parts, source) with Image.open(reference) as image: rgba = np.asarray(image.convert('RGBA')) mask, bounds, mask_method = foreground(image) np.savez_compressed(folder / 'reference.npz', rgba=rgba, mask=mask, bounds=bounds) inputs = [] for index, (key, mesh) in enumerate(parts): texture = np.asarray(mesh.visual.material.baseColorTexture.convert('RGBA')) filename = f'base-{index:03d}.npy' np.save(folder / filename, texture) inputs.append({'part_id': key, 'file': filename}) (folder / 'inputs.json').write_text(json.dumps(inputs)) command = [blender(), '--background', '--factory-startup', '--python-exit-code', '1', '--python', str(ROOT / 'scripts/project_reference_texture.py'), '--', '--folder', str(folder), '--front-axis=' + front_axis, '--strength', str(strength)] with (folder / 'projection.log').open('w') as log: subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=True, timeout=600) metrics = json.loads((folder / 'projection.json').read_text()) metrics['foreground_method'] = mask_method candidate = [] for (key, mesh), item in zip(parts, inputs, strict=True): result = mesh.copy(include_cache=True) result.visual.material = copy.deepcopy(mesh.visual.material) image = np.load(folder / ('projected-' + item['file'])) if image.shape != np.asarray(mesh.visual.material.baseColorTexture.convert('RGBA')).shape: raise ValueError('Projection changed texture dimensions.') result.visual.material.baseColorTexture = Image.fromarray(image) candidate.append((key, result)) export(candidate, folder / 'candidate.glb') (folder / 'projection.json').write_text(json.dumps(metrics, indent=2)) return candidate, metricsREADME.md+30-18
app.py+1-1
scripts/audit_character_collisions.py+38
scripts/project_reference_texture.pyAdded+130
scripts/retarget_character.py+142-14
scripts/transfer_learned_rig.py+13
studio/animation.py+5-1
studio/contracts.py+3
studio/motion.py+10-6
studio/native.py+2-2
studio/pipeline.py+8-2
studio/refine.py+112-25
studio/rigging.py+55-22
studio/texture_repair.pyAdded+74