agent-manifesto-kit 1.1.2 → 1.3.0

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.
Files changed (33) hide show
  1. package/README.md +70 -3
  2. package/collection/bundles/blender-3d/README.md +41 -0
  3. package/collection/bundles/blender-3d/agents/visual-reviewer.md +51 -0
  4. package/collection/bundles/blender-3d/skills/blender-mocap-retarget/SKILL.md +96 -0
  5. package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/check_motion.py +162 -0
  6. package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/export_gltf_clip.py +71 -0
  7. package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/godot_verify.py +87 -0
  8. package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/inspect_motion_source.py +107 -0
  9. package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/render_frames.py +117 -0
  10. package/collection/bundles/blender-3d/skills/blender-mocap-retarget/scripts/verify_gltf.py +44 -0
  11. package/collection/bundles/blender-3d/skills/blender-reference-model/SKILL.md +83 -0
  12. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/colors.py +50 -0
  13. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/compare.py +77 -0
  14. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/contact_sheet.py +51 -0
  15. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/diff_renders.py +58 -0
  16. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/edges.py +54 -0
  17. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/measure_ref.py +137 -0
  18. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/mesh_report.py +67 -0
  19. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/refspec.py +91 -0
  20. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/render_views.py +99 -0
  21. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/zoom.py +47 -0
  22. package/collection/bundles/kit-adopt/README.md +1 -1
  23. package/collection/bundles/kit-adopt/skills/kit-adopt/SKILL.md +2 -2
  24. package/dist/agent-format.js +218 -0
  25. package/dist/catalog.js +13 -13
  26. package/dist/cli.js +62 -5
  27. package/dist/commands/adopt.js +13 -3
  28. package/dist/commands/ingest.js +120 -0
  29. package/dist/commands/list.js +54 -6
  30. package/dist/commands/sync.js +201 -0
  31. package/dist/portability.js +19 -2
  32. package/dist/providers.js +12 -2
  33. package/package.json +1 -1
