Repository navigation
Expand file tree
/
Copy pathaddon.py
More file actions
740 lines (584 loc) · 23 KB
/
Copy pathaddon.py
File metadata and controls
740 lines (584 loc) · 23 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
bl_info = {
"name": "Turntable Strip Generator",
"author": "Monster_Domosed",
"version": (1, 0, 0),
"blender": (3, 6, 0),
"location": "View3D > Sidebar > Turntable",
"description": "Generate multi-angle turntable-style image strips from 3D models",
"category": "Render",
}
import bpy
import os
import sys
import math
import tempfile
import shutil
import subprocess
from bpy.props import (
StringProperty,
IntProperty,
FloatProperty,
BoolProperty,
EnumProperty,
PointerProperty,
)
from bpy.types import (
Operator,
Panel,
PropertyGroup,
)
from mathutils import Vector
# ─────────────────────────────────────────────────────────────
# Pillow dependency
# ─────────────────────────────────────────────────────────────
_pillow_checked = None
def _get_python_path():
exe = sys.executable
if os.path.basename(exe).lower().startswith("python"):
return exe
if sys.platform == "win32":
candidate = os.path.join(sys.prefix, "bin", "python.exe")
else:
ver = f"{sys.version_info.major}.{sys.version_info.minor}"
candidate = os.path.join(sys.prefix, "bin", f"python{ver}")
return candidate if os.path.isfile(candidate) else exe
def _lib_dir():
return os.path.join(os.path.dirname(os.path.realpath(__file__)), "_libs")
def ensure_pillow():
global _pillow_checked
if _pillow_checked is not None:
return _pillow_checked
lib = _lib_dir()
if lib not in sys.path:
sys.path.insert(0, lib)
try:
from PIL import Image
_pillow_checked = True
return True
except ImportError:
pass
python = _get_python_path()
subprocess.run(
[python, "-m", "ensurepip", "--default-pip"],
capture_output=True,
)
os.makedirs(lib, exist_ok=True)
result = subprocess.run(
[python, "-m", "pip", "install", "--no-input", "--target", lib, "Pillow"],
capture_output=True, text=True,
)
if result.returncode != 0:
print(f"Pillow installation failed:\n{result.stderr}")
_pillow_checked = False
return False
try:
from PIL import Image
_pillow_checked = True
except ImportError:
_pillow_checked = False
return _pillow_checked
# ─────────────────────────────────────────────────────────────
# Property Group
# ─────────────────────────────────────────────────────────────
class TurntableProperties(PropertyGroup):
glb_path: StringProperty(
name="GLB File",
description="Path to the GLB/GLTF file to import",
subtype='FILE_PATH',
default="",
)
output_dir: StringProperty(
name="Output Directory",
description="Directory to save the rendered strip image",
subtype='DIR_PATH',
default="//renders/",
)
output_name: StringProperty(
name="Output Name",
description="Base name for the output file (blank = use GLB filename)",
default="",
)
step_degrees: FloatProperty(
name="Step (°)",
description="Rotation step in degrees between frames",
default=15.0,
min=1.0,
max=90.0,
step=500,
)
resolution: IntProperty(
name="Resolution",
description="Per-frame resolution in pixels (square)",
default=1024,
min=64,
max=8192,
)
samples: IntProperty(
name="Samples",
description="Render samples (Cycles)",
default=64,
min=1,
max=4096,
)
engine: EnumProperty(
name="Engine",
description="Render engine to use",
items=[
('CYCLES', "Cycles", "Path-traced renderer"),
('EEVEE', "EEVEE", "Real-time renderer"),
],
default='CYCLES',
)
camera_height_offset: FloatProperty(
name="Height Offset",
description="Vertical offset for the camera target in world units",
default=1.0,
soft_min=-10.0,
soft_max=10.0,
)
padding: FloatProperty(
name="Padding",
description="Fraction of padding around the model in the frame",
default=0,
min=0.0,
max=0.5,
)
auto_crop: BoolProperty(
name="Auto Crop",
description="Automatically crop empty space from each frame",
default=True,
)
is_setup: BoolProperty(default=False)
model_radius: FloatProperty(default=1.0)
model_size_x: FloatProperty(default=1.0)
model_size_y: FloatProperty(default=1.0)
model_size_z: FloatProperty(default=1.0)
# ─────────────────────────────────────────────────────────────
# Utility Functions
# ─────────────────────────────────────────────────────────────
_RIG_NAMES = {"TurntableCamera", "CameraPivot", "KeyLight", "FillLight", "RimLight"}
def get_model_bounds(objects):
min_c = Vector((float('inf'),) * 3)
max_c = Vector((float('-inf'),) * 3)
found = False
for obj in objects:
if obj.type != 'MESH':
continue
found = True
for corner in obj.bound_box:
wc = obj.matrix_world @ Vector(corner)
min_c.x = min(min_c.x, wc.x)
min_c.y = min(min_c.y, wc.y)
min_c.z = min(min_c.z, wc.z)
max_c.x = max(max_c.x, wc.x)
max_c.y = max(max_c.y, wc.y)
max_c.z = max(max_c.z, wc.z)
if not found:
return Vector((0, 0, 0)), Vector((1, 1, 1))
return min_c, max_c
def get_all_imported_meshes():
return [
o for o in bpy.context.scene.objects
if o.type == 'MESH' and o.name not in _RIG_NAMES
]
def remove_all_objects():
while bpy.data.objects:
bpy.data.objects.remove(bpy.data.objects[0], do_unlink=True)
# ─────────────────────────────────────────────────────────────
# Camera / Lighting / World Setup
# ─────────────────────────────────────────────────────────────
def compute_auto_distance(model_size, cam_data, padding):
sx, sy, sz = model_size.x, model_size.y, model_size.z
apparent_width = math.sqrt(sx * sx + sy * sy)
apparent_height = sz
usable = max(1.0 - padding, 0.1)
needed_half_w = (apparent_width / 2.0) / usable
needed_half_h = (apparent_height / 2.0) / usable
sensor_h = cam_data.sensor_height
fov_y = 2.0 * math.atan(sensor_h / (2.0 * cam_data.lens))
fov_x = fov_y
dist_h = needed_half_h / math.tan(fov_y / 2.0)
dist_w = needed_half_w / math.tan(fov_x / 2.0)
return max(dist_h, dist_w)
def remove_turntable_rig():
for name in _RIG_NAMES:
obj = bpy.data.objects.get(name)
if obj:
bpy.data.objects.remove(obj, do_unlink=True)
def setup_camera(props):
radius = props.model_radius
model_size = Vector((props.model_size_x, props.model_size_y, props.model_size_z))
cam_data = bpy.data.cameras.get("TurntableCamera")
if cam_data is None:
cam_data = bpy.data.cameras.new("TurntableCamera")
cam_data.lens = 50
cam_data.clip_start = 0.01
cam_data.clip_end = 1000
cam_obj = bpy.data.objects.get("TurntableCamera")
if cam_obj is None:
cam_obj = bpy.data.objects.new("TurntableCamera", cam_data)
bpy.context.collection.objects.link(cam_obj)
bpy.context.scene.camera = cam_obj
distance = compute_auto_distance(model_size, cam_data, props.padding)
cam_obj.location = (distance, 0.0, props.camera_height_offset)
target = Vector((0, 0, props.camera_height_offset))
direction = target - cam_obj.location
cam_obj.rotation_euler = direction.to_track_quat('-Z', 'Y').to_euler()
return cam_obj
def setup_lighting(camera, radius):
lights_info = [
("KeyLight", 'AREA', radius * 250, (1, 1, 1), radius * 2,
(radius * 0.5, -radius * 0.8, radius * 1.2)),
("FillLight", 'AREA', radius * 80, (1, 1, 1), radius * 4,
(-radius * 0.6, radius * 0.6, radius * 0.5)),
("RimLight", 'AREA', radius * 150, (1, 1, 1), radius * 1.5,
(-radius * 0.3, radius * 0.2, radius * 1.5)),
]
for name, ltype, energy, color, size, loc in lights_info:
ldata = bpy.data.lights.get(name)
if ldata is None:
ldata = bpy.data.lights.new(name, ltype)
ldata.energy = energy
ldata.color = color
ldata.size = size
lobj = bpy.data.objects.get(name)
if lobj is None:
lobj = bpy.data.objects.new(name, ldata)
bpy.context.collection.objects.link(lobj)
lobj.location = loc
lobj.parent = camera
lobj.rotation_euler = (
(Vector((0, 0, 0)) - Vector(loc)).to_track_quat('-Z', 'Y').to_euler()
)
def setup_world():
world = bpy.data.worlds.get("TurntableWorld")
if world is None:
world = bpy.data.worlds.new("TurntableWorld")
bpy.context.scene.world = world
world.use_nodes = True
bg = world.node_tree.nodes.get("Background")
if bg:
bg.inputs["Color"].default_value = (0, 0, 0, 1)
bg.inputs["Strength"].default_value = 0.0
def configure_render(props):
scene = bpy.context.scene
if props.engine == 'CYCLES':
scene.render.engine = 'CYCLES'
scene.cycles.samples = props.samples
scene.cycles.use_denoising = True
prefs = bpy.context.preferences.addons.get('cycles')
if prefs:
try:
prefs.preferences.compute_device_type = 'CUDA'
prefs.preferences.get_devices()
for dev in prefs.preferences.devices:
dev.use = True
scene.cycles.device = 'GPU'
except Exception:
pass
else:
scene.render.engine = (
'BLENDER_EEVEE_NEXT'
if bpy.app.version >= (4, 0, 0)
else 'BLENDER_EEVEE'
)
scene.render.resolution_x = props.resolution
scene.render.resolution_y = props.resolution
scene.render.resolution_percentage = 100
scene.render.image_settings.file_format = 'PNG'
scene.render.image_settings.color_mode = 'RGBA'
scene.render.image_settings.compression = 15
scene.render.film_transparent = True
# ─────────────────────────────────────────────────────────────
# Operators
# ─────────────────────────────────────────────────────────────
class TURNTABLE_OT_import_glb(Operator):
bl_idname = "turntable.import_glb"
bl_label = "Import GLB"
bl_description = "Import the selected GLB/GLTF model into the current scene"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
props = context.scene.turntable_props
filepath = bpy.path.abspath(props.glb_path)
if not filepath or not os.path.exists(filepath):
self.report({'ERROR'}, f"File not found: {filepath}")
return {'CANCELLED'}
bpy.ops.import_scene.gltf(filepath=filepath)
self.report({'INFO'}, f"Imported: {os.path.basename(filepath)}")
return {'FINISHED'}
class TURNTABLE_OT_setup_scene(Operator):
bl_idname = "turntable.setup_scene"
bl_label = "Setup Scene"
bl_description = "Create camera, lighting, and world setup based on the imported model"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
props = context.scene.turntable_props
meshes = get_all_imported_meshes()
if meshes:
min_c, max_c = get_model_bounds(meshes)
size = max_c - min_c
props.model_radius = size.length / 2.0
props.model_size_x = size.x
props.model_size_y = size.y
props.model_size_z = size.z
remove_turntable_rig()
cam = setup_camera(props)
setup_lighting(cam, props.model_radius)
setup_world()
configure_render(props)
props.is_setup = True
self.report({'INFO'}, "Turntable scene ready")
return {'FINISHED'}
class TURNTABLE_OT_update_camera(Operator):
bl_idname = "turntable.update_camera"
bl_label = "Update Camera"
bl_description = "Refresh camera position and lighting after changing camera settings"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
props = context.scene.turntable_props
remove_turntable_rig()
cam = setup_camera(props)
setup_lighting(cam, props.model_radius)
configure_render(props)
return {'FINISHED'}
class TURNTABLE_OT_render_strip(Operator):
bl_idname = "turntable.render_strip"
bl_label = "Render Turntable Strip"
bl_description = "Render all rotation frames and stitch them into a single horizontal strip image"
bl_options = {'REGISTER'}
def execute(self, context):
props = context.scene.turntable_props
if not ensure_pillow():
self.report(
{'ERROR'},
"Pillow (PIL) is required but could not be installed. ",
)
return {'CANCELLED'}
from PIL import Image
if not props.is_setup:
self.report({'WARNING'}, "Run 'Setup Scene' first")
return {'CANCELLED'}
output_dir = bpy.path.abspath(props.output_dir)
os.makedirs(output_dir, exist_ok=True)
temp_dir = tempfile.mkdtemp(prefix="turntable_")
configure_render(props)
cam_obj = bpy.data.objects.get("TurntableCamera")
if not cam_obj:
self.report({'ERROR'}, "TurntableCamera not found — run Setup first")
return {'CANCELLED'}
pivot = bpy.data.objects.get("CameraPivot")
if pivot is None:
pivot = bpy.data.objects.new("CameraPivot", None)
bpy.context.collection.objects.link(pivot)
pivot.empty_display_type = 'PLAIN_AXES'
pivot.location = (0, 0, 0)
context.view_layer.update()
cam_obj.parent = pivot
cam_obj.matrix_parent_inverse = pivot.matrix_world.inverted()
num_steps = int(360 / props.step_degrees)
scene = context.scene
frame_paths = []
print(f"\n{'=' * 50}")
print(f"Rendering {num_steps} frames at {props.step_degrees}° intervals")
print(f"{'=' * 50}\n")
for i in range(num_steps):
angle = i * props.step_degrees
pivot.rotation_euler = (0, 0, math.radians(angle))
context.view_layer.update()
fp = os.path.join(temp_dir, f"frame_{i:04d}")
scene.render.filepath = fp
print(f" [{i + 1}/{num_steps}] {angle:6.1f}°")
bpy.ops.render.render(write_still=True)
frame_paths.append(fp + ".png")
print(f"\nStitching {num_steps} frames …")
frames = [Image.open(p).convert('RGBA') for p in frame_paths]
resolution = props.resolution
if props.auto_crop:
bboxes = [img.split()[3].getbbox() for img in frames]
bboxes = [b for b in bboxes if b]
if bboxes:
ux0 = min(b[0] for b in bboxes)
uy0 = min(b[1] for b in bboxes)
ux1 = max(b[2] for b in bboxes)
uy1 = max(b[3] for b in bboxes)
cw, ch = ux1 - ux0, uy1 - uy0
pad_px = int(max(cw, ch) * props.padding)
ux0 = max(ux0 - pad_px, 0)
uy0 = max(uy0 - pad_px, 0)
ux1 = min(ux1 + pad_px, resolution)
uy1 = min(uy1 + pad_px, resolution)
cw, ch = ux1 - ux0, uy1 - uy0
side = max(cw, ch)
cx, cy = (ux0 + ux1) // 2, (uy0 + uy1) // 2
half = side // 2
sx0 = max(cx - half, 0)
sy0 = max(cy - half, 0)
sx1 = min(sx0 + side, resolution)
sy1 = min(sy0 + side, resolution)
if sx1 - sx0 < side:
sx0 = max(sx1 - side, 0)
if sy1 - sy0 < side:
sy0 = max(sy1 - side, 0)
crop_box = (sx0, sy0, sx1, sy1)
else:
crop_box = (0, 0, resolution, resolution)
cropped = [img.crop(crop_box) for img in frames]
cell_w = crop_box[2] - crop_box[0]
cell_h = crop_box[3] - crop_box[1]
else:
cropped = frames
cell_w = cell_h = resolution
strip = Image.new('RGBA', (cell_w * num_steps, cell_h), (0, 0, 0, 0))
for i, frame in enumerate(cropped):
strip.paste(frame, (i * cell_w, 0))
if props.output_name:
base = props.output_name
elif props.glb_path:
base = os.path.splitext(
os.path.basename(bpy.path.abspath(props.glb_path))
)[0]
else:
base = "turntable"
out_path = os.path.join(output_dir, f"{base}_3d.png")
strip.save(out_path, 'PNG')
for img in frames:
img.close()
if cropped is not frames:
for img in cropped:
img.close()
strip.close()
shutil.rmtree(temp_dir, ignore_errors=True)
self.report(
{'INFO'},
f"Saved: {out_path} ({cell_w * num_steps}×{cell_h} px, "
f"{num_steps} frames @ {cell_w}×{cell_h})",
)
return {'FINISHED'}
class TURNTABLE_OT_clean_scene(Operator):
bl_idname = "turntable.clean_scene"
bl_label = "Clean Scene"
bl_description = "Remove all objects and orphan data from the scene"
bl_options = {'REGISTER', 'UNDO'}
def invoke(self, context, event):
return context.window_manager.invoke_confirm(self, event)
def execute(self, context):
remove_all_objects()
for collection in (
bpy.data.meshes, bpy.data.materials, bpy.data.cameras,
bpy.data.lights, bpy.data.images,
):
for block in list(collection):
if block.users == 0:
collection.remove(block)
context.scene.turntable_props.is_setup = False
self.report({'INFO'}, "Scene cleaned")
return {'FINISHED'}
# ─────────────────────────────────────────────────────────────
# UI Panels
# ─────────────────────────────────────────────────────────────
class TURNTABLE_PT_main(Panel):
bl_label = "Turntable Renderer"
bl_idname = "TURNTABLE_PT_main"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = "Turntable"
def draw(self, context):
layout = self.layout
props = context.scene.turntable_props
box = layout.box()
box.label(text="Import", icon='IMPORT')
box.prop(props, "glb_path")
row = box.row(align=True)
row.operator("turntable.import_glb", icon='FILE_3D')
row.operator("turntable.clean_scene", text="", icon='TRASH')
class TURNTABLE_PT_camera(Panel):
bl_label = "Camera"
bl_idname = "TURNTABLE_PT_camera"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = "Turntable"
bl_parent_id = "TURNTABLE_PT_main"
def draw(self, context):
layout = self.layout
props = context.scene.turntable_props
col = layout.column(align=True)
col.prop(props, "camera_height_offset")
col.prop(props, "padding")
layout.operator("turntable.update_camera", icon='OUTLINER_OB_CAMERA')
class TURNTABLE_PT_render(Panel):
bl_label = "Render Settings"
bl_idname = "TURNTABLE_PT_render"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = "Turntable"
bl_parent_id = "TURNTABLE_PT_main"
def draw(self, context):
layout = self.layout
props = context.scene.turntable_props
col = layout.column(align=True)
col.prop(props, "engine")
col.prop(props, "resolution")
col.prop(props, "samples")
col.prop(props, "step_degrees")
col.prop(props, "auto_crop")
class TURNTABLE_PT_output(Panel):
bl_label = "Output & Render"
bl_idname = "TURNTABLE_PT_output"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = "Turntable"
bl_parent_id = "TURNTABLE_PT_main"
def draw(self, context):
layout = self.layout
props = context.scene.turntable_props
col = layout.column(align=True)
col.prop(props, "output_dir")
col.prop(props, "output_name")
layout.separator()
col = layout.column(align=True)
col.scale_y = 1.5
col.operator(
"turntable.setup_scene",
text="Setup Scene",
icon='SCENE_DATA',
)
col.separator()
row = col.row()
row.scale_y = 1.3
row.alert = True
row.operator(
"turntable.render_strip",
text="RENDER TURNTABLE STRIP",
icon='RENDER_ANIMATION',
)
if props.is_setup:
num_frames = int(360 / props.step_degrees)
layout.label(
text=f"Ready: {num_frames} frames @ {props.step_degrees}°",
icon='CHECKMARK',
)
# ─────────────────────────────────────────────────────────────
# Registration
# ─────────────────────────────────────────────────────────────
classes = (
TurntableProperties,
TURNTABLE_OT_import_glb,
TURNTABLE_OT_setup_scene,
TURNTABLE_OT_update_camera,
TURNTABLE_OT_render_strip,
TURNTABLE_OT_clean_scene,
TURNTABLE_PT_main,
TURNTABLE_PT_camera,
TURNTABLE_PT_render,
TURNTABLE_PT_output,
)
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.Scene.turntable_props = PointerProperty(type=TurntableProperties)
def unregister():
del bpy.types.Scene.turntable_props
for cls in reversed(classes):
bpy.utils.unregister_class(cls)
if __name__ == "__main__":
register()