File size: 9,547 Bytes
a5c598b
84669f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdfeaf1
84669f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
"""Replace paired wall/floor textures, configure lighting, and render a top preview."""
import argparse
import os
from pathlib import Path
import runpy
import shutil
import subprocess
import sys


HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from texture_library import choose_set, texture_sets


OUTPUT_NAMES = {"flat.blend", "preview_top.png"}


def positive_int(value):
    value = int(value)
    if value <= 0:
        raise argparse.ArgumentTypeError("Must be a positive integer")
    return value


def arguments(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--input", required=True, type=Path,
                        help="A .blend file, scene folder, batch folder, or data_scene root")
    parser.add_argument("--output", type=Path,
                        help="Output folder; default: a sibling folder ending in _processed")
    parser.add_argument("--textures", type=Path, default=HERE / "textures",
                        help="Texture library; default: textures/ next to this script")
    parser.add_argument("--texture-set", default="random",
                        help="A texture subdirectory name, or random (default)")
    parser.add_argument("--seed", type=int, help="Seed for repeatable per-scene selection")
    parser.add_argument("--size", type=positive_int, default=768, help="Preview pixels (default: 768)")
    parser.add_argument("--samples", type=positive_int, default=32, help="Cycles samples (default: 32)")
    parser.add_argument("--limit", type=positive_int, help="Process the first N scenes")
    parser.add_argument("--blender", help="Blender executable; normal Python invocation only")
    existing = parser.add_mutually_exclusive_group()
    existing.add_argument("--overwrite", action="store_true",
                          help="Replace existing outputs containing only blend and preview")
    existing.add_argument("--skip-existing", action="store_true",
                          help="Skip existing scene folders containing both nonempty outputs")
    parser.add_argument("--dry-run", action="store_true",
                        help="Print source, output and texture choices without processing")
    return parser.parse_args(argv)


def sources(input_path):
    if input_path.is_file():
        if input_path.suffix.lower() != ".blend":
            raise ValueError("--input file must end in .blend")
        found = [(input_path, Path("flat.blend"))]
    elif input_path.is_dir():
        if (input_path / "flat.blend").is_file():
            found = [(input_path / "flat.blend", Path("flat.blend"))]
        else:
            found = [
                (path, path.relative_to(input_path))
                for path in sorted(input_path.rglob("flat.blend"))
                if not any(part.startswith(".") for part in path.relative_to(input_path).parts)
            ]
    else:
        raise ValueError(f"Input does not exist: {input_path}")
    if not found:
        raise ValueError(f"No flat.blend scenes found under {input_path}")
    for path, _ in found:
        if path.is_symlink() or not path.is_file() or path.stat().st_size == 0:
            raise ValueError(f"Expected a nonempty source .blend: {path}")
        if input_path.is_dir() and not path.resolve().is_relative_to(input_path):
            raise ValueError(f"Source resolves outside the input tree: {path}")
    return found


def default_output(input_path):
    base = input_path.parent if input_path.is_file() else input_path
    return base.with_name(base.name + "_processed")


def output_action(source, target, args):
    resolved = target.resolve()
    if resolved == source.resolve() or resolved.parent == source.resolve().parent:
        raise ValueError(f"Output must be separate from the source: {target}")
    # Reject symlinks at any existing level so replacing outputs stays predictable.
    if any(path.is_symlink() for path in (target, *target.parents)):
        raise ValueError(f"Output path contains a symlink: {target}")
    if not target.parent.exists():
        return "process"
    if not target.parent.is_dir():
        raise ValueError(f"Output is not a directory: {target.parent}")
    entries = list(target.parent.iterdir())
    if (set(path.name for path in entries) - OUTPUT_NAMES
            or any(not path.is_file() or path.is_symlink() for path in entries)):
        raise ValueError(f"Unexpected content in output scene folder: {target.parent}")
    if args.skip_existing:
        if ({path.name for path in entries} == OUTPUT_NAMES
                and all(path.stat().st_size > 0 for path in entries)):
            return "skip"
        raise ValueError(f"Incomplete existing output; use --overwrite: {target.parent}")
    if not args.overwrite:
        raise ValueError(f"Output exists; use --skip-existing or --overwrite: {target.parent}")
    return "process"


