-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender_preview.py
More file actions
188 lines (155 loc) · 6.43 KB
/
Copy pathrender_preview.py
File metadata and controls
188 lines (155 loc) · 6.43 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
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
# render_preview.py — 병합된 최종 캐릭터의 정면을 렌더
# 명령어: blender --background --python render_preview.py -- <glb_path> <out_png>
import bpy
import sys
import os
import math
from mathutils import Vector
def log(msg):
print(f"[RENDER] {msg}", flush=True)
# -------------------- Args --------------------
argv = sys.argv
argv = argv[argv.index("--") + 1:] if "--" in argv else []
if len(argv) < 2:
print("Usage: blender --background --python render_preview.py -- <glb_path> <out_png>")
sys.exit(1)
glb_path, out_png = argv[:2]
glb_path = os.path.abspath(glb_path)
out_png = os.path.abspath(out_png)
# 출력 폴더가 없으면 생성
out_dir = os.path.dirname(out_png)
if out_dir and not os.path.exists(out_dir):
os.makedirs(out_dir, exist_ok=True)
# -------------------- Reset scene --------------------
bpy.ops.wm.read_factory_settings(use_empty=True)
try:
bpy.data.orphans_purge(do_recursive=True)
except Exception:
pass
scn = bpy.context.scene
# 해상도 먼저 지정(카메라 FOV 계산에 영향을 줌)
scn.render.resolution_x = 1536
scn.render.resolution_y = 1536
scn.render.resolution_percentage = 100
# -------------------- Import GLB --------------------
log(f"IMPORT {glb_path}")
bpy.ops.import_scene.gltf(filepath=glb_path, loglevel=0)
objs = list(bpy.context.scene.objects)
log(f"IMPORTED objects={len(objs)}")
# -------------------- Camera --------------------
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
bpy.context.scene.collection.objects.link(cam)
bpy.context.scene.camera = cam
# 카메라 기본값
cam.data.type = 'PERSP'
cam.data.lens = 35
cam.data.sensor_fit = 'VERTICAL'
cam.data.dof.use_dof = False
cam.location = (0.0, -3.0, 1.5)
cam.rotation_euler = (1.47, 0.0, 0.0)
# --- 자동 전신 프레이밍 ---
def frame_objects_full_body(cam_obj, objs, margin=1.07, elev_deg=17):
meshes = [o for o in objs if o.type == 'MESH']
if not meshes:
return None
mins = Vector((1e9, 1e9, 1e9))
maxs = Vector((-1e9, -1e9, -1e9))
for o in meshes:
try:
bb = o.bound_box
except Exception:
continue
for v in bb:
vw = o.matrix_world @ Vector(v)
mins.x = min(mins.x, vw.x); mins.y = min(mins.y, vw.y); mins.z = min(mins.z, vw.z)
maxs.x = max(maxs.x, vw.x); maxs.y = max(maxs.y, vw.y); maxs.z = max(maxs.z, vw.z)
center = (mins + maxs) * 0.5
size = maxs - mins
width, height = size.x, size.z
# 카메라 FOV (렌즈/센서/해상도에 의존)
fov_y = cam_obj.data.angle_y
fov_x = cam_obj.data.angle_x
dist_v = (height * margin * 0.5) / math.tan(fov_y * 0.5)
dist_h = (width * margin * 0.5) / math.tan(fov_x * 0.5)
dist = max(dist_v, dist_h)
phi = math.radians(max(0.0, min(30.0, elev_deg))) # 0~30°
dy = math.cos(phi) * dist
dz = math.sin(phi) * dist
cam_obj.location = (center.x, center.y - dy, center.z + dz)
direction = (center - cam_obj.location).normalized()
cam_obj.rotation_euler = direction.to_track_quat('-Z', 'Y').to_euler()
safety = 1.0 + 0.002 * max(0.0, elev_deg - 10.0)
return {"center": center, "dist": dist * safety, "width": width, "height": height}
info = frame_objects_full_body(cam, objs, margin=1.07, elev_deg=17)
log(f"FRAME {info}")
# -------------------- Lighting --------------------
def look_at(obj, target_vec):
direction = (target_vec - obj.location).normalized()
obj.rotation_euler = direction.to_track_quat('-Z', 'Y').to_euler()
# 메인 AREA 라이트
key_data = bpy.data.lights.new(name="KeyLight", type='AREA')
key = bpy.data.objects.new("KeyLight", key_data)
bpy.context.collection.objects.link(key)
if info:
c = info["center"]; d = info["dist"]; h = info["height"]
key.location = (c.x, c.y - d * 0.55, c.z + h * 0.05)
else:
key.location = (0.0, -2.0, 1.6)
key.data.size = 2.2
key.data.energy = 180
look_at(key, info["center"] if info else Vector((0.0, 0.0, 1.5)))
# 보조 AREA 라이트 (좌/우)
for sign in (-1, 1):
side_data = bpy.data.lights.new(name=f"SideLight_{sign}", type='AREA')
side = bpy.data.objects.new(f"SideLight_{sign}", side_data)
bpy.context.collection.objects.link(side)
if info:
c = info["center"]; d = info["dist"]; h = info["height"]; w = info["width"]
side.location = (c.x + sign * (w * 0.55), c.y - d * 0.6, c.z + h * 0.05)
else:
side.location = (sign * 1.5, -2.0, 1.6)
side.data.size = 1.6
side.data.energy = 40
look_at(side, info["center"] if info else Vector((0.0, 0.0, 1.5)))
# -------------------- Eevee Render --------------------
log("CONFIGURE EEVEE")
scn.render.engine = 'BLENDER_EEVEE' # Eevee (GPU)
scn.eevee.taa_samples = 8 # viewport TAA (참고)
scn.eevee.taa_render_samples = 16 # 렌더 샘플 (속도↑)
scn.eevee.use_bloom = False
scn.eevee.use_ssr = False # 반사 트레이싱 끔(속도↑)
scn.eevee.use_ssr_refraction = False
scn.eevee.use_gtao = True # 적당히 깊이감
scn.eevee.use_soft_shadows = True
# 투명 배경 + RGBA
scn.render.film_transparent = True
scn.render.image_settings.file_format = 'PNG'
scn.render.image_settings.color_mode = 'RGBA'
scn.render.image_settings.color_depth = '8'
# 컬러 매니지먼트
scn.view_settings.view_transform = 'Filmic'
scn.view_settings.look = 'None'
scn.view_settings.exposure = 0.0
scn.view_settings.gamma = 1.0
# 월드(배경 색은 조명에 영향, 화면에는 투명 처리됨)
if scn.world is None:
scn.world = bpy.data.worlds.new("World")
scn.world.use_nodes = True
bg = scn.world.node_tree.nodes.get("Background")
if not bg:
bg = scn.world.node_tree.nodes.new("ShaderNodeBackground")
bg.inputs[0].default_value = (0.12, 0.12, 0.12, 1.0) # 약한 회색빛
bg.inputs[1].default_value = 0.2
# 출력 경로: *_rgba.png (메인 파이프라인 호환)
root, _ = os.path.splitext(out_png)
tmp_png = root + "_rgba.png"
scn.render.filepath = tmp_png
# -------------------- Render --------------------
log("RENDER BEGIN (Eevee)")
bpy.ops.render.render(write_still=True)
log(f"RENDER DONE -> {tmp_png}")
if not os.path.isfile(tmp_png):
print(f"[render_preview] Failed: {tmp_png} not created.")
sys.exit(2)
print(f"[render_preview] Transparent RGBA saved at: {tmp_png}")