Datasets:
Download code/blender_render.py from spatial-evidence-bench/SpatialEvidenceBench: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/datasets/spatial-evidence-bench/SpatialEvidenceBench/resolve/81ec431b4e89dd554f2e9ee6ee04e3e137bca476/code/blender_render.py
- Command line
-
hf download hf://datasets/spatial-evidence-bench/SpatialEvidenceBench@81ec431b4e89dd554f2e9ee6ee04e3e137bca476/code/blender_render.py
-
curl -L -o blender_render.py https://huggingface.co/datasets/spatial-evidence-bench/SpatialEvidenceBench/resolve/81ec431b4e89dd554f2e9ee6ee04e3e137bca476/code/blender_render.py
12.9 kB
| import argparse | |
| import json | |
| import math | |
| import sys | |
| from pathlib import Path | |
| import bpy | |
| from mathutils import Vector | |
| def clear_scene(): | |
| bpy.ops.wm.read_factory_settings(use_empty=True) | |
| def add_shelf(name, size_x, size_y, thickness, z_top, location): | |
| bpy.ops.mesh.primitive_cube_add(size=1.0, location=(location[0], location[1], z_top - thickness / 2.0)) | |
| obj = bpy.context.active_object | |
| obj.name = name | |
| obj.scale = (size_x, size_y, thickness) | |
| bpy.ops.object.transform_apply(location=False, rotation=False, scale=True) | |
| mat = bpy.data.materials.new(f"{name}_mat") | |
| mat.use_nodes = True | |
| bsdf = mat.node_tree.nodes["Principled BSDF"] | |
| bsdf.inputs["Base Color"].default_value = (0.82, 0.80, 0.76, 1.0) | |
| bsdf.inputs["Roughness"].default_value = 0.75 | |
| obj.data.materials.append(mat) | |
| return obj | |
| def import_glb(path): | |
| before = set(bpy.data.objects) | |
| bpy.ops.import_scene.gltf(filepath=str(path)) | |
| new = [o for o in bpy.data.objects if o not in before and o.type == "MESH"] | |
| if not new: | |
| raise RuntimeError(f"no mesh imported from {path}") | |
| bpy.ops.object.select_all(action="DESELECT") | |
| for o in new: | |
| o.select_set(True) | |
| bpy.context.view_layer.objects.active = new[0] | |
| bpy.ops.object.parent_clear(type="CLEAR_KEEP_TRANSFORM") | |
| bpy.ops.object.join() | |
| obj = bpy.context.active_object | |
| if obj is None or obj.type != "MESH": | |
| raise RuntimeError(f"join failed for {path}") | |
| bpy.ops.object.transform_apply(location=True, rotation=True, scale=True) | |
| return obj | |
| def normalize_object(obj, target_extent): | |
| xs = [v.co.x for v in obj.data.vertices] | |
| ys = [v.co.y for v in obj.data.vertices] | |
| zs = [v.co.z for v in obj.data.vertices] | |
| extent = max(max(xs) - min(xs), max(ys) - min(ys), max(zs) - min(zs)) | |
| if extent <= 1e-6: | |
| raise RuntimeError("degenerate mesh") | |
| scale = target_extent / extent | |
| obj.scale = (scale, scale, scale) | |
| bpy.ops.object.transform_apply(location=False, rotation=False, scale=True) | |
| xs = [v.co.x for v in obj.data.vertices] | |
| ys = [v.co.y for v in obj.data.vertices] | |
| zs = [v.co.z for v in obj.data.vertices] | |
| cx = (max(xs) + min(xs)) / 2.0 | |
| cy = (max(ys) + min(ys)) / 2.0 | |
| cz = min(zs) | |
| for v in obj.data.vertices: | |
| v.co.x -= cx | |
| v.co.y -= cy | |
| v.co.z -= cz | |
| return { | |
| "size_x": max(xs) - min(xs), | |
| "size_y": max(ys) - min(ys), | |
| "size_z": max(zs) - min(zs), | |
| } | |
| def world_bbox(obj): | |
| corners = [obj.matrix_world @ Vector(c) for c in obj.bound_box] | |
| xs = [c.x for c in corners] | |
| ys = [c.y for c in corners] | |
| zs = [c.z for c in corners] | |
| return { | |
| "min": [min(xs), min(ys), min(zs)], | |
| "max": [max(xs), max(ys), max(zs)], | |
| "center": [(min(xs) + max(xs)) / 2.0, (min(ys) + max(ys)) / 2.0, (min(zs) + max(zs)) / 2.0], | |
| } | |
| def look_at(obj, target): | |
| direction = target - obj.location | |
| obj.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler() | |
| def setup_camera(cam_cfg, look_at_point, resolution, near, far): | |
| bpy.ops.object.camera_add() | |
| cam = bpy.context.active_object | |
| az = math.radians(cam_cfg["azimuth_deg"]) | |
| el = math.radians(cam_cfg["elevation_deg"]) | |
| dist = cam_cfg["distance_m"] | |
| cam.location = ( | |
| look_at_point[0] + dist * math.cos(el) * math.cos(az), | |
| look_at_point[1] + dist * math.cos(el) * math.sin(az), | |
| look_at_point[2] + dist * math.sin(el), | |
| ) | |
| look_at(cam, Vector(look_at_point)) | |
| cam.data.lens = cam_cfg["lens_mm"] | |
| cam.data.sensor_width = cam_cfg["sensor_mm"] | |
| cam.data.clip_start = near | |
| cam.data.clip_end = far | |
| bpy.context.scene.camera = cam | |
| bpy.context.scene.render.resolution_x = resolution[0] | |
| bpy.context.scene.render.resolution_y = resolution[1] | |
| bpy.context.scene.render.resolution_percentage = 100 | |
| return cam | |
| def setup_lights(cfg, look_at_point): | |
| world = bpy.data.worlds.new("World") | |
| world.use_nodes = True | |
| bg = world.node_tree.nodes["Background"] | |
| bg.inputs["Color"].default_value = (*cfg["render"]["background_rgb"], 1.0) | |
| bg.inputs["Strength"].default_value = cfg["render"]["ambient_strength"] | |
| bpy.context.scene.world = world | |
| bpy.ops.object.light_add(type="AREA", location=(look_at_point[0] - 1.4, look_at_point[1] - 1.6, look_at_point[2] + 2.0)) | |
| light = bpy.context.active_object | |
| light.data.energy = cfg["render"]["light_energy"] | |
| light.data.size = cfg["render"]["light_size_m"] | |
| look_at(light, Vector(look_at_point)) | |
| def enable_depth_pass(near, far): | |
| scene = bpy.context.scene | |
| bpy.context.view_layer.use_pass_z = True | |
| scene.use_nodes = True | |
| tree = scene.node_tree | |
| tree.nodes.clear() | |
| layers = tree.nodes.new("CompositorNodeRLayers") | |
| mapping = tree.nodes.new("CompositorNodeMapRange") | |
| mapping.inputs["From Min"].default_value = near | |
| mapping.inputs["From Max"].default_value = far | |
| mapping.inputs["To Min"].default_value = 1.0 | |
| mapping.inputs["To Max"].default_value = 0.0 | |
| composite = tree.nodes.new("CompositorNodeComposite") | |
| tree.links.new(layers.outputs["Depth"], mapping.inputs["Value"]) | |
| tree.links.new(mapping.outputs["Value"], composite.inputs["Image"]) | |
| def apply_render_settings(cfg, device="CPU", threads=16): | |
| scene = bpy.context.scene | |
| scene.render.engine = "CYCLES" | |
| scene.cycles.device = device | |
| scene.render.threads_mode = "FIXED" | |
| scene.render.threads = threads | |
| scene.cycles.samples = cfg["render"]["samples"] | |
| scene.cycles.use_denoising = False | |
| scene.cycles.max_bounces = 4 | |
| scene.render.image_settings.color_mode = "RGB" | |
| scene.view_settings.view_transform = "Standard" | |
| def render_rgb(path): | |
| scene = bpy.context.scene | |
| scene.use_nodes = False | |
| scene.render.image_settings.color_depth = "8" | |
| scene.render.filepath = str(path) | |
| scene.render.image_settings.file_format = "PNG" | |
| scene.render.image_settings.color_mode = "RGB" | |
| bpy.ops.render.render(write_still=True) | |
| def set_emission(bsdf, color, strength): | |
| socket = bsdf.inputs.get("Emission Color") or bsdf.inputs.get("Emission") | |
| if socket is None: | |
| raise RuntimeError("找不到自发光输入端口") | |
| socket.default_value = color | |
| bsdf.inputs["Emission Strength"].default_value = strength | |
| def render_mask(path, ids): | |
| scene = bpy.context.scene | |
| scene.use_nodes = False | |
| colors = [(0.0, 0.0, 0.0, 1.0), (1.0, 0.0, 0.0, 1.0), (0.0, 1.0, 0.0, 1.0), (0.0, 0.0, 1.0, 1.0)] | |
| saved = [] | |
| for obj, idx in ids.items(): | |
| mat = bpy.data.materials.new(f"mask_{idx}") | |
| mat.use_nodes = True | |
| bsdf = mat.node_tree.nodes["Principled BSDF"] | |
| bsdf.inputs["Base Color"].default_value = colors[idx] | |
| set_emission(bsdf, colors[idx], 1.0) | |
| bsdf.inputs["Roughness"].default_value = 1.0 | |
| saved.append((obj, list(obj.data.materials))) | |
| obj.data.materials.clear() | |
| obj.data.materials.append(mat) | |
| scene.render.filepath = str(path) | |
| scene.render.image_settings.file_format = "PNG" | |
| scene.render.image_settings.color_mode = "RGB" | |
| bpy.ops.render.render(write_still=True) | |
| for obj, mats in saved: | |
| obj.data.materials.clear() | |
| for mat in mats: | |
| obj.data.materials.append(mat) | |
| def build_state(spec, state_key, cfg, work_dir): | |
| state = spec["states"][state_key] | |
| scene_cfg = cfg["scene"] | |
| clear_scene() | |
| support = add_shelf( | |
| "support", | |
| scene_cfg["support_size_m"], | |
| scene_cfg["support_size_m"], | |
| 0.08, | |
| scene_cfg["support_height_m"], | |
| (0.0, 0.0), | |
| ) | |
| top_z = scene_cfg["support_height_m"] | |
| entities = {} | |
| if spec["family"] == "above_below": | |
| shelf_z = top_z + state["subject"][2] | |
| add_shelf("subject_shelf", 0.55, 0.55, 0.03, shelf_z, (state["subject"][0], state["subject"][1])) | |
| state = dict(state) | |
| state["subject"] = [state["subject"][0], state["subject"][1], state["subject"][2] + 0.0] | |
| for role in ("object", "subject"): | |
| info = spec[role] | |
| obj = import_glb(Path(info["path"])) | |
| target_extent = scene_cfg["object_scale_m"] | |
| if spec["family"] == "on_not_on" and role == "subject": | |
| target_extent = scene_cfg["object_scale_m"] * 0.55 | |
| dims = normalize_object(obj, target_extent) | |
| pos = state[role] | |
| z = top_z + pos[2] | |
| if spec["family"] == "above_below" and role == "subject": | |
| z = top_z + pos[2] + 0.03 | |
| obj.location = (pos[0], pos[1], z) | |
| obj.rotation_euler = (0.0, 0.0, math.radians(spec.get("yaw", {}).get(role, 0.0))) | |
| bpy.context.view_layer.update() | |
| if spec["family"] == "on_not_on" and role == "subject" and state.get("contact"): | |
| object_top = world_bbox(entities["object"]["obj"])["max"][2] | |
| obj.location = (pos[0], pos[1], object_top) | |
| bpy.context.view_layer.update() | |
| entities[role] = {"obj": obj, "dims": dims, "uid": info["uid"], "category": info["category"]} | |
| near = max(0.1, cfg["camera"]["distance_m"] - 1.6) | |
| far = cfg["camera"]["distance_m"] + 2.0 | |
| cam = setup_camera(spec["camera"], spec["look_at"], cfg["resolution"], near, far) | |
| setup_lights(cfg, spec["look_at"]) | |
| return cam, entities, support, near, far | |
| def export_meta(path, spec, state_key, cam, entities, support, near, far, resolution): | |
| def obj_row(name, entry): | |
| bbox = world_bbox(entry["obj"]) | |
| return { | |
| "role": name, | |
| "uid": entry.get("uid"), | |
| "category": entry.get("category"), | |
| "world_bbox": bbox, | |
| "dims": entry.get("dims"), | |
| } | |
| cam_matrix = [[cam.matrix_world[i][j] for j in range(4)] for i in range(4)] | |
| meta = { | |
| "scene_id": spec["scene_id"], | |
| "family": spec["family"], | |
| "state": state_key, | |
| "question": spec["question"], | |
| "truth": spec["states"][state_key]["truth"], | |
| "image": f"{spec['scene_id']}_{state_key}.png", | |
| "mask": f"{spec['scene_id']}_{state_key}_mask.png", | |
| "depth": f"{spec['scene_id']}_{state_key}_depth.png", | |
| "camera": { | |
| "matrix_world": cam_matrix, | |
| "lens_mm": cam.data.lens, | |
| "sensor_mm": cam.data.sensor_width, | |
| "clip_near": near, | |
| "clip_far": far, | |
| "resolution": resolution, | |
| }, | |
| "objects": [obj_row("subject", entities["subject"]), obj_row("object", entities["object"])], | |
| "support": {"category": "table", "world_bbox": world_bbox(support)}, | |
| "assets": { | |
| "subject_uid": spec["subject"]["uid"], | |
| "object_uid": spec["object"]["uid"], | |
| "support_uid": spec["support"]["uid"], | |
| }, | |
| } | |
| Path(path).write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8") | |
| def main(): | |
| argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else sys.argv[1:] | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--specs", required=True) | |
| parser.add_argument("--config", required=True) | |
| parser.add_argument("--out", required=True) | |
| parser.add_argument("--shard", type=int, default=0) | |
| parser.add_argument("--shards", type=int, default=1) | |
| parser.add_argument("--limit", type=int, default=0) | |
| parser.add_argument("--device", default="CPU", choices=["CPU", "GPU"]) | |
| parser.add_argument("--threads", type=int, default=16) | |
| args = parser.parse_args(argv) | |
| cfg = json.loads(Path(args.config).read_text(encoding="utf-8")) | |
| specs = [json.loads(line) for line in Path(args.specs).open(encoding="utf-8")] | |
| specs = [s for i, s in enumerate(specs) if i % args.shards == args.shard] | |
| if args.limit: | |
| specs = specs[: args.limit] | |
| out = Path(args.out) | |
| out.mkdir(parents=True, exist_ok=True) | |
| total = len(specs) * 2 | |
| done = 0 | |
| for spec in specs: | |
| for state_key in ("a", "b"): | |
| cam, entities, support, near, far = build_state(spec, state_key, cfg, out) | |
| apply_render_settings(cfg, args.device, args.threads) | |
| stem = f"{spec['scene_id']}_{state_key}" | |
| scene = bpy.context.scene | |
| render_rgb(out / f"{stem}.png") | |
| ids = {entities["subject"]["obj"]: 1, entities["object"]["obj"]: 2, support: 3} | |
| render_mask(out / f"{stem}_mask.png", ids) | |
| enable_depth_pass(near, far) | |
| scene.render.image_settings.file_format = "PNG" | |
| scene.render.image_settings.color_depth = "16" | |
| scene.render.filepath = str(out / f"{stem}_depth.png") | |
| bpy.ops.render.render(write_still=True) | |
| export_meta(out / f"{stem}.json", spec, state_key, cam, entities, support, near, far, cfg["resolution"]) | |
| done += 1 | |
| print(f"PROGRESS {done}/{total} {stem}", flush=True) | |
| if __name__ == "__main__": | |
| main() | |