def make_plan(args):
    input_path = args.input.expanduser().resolve()
    output = (args.output.expanduser().absolute() if args.output
              else default_output(input_path))
    if output.is_symlink():
        raise ValueError(f"Output directory must not be a symlink: {output}")
    # Resolve parent aliases such as macOS /tmp before checking scene outputs.
    output = output.resolve()
    protected = input_path if input_path.is_dir() else input_path.parent
    if output.resolve().is_relative_to(protected) or protected.is_relative_to(output.resolve()):
        raise ValueError("Input and output directory trees must be separate")
    library = args.textures.expanduser().resolve()
    texture_sets(library)
    if library.is_relative_to(output.resolve()) or output.resolve().is_relative_to(library):
        raise ValueError("Output directory and texture library must be separate")
    found = sources(input_path)
    if args.limit:
        found = found[:args.limit]
    plan = []
    for source, relative in found:
        target = output / relative
        action = output_action(source, target, args)
        scene_key = relative.as_posix() if len(relative.parts) > 1 else source.parent.name
        selected = choose_set(library, args.texture_set, args.seed, scene_key)
        plan.append((source, target, selected, action))
    return plan, library


def blender_executable(requested):
    candidate = requested or os.environ.get("BLENDER_BIN")
    if candidate:
        resolved = shutil.which(str(Path(candidate).expanduser()))
        if not resolved:
            raise ValueError(f"Blender executable not found: {candidate}")
        return resolved
    found = shutil.which("blender")
    if found:
        return found
    mac = Path("/Applications/Blender.app/Contents/MacOS/Blender")
    if mac.is_file():
        return str(mac)
    raise ValueError("Blender was not found; pass --blender /path/to/blender or set BLENDER_BIN")


def run(args):
    plan, library = make_plan(args)
    try:
        import bpy
    except ModuleNotFoundError:
        bpy = None
    process_scene = None
    executable = None
    if not args.dry_run and any(row[3] == "process" for row in plan):
        if bpy is not None:
            if bpy.app.version < (4, 5, 0):
                raise ValueError("Use Blender 4.5 LTS or newer")
            process_scene = runpy.run_path(str(HERE / "_blender" / "process_scene_textured.py"))["process"]
        else:
            executable = blender_executable(args.blender)
    print(f"SCENES={len(plan)} TEXTURE_SETS={len(texture_sets(library))} TEXTURES={library}", flush=True)
    done = skipped = 0
    for index, (source, target, selected, action) in enumerate(plan, 1):
        print(f"[{index}/{len(plan)}] {action.upper()} input={source} output={target} texture={selected}",
              flush=True)
        if action == "skip":
            skipped += 1
            continue
        if args.dry_run:
            continue
        if bpy is not None:
            bpy.ops.wm.open_mainfile(filepath=str(source))
            process_scene(
                target, library, requested_set=selected,
                preview_size=args.size, preview_samples=args.samples,
                replace_existing=args.overwrite,
            )
        else:
            command = [
                executable, "--background", "--factory-startup", "--disable-autoexec",
                "--python-exit-code", "1", "--python", str(HERE / "process.py"), "--",
                "--input", str(source), "--output", str(target.parent),
                "--textures", str(library), "--texture-set", selected,
                "--size", str(args.size), "--samples", str(args.samples),
            ]
            if args.overwrite:
                command.append("--overwrite")
            subprocess.run(command, check=True)
        if ({path.name for path in target.parent.iterdir()} != OUTPUT_NAMES
                or any((target.parent / name).stat().st_size == 0 for name in OUTPUT_NAMES)):
            raise RuntimeError(f"Expected only flat.blend and preview_top.png in {target.parent}")
        done += 1
    label = "DRY_RUN_DONE" if args.dry_run else "DONE"
    print(f"{label} processed={done} skipped={skipped} scenes={len(plan)}", flush=True)


def main(argv=None):
    try:
        run(arguments(argv))
    except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error:
        print(f"ERROR: {error}", file=sys.stderr, flush=True)
        raise SystemExit(1)


if __name__ == "__main__":
    cli_args = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else sys.argv[1:]
    main(cli_args)