Spaces:
Running
Running
Add the bedroom, kitchen and garage scenes (part 3)
Browse filesFiles changed (10)
117 unmodified lines118119120121122123124117 unmodified lines.card[aria-current="true"] { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }.thumb { position: relative; aspect-ratio: 1; background: var(--thumb); display: grid; place-items: center; }.thumb img { width: 100%; height: 100%; object-fit: contain; display: block; }.thumb img.cover { object-fit: cover; }.badges { position: absolute; top: 7px; left: 7px; display: flex; gap: 4px; pointer-events: none; }.badge { display: inline-flex; align-items: center; height: 20px; padding: 0 6px; font: 600 10.5px/1 var(--mono); letter-spacing: 0.03em; border-radius: 5px; background: var(--scrim); color: #f3eee8; }.card-text { padding: 9px 10px 10px; display: grid; align-content: start; gap: 2px; min-width: 0; }123456789101112131415161718192021222324252627282930"""Blender (5.x) script: shrink a scene GLB for the web viewer.
Run: Blender -b --factory-startup --python tools/blender_scene_glb.py -- <in.glb> <out.glb> [max_texture_px]
Re-exports with textures downsized (JPEG) and Draco-compressed geometry; layout,materials and object names stay as they are."""
import sys
import bpy
args = sys.argv[sys.argv.index("--") + 1:]src, out = args[0], args[1]max_px = int(args[2]) if len(args) > 2 else 2048
bpy.ops.wm.read_factory_settings(use_empty=True)bpy.ops.import_scene.gltf(filepath=src)for img in bpy.data.images: w, h = img.size if max(w, h) > max_px: s = max_px / max(w, h) img.scale(max(1, int(w * s)), max(1, int(h * s)))bpy.ops.export_scene.gltf( filepath=out, export_format="GLB", export_yup=True, export_apply=True, export_draco_mesh_compression_enable=True, export_draco_mesh_compression_level=6, export_image_format="JPEG", export_image_quality=82, export_cameras=False, export_lights=False, export_animations=False,)print("SCENE_OK")101 unmodified lines10210310410510610710810911011111211311411511611711811912012112212312474 unmodified lines199200201202203204205206101 unmodified lines return read_root_layer(local)
def scene_records(previews): """Scenes from tools/scenes.json (gated dataset projectsim/scenes-and-worlds).""" path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "scenes.json") if not os.path.exists(path): return [] cfg = json.load(open(path)) return [{ "id": s["id"], "name": s["name"], "kind": "scene", "group": "Scenes", "category": "indoor rooms", "class": "indoor scene", "qcode": None, "mass": None, "extents": s["extents"], "rigid_bodies": None, "joints": [], "mounted": False, "license": "CC-BY-4.0", "date": None, "version": None, "glass": False, "scene": s["scene"], "scene_dataset": cfg["dataset"], "objects": s["objects"], "triangles": s["triangles"], "splat": s["splat"], "summary": s["summary"], "preview": os.path.exists(os.path.join(previews, "scenes", f"{s['scene']}.glb")), "thumb": os.path.exists(os.path.join(previews, "thumbs", f"{s['id']}.webp")), } for s in cfg["scenes"]]
def thumbs_rev(previews): folder = os.path.join(previews, "thumbs") if not os.path.isdir(folder):74 unmodified lines "glass": any("/simready_usd/materials/" in p for p in paths), })
records += scene_records(args.previews)
out = { "dataset": args.dataset, "commit": sha,8 unmodified lines91011121314158 unmodified lines "Office & electronics", "Packaging & logistics", "Toys, hobbies & sports", "Scenes", "Other" ], "categories": {123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263# /// script# requires-python = ">=3.10"# dependencies = ["pillow"]# ///"""Make the web previews for the scenes listed in tools/scenes.json.
For each scene, downloads scenes/<scene>/<scene>.glb and preview.png from the gateddataset (read only; needs HF_TOKEN from an account with access), shrinks the GLB withBlender (tools/blender_scene_glb.py) into previews/scenes/<scene>.glb, and writes a960 px thumbnail to previews/thumbs/<id>.webp.
Run from the Space folder: HF_TOKEN=$(hf auth token) uv run tools/make_scene_previews.py"""
import argparseimport jsonimport osimport subprocessimport sysimport tempfileimport urllib.request
from PIL import Image
HF = "https://huggingface.co"HERE = os.path.dirname(os.path.abspath(__file__))
def download(url, dest): headers = {"Authorization": f"Bearer {os.environ['HF_TOKEN']}"} if os.environ.get("HF_TOKEN") else {} with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=600) as r, open(dest, "wb") as f: while chunk := r.read(1 << 20): f.write(chunk)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--blender", default="/Applications/Blender.app/Contents/MacOS/Blender") ap.add_argument("--max-texture", type=int, default=2048) args = ap.parse_args() cfg = json.load(open(os.path.join(HERE, "scenes.json"))) os.makedirs("previews/scenes", exist_ok=True) os.makedirs("previews/thumbs", exist_ok=True) for s in cfg["scenes"]: base = f"{HF}/datasets/{cfg['dataset']}/resolve/main/scenes/{s['scene']}" with tempfile.TemporaryDirectory() as tmp: glb, png = os.path.join(tmp, "in.glb"), os.path.join(tmp, "preview.png") download(f"{base}/{s['scene']}.glb", glb) download(f"{base}/preview.png", png) out = f"previews/scenes/{s['scene']}.glb" run = subprocess.run([args.blender, "-b", "--factory-startup", "--python", os.path.join(HERE, "blender_scene_glb.py"), "--", glb, out, str(args.max_texture)], capture_output=True, text=True) if "SCENE_OK" not in run.stdout: sys.exit(f"{s['scene']}: Blender failed\n{(run.stdout + run.stderr)[-800:]}") img = Image.open(png).convert("RGB") img.thumbnail((960, 960)) img.save(f"previews/thumbs/{s['id']}.webp", quality=88) print(f"{s['name']}: {os.path.getsize(out) / 1e6:.1f} MB GLB", file=sys.stderr)
if __name__ == "__main__": main()123456789101112131415161718192021{ "_comment": "Scenes shown in the Library (group 'Scenes'), from the gated dataset projectsim/scenes-and-worlds. tools/make_scene_previews.py makes previews/scenes/<scene>.glb and previews/thumbs/<id>.webp; build_catalog.py adds these entries to the catalog. extents are metres x, y (depth), z (height).", "dataset": "projectsim/scenes-and-worlds", "scenes": [ { "id": "scene-bedroom", "scene": "bedroom", "name": "Bedroom", "extents": [4.5, 4.5, 3.0], "objects": 35, "triangles": 269472, "splat": false, "summary": "A furnished bedroom: bed, nightstands, lamps, drawers, mirror, books and small items, each its own USD." }, { "id": "scene-kitchen", "scene": "kitchen", "name": "Kitchen", "extents": [5.0, 4.5, 3.0], "objects": 18, "triangles": 346058, "splat": true, "summary": "A kitchen wall with cabinets, sink, fridge and countertop items, plus a Gaussian splat backdrop." }, { "id": "scene-garage", "scene": "garage", "name": "Garage", "extents": [7.0, 6.0, 3.5], "objects": 40, "triangles": 840444, "splat": true, "summary": "A garage workshop with shelving, a work table, storage bins, a desk and tools, plus a Gaussian splat backdrop." } ]}229 unmodified lines2302312322332332342352362372382392402402412422432442456 unmodified lines25225325425325525625725840 unmodified lines299300301300302303304305306307308309310311312313302303304314315316317318319320229 unmodified lines onJoint(r.index, v); }
// opts.interior: a room. Start inside at eye height, no shadows; opts.enclosed keeps the camera inside the walls. async function load(glbUrl, rigUrl) { async function load(glbUrl, rigUrl, opts = {}) { const mine = ++gen; clear(); status.textContent = "Loading 3D preview…"; status.hidden = false; let gltf, data; try { [gltf, data] = await Promise.all([loader.loadAsync(glbUrl), fetch(rigUrl).then((r) => r.ok ? r.json() : { joints: [] })]); [gltf, data] = await Promise.all([loader.loadAsync(glbUrl), rigUrl ? fetch(rigUrl).then((r) => r.ok ? r.json() : { joints: [] }) : { joints: [] }]); } catch (e) { console.error("3D preview failed to load", glbUrl, e); if (mine === gen) status.textContent = `The 3D preview didn't load (${String((e && e.message) || e).slice(0, 120)}).`;6 unmodified lines model.add(inner); scene.add(model); model.updateMatrixWorld(true); model.traverse((o) => { if (o.isMesh) o.castShadow = true; }); model.traverse((o) => { if (o.isMesh) o.castShadow = !opts.interior; });
const byName = {}; gltf.scene.traverse((n) => { if (n.name && !(clean(n.name) in byName)) byName[clean(n.name)] = n; });40 unmodified lines
const box = new THREE.Box3().setFromObject(model); const c = box.getCenter(new THREE.Vector3()); const size = Math.max(box.getSize(new THREE.Vector3()).length(), 0.02); const dims = box.getSize(new THREE.Vector3()); const size = Math.max(dims.length(), 0.02); camera.near = size / 400; camera.far = size * 80; camera.fov = opts.interior ? 68 : 35; // a room needs a wide, photo-like lens if (opts.interior) { const eye = box.min.y + Math.min(1.6, dims.y * 0.55); camera.near = 0.02; camera.position.set(c.x + dims.x * 0.4, eye, c.z + dims.z * 0.4); // near a corner controls.target.set(c.x, eye - 0.55, c.z); // looking into the room controls.minDistance = 0.1; controls.maxDistance = opts.enclosed ? Math.min(dims.x, dims.z) * 0.45 : size * 3; } else { camera.position.set(c.x + size * 0.85, c.y + size * 0.55, c.z + size * 1.05); controls.target.copy(c); controls.minDistance = size * 0.05; controls.maxDistance = size * 10; camera.position.set(c.x + size * 0.85, c.y + size * 0.55, c.z + size * 1.05); controls.target.copy(c); controls.minDistance = size * 0.05; controls.maxDistance = size * 10; } camera.updateProjectionMatrix(); placeGrid(); status.hidden = true;previews/thumbs/scene-bedroom.webpAdded
Large File Pointer Details
- SHA256: bb945041c3882af25286d95c992d48fbbd2f84d1e2dadfa1fc9ed25f8ba53ccd
- Pointer size: 130 Bytes
- Size of remote file: 74.3 kB
previews/thumbs/scene-garage.webpAdded
Large File Pointer Details
- SHA256: 3d2f9899481aca8bcbabc17571a0e7d99a159bcd2d0de7bfce88634bddc5cc67
- Pointer size: 130 Bytes
- Size of remote file: 62.6 kB
previews/thumbs/scene-kitchen.webpAdded
Large File Pointer Details
- SHA256: d93de071bdf6a714ae46bb194fa17fa67ca0cb0dfa4bd8632d01b3551f72fd57
- Pointer size: 130 Bytes
- Size of remote file: 49 kB
style.css+1
tools/blender_scene_glb.pyAdded+30
tools/build_catalog.py+19
tools/groups.json+1
tools/make_scene_previews.pyAdded+63
tools/scenes.jsonAdded+21
viewer.js+20-7