#!/usr/bin/env python3 """ Create a fixed render_config.json from a .blend template. This script is designed to run in Blender before the actual render step: blender -b template_smplx_uv.blend -P scripts/create_render_config.py -- ... """ from __future__ import annotations import argparse import json import random import sys from pathlib import Path from typing import Any import bpy def parse_blender_args() -> argparse.Namespace: argv = sys.argv if "--" in argv: argv = argv[argv.index("--") + 1 :] else: argv = [] parser = argparse.ArgumentParser() parser.add_argument("--manifest", required=True, type=Path) parser.add_argument("--out", required=True, type=Path) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--camera-collection", default="CAMERA_PRESETS") parser.add_argument("--camera-roll-deg", type=float, default=5.0) parser.add_argument("--camera-dolly-m", type=float, default=0.2) parser.add_argument("--world-z-rotation-min", type=float, default=0.0) parser.add_argument("--world-z-rotation-max", type=float, default=360.0) parser.add_argument("--gender", choices=["random", "female", "male"], default="random") parser.add_argument("--hair-manifest", default=None, type=Path) parser.add_argument("--hair-max-bytes", type=int, default=200_000_000, help="Exclude pathological grooms larger than this many bytes; <=0 disables the limit.") parser.add_argument("--disable-hair", action="store_true") parser.add_argument("--world-exclude", default="", help="Comma-separated world names to exclude.") parser.add_argument("--disable-script-lights", action="store_true", default=True) parser.add_argument("--enable-script-lights", dest="disable_script_lights", action="store_false") return parser.parse_args(argv) def parse_csv(value: str) -> set[str]: return {item.strip() for item in value.split(",") if item.strip()} def mapping_nodes(world: bpy.types.World) -> list[bpy.types.Node]: if not world.use_nodes or world.node_tree is None: return [] return [node for node in world.node_tree.nodes if node.type == "MAPPING"] def candidate_worlds(exclude: set[str]) -> list[bpy.types.World]: worlds = [] missing_mapping = [] for world in bpy.data.worlds: if world.name in exclude: continue if not mapping_nodes(world): missing_mapping.append(world.name) continue worlds.append(world) if missing_mapping: raise RuntimeError(f"Worlds missing Mapping node: {', '.join(missing_mapping)}") if not worlds: raise RuntimeError("No usable world datablocks found.") return sorted(worlds, key=lambda item: item.name) def candidate_cameras(collection_name: str) -> list[bpy.types.Object]: collection = bpy.data.collections.get(collection_name) if collection is None: raise RuntimeError(f"Camera collection not found: {collection_name}") cameras = [obj for obj in collection.all_objects if obj.type == "CAMERA"] if not cameras: raise RuntimeError(f"No cameras found in collection: {collection_name}") return sorted(cameras, key=lambda item: item.name) def load_manifest(path: Path) -> dict[str, Any]: if not path.exists(): raise FileNotFoundError(path) with open(path, "r", encoding="utf-8") as f: manifest = json.load(f) if "textures" not in manifest: raise KeyError("Manifest must contain a 'textures' list.") return manifest def choose_gender(manifest: dict[str, Any], requested_gender: str, rng: random.Random) -> str: if requested_gender in {"female", "male"}: return requested_gender texture_items = manifest.get("texture_items") or [] available = sorted({item.get("gender") for item in texture_items if item.get("gender") in {"female", "male"}}) if available: return rng.choice(available) return rng.choice(["female", "male"]) def choose_texture(manifest: dict[str, Any], gender: str, rng: random.Random) -> dict[str, Any] | None: texture_items = manifest.get("texture_items") or [] if texture_items: gender_items = [item for item in texture_items if item.get("gender") == gender] if not gender_items: raise RuntimeError(f"No texture_items found for gender '{gender}'.") return rng.choice(gender_items) textures = manifest.get("textures") or [] if textures: return {"texture": rng.choice(textures), "gender": gender} return None def load_hair_manifest(path: Path | None) -> dict[str, Any] | None: if path is None: return None if not path.exists(): raise FileNotFoundError(f"Hair manifest not found: {path}") with open(path, "r", encoding="utf-8") as f: manifest = json.load(f) if "items" not in manifest: raise KeyError("Hair manifest must contain an 'items' list.") return manifest def choose_hair_item( hair_manifest: dict[str, Any] | None, gender: str, rng: random.Random, max_bytes: int, ) -> tuple[bool, dict | None, str | None]: if hair_manifest is None: return False, None, "no_hair_manifest" compatible = [ item for item in hair_manifest.get("items", []) if gender in set(item.get("gender_tags", [])) and (max_bytes <= 0 or int(item.get("bytes", 0)) <= max_bytes) ] if not compatible: return False, None, f"no_compatible_hair_for_{gender}" return True, rng.choice(compatible), None def choose_hair_color(rng: random.Random) -> list[float]: palette = [ [0.018, 0.014, 0.010, 1.0], [0.045, 0.030, 0.018, 1.0], [0.085, 0.052, 0.028, 1.0], [0.140, 0.090, 0.050, 1.0], [0.240, 0.185, 0.105, 1.0], ] return rng.choice(palette) def main() -> None: args = parse_blender_args() rng = random.Random(args.seed) worlds = candidate_worlds(parse_csv(args.world_exclude)) cameras = candidate_cameras(args.camera_collection) manifest = load_manifest(args.manifest) gender = choose_gender(manifest, args.gender, rng) hair_manifest = None if args.disable_hair else load_hair_manifest(args.hair_manifest) hair_enabled, hair_item, hair_disabled_reason = choose_hair_item( hair_manifest, gender, rng, args.hair_max_bytes ) world = rng.choice(worlds) camera = rng.choice(cameras) mapping = mapping_nodes(world)[0] config = { "schema": "smplx_coco_render_config_v1", "seed": args.seed, "gender": gender, "world_name": world.name, "world_mapping_node": mapping.name, "world_rotation_z_degrees": rng.uniform(args.world_z_rotation_min, args.world_z_rotation_max), "camera_collection": args.camera_collection, "camera_preset_name": camera.name, "camera_roll_degrees": rng.uniform(-abs(args.camera_roll_deg), abs(args.camera_roll_deg)), "camera_dolly_meters": rng.uniform(-abs(args.camera_dolly_m), abs(args.camera_dolly_m)), "texture_item": choose_texture(manifest, gender, rng), "hair_enabled": bool(hair_enabled), "hair_item": hair_item, "hair_color": choose_hair_color(rng) if hair_enabled else None, "hair_disabled_reason": hair_disabled_reason, "hair_max_bytes": int(args.hair_max_bytes), "disable_script_lights": bool(args.disable_script_lights), "available_world_count": len(worlds), "available_camera_count": len(cameras), "ranges": { "world_z_rotation_degrees": [args.world_z_rotation_min, args.world_z_rotation_max], "camera_roll_degrees": [-abs(args.camera_roll_deg), abs(args.camera_roll_deg)], "camera_dolly_meters": [-abs(args.camera_dolly_m), abs(args.camera_dolly_m)], }, } args.out.parent.mkdir(parents=True, exist_ok=True) with open(args.out, "w", encoding="utf-8") as f: json.dump(config, f, indent=2, ensure_ascii=False) print(f"[OK] Wrote render config to {args.out}") if __name__ == "__main__": main()