diff options
| author | Vonsek <45567075+Vonsek@users.noreply.github.com> | 2026-11-22 19:07:53 +0100 |
|---|---|---|
| committer | Vonsek <45567075+Vonsek@users.noreply.github.com> | 2026-11-22 19:07:53 +0100 |
| commit | 46a196cde9328e2a232ee15c19556eb962cda0ab (patch) | |
| tree | d1cd03326530912d925ee1a7ba7fa735006f004f /tools/batch_glb.py | |
| parent | d3fab00a78967adf357596996190afdf33dc09d5 (diff) | |
| parent | ec8ec4c9a46c6623f1a9c125afd3566da97f1e0c (diff) | |
Merge upstream main into first-light shader identity
Diffstat (limited to 'tools/batch_glb.py')
| -rw-r--r-- | tools/batch_glb.py | 208 |
1 files changed, 208 insertions, 0 deletions
diff --git a/tools/batch_glb.py b/tools/batch_glb.py new file mode 100644 index 000000000..e62b6fe42 --- /dev/null +++ b/tools/batch_glb.py | |||
| @@ -0,0 +1,208 @@ | |||
| 1 | """Batch converter from Wavefront OBJ files to binary glTF 2.0 (.glb). | ||
| 2 | |||
| 3 | Uses tools/glb_writer.py to process entire directories of OBJ models | ||
| 4 | with multi-core parallelism and progress reporting. Can optionally link | ||
| 5 | and embed textures (.png or .dds) directly into glTF materials. | ||
| 6 | |||
| 7 | Usage: | ||
| 8 | python -I tools/batch_glb.py <in_dir> <out_dir> [--jobs N] [--up z|y] [--textures <dir>] | ||
| 9 | """ | ||
| 10 | from __future__ import annotations | ||
| 11 | |||
| 12 | import argparse | ||
| 13 | import concurrent.futures | ||
| 14 | import os | ||
| 15 | import sys | ||
| 16 | import time | ||
| 17 | |||
| 18 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | ||
| 19 | import glb_writer | ||
| 20 | import dds_png | ||
| 21 | |||
| 22 | |||
| 23 | def _build_texture_index(texture_dir: str | None) -> dict[str, str]: | ||
| 24 | """Index available texture files (.png and .dds) by lowercase basename without extension.""" | ||
| 25 | if not texture_dir or not os.path.isdir(texture_dir): | ||
| 26 | return {} | ||
| 27 | index: dict[str, str] = {} | ||
| 28 | for entry in os.scandir(texture_dir): | ||
| 29 | if not entry.is_file(): | ||
| 30 | continue | ||
| 31 | lower = entry.name.lower() | ||
| 32 | if lower.endswith(".png") or lower.endswith(".dds"): | ||
| 33 | stem = os.path.splitext(lower)[0] | ||
| 34 | # Prefer png over dds if both exist | ||
| 35 | if stem not in index or lower.endswith(".png"): | ||
| 36 | index[stem] = entry.path | ||
| 37 | return index | ||
| 38 | |||
| 39 | |||
| 40 | def _load_png_bytes(tex_path: str, max_size: int = 0) -> bytes | None: | ||
| 41 | """Load PNG bytes from file or decode DDS directly to PNG bytes.""" | ||
| 42 | lower = tex_path.lower() | ||
| 43 | if lower.endswith(".png"): | ||
| 44 | with open(tex_path, "rb") as f: | ||
| 45 | return f.read() | ||
| 46 | elif lower.endswith(".dds"): | ||
| 47 | try: | ||
| 48 | return dds_png.dds_file_to_png_bytes(tex_path, max_size=max_size) | ||
| 49 | except Exception: | ||
| 50 | return None | ||
| 51 | return None | ||
| 52 | |||
| 53 | |||
| 54 | def convert_single( | ||
| 55 | args_tuple: tuple[str, str, str, dict[str, str], int, dict[str, bytes]], | ||
| 56 | ) -> tuple[bool, str, str]: | ||
| 57 | in_path, out_path, up_axis, tex_index, max_tex_size, tex_cache = args_tuple | ||
| 58 | try: | ||
| 59 | primitives = glb_writer.parse_obj(in_path, is_path=True, up_axis=up_axis) | ||
| 60 | materials: dict[str, dict] = {} | ||
| 61 | |||
| 62 | if tex_index: | ||
| 63 | base_stem = os.path.splitext(os.path.basename(in_path))[0].lower() | ||
| 64 | # Clean possible hash suffix like 'ambient_femalebb._ft_at_...' -> 'ambient_femalebb' | ||
| 65 | clean_stem = base_stem.split(".")[0] | ||
| 66 | |||
| 67 | for prim in primitives: | ||
| 68 | mat_name = prim.get("material", "") | ||
| 69 | lookup_keys = [] | ||
| 70 | if mat_name: | ||
| 71 | lookup_keys.extend([ | ||
| 72 | mat_name.lower(), | ||
| 73 | f"{mat_name.lower()}_d", | ||
| 74 | f"{mat_name.lower()}_diff", | ||
| 75 | ]) | ||
| 76 | lookup_keys.extend([ | ||
| 77 | base_stem, | ||
| 78 | clean_stem, | ||
| 79 | f"{clean_stem}_d", | ||
| 80 | f"{clean_stem}_diff", | ||
| 81 | ]) | ||
| 82 | |||
| 83 | found_path = None | ||
| 84 | for key in lookup_keys: | ||
| 85 | if key in tex_index: | ||
| 86 | found_path = tex_index[key] | ||
| 87 | break | ||
| 88 | |||
| 89 | if found_path: | ||
| 90 | png_bytes = tex_cache.get(found_path) | ||
| 91 | if png_bytes is None: | ||
| 92 | png_bytes = _load_png_bytes(found_path, max_size=max_tex_size) | ||
| 93 | if png_bytes: | ||
| 94 | tex_cache[found_path] = png_bytes | ||
| 95 | if png_bytes: | ||
| 96 | mat_key = mat_name if mat_name else clean_stem | ||
| 97 | prim["material"] = mat_key | ||
| 98 | materials[mat_key] = { | ||
| 99 | "name": mat_key, | ||
| 100 | "png_bytes": png_bytes, | ||
| 101 | } | ||
| 102 | |||
| 103 | glb_writer.write_glb(out_path, primitives, materials=materials if materials else None) | ||
| 104 | return True, in_path, "" | ||
| 105 | except Exception as exc: | ||
| 106 | return False, in_path, str(exc) | ||
| 107 | |||
| 108 | |||
| 109 | def batch_convert( | ||
| 110 | in_dir: str, | ||
| 111 | out_dir: str, | ||
| 112 | up_axis: str = "z", | ||
| 113 | jobs: int | None = None, | ||
| 114 | texture_dir: str | None = None, | ||
| 115 | max_tex_size: int = 0, | ||
| 116 | ) -> dict[str, int]: | ||
| 117 | if not os.path.isdir(in_dir): | ||
| 118 | raise ValueError(f"Input directory does not exist: {in_dir}") | ||
| 119 | |||
| 120 | os.makedirs(out_dir, exist_ok=True) | ||
| 121 | obj_files = [ | ||
| 122 | f for f in os.listdir(in_dir) if f.lower().endswith(".obj") and os.path.isfile(os.path.join(in_dir, f)) | ||
| 123 | ] | ||
| 124 | |||
| 125 | tex_index = _build_texture_index(texture_dir) | ||
| 126 | tex_cache: dict[str, bytes] = {} | ||
| 127 | |||
| 128 | tasks = [ | ||
| 129 | ( | ||
| 130 | os.path.join(in_dir, f), | ||
| 131 | os.path.join(out_dir, os.path.splitext(f)[0] + ".glb"), | ||
| 132 | up_axis, | ||
| 133 | tex_index, | ||
| 134 | max_tex_size, | ||
| 135 | tex_cache, | ||
| 136 | ) | ||
| 137 | for f in obj_files | ||
| 138 | ] | ||
| 139 | |||
| 140 | total = len(tasks) | ||
| 141 | succeeded = 0 | ||
| 142 | failed = 0 | ||
| 143 | |||
| 144 | max_workers = jobs if jobs and jobs > 0 else (os.cpu_count() or 4) | ||
| 145 | |||
| 146 | with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: | ||
| 147 | for ok, path, err in executor.map(convert_single, tasks): | ||
| 148 | if ok: | ||
| 149 | succeeded += 1 | ||
| 150 | else: | ||
| 151 | failed += 1 | ||
| 152 | |||
| 153 | return {"total": total, "succeeded": succeeded, "failed": failed} | ||
| 154 | |||
| 155 | |||
| 156 | def main(argv: list[str] | None = None) -> int: | ||
| 157 | parser = argparse.ArgumentParser( | ||
| 158 | description="Batch convert Wavefront OBJ models to binary glTF 2.0 (.glb)." | ||
| 159 | ) | ||
| 160 | parser.add_argument("in_dir", help="Directory containing .obj files") | ||
| 161 | parser.add_argument("out_dir", help="Output directory for .glb files") | ||
| 162 | parser.add_argument( | ||
| 163 | "--jobs", | ||
| 164 | type=int, | ||
| 165 | default=None, | ||
| 166 | help="Number of parallel worker threads (default: CPU count)", | ||
| 167 | ) | ||
| 168 | parser.add_argument( | ||
| 169 | "--up", | ||
| 170 | choices=("z", "y"), | ||
| 171 | default="z", | ||
| 172 | help="Source up axis: 'z' converts RAGE Z-up to glTF Y-up (default), 'y' keeps Y-up", | ||
| 173 | ) | ||
| 174 | parser.add_argument( | ||
| 175 | "--textures", | ||
| 176 | type=str, | ||
| 177 | default=None, | ||
| 178 | help="Optional directory containing textures (.png or .dds) to link and embed", | ||
| 179 | ) | ||
| 180 | parser.add_argument( | ||
| 181 | "--max-tex-size", | ||
| 182 | type=int, | ||
| 183 | default=0, | ||
| 184 | help="Max texture dimension in pixels when decoding DDS (0 = unconstrained)", | ||
| 185 | ) | ||
| 186 | |||
| 187 | args = parser.parse_args(argv) | ||
| 188 | t0 = time.monotonic() | ||
| 189 | stats = batch_convert( | ||
| 190 | args.in_dir, | ||
| 191 | args.out_dir, | ||
| 192 | up_axis=args.up, | ||
| 193 | jobs=args.jobs, | ||
| 194 | texture_dir=args.textures, | ||
| 195 | max_tex_size=args.max_tex_size, | ||
| 196 | ) | ||
| 197 | elapsed = time.monotonic() - t0 | ||
| 198 | |||
| 199 | print( | ||
| 200 | f"batch_glb: converted {stats['succeeded']}/{stats['total']} models " | ||
| 201 | f"({stats['failed']} failed) in {elapsed:.2f}s" | ||
| 202 | ) | ||
| 203 | return 0 if stats["failed"] == 0 else 1 | ||
| 204 | |||
| 205 | |||
| 206 | if __name__ == "__main__": | ||
| 207 | sys.stdout.reconfigure(errors="replace") | ||
| 208 | sys.exit(main()) | ||