| import argparse |
| import json |
| import math |
| import sys |
| from pathlib import Path |
|
|
| import bpy |
| import numpy as np |
| from mathutils import Vector |
|
|
|
|
| IMPORTERS = { |
| "obj": bpy.ops.wm.obj_import, |
| "ply": bpy.ops.wm.ply_import, |
| "glb": bpy.ops.import_scene.gltf, |
| "gltf": bpy.ops.import_scene.gltf, |
| "fbx": bpy.ops.import_scene.fbx, |
| "stl": bpy.ops.import_mesh.stl, |
| } |
|
|
|
|
| def orthographic_views(num_views: int) -> list[dict[str, float]]: |
| base_views = [ |
| (-0.5 * np.pi, 0.0), |
| (0.0, 0.0), |
| (0.5 * np.pi, 0.0), |
| (np.pi, 0.0), |
| (-0.5 * np.pi, 0.5 * np.pi), |
| (-0.5 * np.pi, -0.5 * np.pi), |
| ] |
| if num_views <= len(base_views): |
| selected = base_views[:num_views] |
| else: |
| selected = base_views[:] |
| for index in range(num_views - len(base_views)): |
| azimuth = 2.0 * np.pi * index / max(1, num_views - len(base_views)) |
| selected.append((azimuth, np.pi / 6.0)) |
| return [{"azimuth": yaw, "elevation": pitch, "distance": 1.5, "fov": 0.6} for yaw, pitch in selected] |
|
|
|
|
| def clear_scene() -> None: |
| for collection in (bpy.data.objects, bpy.data.materials, bpy.data.textures, bpy.data.images): |
| for item in list(collection): |
| collection.remove(item, do_unlink=True) |
|
|
|
|
| def load_model(path: Path) -> None: |
| extension = path.suffix.lower().lstrip(".") |
| if extension not in IMPORTERS: |
| raise ValueError(f"Unsupported model format: {path.suffix}") |
| importer = IMPORTERS[extension] |
| if extension in {"glb", "gltf"}: |
| importer(filepath=str(path), merge_vertices=True, import_shading="NORMALS") |
| else: |
| importer(filepath=str(path)) |
|
|
|
|
| def scene_bbox() -> tuple[Vector, Vector]: |
| bbox_min = Vector((math.inf, math.inf, math.inf)) |
| bbox_max = Vector((-math.inf, -math.inf, -math.inf)) |
| found = False |
| for obj in bpy.context.scene.objects: |
| if not isinstance(obj.data, bpy.types.Mesh): |
| continue |
| found = True |
| for coord in obj.bound_box: |
| world_coord = obj.matrix_world @ Vector(coord) |
| bbox_min = Vector(tuple(min(bbox_min[i], world_coord[i]) for i in range(3))) |
| bbox_max = Vector(tuple(max(bbox_max[i], world_coord[i]) for i in range(3))) |
| if not found: |
| raise RuntimeError("The scene does not contain a mesh object.") |
| return bbox_min, bbox_max |
|
|
|
|
| def normalize_scene() -> tuple[float, Vector]: |
| root_objects = [obj for obj in bpy.context.scene.objects if obj.parent is None] |
| if len(root_objects) > 1: |
| parent = bpy.data.objects.new("SceneRoot", None) |
| bpy.context.scene.collection.objects.link(parent) |
| for obj in root_objects: |
| obj.parent = parent |
| else: |
| parent = root_objects[0] |
|
|
| bbox_min, bbox_max = scene_bbox() |
| scale = 1.0 / max(bbox_max - bbox_min) |
| parent.scale *= scale |
| bpy.context.view_layer.update() |
|
|
| bbox_min, bbox_max = scene_bbox() |
| offset = -(bbox_min + bbox_max) * 0.5 |
| parent.matrix_world.translation += offset |
| bpy.context.view_layer.update() |
| return scale, offset |
|
|
|
|
| def configure_render(resolution: int, engine: str) -> None: |
| scene = bpy.context.scene |
| scene.render.engine = engine |
| scene.render.resolution_x = resolution |
| scene.render.resolution_y = resolution |
| scene.render.resolution_percentage = 100 |
| scene.render.image_settings.file_format = "PNG" |
| scene.render.image_settings.color_mode = "RGBA" |
| scene.render.film_transparent = True |
|
|
| if engine == "CYCLES": |
| scene.cycles.device = "GPU" |
| scene.cycles.samples = 64 |
| scene.cycles.use_denoising = True |
| try: |
| prefs = bpy.context.preferences.addons["cycles"].preferences |
| prefs.compute_device_type = "CUDA" |
| prefs.get_devices() |
| for device in prefs.devices: |
| device.use = device.type == "CUDA" |
| except Exception: |
| pass |
|
|
|
|
| def create_camera() -> bpy.types.Object: |
| camera = bpy.data.objects.new("Camera", bpy.data.cameras.new("Camera")) |
| bpy.context.collection.objects.link(camera) |
| bpy.context.scene.camera = camera |
| camera.data.type = "ORTHO" |
| camera.data.ortho_scale = 1.2 |
|
|
| target = bpy.data.objects.new("CameraTarget", None) |
| bpy.context.collection.objects.link(target) |
| target.location = (0.0, 0.0, 0.0) |
|
|
| constraint = camera.constraints.new(type="TRACK_TO") |
| constraint.track_axis = "TRACK_NEGATIVE_Z" |
| constraint.up_axis = "UP_Y" |
| constraint.target = target |
| return camera |
|
|
|
|
| def add_lighting() -> None: |
| light_specs = [ |
| ("KeyLight", "POINT", 1000.0, (4.0, 1.0, 6.0), (1.0, 1.0, 1.0)), |
| ("TopLight", "AREA", 10000.0, (0.0, 0.0, 10.0), (100.0, 100.0, 100.0)), |
| ("BottomLight", "AREA", 1000.0, (0.0, 0.0, -10.0), (100.0, 100.0, 100.0)), |
| ] |
| for name, kind, energy, location, scale in light_specs: |
| light = bpy.data.objects.new(name, bpy.data.lights.new(name, type=kind)) |
| bpy.context.collection.objects.link(light) |
| light.data.energy = energy |
| light.location = location |
| light.scale = scale |
|
|
|
|
| def apply_neutral_material() -> None: |
| material = bpy.data.materials.new("NeutralMaterial") |
| material.use_nodes = True |
| material.node_tree.nodes.clear() |
| shader = material.node_tree.nodes.new("ShaderNodeBsdfDiffuse") |
| shader.inputs[0].default_value = (0.5, 0.5, 0.5, 1.0) |
| output = material.node_tree.nodes.new("ShaderNodeOutputMaterial") |
| material.node_tree.links.new(shader.outputs["BSDF"], output.inputs["Surface"]) |
| bpy.context.scene.view_layers["ViewLayer"].material_override = material |
|
|
|
|
| def camera_transform(camera: bpy.types.Object) -> list[list[float]]: |
| location, rotation, _ = camera.matrix_world.decompose() |
| rotation = rotation.to_matrix() |
| rows = [] |
| for row_index in range(3): |
| row = [rotation[row_index][col_index] for col_index in range(3)] |
| row.append(location[row_index]) |
| rows.append(row) |
| rows.append([0.0, 0.0, 0.0, 1.0]) |
| return rows |
|
|
|
|
| def export_mesh(path: Path) -> None: |
| bpy.ops.object.select_all(action="DESELECT") |
| mesh_objects = [obj for obj in bpy.context.scene.objects if obj.type == "MESH"] |
| if not mesh_objects: |
| return |
| bpy.context.view_layer.objects.active = mesh_objects[0] |
| for obj in mesh_objects: |
| obj.select_set(True) |
| bpy.ops.object.convert(target="MESH") |
| bpy.ops.object.mode_set(mode="EDIT") |
| bpy.ops.mesh.select_all(action="SELECT") |
| bpy.ops.mesh.quads_convert_to_tris(quad_method="BEAUTY", ngon_method="BEAUTY") |
| bpy.ops.object.mode_set(mode="OBJECT") |
| bpy.ops.wm.ply_export(filepath=str(path), export_triangulated_mesh=True, up_axis="Y", forward_axis="NEGATIVE_Z") |
|
|
|
|
| def render(args: argparse.Namespace) -> None: |
| output_dir = Path(args.output_folder) |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| clear_scene() |
| load_model(Path(args.object)) |
| scale, offset = normalize_scene() |
| configure_render(args.resolution, args.engine) |
| camera = create_camera() |
| add_lighting() |
| apply_neutral_material() |
|
|
| metadata = { |
| "aabb": [[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]], |
| "scale": scale, |
| "offset": [offset.x, offset.y, offset.z], |
| "frames": [], |
| } |
|
|
| for index, view in enumerate(orthographic_views(args.num_views)): |
| camera.location = ( |
| view["distance"] * np.cos(view["azimuth"]) * np.cos(view["elevation"]), |
| view["distance"] * np.sin(view["azimuth"]) * np.cos(view["elevation"]), |
| view["distance"] * np.sin(view["elevation"]), |
| ) |
| bpy.context.scene.render.filepath = str(output_dir / f"{index:03d}.png") |
| bpy.ops.render.render(write_still=True) |
| metadata["frames"].append( |
| { |
| "file_path": f"{index:03d}.png", |
| "camera_angle_x": view["fov"], |
| "azimuth": view["azimuth"], |
| "elevation": view["elevation"], |
| "cam_dis": view["distance"], |
| "transform_matrix": camera_transform(camera), |
| } |
| ) |
|
|
| with (output_dir / "transforms.json").open("w") as handle: |
| json.dump(metadata, handle, indent=2) |
|
|
| if args.geo_mode: |
| export_mesh(output_dir / "mesh.ply") |
|
|
|
|
| def build_parser() -> argparse.ArgumentParser: |
| parser = argparse.ArgumentParser(description="Render a 3D model from fixed orthographic views.") |
| parser.add_argument("--object", required=True, help="Path to the model file.") |
| parser.add_argument("--output-folder", "--output_folder", dest="output_folder", required=True) |
| parser.add_argument("--resolution", type=int, default=512) |
| parser.add_argument("--num-views", type=int, default=6) |
| parser.add_argument("--engine", default="CYCLES", choices=("CYCLES", "BLENDER_EEVEE_NEXT", "BLENDER_EEVEE")) |
| parser.add_argument("--geo-mode", "--geo_mode", dest="geo_mode", action="store_true") |
| return parser |
|
|
|
|
| if __name__ == "__main__": |
| argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else sys.argv[1:] |
| render(build_parser().parse_args(argv)) |
|
|