@@ -0,0 +1,107 @@
1
+ """Inspect a motion source (FBX or glTF) before designing a retarget.
2
+
3
+ blender -b --factory-startup --python inspect_motion_source.py -- source.fbx [--json out.json]
4
+
5
+ Reports the skeleton (bone count, roots, finger bones), armature object scale, frame range and
6
+ fps, rest-pose arm angle (T- or A-pose), root motion of the hips over the clip, per-foot lowest
7
+ height relative to the rest pose, and the loop seam: how far the last frame's pose is from the
8
+ first, ignoring root translation. Works in an empty scene; nothing is saved.
9
+ """
10
+ import argparse
11
+ import json
12
+ import math
13
+ import sys
14
+
15
+ import bpy
16
+
17
+ argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
18
+ p = argparse.ArgumentParser()
19
+ p.add_argument("source")
20
+ p.add_argument("--json")
21
+ args = p.parse_args(argv)
22
+
23
+ bpy.ops.wm.read_factory_settings(use_empty=True)
24
+ if args.source.lower().endswith(".fbx"):
25
+ bpy.ops.import_scene.fbx(filepath=args.source, use_anim=True)
26
+ else:
27
+ bpy.ops.import_scene.gltf(filepath=args.source)
28
+ scene = bpy.context.scene
29
+ arms = [o for o in scene.objects if o.type == "ARMATURE"]
30
+ if not arms:
31
+ raise SystemExit("no armature in source")
32
+ arm = max(arms, key=lambda a: len(a.data.bones))
33
+ act = arm.animation_data.action if arm.animation_data else None
34
+ if act is None:
35
+ raise SystemExit(f"armature {arm.name} has no action")
36
+ f0, f1 = (int(round(v)) for v in act.frame_range)
37
+ names = [b.name for b in arm.data.bones]
38
+
39
+
40
+ def find(*keys, exclude=()):
41
+ for n in names:
42
+ low = n.lower()
43
+ if all(k in low for k in keys) and not any(x in low for x in exclude):
44
+ return n
45
+ return None
46
+
47
+
48
+ hips = find("hips") or next(b.name for b in arm.data.bones if b.parent is None)
49
+ feet = {side: find(side, "foot") for side in ("left", "right")}
50
+ upper_arm = find("left", "arm", exclude=("fore", "shoulder", "hand"))
51
+ fingers = [n for n in names if any(k in n.lower() for k in ("index", "middle", "ring", "pinky", "thumb"))]
52
+ mw = arm.matrix_world
53
+
54
+
55
+ def head(bone, frame=None):
56
+ if frame is None:
57
+ return mw @ arm.data.bones[bone].head_local
58
+ scene.frame_set(frame)
59
+ return mw @ arm.pose.bones[bone].head
60
+
61
+
62
+ rest_pose = None
63
+ if upper_arm:
64
+ b = arm.data.bones[upper_arm]
65
+ d = (mw.to_3x3() @ (b.tail_local - b.head_local)).normalized()
66
+ rest_pose = round(math.degrees(math.asin(max(-1.0, min(1.0, -d.z)))), 1)
67
+
68
+ report = {
69
+ "armature": arm.name,
70
+ "object_scale": [round(s, 4) for s in arm.scale],
71
+ "bones": len(names),
72
+ "roots": [b.name for b in arm.data.bones if b.parent is None],
73
+ "finger_bones": len(fingers),
74
+ "fps": scene.render.fps / scene.render.fps_base,
75
+ "frame_range": [f0, f1],
76
+ "hips": hips,
77
+ "upper_arm_below_horizontal_deg": rest_pose,
78
+ }
79
+ h0, h1 = head(hips, f0), head(hips, f1)
80
+ report["hips_root_motion_m"] = [round(v, 4) for v in (h1 - h0)]
81
+ report["hips_height_rest_m"] = round(head(hips).z, 4)
82
+ report["hips_height_range_m"] = [round(min(head(hips, f).z for f in range(f0, f1 + 1)), 4),
83
+ round(max(head(hips, f).z for f in range(f0, f1 + 1)), 4)]
84
+ report["feet"] = {}
85
+ for side, foot in feet.items():
86
+ if foot:
87
+ zs = [(head(foot, f).z, f) for f in range(f0, f1 + 1)]
88
+ low, frame = min(zs)
89
+ report["feet"][foot] = {"rest_z": round(head(foot).z, 4), "lowest_z": round(low, 4),
90
+ "lowest_minus_rest_m": round(low - head(foot).z, 4), "lowest_frame": frame}
91
+
92
+
93
+ def pose_rotations(frame):
94
+ scene.frame_set(frame)
95
+ return {pb.name: pb.matrix_basis.to_quaternion() for pb in arm.pose.bones}
96
+
97
+
98
+ a, b = pose_rotations(f0), pose_rotations(f1)
99
+ worst = max(a, key=lambda n: a[n].rotation_difference(b[n]).angle)
100
+ report["loop_seam"] = {"max_rotation_diff_deg": round(math.degrees(a[worst].rotation_difference(b[worst]).angle), 3),
101
+ "worst_bone": worst,
102
+ "note": "near 0 with nonzero root motion means the last frame repeats the first plus one stride"}
103
+
104
+ print(json.dumps(report, indent=2))
105
+ if args.json:
106
+ with open(args.json, "w") as f:
107
+ json.dump(report, f, indent=2)
@@ -0,0 +1,117 @@
1
+ """Render animation frames from several angles with cameras that follow the character.
2
+
3
+ blender -b model.blend --python render_frames.py -- OUTDIR --rig Armature \
4
+ [--views front,side,q34,back,feet] [--frames all|1,5,9|1-41:4] [--res 520] [--follow Hips]
5
+
6
+ A checker floor makes foot sliding visible; cameras track the --follow bone horizontally so root
7
+ motion stays in frame. Writes OUTDIR/<view>_<frame>.png; tile them with contact_sheet.py from the
8
+ sibling skill (../blender-reference-model/scripts/ relative to this skill's folder). Never saves the .blend.
9
+ Views: front, back, side (character's right), left, q34, q34b, feet, hipL, hipR, shoulderL, shoulderR.
10
+ """
11
+ import argparse
12
+ import math
13
+ import os
14
+ import sys
15
+
16
+ import bpy
17
+ from mathutils import Vector
18
+
19
+ argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
20
+ p = argparse.ArgumentParser()
21
+ p.add_argument("outdir")
22
+ p.add_argument("--rig", required=True)
23
+ p.add_argument("--views", default="front,side,q34")
24
+ p.add_argument("--frames", default="all")
25
+ p.add_argument("--res", type=int, default=520)
26
+ p.add_argument("--follow", default="Hips", help="bone whose ground position the cameras track")
27
+ p.add_argument("--height", type=float, default=1.8, help="character height, scales camera distances")
28
+ args = p.parse_args(argv)
29
+
30
+ scene = bpy.context.scene
31
+ rig = bpy.data.objects.get(args.rig)
32
+ if rig is None or args.follow not in rig.pose.bones:
33
+ raise SystemExit(f"need armature {args.rig} with bone {args.follow}")
34
+ if args.frames == "all":
35
+ frames = list(range(scene.frame_start, scene.frame_end + 1))
36
+ elif "-" in args.frames:
37
+ span, _, step = args.frames.partition(":")
38
+ a, b = (int(x) for x in span.split("-"))
39
+ frames = list(range(a, b + 1, int(step or 1)))
40
+ else:
41
+ frames = [int(x) for x in args.frames.split(",")]
42
+ os.makedirs(args.outdir, exist_ok=True)
43
+
44
+ k = args.height / 1.8
45
+ # view: (camera offset from the tracked ground point, look-at offset, ortho scale or None, lens)
46
+ SETUPS = {
47
+ "front": ((0, -6, 0.95), (0, 0, 0.95), 2.2, None),
48
+ "back": ((0, 6, 0.95), (0, 0, 0.95), 2.2, None),
49
+ "side": ((-6, 0, 0.95), (0, 0, 0.95), 2.2, None),
50
+ "left": ((6, 0, 0.95), (0, 0, 0.95), 2.2, None),
51
+ "q34": ((2.4, -3.6, 1.5), (0, 0, 0.9), None, 45),
52
+ "q34b": ((-2.6, 3.4, 1.5), (0, 0, 0.9), None, 45),
53
+ "feet": ((1.4, -2.0, 0.6), (0, 0, 0.18), None, 45),
54
+ "hipL": ((1.3, -0.9, 1.05), (0.25, 0, 0.85), None, 40),
55
+ "hipR": ((-1.3, -0.9, 1.05), (-0.25, 0, 0.85), None, 40),
56
+ "shoulderL": ((1.2, -1.2, 1.55), (0.3, 0, 1.2), None, 40),
57
+ "shoulderR": ((-1.2, -1.2, 1.55), (-0.3, 0, 1.2), None, 40),
58
+ }
59
+ views = args.views.split(",")
60
+ unknown = [v for v in views if v not in SETUPS]
61
+ if unknown:
62
+ raise SystemExit(f"unknown views {unknown}; choose from {sorted(SETUPS)}")
63
+
64
+ engines = {i.identifier for i in scene.render.bl_rna.properties["engine"].enum_items}
65
+ scene.render.engine = next(e for e in ("BLENDER_EEVEE", "BLENDER_EEVEE_NEXT", "BLENDER_WORKBENCH") if e in engines)
66
+ scene.render.film_transparent = False
67
+ scene.view_settings.view_transform = "Standard"
68
+ world = bpy.data.worlds.new("FramesWorld")
69
+ scene.world = world
70
+ world.use_nodes = True
71
+ world.node_tree.nodes["Background"].inputs["Color"].default_value = (0.16, 0.16, 0.16, 1)
72
+ for name, rot, energy in (("FramesKey", (50, 0, -30), 3.0), ("FramesFill", (70, 0, 150), 0.8)):
73
+ light = bpy.data.lights.new(name, "SUN")
74
+ light.energy = energy
75
+ ob = bpy.data.objects.new(name, light)
76
+ ob.rotation_euler = [math.radians(a) for a in rot]
77
+ scene.collection.objects.link(ob)
78
+
79
+ mesh = bpy.data.meshes.new("FramesFloor")
80
+ size = 20.0
81
+ mesh.from_pydata([(-size, -size, 0), (size, -size, 0), (size, size, 0), (-size, size, 0)], [], [(0, 1, 2, 3)])
82
+ floor = bpy.data.objects.new("FramesFloor", mesh)
83
+ scene.collection.objects.link(floor)
84
+ mat = bpy.data.materials.new("FramesChecker")
85
+ mat.use_nodes = True
86
+ nodes = mat.node_tree.nodes
87
+ checker = nodes.new("ShaderNodeTexChecker")
88
+ checker.inputs["Scale"].default_value = 2 # object coords: 0.5 m tiles
89
+ checker.inputs["Color1"].default_value = (0.42, 0.42, 0.42, 1)
90
+ checker.inputs["Color2"].default_value = (0.36, 0.36, 0.36, 1)
91
+ coords = nodes.new("ShaderNodeTexCoord")
92
+ mat.node_tree.links.new(coords.outputs["Object"], checker.inputs["Vector"])
93
+ mat.node_tree.links.new(checker.outputs["Color"], nodes["Principled BSDF"].inputs["Base Color"])
94
+ mesh.materials.append(mat)
95
+
96
+ cam_data = bpy.data.cameras.new("FramesCam")
97
+ cam = bpy.data.objects.new("FramesCam", cam_data)
98
+ scene.collection.objects.link(cam)
99
+ scene.camera = cam
100
+
101
+ for view in views:
102
+ offset, target, ortho, lens = SETUPS[view]
103
+ for frame in frames:
104
+ scene.frame_set(frame)
105
+ hp = rig.matrix_world @ rig.pose.bones[args.follow].head
106
+ base = Vector((hp.x, hp.y, 0))
107
+ cam.location = base + Vector(offset) * k
108
+ cam.rotation_euler = ((base + Vector(target) * k) - cam.location).to_track_quat("-Z", "Y").to_euler()
109
+ if ortho:
110
+ cam_data.type, cam_data.ortho_scale = "ORTHO", ortho * k
111
+ scene.render.resolution_x, scene.render.resolution_y = int(args.res * 0.8), args.res
112
+ else:
113
+ cam_data.type, cam_data.lens = "PERSP", lens
114
+ scene.render.resolution_x = scene.render.resolution_y = args.res
115
+ scene.render.filepath = os.path.join(args.outdir, f"{view}_{frame:03d}.png")
116
+ bpy.ops.render.render(write_still=True)
117
+ print(f"RENDERED {len(views) * len(frames)} frame(s) -> {args.outdir}")
@@ -0,0 +1,44 @@
1
+ """Re-import an exported glTF/GLB into an empty scene and report what actually arrived.
2
+
3
+ blender -b --factory-startup --python verify_gltf.py -- OUT.glb [--expect-clips Walk,Run] [--fps 30]
4
+
5
+ Reports meshes, skinned meshes, armatures, bone count, and each imported clip with its frame
6
+ range and duration. Exits non-zero when an expected clip is missing or a clip does not start at
7
+ frame 0 (a sign the export offset was wrong). Blender may suffix imported action names with the
8
+ object name, so clips match by prefix.
9
+ """
10
+ import argparse
11
+ import sys
12
+
13
+ import bpy
14
+
15
+ argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
16
+ p = argparse.ArgumentParser()
17
+ p.add_argument("path")
18
+ p.add_argument("--expect-clips", default="")
19
+ p.add_argument("--fps", type=float, default=30.0)
20
+ args = p.parse_args(argv)
21
+
22
+ bpy.ops.wm.read_factory_settings(use_empty=True)
23
+ bpy.context.scene.render.fps = int(args.fps)
24
+ bpy.ops.import_scene.gltf(filepath=args.path)
25
+ objects = bpy.context.scene.objects
26
+ meshes = [o for o in objects if o.type == "MESH"]
27
+ skinned = [o for o in meshes if any(m.type == "ARMATURE" for m in o.modifiers)]
28
+ arms = [o for o in objects if o.type == "ARMATURE"]
29
+ print(f"MESHES {len(meshes)} (skinned {len(skinned)}) ARMATURES {len(arms)} BONES {sum(len(a.data.bones) for a in arms)}")
30
+
31
+ problems = []
32
+ clips = {}
33
+ for act in bpy.data.actions:
34
+ f0, f1 = act.frame_range
35
+ clips[act.name] = (f0, f1)
36
+ print(f"CLIP {act.name}: frames {f0:g}-{f1:g} duration {(f1 - f0) / args.fps:.3f} s")
37
+ if abs(f0) > 1e-3:
38
+ problems.append(f"clip {act.name} starts at frame {f0:g}, not 0")
39
+ for want in filter(None, args.expect_clips.split(",")):
40
+ if not any(name == want or name.startswith(want + "_") or name.startswith(want + ".") for name in clips):
41
+ problems.append(f"expected clip {want} not found (have {sorted(clips)})")
42
+ for problem in problems:
43
+ print("PROBLEM", problem)
44
+ sys.exit(1 if problems else 0)
@@ -0,0 +1,83 @@
1
+ ---
2
+ name: blender-reference-model
3
+ description: Build or revise a game-ready low-poly Blender model that must match a supplied reference image (turnaround or orthographic views) as closely as possible. Use for scripted Blender modeling from a reference sheet; not for rigging or animation, and not for free concept design.
4
+ ---
5
+
6
+ # Blender Reference Model
7
+
8
+ ## Outcome
9
+
10
+ An editable `.blend` produced entirely by a saved Blender Python builder, whose renders match the
11
+ reference in every supplied view, with modular parts as separate objects, clean meshes and a
12
+ validated export. The reference is authoritative, except where the user explicitly asks for a
13
+ deviation (for example a different colour or hand pose); a requested deviation is not a defect.
14
+
15
+ ## Invariants
16
+
17
+ - Build through a persisted Python builder run with `blender -b`; no unrecorded manual edits.
18
+ Rebuilding must reproduce the model. If the user edits the `.blend` by hand, that file becomes
19
+ authoritative: never rebuild over it; build into a new file and reconcile.
20
+ - Units are metres, Z up, character facing -Y, character's left on +X, origin on the ground.
21
+ - Each removable or separately animated part (clothing, boots, belt, pouches, props, hair) is its
22
+ own object, named for its role, with a deliberate origin (attachment point or joint).
23
+ - Measure before modeling. Take proportions from the reference in pixels, not from generic anatomy.
24
+ - Silhouette overlap is a floor, not the target. It cannot see faces, hands, colours or details
25
+ inside the outline. Those need magnified side-by-side inspection.
26
+ - Keep machine paths (Blender and engine executables) in the project's own instructions, not in
27
+ builders.
28
+
29
+ ## Tools
30
+
31
+ Scripts in this skill's `scripts/` folder. Image scripts run with system Python 3 plus Pillow and
32
+ numpy. Blender's bundled Python has neither, so run them outside Blender.
33
+
34
+ | Script | Purpose |
35
+ | --- | --- |
36
+ | `measure_ref.py` | Draft `ref_spec.json` (view crops, cameras, ground row, metres per pixel) and print a view's silhouette profile in metres |
37
+ | `render_views.py` | Blender: orthographic renders at the reference's pixel scale, transparent background, armatures in rest pose |
38
+ | `compare.py` | IoU per view, red/blue overlay sheet, height difference; writes `compare.png` and `compare.json` |
39
+ | `edges.py` | Row-by-row edge differences in mm for one view: turns the overlay into concrete corrections |
40
+ | `zoom.py` | Magnified reference and render side by side for one region (face, hands, belt, boots) |
41
+ | `colors.py` | Sampled colour ratios between the reference and the render |
42
+ | `diff_renders.py` | Pixel diff of two render folders, e.g. before and after rigging; exits non-zero on change |
43
+ | `contact_sheet.py` | Tile renders into one image for review |
44
+ | `mesh_report.py` | Blender: per-object triangles, non-manifold edges, degenerate faces, loose vertices, empty slots |
45
+
46
+ `refspec.py` documents the spec format. Drafted view names and cameras are guesses: confirm them
47
+ against the sheet's labels before building.
48
+
49
+ ## Method That Works
50
+
51
+ 1. Draft and confirm the spec. Set `meters_per_px` from the intended height.
52
+ 2. Print silhouette profiles for each view and build primary forms from those numbers.
53
+ 3. Render, compare, and correct from `edges.py` output. Repeat until each view reaches roughly
54
+ 0.94 IoU or better, and the remaining red/blue areas are explained (reference perspective,
55
+ stylization, requested deviations) rather than ignored.
56
+ 4. Inspect zoom crops of the head, hands, torso, belt and boots in every view. Fix identity
57
+ features (hairline, beard boundary, facial planes) even when the IoU is already high.
58
+ 5. Calibrate colours with `colors.py`, except colours the user asked to change.
59
+ 6. Render angles the reference does not show (3/4 front and back, low, close-ups) and fix
60
+ poke-through, floating parts and hollow backs.
61
+ 7. Run `mesh_report.py`, export, and re-import or engine-import the export to confirm it arrives.
62
+ 8. Before handing over, have the `visual-reviewer` agent review the comparison sheet, the zoom
63
+ crops and the extra-angle renders, then fix major findings. If the reviewer cannot run or
64
+ cannot view images in the current tool, say so in the evidence instead of skipping silently.
65
+
66
+ ## Known Pitfalls
67
+
68
+ - A flat plate placed on a lofted, curved surface gets swallowed by the bulge. Make pockets,
69
+ flaps and patches follow the surface.
70
+ - Colours sampled from the reference are display (sRGB) values, and Blender's Base Color is
71
+ linear: convert before use. Lighting then shifts the rendered value either way, so treat the
72
+ first material colours as a starting point and iterate until `colors.py` ratios are close
73
+ to 1. Render with the Standard view transform; Filmic/AgX shifts colours.
74
+ - AI-generated turnaround sheets often disagree slightly between views (head height, prop side).
75
+ Match the priority the user set, and report the conflict instead of averaging silently.
76
+ - A rigged model renders in its animated pose unless the armature is set to rest.
77
+ `render_views.py` does this by default.
78
+
79
+ ## Evidence To Report
80
+
81
+ The final `compare.png` with per-view IoU, the zoom crops, the extra-angle renders, the mesh
82
+ report totals, the export check, the review findings with their resolution, and any remaining
83
+ known differences from the reference.
@@ -0,0 +1,50 @@
1
+ """Compare sampled colours between the reference and the renders.
2
+
3
+ python3 colors.py ref_spec.json RENDERDIR points.json
4
+
5
+ points.json maps a label to [view, x, y] in reference image pixels, for example
6
+ {"skin_cheek": ["front", 278, 85], "trousers": ["front", 260, 330]}
7
+ Each sample averages a 5x5 patch. ratio = reference / render per channel: values above 1 mean the
8
+ render is too dark. Reference samples are display (sRGB) values while Blender's Base Color is
9
+ linear, so convert before use, then adjust until the ratios are close to 1.
10
+ """
11
+ import argparse
12
+ import json
13
+ import os
14
+ import sys
15
+
16
+ import numpy as np
17
+ from PIL import Image
18
+
19
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
20
+ from refspec import background_colour, composite, load_reference, load_spec # noqa: E402
21
+
22
+
23
+ def main():
24
+ p = argparse.ArgumentParser()
25
+ p.add_argument("spec")
26
+ p.add_argument("render_dir")
27
+ p.add_argument("points")
28
+ args = p.parse_args()
29
+ spec = load_spec(args.spec)
30
+ _, arr = load_reference(spec)
31
+ bg = background_colour(arr)
32
+ with open(args.points) as f:
33
+ points = json.load(f)
34
+ renders = {}
35
+ print(f"{'label':16s} {'reference':>15s} {'render':>15s} ratio")
36
+ for label, (view, x, y) in points.items():
37
+ cx0, cy0, cx1, cy1 = spec["views"][view]["crop"]
38
+ if view not in renders:
39
+ img = composite(Image.open(os.path.join(args.render_dir, f"{view}.png")).convert("RGBA"), bg)
40
+ renders[view] = (np.asarray(img).astype(float), img.size[0] / (cx1 - cx0), img.size[1] / (cy1 - cy0))
41
+ ren, sx, sy = renders[view]
42
+ rx, ry = round((x - cx0) * sx), round((y - cy0) * sy)
43
+ a = arr[y - 2:y + 3, x - 2:x + 3].reshape(-1, 3).mean(0)
44
+ b = ren[max(ry - 2, 0):ry + 3, max(rx - 2, 0):rx + 3].reshape(-1, 3).mean(0)
45
+ ratio = np.round(a / np.maximum(b, 1), 2)
46
+ print(f"{label:16s} {str(a.astype(int).tolist()):>15s} {str(b.astype(int).tolist()):>15s} {ratio.tolist()}")
47
+
48
+
49
+ if __name__ == "__main__":
50
+ main()
@@ -0,0 +1,77 @@
1
+ """Silhouette overlap and comparison sheet: reference vs render_views.py output.
2
+
3
+ python3 compare.py ref_spec.json RENDERDIR [--out RENDERDIR/compare.png] [--json RENDERDIR/compare.json]
4
+
5
+ Sheet rows: reference crop, render on the reference background, overlay
6
+ (grey = both, red = reference only / missing in model, blue = model only / extra).
7
+ IoU (intersection over union) is 1.0 for identical silhouettes. It says nothing about details
8
+ inside the outline; inspect zoom crops for those.
9
+ """
10
+ import argparse
11
+ import json
12
+ import os
13
+ import sys
14
+
15
+ import numpy as np
16
+ from PIL import Image, ImageDraw
17
+
18
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
19
+ from refspec import background_colour, composite, load_reference, load_spec, reference_mask, render_image, render_mask # noqa: E402
20
+
21
+
22
+ def main():
23
+ p = argparse.ArgumentParser()
24
+ p.add_argument("spec")
25
+ p.add_argument("render_dir")
26
+ p.add_argument("--out")
27
+ p.add_argument("--json")
28
+ args = p.parse_args()
29
+ spec = load_spec(args.spec)
30
+ ref, arr = load_reference(spec)
31
+ bg = background_colour(arr)
32
+ mpp = spec["meters_per_px"]
33
+
34
+ columns, report = [], {}
35
+ for name, view in spec["views"].items():
36
+ x0, y0, x1, y1 = view["crop"]
37
+ crop = ref.crop((x0, y0, x1, y1))
38
+ rm = reference_mask(spec, arr, name)
39
+ img = render_image(args.render_dir, name, crop.size)
40
+ mm = render_mask(img)
41
+ inter, union = int((rm & mm).sum()), int((rm | mm).sum())
42
+ ref_rows, ren_rows = np.flatnonzero(rm.any(1)), np.flatnonzero(mm.any(1))
43
+ height_diff_mm = None
44
+ if ref_rows.size and ren_rows.size:
45
+ height_diff_mm = round(((ren_rows[-1] - ren_rows[0]) - (ref_rows[-1] - ref_rows[0])) * mpp * 1000, 1)
46
+ report[name] = {
47
+ "iou": round(inter / max(union, 1), 4),
48
+ "ref_only_px": int((rm & ~mm).sum()),
49
+ "render_only_px": int((mm & ~rm).sum()),
50
+ "height_diff_mm": height_diff_mm,
51
+ }
52
+ overlay = np.full(rm.shape + (3,), 40, np.uint8)
53
+ overlay[rm & mm] = (200, 200, 200)
54
+ overlay[rm & ~mm] = (230, 60, 60)
55
+ overlay[mm & ~rm] = (60, 170, 240)
56
+ columns.append((crop, composite(img, bg), Image.fromarray(overlay)))
57
+
58
+ h = max(c[0].size[1] for c in columns)
59
+ sheet = Image.new("RGB", (sum(c[0].size[0] for c in columns), h * 3 + 24), (30, 30, 30))
60
+ x = 0
61
+ for col in columns:
62
+ for i, im in enumerate(col):
63
+ sheet.paste(im, (x, i * h))
64
+ x += col[0].size[0]
65
+ summary = " | ".join(f"{n} IoU={r['iou']:.3f} ref_only={r['ref_only_px']} extra={r['render_only_px']}" for n, r in report.items())
66
+ ImageDraw.Draw(sheet).text((5, h * 3 + 6), summary, fill=(255, 255, 255))
67
+ out = args.out or os.path.join(args.render_dir, "compare.png")
68
+ sheet.save(out)
69
+ with open(args.json or os.path.join(args.render_dir, "compare.json"), "w") as f:
70
+ json.dump(report, f, indent=2)
71
+ for n, r in report.items():
72
+ print(f"{n:8s} IoU {r['iou']:.3f} ref_only {r['ref_only_px']:6d} extra {r['render_only_px']:6d} height diff {r['height_diff_mm']} mm")
73
+ print(f"sheet: {out}")
74
+
75
+
76
+ if __name__ == "__main__":
77
+ main()
@@ -0,0 +1,51 @@
1
+ """Tile rendered images into one labelled contact sheet (one row per prefix).
2
+
3
+ python3 contact_sheet.py FRAMEDIR front,side,q34 --out sheet.png [--every 2] [--max-width 1600]
4
+
5
+ Expects files named <prefix>_<label>.png (for example front_012.png). Rows that are wider than
6
+ --max-width are scaled down so the sheet stays readable in one image.
7
+ """
8
+ import argparse
9
+ import glob
10
+ import os
11
+
12
+ from PIL import Image, ImageDraw
13
+
14
+
15
+ def main():
16
+ p = argparse.ArgumentParser()
17
+ p.add_argument("frame_dir")
18
+ p.add_argument("prefixes")
19
+ p.add_argument("--out", required=True)
20
+ p.add_argument("--every", type=int, default=1, help="keep every Nth frame")
21
+ p.add_argument("--max-width", type=int, default=1600)
22
+ args = p.parse_args()
23
+ rows = []
24
+ for prefix in args.prefixes.split(","):
25
+ files = sorted(glob.glob(os.path.join(args.frame_dir, f"{prefix}_*.png")))[:: args.every]
26
+ if not files:
27
+ raise SystemExit(f"no {prefix}_*.png in {args.frame_dir}")
28
+ tiles = []
29
+ for f in files:
30
+ im = Image.open(f).convert("RGB")
31
+ ImageDraw.Draw(im).text((4, 4), os.path.basename(f)[len(prefix) + 1:-4], fill=(255, 255, 0))
32
+ tiles.append(im)
33
+ row = Image.new("RGB", (sum(t.size[0] for t in tiles), max(t.size[1] for t in tiles)), (20, 20, 20))
34
+ x = 0
35
+ for t in tiles:
36
+ row.paste(t, (x, 0))
37
+ x += t.size[0]
38
+ if row.size[0] > args.max_width:
39
+ row = row.resize((args.max_width, round(row.size[1] * args.max_width / row.size[0])), Image.LANCZOS)
40
+ rows.append(row)
41
+ sheet = Image.new("RGB", (max(r.size[0] for r in rows), sum(r.size[1] for r in rows)), (20, 20, 20))
42
+ y = 0
43
+ for r in rows:
44
+ sheet.paste(r, (0, y))
45
+ y += r.size[1]
46
+ sheet.save(args.out)
47
+ print(f"{len(rows)} row(s) -> {args.out}")
48
+
49
+
50
+ if __name__ == "__main__":
51
+ main()
@@ -0,0 +1,58 @@
1
+ """Compare two folders of renders view by view (for example before and after rigging).
2
+
3
+ python3 diff_renders.py BEFORE_DIR AFTER_DIR [--tolerance 2] [--out diff.png]
4
+
5
+ For every <view>.png present in both folders: silhouette IoU of the alpha masks, the largest
6
+ per-channel difference, and how many pixels differ by more than --tolerance (0-255). Exits
7
+ non-zero when any view changed beyond the tolerance, so a "the model did not change" claim is
8
+ checked rather than asserted. --out writes a sheet highlighting changed pixels in red.
9
+ """
10
+ import argparse
11
+ import glob
12
+ import os
13
+
14
+ import numpy as np
15
+ from PIL import Image
16
+
17
+
18
+ def main():
19
+ p = argparse.ArgumentParser()
20
+ p.add_argument("before")
21
+ p.add_argument("after")
22
+ p.add_argument("--tolerance", type=int, default=2)
23
+ p.add_argument("--out")
24
+ args = p.parse_args()
25
+ views = sorted(os.path.basename(f) for f in glob.glob(os.path.join(args.before, "*.png"))
26
+ if os.path.exists(os.path.join(args.after, os.path.basename(f))))
27
+ if not views:
28
+ raise SystemExit("no matching <view>.png files in both folders")
29
+ changed, tiles = False, []
30
+ for name in views:
31
+ a = np.asarray(Image.open(os.path.join(args.before, name)).convert("RGBA")).astype(int)
32
+ b = np.asarray(Image.open(os.path.join(args.after, name)).convert("RGBA")).astype(int)
33
+ if a.shape != b.shape:
34
+ print(f"{name}: size differs {a.shape[1]}x{a.shape[0]} vs {b.shape[1]}x{b.shape[0]}")
35
+ changed = True
36
+ continue
37
+ ma, mb = a[..., 3] > 128, b[..., 3] > 128
38
+ iou = (ma & mb).sum() / max((ma | mb).sum(), 1)
39
+ diff = np.abs(a - b).max(2)
40
+ over = diff > args.tolerance
41
+ changed |= bool(over.any())
42
+ print(f"{name:14s} IoU {iou:.4f} max channel diff {int(diff.max()):3d} pixels over tolerance {int(over.sum())}")
43
+ tile = np.asarray(Image.fromarray(b.astype(np.uint8)).convert("RGB")).copy()
44
+ tile[over] = (230, 40, 40)
45
+ tiles.append(Image.fromarray(tile))
46
+ if args.out and tiles:
47
+ sheet = Image.new("RGB", (sum(t.size[0] for t in tiles), max(t.size[1] for t in tiles)), (20, 20, 20))
48
+ x = 0
49
+ for t in tiles:
50
+ sheet.paste(t, (x, 0))
51
+ x += t.size[0]
52
+ sheet.save(args.out)
53
+ print("CHANGED" if changed else "IDENTICAL within tolerance")
54
+ raise SystemExit(1 if changed else 0)
55
+
56
+
57
+ if __name__ == "__main__":
58
+ main()
@@ -0,0 +1,54 @@
1
+ """Row-by-row silhouette edge differences for one view, in millimetres.
2
+
3
+ python3 edges.py ref_spec.json RENDERDIR front [--step 6] [--tol-mm 8]
4
+
5
+ For each sampled row: height above ground, how far the render's left and right edges sit
6
+ outside (+) or inside (-) the reference's, and the width difference. Rows beyond --tol-mm are
7
+ flagged with '!'. Use it to turn the red/blue overlay into concrete geometry corrections.
8
+ """
9
+ import argparse
10
+ import os
11
+ import sys
12
+
13
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
14
+ from refspec import load_reference, load_spec, reference_mask, render_image, render_mask, row_extents # noqa: E402
15
+
16
+
17
+ def main():
18
+ p = argparse.ArgumentParser()
19
+ p.add_argument("spec")
20
+ p.add_argument("render_dir")
21
+ p.add_argument("view")
22
+ p.add_argument("--step", type=int, default=6)
23
+ p.add_argument("--tol-mm", type=float, default=8.0)
24
+ args = p.parse_args()
25
+ spec = load_spec(args.spec)
26
+ _, arr = load_reference(spec)
27
+ view = spec["views"][args.view]
28
+ x0, y0, x1, y1 = view["crop"]
29
+ mm_per_px = spec["meters_per_px"] * 1000
30
+ ref = row_extents(reference_mask(spec, arr, args.view))
31
+ ren = row_extents(render_mask(render_image(args.render_dir, args.view, (x1 - x0, y1 - y0))))
32
+
33
+ print(f"{args.view}: + means the render extends beyond the reference")
34
+ print(" row z left_mm right_mm width_mm")
35
+ flagged = 0
36
+ for r in range(0, len(ref), args.step):
37
+ a, b = ref[r], ren[r]
38
+ z = (spec["ground_px"] - (r + y0 + 0.5)) * spec["meters_per_px"]
39
+ if a is None and b is None:
40
+ continue
41
+ if a is None or b is None:
42
+ print(f"! {r + y0:4d} {z:6.3f} {'render only' if a is None else 'reference only'}")
43
+ flagged += 1
44
+ continue
45
+ left = (a[0] - b[0]) * mm_per_px
46
+ right = (b[1] - a[1]) * mm_per_px
47
+ mark = "!" if max(abs(left), abs(right)) > args.tol_mm else " "
48
+ flagged += mark == "!"
49
+ print(f"{mark} {r + y0:4d} {z:6.3f} {left:+8.1f} {right:+9.1f} {left + right:+9.1f}")
50
+ print(f"{flagged} row(s) beyond {args.tol_mm} mm")
51
+
52
+
53
+ if __name__ == "__main__":
54
+ main()