| import bpy |
| import os |
| import json |
| import math |
| import numpy as np |
| import random |
| from math import radians |
| import struct |
| import mathutils |
|
|
| |
| CONFIG = { |
| "RESULTS_PATH": os.environ.get("RESULTS_PATH"), |
| "EXPOSURES": [0.125, 0.25, 1.0, 2.0, 8.0], |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| "ROWS": 5, |
| "COLS": 7, |
| "ROT_STEP": 2.5, |
| |
| "RESOLUTION": 448, |
| "SAMPLES": 2048, |
| "TONEMAP_POOL": ['AgX', 'Filmic', 'Standard'], |
| } |
|
|
| chosen_tonemap = None |
|
|
| import math |
|
|
| def update_config_from_camera(): |
| cam = bpy.data.objects.get('Camera') |
| if not cam: |
| print("Error: No object named 'Camera' found in the scene") |
| return |
| loc = cam.location |
| CONFIG["INIT_LOC"] = np.array([[loc.x], [loc.z], [-loc.y]]) |
| CONFIG["RADIUS"] = loc.length |
| CONFIG["MAX_DISTANCE"] = loc.length * 1.5 |
| rot = cam.rotation_euler |
| pitch = math.degrees(rot.x) - 90 |
| yaw = math.degrees(rot.z) |
| roll = math.degrees(rot.y) |
| CONFIG["INIT_ROT"] = [pitch, yaw, roll] |
| print(f"--- CONFIG updated automatically ---") |
| print(f"INIT_LOC: {CONFIG['INIT_LOC'].flatten()}") |
| print(f"INIT_ROT: {CONFIG['INIT_ROT']}") |
| print(f"RADIUS: {CONFIG['RADIUS']:.4f}") |
| print(f"MAX_DISTANCE: {CONFIG['MAX_DISTANCE']:.4f}") |
|
|
| def setup_environment(): |
| global chosen_tonemap |
| scene = bpy.context.scene |
| scene.render.engine = 'CYCLES' |
| scene.cycles.samples = CONFIG["SAMPLES"] |
| scene.render.resolution_x = CONFIG["RESOLUTION"] |
| scene.render.resolution_y = CONFIG["RESOLUTION"] |
| scene.render.resolution_percentage = 100 |
| scene.render.dither_intensity = 0.0 |
| scene.render.film_transparent = True |
| scene.render.use_persistent_data = True |
| |
| |
| scene.render.image_settings.file_format = 'OPEN_EXR' |
| scene.render.image_settings.color_depth = '32' |
|
|
| |
| chosen_tonemap = random.choice(CONFIG["TONEMAP_POOL"]) if chosen_tonemap is None else chosen_tonemap |
| bpy.context.scene.view_settings.view_transform = chosen_tonemap |
|
|
| |
| try: |
| cprefs = bpy.context.preferences.addons['cycles'].preferences |
| cprefs.compute_device_type = 'OPTIX' |
| cprefs.get_devices() |
| for d in cprefs.devices: d.use = True |
| scene.cycles.device = 'GPU' |
| except: |
| print("Using CPU Rendering...") |
|
|
| def setup_nodes(save_root): |
| scene = bpy.context.scene |
| scene.use_nodes = True |
| tree = scene.node_tree |
| tree.nodes.clear() |
|
|
| rl = tree.nodes.new('CompositorNodeRLayers') |
| scene.view_layers["ViewLayer"].use_pass_normal = True |
| scene.view_layers["ViewLayer"].use_pass_z = True |
| |
| |
| aux_out = tree.nodes.new('CompositorNodeOutputFile') |
| aux_out.format.file_format = 'PNG' |
| |
| map_node = tree.nodes.new('CompositorNodeMapRange') |
| map_node.inputs['From Max'].default_value = CONFIG["MAX_DISTANCE"] |
| map_node.inputs['To Min'].default_value = 1 |
| map_node.inputs['To Max'].default_value = 0 |
|
|
| tree.links.new(rl.outputs['Depth'], map_node.inputs[0]) |
| |
| aux_out.file_slots[0].path = "depth_" |
| tree.links.new(map_node.outputs[0], aux_out.inputs[0]) |
| aux_out.file_slots.new("normal_") |
| tree.links.new(rl.outputs['Normal'], aux_out.inputs[1]) |
|
|
| |
| ldr_out = tree.nodes.new('CompositorNodeOutputFile') |
| ldr_out.format.file_format = 'PNG' |
| ldr_out.base_path = "" |
| ldr_out.file_slots.clear() |
|
|
| for i, exp_val in enumerate(CONFIG["EXPOSURES"]): |
| mix_node = tree.nodes.new('CompositorNodeMixRGB') |
| mix_node.blend_type = 'MULTIPLY' |
| mix_node.inputs[2].default_value = (exp_val, exp_val, exp_val, 1) |
| mix_node.inputs[0].default_value = 1.0 |
| |
| slot_name = f"ldr_exp_{str(i).replace('.', '_')}_" |
| ldr_out.file_slots.new(slot_name) |
| |
| tree.links.new(rl.outputs['Image'], mix_node.inputs[1]) |
| tree.links.new(mix_node.outputs[0], ldr_out.inputs[i]) |
| |
| return aux_out, ldr_out |
|
|
| def get_pose_matrix(pitch_deg, yaw_deg, radius): |
| phi, theta = radians(pitch_deg), radians(yaw_deg) |
| trans_t = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,radius],[0,0,0,1]], dtype=float) |
| rot_phi = np.array([[1,0,0,0],[0,np.cos(phi),-np.sin(phi),0],[0,np.sin(phi),np.cos(phi),0],[0,0,0,1]], dtype=float) |
| rot_theta = np.array([[np.cos(theta),0,np.sin(theta),0],[0,1,0,0],[-np.sin(theta),0,np.cos(theta),0],[0,0,0,1]], dtype=float) |
| return rot_theta @ (rot_phi @ trans_t) |
|
|
| def save_as_cameras_bin(data, file_path): |
| if os.path.exists(file_path): |
| print(f"Already have {file_path}. Skipping...") |
| return |
| w = int(data["w"]) |
| h = int(data["h"]) |
| fx = data["fl_x"] |
| fy = data["fl_y"] |
| cx = data["cx"] |
| cy = data["cy"] |
| with open(file_path, "wb") as f: |
| |
| f.write(struct.pack("<Q", 1)) |
| |
| f.write(struct.pack("<iiQQ", 1, 1, w, h)) |
| |
| f.write(struct.pack("<dddd", fx, fy, cx, cy)) |
|
|
| def save_all_frames_to_bin(json_data, bin_path): |
| flip_mat = mathutils.Matrix.Scale(-1, 4, (0,1,0)) @ mathutils.Matrix.Scale(-1, 4, (0,0,1)) |
|
|
| if os.path.exists(bin_path): |
| f = open(bin_path, "r+b") |
| total = struct.unpack("<Q", f.read(8))[0] |
| f.seek(0, 2) |
| else: |
| f = open(bin_path, "wb") |
| f.write(struct.pack("<Q", 0)) |
| total = 0 |
|
|
| for frame in json_data["frames"]: |
| total += 1 |
|
|
| m = mathutils.Matrix(frame["transform_matrix"]) |
| w2c = (m @ flip_mat).inverted() |
| q = w2c.to_quaternion() |
| t = w2c.translation |
|
|
| |
| f.write(struct.pack( |
| "<I dddd ddd I", |
| total, |
| q.w, q.x, q.y, q.z, |
| t.x, t.y, t.z, |
| 1 |
| )) |
|
|
| name = os.path.basename(frame["file_path"]) |
| name = name.replace("train_hdr_", "train_ldr_").replace("test_hdr_", "test_ldr_").replace(".exr", "_3.png") |
| name = name.encode("utf-8") + b"\x00" |
| |
| f.write(name) |
| f.write(struct.pack("<Q", 0)) |
| f.seek(0) |
| f.write(struct.pack("<Q", total)) |
| f.close() |
| return |
|
|
|
|
| |
| def render_task(is_train=True): |
| global chosen_tonemap |
| sub_folder = "train" if is_train else "test" |
| flag = 1 if is_train else 0 |
| |
| root_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), CONFIG["RESULTS_PATH"]) |
| |
| setup_environment() |
|
|
| cam = bpy.data.objects['Camera'] |
| bpy.context.scene.camera = cam |
| bpy.context.scene.frame_set(1) |
| if cam.animation_data: |
| cam.animation_data_clear() |
|
|
| aux_node, ldr_node = setup_nodes(root_path) |
|
|
| |
| if 'Empty' in bpy.data.objects: |
| bpy.data.objects.remove(bpy.data.objects['Empty'], do_unlink=True) |
| b_empty = bpy.data.objects.new("Empty", None) |
| bpy.context.scene.collection.objects.link(b_empty) |
| cam.parent = b_empty |
| cam.location = (0, 0, 0) |
| cam.rotation_euler = (0, 0, 0) |
|
|
|
|
| base_matrix = get_pose_matrix(CONFIG["INIT_ROT"][0], CONFIG["INIT_ROT"][1], CONFIG["RADIUS"]) |
| |
|
|
| res_x, res_y = bpy.context.scene.render.resolution_x, bpy.context.scene.render.resolution_y |
| fl_x = (res_x / 2) / math.tan(cam.data.angle_x / 2) |
| fl_y = (res_y / 2) / math.tan(cam.data.angle_y / 2) |
| json_data = { |
| "camera_angle_x": cam.data.angle_x, |
| "camera_angle_y": cam.data.angle_y, |
| "fl_x": fl_x, |
| "fl_y": fl_y, |
| "cx": res_x / 2, |
| "cy": res_y / 2, |
| "w": res_x, |
| "h": res_y, |
| 'tonemapping': chosen_tonemap, |
| 'look': bpy.context.scene.view_settings.look, |
| 'exposure_bracket': CONFIG["EXPOSURES"], |
| "frames": [] |
| } |
| exposure_data = {} |
|
|
| sparse_path = os.path.join(root_path, 'sparse', '0') |
| os.makedirs(sparse_path, exist_ok=True) |
| save_as_cameras_bin(json_data, os.path.join(sparse_path, 'cameras.bin')) |
| |
| count = 0 |
| row_cen, col_cen = (CONFIG["ROWS"]-1)/2, (CONFIG["COLS"]-1)/2 |
|
|
| for r in range(CONFIG["ROWS"]): |
| for c in range(CONFIG["COLS"]): |
| if (r + c) % 2 == flag: continue |
|
|
| |
| curr_pitch = (r - row_cen) * CONFIG["ROT_STEP"] + CONFIG["INIT_ROT"][0] |
| curr_yaw = (c - col_cen) * CONFIG["ROT_STEP"] + CONFIG["INIT_ROT"][1] |
| trans_m = get_pose_matrix(curr_pitch, curr_yaw, CONFIG["RADIUS"]) |
| loc_offset = trans_m[:3, 3:] - base_matrix[:3, 3:] + CONFIG["INIT_LOC"] |
| b_empty.location = (loc_offset[0][0], -loc_offset[2][0], loc_offset[1][0]) |
| b_empty.rotation_euler = (radians(curr_pitch + 90), 0, radians(curr_yaw)) |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| hdr_dir = os.path.join(root_path, 'images_hdr') |
| img_dir = os.path.join(root_path, 'images') |
| depth_dir = os.path.join(root_path, 'depth') |
| normal_dir = os.path.join(root_path, 'normal') |
| for d in [hdr_dir, img_dir, depth_dir, normal_dir]: |
| if not os.path.exists(d): os.makedirs(d) |
|
|
| bpy.context.scene.render.filepath = os.path.join(hdr_dir, f"{sub_folder}_hdr_{count:03d}.exr") |
| ldr_node.base_path = img_dir |
| for i, exp_val in enumerate(CONFIG["EXPOSURES"]): |
| slot_filename = f"{sub_folder}_ldr_{count:03d}_{i}_" |
| ldr_node.file_slots[i].path = slot_filename |
| slot_filename = f"{sub_folder}_ldr_{count:03d}_{i}.png" |
| exposure_data[slot_filename] = exp_val |
| aux_node.base_path = root_path |
| aux_node.file_slots[0].path = f"depth/{sub_folder}_depth_{count:03d}_" |
| aux_node.file_slots[1].path = f"normal/{sub_folder}_normal_{count:03d}_" |
|
|
| |
| bpy.ops.render.render(write_still=True) |
|
|
| |
| for folder in [img_dir, depth_dir, normal_dir]: |
| for f in os.listdir(folder): |
| if f.endswith("0001.png"): |
| os.rename(os.path.join(folder, f), os.path.join(folder, f.replace("_0001.png", ".png"))) |
|
|
| |
| json_data['frames'].append({ |
| 'file_path': os.path.join(f"{CONFIG['RESULTS_PATH']}", 'images_hdr', f"{sub_folder}_hdr_{count:03d}.exr"), |
| 'transform_matrix': [list(row) for row in cam.matrix_world], |
| }) |
| count += 1 |
|
|
| with open(os.path.join(root_path, f"transforms_{sub_folder}.json"), 'w') as f: |
| json.dump(json_data, f, indent=4) |
| save_all_frames_to_bin(json_data, os.path.join(sparse_path, 'images.bin')) |
|
|
| path = os.path.join(root_path, "exposure.json") |
| json_data = json.load(open(path)) if os.path.exists(path) else {} |
| json_data.update(exposure_data) |
| with open(path, "w") as f: |
| json.dump(json_data, f, indent=4) |
|
|
|
|
| if __name__ == "__main__": |
| update_config_from_camera() |
| render_task(True) |
| render_task(False) |
|
|