-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblender_render.py
More file actions
75 lines (61 loc) · 2.38 KB
/
blender_render.py
File metadata and controls
75 lines (61 loc) · 2.38 KB
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
import bpy
import sys
import argparse
from math import radians
from mathutils import Vector
# 解析命令行参数
argv = sys.argv[sys.argv.index("--") + 1:]
parser = argparse.ArgumentParser()
parser.add_argument("--input", required=True, help="Path to .glb file")
parser.add_argument("--output", required=True, help="Path to output .png image")
args = parser.parse_args(argv)
# 清理默认场景
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# 导入 GLB 模型
bpy.ops.import_scene.gltf(filepath=args.input)
# 缩放模型(KiCad 导出是 mm,Blender 默认单位是 m)
for obj in bpy.context.scene.objects:
obj.scale = (1000, 1000, 1000)
scene = bpy.context.scene
# 创建相机
cam_data = bpy.data.cameras.new("Camera")
cam_obj = bpy.data.objects.new("Camera", cam_data)
scene.collection.objects.link(cam_obj)
scene.camera = cam_obj
# 获取所有 MESH 对象的边界框中心和尺寸
mesh_objs = [obj for obj in scene.objects if obj.type == 'MESH']
if not mesh_objs:
print("❌ No mesh objects found.")
sys.exit(1)
min_corner = Vector((float('inf'), float('inf'), float('inf')))
max_corner = Vector((float('-inf'), float('-inf'), float('-inf')))
for obj in mesh_objs:
for v in obj.bound_box:
world_v = obj.matrix_world @ Vector(v)
min_corner = Vector(map(min, min_corner, world_v))
max_corner = Vector(map(max, max_corner, world_v))
center = (min_corner + max_corner) / 2
size = max_corner - min_corner
distance = max(size.x, size.y) * 1.5
# 设置相机位置和角度(俯视角度)
cam_obj.location = (center.x, center.y, center.z + distance)
cam_obj.rotation_euler = (radians(90), 0, 0)
# 添加光照(太阳光)
light_data = bpy.data.lights.new(name="Sun", type='SUN')
light_obj = bpy.data.objects.new(name="Sun", object_data=light_data)
scene.collection.objects.link(light_obj)
light_obj.location = (center.x, center.y, center.z + distance * 2)
light_obj.rotation_euler = (radians(90), 0, 0)
# 设置渲染参数
scene.render.engine = 'CYCLES'
scene.render.resolution_x = 1024
scene.render.resolution_y = 768
scene.render.filepath = args.output
# 使用 GPU 渲染(如果支持)
prefs = bpy.context.preferences
cprefs = prefs.addons['cycles'].preferences
cprefs.compute_device_type = 'CUDA' # 或 'OPTIX' / 'OPENCL' / 'NONE'
scene.cycles.device = 'GPU'
# 渲染并保存图像
bpy.ops.render.render(write_still=True)