| |
| |
| """ |
| Filter rigged low-poly meshes from multiple datasets. |
| |
| A .glb is kept only if ALL of: |
| - valid glTF 2.0 binary |
| - has skins with joints, and at least one scene-reachable node binds mesh+skin |
| - total vertex count of scene-reachable meshes < 10000 |
| |
| Kept meshes are normalized into [-0.5, 0.5]^3 by inserting a wrapper root node |
| (uniform scale + translation) into the scene graph. This preserves skeleton / |
| skin / animation data exactly (a re-export through trimesh would drop them). |
| |
| Dedup: exact file sha256 + geometry hash over POSITION/JOINTS_0/WEIGHTS_0 |
| buffer bytes. Sources are opened read-only; all output goes under OUT_ROOT. |
| Resumable: paths already listed in processed.log are skipped on restart. |
| |
| Run: python filter_meshes.py [--limit-per-source N] |
| """ |
| import argparse |
| import hashlib |
| import itertools |
| import json |
| import os |
| import struct |
| import sys |
| import time |
| from collections import Counter |
| from multiprocessing import Pool |
| from pathlib import Path |
|
|
| import numpy as np |
|
|
| |
| SOURCES = [ |
| ("dataset_rig", "/root/zhaotianhao/dataset_rig"), |
| ("canoverse", "/root/youjiaZhang/topotex_data_CanoVerse/raw"), |
| ("objaverse_xl", "/root/dataset/dataset.2/objaverse-xl/hf-objaverse-v1/glbs"), |
| ] |
|
|
| OUT_ROOT = Path("/root/zhaotianhao/filtered_lowpoly_rig") |
| MESH_DIR = OUT_ROOT / "meshes" |
| TMP_DIR = OUT_ROOT / "tmp" |
| MANIFEST = OUT_ROOT / "manifest.jsonl" |
| PROCESSED = OUT_ROOT / "processed.log" |
| STATS = OUT_ROOT / "stats.json" |
|
|
| MAX_VERTS = 10000 |
| NORM_HALF = 0.5 |
| MAX_FILE_BYTES = 300 << 20 |
| WORKERS = 24 |
| MESH_EXTS = {".glb", ".gltf", ".vrm", ".fbx", ".obj", ".dae", ".ply", ".stl"} |
|
|
| CHUNK_JSON = 0x4E4F534A |
| CHUNK_BIN = 0x004E4942 |
|
|
|
|
| def _quat_to_mat(x, y, z, w): |
| n = x * x + y * y + z * z + w * w |
| if n < 1e-12: |
| return np.eye(3) |
| s = 2.0 / n |
| xx, yy, zz = x * x * s, y * y * s, z * z * s |
| xy, xz, yz = x * y * s, x * z * s, y * z * s |
| wx, wy, wz = w * x * s, w * y * s, w * z * s |
| return np.array([ |
| [1 - (yy + zz), xy - wz, xz + wy], |
| [xy + wz, 1 - (xx + zz), yz - wx], |
| [xz - wy, yz + wx, 1 - (xx + yy)], |
| ]) |
|
|
|
|
| def _node_matrix(node): |
| if "matrix" in node: |
| return np.array(node["matrix"], dtype=np.float64).reshape(4, 4).T |
| m = np.eye(4) |
| if "scale" in node: |
| m[:3, :3] = np.diag(node["scale"]) |
| if "rotation" in node: |
| x, y, z, w = node["rotation"] |
| m[:3, :3] = _quat_to_mat(x, y, z, w) @ m[:3, :3] |
| if "translation" in node: |
| m[:3, 3] = node["translation"] |
| return m |
|
|
|
|
| def _reject(rec, reason, **extra): |
| rec.update(status="reject", reason=reason, **extra) |
| return rec |
|
|
|
|
| def process_one(task): |
| tag, path = task |
| rec = {"src": path, "tag": tag} |
| try: |
| return _process_one(tag, path, rec) |
| except Exception as e: |
| return _reject(rec, "error:%s" % type(e).__name__) |
|
|
|
|
| def _process_one(tag, path, rec): |
| ext = os.path.splitext(path)[1].lower() |
| if ext != ".glb": |
| |
| return _reject(rec, "non_glb:%s" % ext.lstrip(".")) |
| size = os.path.getsize(path) |
| if size > MAX_FILE_BYTES: |
| return _reject(rec, "too_large") |
|
|
| fhash = hashlib.sha256() |
| with open(path, "rb") as f: |
| hdr = f.read(12) |
| if len(hdr) < 12 or hdr[:4] != b"glTF": |
| return _reject(rec, "bad_magic") |
| version, _total = struct.unpack("<II", hdr[4:]) |
| if version != 2: |
| return _reject(rec, "gltf_v%d" % version) |
| ch = f.read(8) |
| if len(ch) < 8: |
| return _reject(rec, "truncated") |
| clen, ctype = struct.unpack("<II", ch) |
| if ctype != CHUNK_JSON: |
| return _reject(rec, "no_json_chunk") |
| raw_json = f.read(clen) |
| try: |
| gltf = json.loads(raw_json) |
| except Exception: |
| return _reject(rec, "json_parse") |
|
|
| |
| skins = gltf.get("skins") or [] |
| joints_union = set() |
| for s in skins: |
| joints_union.update(s.get("joints") or []) |
| if not joints_union: |
| return _reject(rec, "no_skeleton") |
|
|
| nodes = gltf.get("nodes") or [] |
| meshes = gltf.get("meshes") or [] |
| accessors = gltf.get("accessors") or [] |
| scenes = gltf.get("scenes") or [] |
| if not scenes: |
| return _reject(rec, "no_scene") |
| scene_idx = min(gltf.get("scene", 0), len(scenes) - 1) |
| roots = scenes[scene_idx].get("nodes") or [] |
| if not roots: |
| return _reject(rec, "empty_scene") |
|
|
| mesh_nodes = [] |
| has_skinned = False |
| stack = [(r, np.eye(4)) for r in roots] |
| seen = set() |
| while stack: |
| ni, pm = stack.pop() |
| if ni in seen or not (0 <= ni < len(nodes)): |
| continue |
| seen.add(ni) |
| nd = nodes[ni] |
| wm = pm @ _node_matrix(nd) |
| if nd.get("mesh") is not None: |
| mesh_nodes.append((ni, wm)) |
| if nd.get("skin") is not None: |
| has_skinned = True |
| for c in nd.get("children") or []: |
| stack.append((c, wm)) |
| if not mesh_nodes: |
| return _reject(rec, "no_mesh_in_scene") |
| if not has_skinned: |
| return _reject(rec, "no_skinned_mesh") |
|
|
| |
| mesh_ids = sorted({nodes[ni]["mesh"] for ni, _ in mesh_nodes |
| if 0 <= nodes[ni]["mesh"] < len(meshes)}) |
| n_verts = 0 |
| n_faces = 0 |
| for mi in mesh_ids: |
| for prim in meshes[mi].get("primitives") or []: |
| pa = (prim.get("attributes") or {}).get("POSITION") |
| if pa is None or not (0 <= pa < len(accessors)): |
| continue |
| cnt = accessors[pa].get("count", 0) |
| n_verts += cnt |
| if prim.get("mode", 4) == 4: |
| ia = prim.get("indices") |
| if ia is not None and 0 <= ia < len(accessors): |
| n_faces += accessors[ia].get("count", 0) // 3 |
| else: |
| n_faces += cnt // 3 |
| if n_verts == 0: |
| return _reject(rec, "no_position") |
| if n_verts >= MAX_VERTS: |
| return _reject(rec, "too_many_verts", n_verts=n_verts) |
|
|
| |
| mn = np.full(3, np.inf) |
| mx = np.full(3, -np.inf) |
| for ni, wm in mesh_nodes: |
| mi = nodes[ni]["mesh"] |
| if not (0 <= mi < len(meshes)): |
| continue |
| for prim in meshes[mi].get("primitives") or []: |
| pa = (prim.get("attributes") or {}).get("POSITION") |
| if pa is None or not (0 <= pa < len(accessors)): |
| continue |
| acc = accessors[pa] |
| amn, amx = acc.get("min"), acc.get("max") |
| if not amn or not amx or len(amn) < 3 or len(amx) < 3: |
| return _reject(rec, "missing_bounds") |
| cs = np.array(list(itertools.product( |
| (amn[0], amx[0]), (amn[1], amx[1]), (amn[2], amx[2])))) |
| cs4 = np.hstack([cs, np.ones((8, 1))]) |
| w = (wm @ cs4.T).T[:, :3] |
| mn = np.minimum(mn, w.min(axis=0)) |
| mx = np.maximum(mx, w.max(axis=0)) |
| extent = mx - mn |
| max_extent = float(np.max(extent)) |
| if not np.isfinite(max_extent) or max_extent <= 1e-9: |
| return _reject(rec, "degenerate_bbox") |
| scale = (2.0 * NORM_HALF) / max_extent |
| center = (mn + mx) / 2.0 |
|
|
| |
| fhash.update(hdr) |
| fhash.update(ch) |
| fhash.update(raw_json) |
| rest = [] |
| while True: |
| h = f.read(8) |
| if len(h) < 8: |
| break |
| fhash.update(h) |
| cl, ct = struct.unpack("<II", h) |
| payload = f.read(cl) |
| fhash.update(payload) |
| rest.append((ct, payload)) |
| file_hash = fhash.hexdigest() |
|
|
| bin_data = None |
| for ct, payload in rest: |
| if ct == CHUNK_BIN: |
| bin_data = payload |
| break |
|
|
| |
| bvs = gltf.get("bufferViews") or [] |
| buffers = gltf.get("buffers") or [] |
| bin_usable = bin_data is not None and buffers and "uri" not in buffers[0] |
| if bin_usable: |
| gh = hashlib.sha256() |
| gh.update(b"%d/%d/%d" % (n_verts, n_faces, len(joints_union))) |
| for mi in mesh_ids: |
| for prim in meshes[mi].get("primitives") or []: |
| attrs = prim.get("attributes") or {} |
| for name in ("POSITION", "JOINTS_0", "WEIGHTS_0"): |
| ai = attrs.get(name) |
| if ai is None or not (0 <= ai < len(accessors)): |
| continue |
| bvi = accessors[ai].get("bufferView") |
| if bvi is None or not (0 <= bvi < len(bvs)): |
| continue |
| bv = bvs[bvi] |
| if bv.get("buffer", 0) != 0: |
| continue |
| off = bv.get("byteOffset", 0) |
| gh.update(bin_data[off:off + bv.get("byteLength", 0)]) |
| geo_hash = gh.hexdigest() |
| else: |
| geo_hash = "file:" + file_hash |
|
|
| |
| wrapper = { |
| "name": "__normalized_root__", |
| "children": list(roots), |
| "scale": [scale, scale, scale], |
| "translation": [float(-center[0] * scale), |
| float(-center[1] * scale), |
| float(-center[2] * scale)], |
| } |
| gltf.setdefault("nodes", nodes).append(wrapper) |
| scenes[scene_idx]["nodes"] = [len(gltf["nodes"]) - 1] |
|
|
| new_json = json.dumps(gltf, separators=(",", ":")).encode("utf-8") |
| new_json += b" " * ((4 - len(new_json) % 4) % 4) |
| body = bytearray() |
| for ct, payload in rest: |
| if len(payload) % 4: |
| payload = payload + b"\x00" * (4 - len(payload) % 4) |
| body += struct.pack("<II", len(payload), ct) |
| body += payload |
| total = 12 + 8 + len(new_json) + len(body) |
| blob = (struct.pack("<4sII", b"glTF", 2, total) |
| + struct.pack("<II", len(new_json), CHUNK_JSON) + new_json + bytes(body)) |
|
|
| tmp = TMP_DIR / ("%d_%s.glb" % (os.getpid(), hashlib.md5(path.encode()).hexdigest()[:12])) |
| tmp.write_bytes(blob) |
|
|
| rec.update( |
| status="accept", tmp=str(tmp), file_hash=file_hash, geo_hash=geo_hash, |
| n_verts=n_verts, n_faces=n_faces, n_joints=len(joints_union), |
| n_skins=len(skins), scale=round(scale, 6), |
| bbox_min=[round(v, 5) for v in mn.tolist()], |
| bbox_max=[round(v, 5) for v in mx.tolist()], |
| ) |
| return rec |
|
|
|
|
| |
|
|
| def iter_source_files(root): |
| for dirpath, dirnames, filenames in os.walk(root): |
| dirnames[:] = sorted(d for d in dirnames if not d.startswith(".")) |
| for fn in sorted(filenames): |
| if os.path.splitext(fn)[1].lower() in MESH_EXTS: |
| yield os.path.join(dirpath, fn) |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--limit-per-source", type=int, default=0, |
| help="smoke test: only process first N files of each source") |
| args = ap.parse_args() |
|
|
| MESH_DIR.mkdir(parents=True, exist_ok=True) |
| TMP_DIR.mkdir(parents=True, exist_ok=True) |
| for stale in TMP_DIR.glob("*.glb"): |
| stale.unlink(missing_ok=True) |
|
|
| processed = set() |
| if PROCESSED.exists(): |
| with open(PROCESSED) as f: |
| processed = {ln.rstrip("\n") for ln in f} |
| seen_file, seen_geo, used_names = set(), set(), set() |
| if MANIFEST.exists(): |
| with open(MANIFEST) as f: |
| for ln in f: |
| try: |
| r = json.loads(ln) |
| except Exception: |
| continue |
| seen_file.add(r["file_hash"]) |
| seen_geo.add(r["geo_hash"]) |
| used_names.add(r["out"]) |
| print("[init] resume: %d processed, %d accepted so far" |
| % (len(processed), len(seen_file)), flush=True) |
|
|
| def tasks(): |
| for tag, root in SOURCES: |
| it = iter_source_files(root) |
| if args.limit_per_source: |
| it = itertools.islice(it, args.limit_per_source) |
| for p in it: |
| if p not in processed: |
| yield (tag, p) |
|
|
| stats = Counter() |
| t0 = time.time() |
| n_done = 0 |
| man_f = open(MANIFEST, "a") |
| proc_f = open(PROCESSED, "a") |
|
|
| def dump_stats(): |
| payload = { |
| "done_this_run": n_done, |
| "elapsed_sec": round(time.time() - t0, 1), |
| "accepted_total": len(seen_file), |
| "counts": dict(stats), |
| } |
| STATS.write_text(json.dumps(payload, indent=2)) |
|
|
| with Pool(WORKERS, maxtasksperchild=500) as pool: |
| for rec in pool.imap(process_one, tasks(), chunksize=16): |
| n_done += 1 |
| tag = rec["tag"] |
| if rec["status"] == "reject": |
| reason = rec["reason"].split(":")[0] |
| stats["%s.reject.%s" % (tag, rec["reason"])] += 1 |
| else: |
| tmp = Path(rec.pop("tmp")) |
| if rec["file_hash"] in seen_file or rec["geo_hash"] in seen_geo: |
| tmp.unlink(missing_ok=True) |
| stats["%s.dup" % tag] += 1 |
| else: |
| seen_file.add(rec["file_hash"]) |
| seen_geo.add(rec["geo_hash"]) |
| stem = Path(rec["src"]).stem[:64] |
| name = stem + ".glb" |
| if name in used_names: |
| name = "%s_%s.glb" % (stem, rec["file_hash"][:8]) |
| used_names.add(name) |
| os.replace(tmp, MESH_DIR / name) |
| rec["out"] = name |
| man_f.write(json.dumps(rec) + "\n") |
| stats["%s.accept" % tag] += 1 |
| proc_f.write(rec["src"] + "\n") |
| if n_done % 200 == 0: |
| man_f.flush() |
| proc_f.flush() |
| if n_done % 5000 == 0: |
| acc = sum(v for k, v in stats.items() if k.endswith(".accept")) |
| print("[%.0fs] %d files done, %d accepted, %d dup" |
| % (time.time() - t0, n_done, acc, |
| sum(v for k, v in stats.items() if k.endswith(".dup"))), |
| flush=True) |
| dump_stats() |
|
|
| man_f.close() |
| proc_f.close() |
| dump_stats() |
| print("[DONE] %d files in %.0fs" % (n_done, time.time() - t0), flush=True) |
| print(json.dumps(dict(stats), indent=2, sort_keys=True), flush=True) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|