File size: 12,884 Bytes
a863f79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
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()