import argparse import hashlib import json import math import os import struct import subprocess import sys import bpy def documents_dir() -> str: """Dokumente-Ordner des Benutzers; der Name hängt von der Sprache ab.""" home = os.path.expanduser("~") try: result = subprocess.run( ["xdg-user-dir", "DOCUMENTS"], capture_output=True, text=True, check=False, ) except OSError: result = None if result is not None and result.returncode == 0: candidate = result.stdout.strip() # xdg-user-dir liefert $HOME, wenn kein Ordner konfiguriert ist. if candidate and candidate != home and os.path.isdir(candidate): return candidate for name in ("Dokumente", "Documents"): candidate = os.path.join(home, name) if os.path.isdir(candidate): return candidate return os.path.join(home, "Documents") WORKBENCH = os.environ.get("RINKPLANNER_WORKBENCH") or os.path.join( documents_dir(), "workbench_rinkplanner" ) DEFAULT_RIG = os.path.join( WORKBENCH, "source", "characters", "skater", "skater_rig_v006.blend" ) DEFAULT_WORK = os.path.join( WORKBENCH, "source", "characters", "skater", "rotoscope", "rotoscope_work.blend", ) VIDEO_EXTENSIONS = {".mp4", ".mov", ".avi", ".mkv", ".webm", ".m4v"} IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".exr", ".tif", ".tiff", ".bmp"} def parse_args() -> argparse.Namespace: argv = sys.argv if "--" in argv: argv = argv[argv.index("--") + 1 :] else: argv = [] parser = argparse.ArgumentParser( prog="rotoscope.py", description="Rotoscoping-Werkbank für den Rinkplanner-Skater.", ) subparsers = parser.add_subparsers(dest="command", required=True) setup = subparsers.add_parser("setup", help="Arbeitsdatei anlegen") setup.add_argument("--rig", default=DEFAULT_RIG) setup.add_argument("--out", default=DEFAULT_WORK) setup.add_argument("--reference", default="") setup.add_argument("--force", action="store_true") reference = subparsers.add_parser( "reference", help="Referenzvideo in eine Arbeitsdatei laden" ) reference.add_argument("--blend", default=DEFAULT_WORK) reference.add_argument("--reference", required=True) export = subparsers.add_parser("export", help="Alle Clips als GLB exportieren") export.add_argument("--blend", default=DEFAULT_WORK) export.add_argument("--out", required=True) return parser.parse_args(argv) def main() -> None: args = parse_args() if args.command == "setup": setup_workbench(args) elif args.command == "reference": load_reference_into_workbench(args) elif args.command == "export": export_clips(args) else: raise SystemExit("Unbekannter Befehl: " + args.command) def setup_workbench(args: argparse.Namespace) -> None: if not os.path.isfile(args.rig): raise SystemExit("Rig-Datei nicht gefunden: " + args.rig) if os.path.exists(args.out) and not args.force: raise SystemExit( "Arbeitsdatei existiert bereits: %s " "(mit --force überschreiben; das löscht den Arbeitsstand)" % args.out ) bpy.ops.wm.open_mainfile(filepath=args.rig) scene = bpy.context.scene _prepare_scene(scene) _remove_helper_objects() rig = bpy.data.objects.get("rig") model = bpy.data.objects.get("model") if rig is None or model is None: raise SystemExit("Rig oder Modell nicht gefunden.") rotoscope = bpy.data.collections.new("Rotoscope") scene.collection.children.link(rotoscope) camera = _create_camera(scene, rotoscope) _build_rink_guide(rotoscope) _reset_rig(rig) if args.reference: _load_reference(scene, camera, args.reference) os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) bpy.ops.wm.save_as_mainfile(filepath=args.out) print("SETUP_OK", args.out) print( "SETUP_SUMMARY", json.dumps( { "work": args.out, "rig": rig.name, "model": model.name, "camera": camera.name, "frame_start": scene.frame_start, "frame_end": scene.frame_end, "fps": scene.render.fps, "reference": str(scene.get("rotoscope_reference", "")), }, ensure_ascii=False, ), ) def load_reference_into_workbench(args: argparse.Namespace) -> None: if not os.path.isfile(args.blend): raise SystemExit("Arbeitsdatei nicht gefunden: " + args.blend) bpy.ops.wm.open_mainfile(filepath=args.blend) scene = bpy.context.scene camera = bpy.data.objects.get("RotoscopeCamera") if camera is None: raise SystemExit("RotoscopeCamera fehlt in der Arbeitsdatei.") _load_reference(scene, camera, args.reference) bpy.ops.wm.save_as_mainfile(filepath=args.blend) print("REFERENCE_OK", args.reference) def export_clips(args: argparse.Namespace) -> None: if not os.path.isfile(args.blend): raise SystemExit("Arbeitsdatei nicht gefunden: " + args.blend) bpy.ops.wm.open_mainfile(filepath=args.blend) rig = bpy.data.objects.get("rig") model = bpy.data.objects.get("model") if rig is None or model is None: raise SystemExit("Rig oder Modell nicht gefunden.") for obj in bpy.context.view_layer.objects: obj.select_set(False) model.select_set(True) rig.select_set(True) bpy.context.view_layer.objects.active = rig os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) bpy.ops.export_scene.gltf( filepath=args.out, export_format="GLB", use_selection=True, export_apply=False, export_animations=True, export_animation_mode="ACTIONS", export_def_bones=True, export_all_influences=True, export_force_sampling=True, export_bake_animation=True, export_anim_single_armature=True, export_optimize_animation_size=False, export_yup=True, ) size = os.path.getsize(args.out) with open(args.out, "rb") as handle: digest = hashlib.sha256(handle.read()).hexdigest() clips = _read_glb_animations(args.out) source_scene = os.path.relpath( args.blend, WORKBENCH, ).replace(os.sep, "/") sidecar = { "file": os.path.basename(args.out), "sha256": digest, "bytes": size, "source_scene": source_scene, "clips": clips, "clip_names": [clip["name"] for clip in clips], } sidecar_path = os.path.splitext(args.out)[0] + ".json" with open(sidecar_path, "w", encoding="utf-8") as handle: json.dump(sidecar, handle, ensure_ascii=False, indent=2) handle.write("\n") print("EXPORT_OK", args.out) print("EXPORT_SUMMARY", json.dumps(sidecar, ensure_ascii=False)) def _prepare_scene(scene: bpy.types.Scene) -> None: scene.render.fps = 24 scene.render.fps_base = 1.0 scene.frame_start = 1 scene.frame_end = 240 scene.render.resolution_x = 1280 scene.render.resolution_y = 720 scene.render.film_transparent = True scene.unit_settings.system = "METRIC" scene.unit_settings.scale_length = 1.0 def _remove_helper_objects() -> None: keep_prefixes = ("cs_",) for obj in list(bpy.data.objects): if obj.name.startswith(keep_prefixes): continue if obj.type in {"CAMERA", "LIGHT"}: bpy.data.objects.remove(obj, do_unlink=True) continue if obj.name.startswith(("rig_", "glide_")): bpy.data.objects.remove(obj, do_unlink=True) def _create_camera( scene: bpy.types.Scene, collection: bpy.types.Collection, ) -> bpy.types.Object: target = bpy.data.objects.new("CameraTarget", None) target.empty_display_type = "SPHERE" target.empty_display_size = 0.4 target.location = (0.0, 0.0, 1.0) collection.objects.link(target) camera_data = bpy.data.cameras.new("RotoscopeCamera") camera_data.lens = 28.0 camera_data.sensor_width = 36.0 camera_data.clip_start = 0.1 camera_data.clip_end = 300.0 camera_data.show_background_images = True camera = bpy.data.objects.new("RotoscopeCamera", camera_data) camera.location = (0.0, -55.0, 20.0) collection.objects.link(camera) track = camera.constraints.new("TRACK_TO") track.target = target track.track_axis = "TRACK_NEGATIVE_Z" track.up_axis = "UP_Y" scene.camera = camera return camera def _build_rink_guide(collection: bpy.types.Collection) -> None: vertices: list[tuple[float, float, float]] = [] edges: list[tuple[int, int]] = [] outline = _rounded_rect(30.0, 15.0, 8.5, 10) base = len(vertices) vertices.extend((x, y, 0.02) for x, y in outline) for index in range(len(outline)): edges.append((base + index, base + (index + 1) % len(outline))) center_start = len(vertices) vertices.extend([(0.0, -15.0, 0.02), (0.0, 15.0, 0.02)]) edges.append((center_start, center_start + 1)) circle_start = len(vertices) for index in range(64): angle = index / 64.0 * 6.283185307179586 vertices.append( ( 4.5 * math.cos(angle), 4.5 * math.sin(angle), 0.02, ) ) for index in range(64): edges.append((circle_start + index, circle_start + (index + 1) % 64)) for x in range(-25, 26, 5): start = len(vertices) vertices.extend([(float(x), -12.5, 0.01), (float(x), 12.5, 0.01)]) edges.append((start, start + 1)) for y in range(-10, 11, 5): start = len(vertices) vertices.extend([(-27.5, float(y), 0.01), (27.5, float(y), 0.01)]) edges.append((start, start + 1)) axis_start = len(vertices) vertices.extend([(0.0, 0.0, 0.0), (0.0, 0.0, 2.0)]) edges.append((axis_start, axis_start + 1)) mesh = bpy.data.meshes.new("RinkGuideMesh") mesh.from_pydata(vertices, edges, []) mesh.update() guide = bpy.data.objects.new("RinkGuide", mesh) guide.display_type = "WIRE" guide.show_in_front = True guide.hide_render = True guide.color = (0.15, 0.75, 1.0, 1.0) collection.objects.link(guide) def _rounded_rect( half_length: float, half_width: float, radius: float, segments: int, ) -> list[tuple[float, float]]: import math points: list[tuple[float, float]] = [] corners = [ (half_length - radius, -half_width + radius, -math.pi * 0.5, 0.0), (half_length - radius, half_width - radius, 0.0, math.pi * 0.5), (-half_length + radius, half_width - radius, math.pi * 0.5, math.pi), (-half_length + radius, -half_width + radius, math.pi, math.pi * 1.5), ] points.append((-half_length + radius, -half_width)) for center_x, center_y, start, end in corners: for index in range(segments + 1): angle = start + (end - start) * index / segments point = ( center_x + math.cos(angle) * radius, center_y + math.sin(angle) * radius, ) if not points or abs(point[0] - points[-1][0]) > 1e-6 or abs( point[1] - points[-1][1] ) > 1e-6: points.append(point) return points def _reset_rig(rig: bpy.types.Object) -> None: if rig.animation_data is not None: rig.animation_data.action = None for track in rig.animation_data.nla_tracks: track.mute = True for action in bpy.data.actions: action.use_fake_user = True for bone in rig.pose.bones: bone.location = (0.0, 0.0, 0.0) bone.rotation_quaternion = (1.0, 0.0, 0.0, 0.0) bone.rotation_euler = (0.0, 0.0, 0.0) bone.scale = (1.0, 1.0, 1.0) def _load_reference( scene: bpy.types.Scene, camera: bpy.types.Object, path: str, ) -> None: if not os.path.isfile(path): raise SystemExit("Referenz nicht gefunden: " + path) extension = os.path.splitext(path)[1].lower() if extension not in VIDEO_EXTENSIONS and extension not in IMAGE_EXTENSIONS: raise SystemExit("Nicht unterstütztes Referenzformat: " + extension) while camera.data.background_images: camera.data.background_images.remove(camera.data.background_images[0]) camera.data.show_background_images = True if extension in VIDEO_EXTENSIONS: clip = bpy.data.movieclips.load(path) background = camera.data.background_images.new() background.source = "MOVIE_CLIP" background.clip = clip background.display_depth = "BACK" background.frame_method = "FIT" background.alpha = 0.85 scene.frame_start = 1 scene.frame_end = max(1, int(clip.frame_duration)) if clip.fps > 0.0: scene.render.fps = max(1, int(round(clip.fps))) print( "REFERENCE_CLIP", json.dumps( { "path": path, "frames": clip.frame_duration, "fps": clip.fps, }, ensure_ascii=False, ), ) else: image = bpy.data.images.load(path, check_existing=True) background = camera.data.background_images.new() background.source = "IMAGE" background.image = image background.display_depth = "BACK" background.frame_method = "FIT" background.alpha = 0.85 print("REFERENCE_IMAGE", path) scene["rotoscope_reference"] = path scene["rotoscope_reference_type"] = ( "video" if extension in VIDEO_EXTENSIONS else "image" ) def _read_glb_animations(path: str) -> list[dict]: with open(path, "rb") as handle: data = handle.read() _magic, _version, length = struct.unpack_from("<4sII", data, 0) offset = 12 chunks: list[tuple[int, int, int]] = [] while offset < length: chunk_length, chunk_type = struct.unpack_from("