0xZohar commited on
Commit
f187247
·
verified ·
1 Parent(s): 3a6ebff

Add missing code/cube3d/render/render_bricks_safe.py

Browse files
code/cube3d/render/render_bricks_safe.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import subprocess
3
+ import tempfile
4
+ from pathlib import Path
5
+ import sys
6
+ import os
7
+ import platform
8
+
9
+ root_dir = Path(__file__).parents[2]
10
+ sys.path.append(str(root_dir))
11
+
12
+ # 根据操作系统自动检测Blender路径
13
+ def _get_blender_path():
14
+ """自动检测Blender路径(支持Mac/Linux)"""
15
+ system = platform.system()
16
+
17
+ # Mac系统常见的Blender安装路径
18
+ if system == 'Darwin':
19
+ possible_paths = [
20
+ '/Applications/Blender.app/Contents/MacOS/Blender',
21
+ '/Applications/Blender 3.6/Blender.app/Contents/MacOS/Blender',
22
+ '/Applications/Blender 4.0/Blender.app/Contents/MacOS/Blender',
23
+ os.path.expanduser('~/Applications/Blender.app/Contents/MacOS/Blender'),
24
+ ]
25
+ for path in possible_paths:
26
+ if os.path.exists(path):
27
+ print(f"✓ 找到Blender: {path}")
28
+ return path
29
+
30
+ # 如果没找到,提示用户安装
31
+ print("⚠️ 未找到Blender!")
32
+ print("请从以下网址下载并安装Blender 3.6 LTS:")
33
+ print("https://www.blender.org/download/lts/3-6/")
34
+ print("安装到 /Applications/ 目录后重新运行。")
35
+ return None
36
+
37
+ # Linux系统(优先检测系统安装的Blender)
38
+ else:
39
+ # 首先检查通过apt/系统包管理器安装的Blender
40
+ system_paths = [
41
+ '/usr/bin/blender',
42
+ '/usr/local/bin/blender',
43
+ '/snap/bin/blender',
44
+ ]
45
+
46
+ for path in system_paths:
47
+ if os.path.exists(path):
48
+ print(f"✓ 找到系统Blender: {path}")
49
+ return path
50
+
51
+ # 检查手动下载的版本
52
+ linux_path = '/tmp/blender-3.6.5-linux-x64/blender'
53
+ if os.path.exists(linux_path):
54
+ print(f"✓ 找到Blender: {linux_path}")
55
+ return linux_path
56
+
57
+ # 在Hugging Face Spaces等环境中,Blender应该通过packages.txt安装
58
+ # 因此不需要自动下载安装,直接返回系统路径
59
+ print("⚠️ 未找到Blender,尝试使用系统默认路径...")
60
+ return '/usr/bin/blender' # 假设通过packages.txt安装到系统路径
61
+
62
+ BLENDER_PATH = _get_blender_path()
63
+
64
+ if BLENDER_PATH and os.path.exists(BLENDER_PATH):
65
+ # 验证Blender版本
66
+ try:
67
+ version_check = subprocess.run(
68
+ [BLENDER_PATH, '--version'],
69
+ capture_output=True,
70
+ text=True,
71
+ timeout=10
72
+ )
73
+ if version_check.returncode == 0:
74
+ version_info = version_check.stdout.strip().split('\n')[0]
75
+ print(f"✓ Blender版本: {version_info}")
76
+ except Exception as e:
77
+ print(f"⚠️ Blender版本检查失败: {e}")
78
+
79
+ def render_bricks_safe(
80
+ in_file: str,
81
+ out_file: str,
82
+ reposition_camera: bool = True,
83
+ square_image: bool = True,
84
+ instructions_look: bool = False,
85
+ fov: float = 45,
86
+ img_resolution: int = 512,
87
+ ) -> None:
88
+ in_file = os.path.abspath(in_file)
89
+ out_file = os.path.abspath(out_file)
90
+
91
+ # 确保输出目录存在
92
+ out_dir = os.path.dirname(out_file)
93
+ Path(out_dir).mkdir(parents=True, exist_ok=True)
94
+ os.chmod(out_dir, 0o755)
95
+
96
+ ldraw_lib_path = os.environ.get('LDRAW_LIBRARY_PATH')
97
+ if not ldraw_lib_path or not os.path.exists(ldraw_lib_path):
98
+ ldraw_lib_path = Path.home() / 'ldraw'
99
+ ldraw_lib_path = os.path.abspath(ldraw_lib_path)
100
+
101
+ print(f"LDraw库路径: {ldraw_lib_path}")
102
+ print(f"LDraw库是否存在: {os.path.exists(ldraw_lib_path)}")
103
+
104
+ # 修复布尔值格式化问题
105
+ blender_script = '''
106
+ import bpy
107
+ import math
108
+ import os
109
+ import sys
110
+ from pathlib import Path
111
+ import traceback
112
+
113
+ print("=== Blender脚本开始执行 ===")
114
+
115
+ # 添加ImportLDraw路径
116
+ sys.path.append("{import_ldraw_path}")
117
+ print(f"添加的路径: {{sys.path[-1]}}")
118
+
119
+ try:
120
+ print("尝试导入ImportLDraw...")
121
+ import ImportLDraw
122
+ from ImportLDraw.loadldraw.loadldraw import Options, Configure, loadFromFile, FileSystem
123
+ print("ImportLDraw导入成功")
124
+ print(f"ImportLDraw文件位置: {{ImportLDraw.__file__}}")
125
+ except ImportError as import_error:
126
+ print(f"ImportLDraw导入失败: {{import_error}}")
127
+ traceback.print_exc()
128
+ sys.exit(1)
129
+
130
+ try:
131
+ plugin_path = Path(ImportLDraw.__file__).parent
132
+ print(f"插件路径: {{plugin_path}}")
133
+
134
+ print("Blender内部输出路径: " + "{output_file}")
135
+ print("输出目录是否存在: " + str(os.path.exists(os.path.dirname("{output_file}"))))
136
+
137
+ # 检查输入文件
138
+ print(f"输入文件路径: {{'{input_file}'}}")
139
+ print(f"输入文件是否存在: {{os.path.exists('{input_file}')}}")
140
+
141
+ if os.path.exists("{input_file}"):
142
+ with open("{input_file}", "r") as f:
143
+ content = f.read()
144
+ print(f"LDR文件内容长度: {{len(content)}}")
145
+ print("文件前几行:")
146
+ for i, line in enumerate(content.split('\\n')[:5]):
147
+ print(f" {{i+1}}: {{line}}")
148
+
149
+ # 设置选项 - 修复布尔值
150
+ Options.ldrawDirectory = "{ldraw_path}"
151
+ Options.instructionsLook = {instructions_look_bool} # 直接使用布尔值
152
+ Options.useLogoStuds = True
153
+ Options.useUnofficialParts = True
154
+ Options.gaps = True
155
+ Options.studLogoDirectory = os.path.join(str(plugin_path), 'studs')
156
+ Options.LSynthDirectory = os.path.join(str(plugin_path), 'lsynth')
157
+ Options.verbose = 1
158
+ Options.overwriteExistingMaterials = True
159
+ Options.overwriteExistingMeshes = True
160
+ Options.scale = 0.01
161
+ Options.createInstances = True
162
+ Options.removeDoubles = True
163
+ Options.positionObjectOnGroundAtOrigin = True
164
+ Options.flattenHierarchy = False
165
+ Options.edgeSplit = True
166
+ Options.addBevelModifier = True
167
+ Options.bevelWidth = 0.5
168
+ Options.addEnvironmentTexture = True
169
+ Options.scriptDirectory = os.path.join(str(plugin_path), 'loadldraw')
170
+ Options.addWorldEnvironmentTexture = True
171
+ Options.addGroundPlane = True
172
+ Options.setRenderSettings = True
173
+ Options.removeDefaultObjects = True
174
+ Options.positionCamera = {reposition_camera_bool} # 直接使用布尔值
175
+ Options.cameraBorderPercent = 0.05
176
+
177
+ print("开始Configure...")
178
+ Configure()
179
+ print("Configure执行成功")
180
+
181
+ print("清理场景...")
182
+ bpy.ops.object.select_all(action='DESELECT')
183
+ bpy.ops.object.select_by_type(type='MESH')
184
+ bpy.ops.object.delete()
185
+ print("场景清理完成")
186
+
187
+ print("尝试加载LDR文件...")
188
+ ldr_file = FileSystem.locate("{input_file}")
189
+ print(f"找到LDR文件: {{ldr_file}}")
190
+ loadFromFile(None, ldr_file)
191
+ print("LDR文件加载成功")
192
+
193
+ # 检查加载的对象
194
+ mesh_objects = [obj for obj in bpy.data.objects if obj.type == 'MESH']
195
+ print(f"加载的网格对象数量: {{len(mesh_objects)}}")
196
+
197
+ if len(mesh_objects) == 0:
198
+ print("警告: 没有加载任何网格对象!")
199
+ else:
200
+ for obj in mesh_objects[:3]: # 只显示前3个对象
201
+ print(f" 对象: {{obj.name}}, 顶点数: {{len(obj.data.vertices) if obj.data else 0}}")
202
+
203
+ scene = bpy.context.scene
204
+ if {square_image_bool}: # 直接使用布尔值
205
+ scene.render.resolution_x = {img_resolution}
206
+ scene.render.resolution_y = {img_resolution}
207
+ if scene.camera:
208
+ scene.camera.data.angle = math.radians({fov})
209
+ else:
210
+ print("警告:场景中没有相机,创建默认相机")
211
+ bpy.ops.object.camera_add(location=(5, -5, 3))
212
+ scene.camera = bpy.context.active_object
213
+
214
+ scene.render.engine = 'CYCLES'
215
+ scene.cycles.samples = 512
216
+ scene.cycles.device = 'GPU'
217
+ scene.render.image_settings.file_format = 'PNG'
218
+ scene.render.filepath = "{output_file}"
219
+ scene.render.use_overwrite = True
220
+
221
+ if sys.platform == 'darwin':
222
+ compute_device_type = 'METAL'
223
+ else:
224
+ compute_device_type = 'CUDA'
225
+
226
+ print("配置GPU...")
227
+ bpy.context.preferences.addons['cycles'].preferences.compute_device_type = compute_device_type
228
+ bpy.context.preferences.addons['cycles'].preferences.get_devices()
229
+ gpu_used = False
230
+ for device in bpy.context.preferences.addons['cycles'].preferences.devices:
231
+ if device['name'].startswith(('NVIDIA', 'Apple')):
232
+ device['use'] = 1
233
+ gpu_used = True
234
+ print("启用GPU: " + device['name'])
235
+ else:
236
+ device['use'] = 0
237
+ if not gpu_used:
238
+ print("警告:未找到可用GPU,使用CPU渲染")
239
+
240
+ print("开始渲染...")
241
+ result = bpy.ops.render.render(write_still=True)
242
+ print("渲染执行结果: " + str(result))
243
+ print("渲染后文件是否存在: " + str(os.path.exists("{output_file}")))
244
+
245
+ if os.path.exists("{output_file}"):
246
+ file_size = os.path.getsize("{output_file}")
247
+ print("文件生成成功: " + str(file_size) + " 字节")
248
+ else:
249
+ print("严重错误:渲染完成但未生成文件")
250
+
251
+ print("=== Blender脚本执行完成 ===")
252
+
253
+ except Exception as e:
254
+ print(f"脚本执行过程中发生错误: {{e}}")
255
+ traceback.print_exc()
256
+ sys.exit(1)
257
+ '''
258
+
259
+ # 写入临时脚本 - 修复布尔值格式化
260
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
261
+ script_content = blender_script.format(
262
+ import_ldraw_path=str(root_dir),
263
+ ldraw_path=ldraw_lib_path,
264
+ instructions_look_bool=str(instructions_look), # 直接使用Python布尔值
265
+ reposition_camera_bool=str(reposition_camera), # 直接使用Python布尔值
266
+ square_image_bool=str(square_image), # 直接使用Python布尔值
267
+ fov=fov,
268
+ img_resolution=img_resolution,
269
+ input_file=in_file,
270
+ output_file=out_file
271
+ )
272
+ f.write(script_content)
273
+ script_path = f.name
274
+
275
+ try:
276
+ # 检查Blender路径是否存在
277
+ if not BLENDER_PATH or not os.path.exists(BLENDER_PATH):
278
+ print("⚠️ 跳过渲染:未找到Blender")
279
+ print("如需3D渲染功能,请安装Blender 3.6+")
280
+ # 创建一个占位图片,避免程序崩溃
281
+ from PIL import Image, ImageDraw, ImageFont
282
+ img = Image.new('RGB', (512, 512), color=(240, 240, 240))
283
+ draw = ImageDraw.Draw(img)
284
+ draw.text((150, 250), "Blender未安装\n渲染功能不可用", fill=(100, 100, 100))
285
+ img.save(out_file)
286
+ print(f"已生成占位图片: {out_file}")
287
+ return
288
+
289
+ cmd = [
290
+ BLENDER_PATH, '--background', #'--factory-startup',
291
+ '--python', script_path, #'--enable-autoexec'
292
+ ]
293
+
294
+ print(f"执行命令: {' '.join(cmd)}")
295
+
296
+ result = subprocess.run(
297
+ cmd,
298
+ stdout=subprocess.PIPE,
299
+ stderr=subprocess.PIPE,
300
+ text=True,
301
+ timeout=300
302
+ )
303
+
304
+ # 输出Blender日志
305
+ if result.stdout:
306
+ print("=== Blender标准输出 ===")
307
+ print(result.stdout)
308
+
309
+ if result.stderr:
310
+ print("=== Blender错误输出 ===")
311
+ print(result.stderr)
312
+
313
+ if result.returncode != 0:
314
+ raise RuntimeError(f"Blender返回错误码: {result.returncode}")
315
+
316
+ if not os.path.exists(out_file):
317
+ raise FileNotFoundError(f"渲染失败:未生成输出文件 {out_file}")
318
+
319
+ # 验证文件大小
320
+ file_size = os.path.getsize(out_file)
321
+ if file_size < 100:
322
+ raise RuntimeError(f"生成的文件无效(大小:{file_size}字节)")
323
+
324
+ print(f"渲染成功!文件大小: {file_size} 字节")
325
+
326
+ except subprocess.TimeoutExpired:
327
+ raise TimeoutError("渲染超时(超过5分钟)")
328
+ except Exception as e:
329
+ raise e
330
+ finally:
331
+ if os.path.exists(script_path):
332
+ os.unlink(script_path)
333
+
334
+ def main():
335
+ parser = argparse.ArgumentParser()
336
+ parser.add_argument('--in_file', type=str, required=True, help='Path to LDR file')
337
+ parser.add_argument('--out_file', type=str, required=True, help='Path to output image file')
338
+ args = parser.parse_args()
339
+
340
+ # 检查输入文件是否存在
341
+ if not os.path.exists(args.in_file):
342
+ print(f"错误: 输入文件不存在: {args.in_file}")
343
+ return
344
+
345
+ # 获取输入文件的绝对路径
346
+ in_file = os.path.abspath(args.in_file)
347
+ out_file = os.path.abspath(args.out_file)
348
+
349
+ print(f"输入文件: {in_file}")
350
+ print(f"输出文件: {out_file}")
351
+
352
+ try:
353
+ render_bricks_safe(in_file, out_file, square_image=True, instructions_look=False)
354
+ print(f'成功渲染图像到: {out_file}')
355
+ except Exception as e:
356
+ print(f'渲染失败: {e}')
357
+
358
+ if __name__ == '__main__':
359
+ main()