-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblender_script.py
More file actions
1290 lines (1012 loc) · 49 KB
/
blender_script.py
File metadata and controls
1290 lines (1012 loc) · 49 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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Blender Automation Script - Video Generation Pipeline
Phase 2: Scene Setup and Animation Stub
This script runs inside Blender to:
1. Set up the 3D scene
2. Import mascot image
3. Create basic rig (stub)
4. Generate animations (lip-sync, gestures, lyrics)
5. Set up lighting and effects
6. Render frames
Author: Claude (Anthropic)
Version: 2.0
Date: November 2025
Platform: Cross-platform (Windows 11 optimized)
"""
import os
import sys
import json
import argparse
from pathlib import Path
from typing import Dict, List
# Add script directory to Python path for module imports
script_dir = os.path.dirname(os.path.abspath(__file__))
if script_dir not in sys.path:
sys.path.insert(0, script_dir)
# Check if running in Blender
try:
import bpy
import mathutils
RUNNING_IN_BLENDER = True
except ImportError:
RUNNING_IN_BLENDER = False
print("WARNING: Not running in Blender. This script requires Blender's Python environment.")
print("Run with: blender --background --python blender_script.py -- [args]")
import yaml
class BlenderSceneBuilder:
"""Builds and configures the 3D scene in Blender."""
def __init__(self, config: Dict, prep_data: Dict):
"""
Initialize scene builder.
Args:
config: Pipeline configuration from YAML
prep_data: Preprocessed audio data (beats, phonemes, etc.)
"""
self.config = config
self.prep_data = prep_data
self.scene = bpy.context.scene
# Set up scene basics
self.fps = config.get('video', {}).get('fps', 24)
self.scene.render.fps = self.fps
self.scene.render.fps_base = 1.0
# Calculate frame range from audio duration
duration = prep_data.get('audio', {}).get('duration', 30)
self.total_frames = int(duration * self.fps)
self.scene.frame_start = 1
self.scene.frame_end = self.total_frames
print(f"Scene setup: {self.total_frames} frames @ {self.fps} fps")
def clear_scene(self):
"""Clear default Blender scene."""
print("Clearing default scene...")
# Delete all objects
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()
# Delete all materials
for material in bpy.data.materials:
bpy.data.materials.remove(material)
# Delete all textures
for texture in bpy.data.textures:
bpy.data.textures.remove(texture)
print("[OK] Scene cleared")
def setup_camera(self):
"""Create and position camera."""
print("Setting up camera...")
# Create camera - position to face mascot straight-on
# Mascot is at (0, 0, 1), so camera should be on negative Y axis
bpy.ops.object.camera_add(location=(0, -6, 1))
camera = bpy.context.object
camera.name = "MainCamera"
# Point camera straight at mascot (only slight upward tilt)
camera.rotation_euler = (1.5708, 0, 0) # 90 degrees = face forward
# Set as active camera
self.scene.camera = camera
# Configure render resolution
resolution = self.config.get('video', {}).get('resolution', [1920, 1080])
self.scene.render.resolution_x = resolution[0]
self.scene.render.resolution_y = resolution[1]
self.scene.render.resolution_percentage = 100
print(f"[OK] Camera created: {resolution[0]}x{resolution[1]}")
return camera
def setup_lighting(self):
"""Create production-quality lighting with HDRI environment."""
print("Setting up production lighting...")
style = self.config.get('style', {}).get('lighting', 'jazzy')
colors = self.config.get('style', {}).get('colors', {})
effects = self.config.get('effects', {})
lights_config = effects.get('lights', {})
hdri_config = lights_config.get('hdri', {})
lights = []
# Setup HDRI environment lighting (production feature)
if hdri_config.get('enabled', False):
print(" Setting up HDRI environment...")
# Enable world nodes
world = bpy.data.worlds.get("World")
if not world:
world = bpy.data.worlds.new("World")
self.scene.world = world
world.use_nodes = True
nodes = world.node_tree.nodes
links = world.node_tree.links
# Clear existing nodes
nodes.clear()
# Create output node
output_node = nodes.new('ShaderNodeOutputWorld')
output_node.location = (600, 0)
# Create background shader
background = nodes.new('ShaderNodeBackground')
background.location = (400, 0)
background.inputs['Strength'].default_value = hdri_config.get('strength', 1.5)
# Try to load HDRI texture (if available)
# For now, use procedural sky as fallback
hdri_loaded = False
# Check for HDRI file in assets
# hdri_path = "path/to/hdri.exr" # TODO: Add HDRI path to config
# if os.path.exists(hdri_path):
# tex_env = nodes.new('ShaderNodeTexEnvironment')
# tex_env.image = bpy.data.images.load(hdri_path)
# hdri_loaded = True
if not hdri_loaded:
# Use procedural sky as fallback
print(" Using procedural sky (no HDRI file)")
sky_texture = nodes.new('ShaderNodeTexSky')
sky_texture.location = (0, 0)
sky_texture.sky_type = 'NISHITA' # Physically accurate sky
# Sky rotation can be controlled via sun direction
rotation_z = hdri_config.get('rotation', 45)
# Adjust sun direction based on rotation (simplified)
# Sky texture uses sun position, not vector input
# Connect procedural sky directly (no vector input needed)
links.new(sky_texture.outputs['Color'], background.inputs['Color'])
else:
# Connect HDRI texture (when available)
mapping = nodes.new('ShaderNodeMapping')
mapping.location = (-200, 0)
rotation_z = hdri_config.get('rotation', 45)
mapping.inputs['Rotation'].default_value = (0, 0, rotation_z * 0.0174533)
tex_coord = nodes.new('ShaderNodeTexCoord')
tex_coord.location = (-400, 0)
# Would connect to tex_env here
# links.new(tex_coord.outputs['Generated'], mapping.inputs['Vector'])
# links.new(mapping.outputs['Vector'], tex_env.inputs['Vector'])
# links.new(tex_env.outputs['Color'], background.inputs['Color'])
# Fallback color tint (if specified)
fallback_color = hdri_config.get('fallback_color', [0.8, 0.9, 1.0])
if len(fallback_color) == 3:
color_ramp = nodes.new('ShaderNodeValToRGB')
color_ramp.location = (200, -200)
color_ramp.color_ramp.elements[0].color = (*fallback_color, 1.0)
# Connect to output
links.new(background.outputs['Background'], output_node.inputs['Surface'])
print(f" [OK] HDRI environment configured (strength: {hdri_config.get('strength', 1.5)})")
# Key light (main spotlight) - adjusted for HDRI workflow
spotlight_config = lights_config.get('spotlight', {})
if spotlight_config.get('enabled', True):
bpy.ops.object.light_add(type='SPOT', location=(2, -3, 4))
key_light = bpy.context.object
key_light.name = "KeyLight"
key_light.data.energy = spotlight_config.get('intensity', 800)
key_light.data.spot_size = spotlight_config.get('spot_size', 60) * 0.0174533 # degrees to radians
key_light.data.spot_blend = spotlight_config.get('spot_blend', 0.3)
# Color from config
spot_color = spotlight_config.get('color', [1.0, 0.98, 0.95])
if len(spot_color) == 3:
key_light.data.color = spot_color
lights.append(key_light)
print(f" [OK] Spotlight: {key_light.data.energy}W")
# Fill light (softer area light)
bpy.ops.object.light_add(type='AREA', location=(-2, -2, 3))
fill_light = bpy.context.object
fill_light.name = "FillLight"
fill_light.data.energy = 200
fill_light.data.size = 2.0
lights.append(fill_light)
# Rim/back light for edge definition
rim_config = lights_config.get('rim_light', {})
if rim_config.get('enabled', False):
bpy.ops.object.light_add(type='SPOT', location=(0, 2, 3))
rim_light = bpy.context.object
rim_light.name = "RimLight"
rim_light.data.energy = rim_config.get('intensity', 500)
rim_light.data.spot_size = 1.0
# Cool colored rim light
rim_color = rim_config.get('color', [0.3, 0.5, 1.0])
if len(rim_color) == 3:
rim_light.data.color = rim_color
lights.append(rim_light)
print(f" [OK] Rim light: {rim_light.data.energy}W")
print(f"[OK] Production lighting complete ({style} style, {len(lights)} lights)")
return lights
def create_stage_environment(self):
"""Create production-quality stage environment with floor."""
style_config = self.config.get('style', {})
if not style_config.get('stage', False):
print("Stage environment disabled in config")
return None
print("Creating stage environment...")
# Create floor plane
bpy.ops.mesh.primitive_plane_add(size=20, location=(0, 0, 0))
stage = bpy.context.object
stage.name = "Stage"
# Subdivide for better detail
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.subdivide(number_cuts=10)
bpy.ops.object.mode_set(mode='OBJECT')
# Smooth shading
bpy.ops.object.shade_smooth()
# Create PBR material for stage
materials_config = self.config.get('materials', {})
stage_mat_config = materials_config.get('stage', {})
mat = bpy.data.materials.new(name="StageMaterial_PBR")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
stage.data.materials.append(mat)
# Get Principled BSDF
bsdf = nodes.get("Principled BSDF")
if not bsdf:
bsdf = nodes.new('ShaderNodeBsdfPrincipled')
# Configure PBR properties
if stage_mat_config.get('type') == 'pbr':
# Dark, slightly rough stage floor
stage_color = stage_mat_config.get('color', [0.15, 0.15, 0.18])
if len(stage_color) == 3:
bsdf.inputs['Base Color'].default_value = (*stage_color, 1.0)
bsdf.inputs['Roughness'].default_value = stage_mat_config.get('roughness', 0.7)
bsdf.inputs['Metallic'].default_value = stage_mat_config.get('metallic', 0.0)
bsdf.inputs['Specular IOR Level'].default_value = 0.3
# Add subtle normal map variation for surface detail
# (Could be enhanced with actual texture maps)
print(f" Stage material: {stage_color}, roughness: {bsdf.inputs['Roughness'].default_value}")
print("[OK] Stage environment created")
return stage
def create_mascot_placeholder(self):
"""
Create production-quality mascot with PBR materials.
Returns:
Mascot object
"""
print("Creating mascot with PBR materials...")
mascot_image = self.config.get('inputs', {}).get('mascot_image')
# Use billboard plane for flat image mascots (preserves 2D design)
# This works much better than wrapping around a sphere!
bpy.ops.mesh.primitive_plane_add(size=2, location=(0, 0, 1))
mascot = bpy.context.object
mascot.name = "Mascot"
# Rotate plane to face camera (90 degrees around X axis)
mascot.rotation_euler[0] = 1.5708 # 90 degrees in radians
# Scale slightly to match expected size
mascot.scale = (1.2, 1.2, 1.2)
# Smooth shading for better appearance
bpy.ops.object.shade_smooth()
print(" Using billboard plane (preserves flat design)")
# Create production-quality PBR material
mat = bpy.data.materials.new(name="MascotMaterial_PBR")
mat.use_nodes = True
mat.blend_method = 'BLEND' # Enable alpha transparency
mat.shadow_method = 'CLIP' # Proper shadows with transparency
mat.use_backface_culling = False # Render both sides
nodes = mat.node_tree.nodes
links = mat.node_tree.links
mascot.data.materials.append(mat)
# Get material config
materials_config = self.config.get('materials', {})
mascot_mat_config = materials_config.get('mascot', {})
# Get Principled BSDF (default shader)
bsdf = nodes.get("Principled BSDF")
if not bsdf:
bsdf = nodes.new('ShaderNodeBsdfPrincipled')
# Configure PBR properties
if mascot_mat_config.get('type') == 'pbr':
print(" Applying PBR material properties...")
# Physical properties
bsdf.inputs['Roughness'].default_value = mascot_mat_config.get('roughness', 0.4)
bsdf.inputs['Metallic'].default_value = mascot_mat_config.get('metallic', 0.0)
bsdf.inputs['Specular IOR Level'].default_value = mascot_mat_config.get('specular', 0.5)
# Subsurface scattering for organic look
subsurface = mascot_mat_config.get('subsurface', 0.0)
if subsurface > 0:
bsdf.inputs['Subsurface Weight'].default_value = subsurface
bsdf.inputs['Subsurface Radius'].default_value = (1.0, 0.5, 0.25) # R, G, B radii
print(f" SSS: {subsurface} (organic look)")
# Sheen for fur-like appearance
sheen = mascot_mat_config.get('sheen', 0.0)
if sheen > 0:
bsdf.inputs['Sheen Weight'].default_value = sheen
bsdf.inputs['Sheen Roughness'].default_value = 0.5
# Use primary color for sheen tint
primary_color = self.config.get('style', {}).get('colors', {}).get('primary', [0.95, 0.4, 0.2])
if len(primary_color) == 3:
bsdf.inputs['Sheen Tint'].default_value = (*primary_color, 1.0)
print(f" Sheen: {sheen} (fur-like)")
print(f" Roughness: {bsdf.inputs['Roughness'].default_value}")
print(f" Metallic: {bsdf.inputs['Metallic'].default_value}")
print(f" Specular: {bsdf.inputs['Specular IOR Level'].default_value}")
# Load mascot image texture
if mascot_image and os.path.exists(mascot_image):
print(f" Loading mascot texture: {mascot_image}")
# Create UV mapping node for proper texture mapping
mapping = nodes.new('ShaderNodeMapping')
mapping.location = (-600, 0)
tex_coord = nodes.new('ShaderNodeTexCoord')
tex_coord.location = (-800, 0)
# Create image texture node
tex_image = nodes.new('ShaderNodeTexImage')
tex_image.location = (-400, 0)
tex_image.image = bpy.data.images.load(mascot_image)
tex_image.interpolation = 'Smart' # Better quality
# Connect texture pipeline
links.new(tex_coord.outputs['UV'], mapping.inputs['Vector'])
links.new(mapping.outputs['Vector'], tex_image.inputs['Vector'])
links.new(tex_image.outputs['Color'], bsdf.inputs['Base Color'])
# Also use alpha if available
if tex_image.image.alpha_mode != 'NONE':
links.new(tex_image.outputs['Alpha'], bsdf.inputs['Alpha'])
print(" [OK] Texture loaded with UV mapping")
else:
# Use primary color from config if no texture
primary_color = self.config.get('style', {}).get('colors', {}).get('primary', [0.95, 0.4, 0.2])
if len(primary_color) == 3:
bsdf.inputs['Base Color'].default_value = (*primary_color, 1.0)
print(" Using solid color (no texture)")
print("[OK] Mascot created with production PBR materials")
print(" NOTE: Full image-to-mesh rigging not yet implemented")
return mascot
def create_phoneme_shape_keys(self, mascot):
"""
Create shape keys for phoneme-based lip sync.
Args:
mascot: Mascot mesh object
Note: This is a stub. Full implementation requires proper mouth rigging.
"""
print("Creating phoneme shape keys (stub)...")
# Common phoneme shapes (Preston Blair mouth positions)
phoneme_shapes = ['X', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
# Add basis shape key
mascot.shape_key_add(name='Basis')
# Add phoneme shape keys (placeholders)
for phoneme in phoneme_shapes:
sk = mascot.shape_key_add(name=f'Phoneme_{phoneme}')
# TODO: Actually deform mesh for each phoneme
print(f"[OK] Created {len(phoneme_shapes)} phoneme shape keys (placeholders)")
def animate_lip_sync(self, mascot):
"""
Generate lip-sync animation from phoneme data.
Args:
mascot: Mascot mesh object with shape keys
"""
if not self.config.get('animation', {}).get('enable_lipsync', True):
print("Lip-sync disabled in config")
return
print("Generating lip-sync animation...")
phonemes = self.prep_data.get('phonemes', [])
if not phonemes:
print(" WARNING: No phoneme data available")
return
# Animate shape keys based on phoneme timings
for i, phoneme_data in enumerate(phonemes):
time = phoneme_data['time']
phoneme = phoneme_data['phoneme']
# Convert time to frame
frame = int(time * self.fps) + 1
# Find corresponding shape key
sk_name = f'Phoneme_{phoneme}'
if sk_name in mascot.data.shape_keys.key_blocks:
sk = mascot.data.shape_keys.key_blocks[sk_name]
# Keyframe: set to 1.0 at this frame
sk.value = 1.0
sk.keyframe_insert(data_path='value', frame=frame)
# Keyframe: set to 0.0 at next frame (or slightly after)
next_time = phonemes[i + 1]['time'] if i + 1 < len(phonemes) else time + 0.15
next_frame = int(next_time * self.fps) + 1
sk.value = 0.0
sk.keyframe_insert(data_path='value', frame=next_frame)
print(f"[OK] Lip-sync animation generated ({len(phonemes)} phoneme transitions)")
def animate_gestures(self, mascot):
"""
Generate body gesture animations synced to beats.
Args:
mascot: Mascot object
"""
if not self.config.get('animation', {}).get('enable_gestures', True):
print("Gestures disabled in config")
return
print("Generating gesture animation...")
beat_times = self.prep_data.get('beats', {}).get('beat_times', [])
if not beat_times:
print(" WARNING: No beat data available")
return
intensity = self.config.get('animation', {}).get('gesture_intensity', 0.7)
# Simple bounce animation on beats
for beat_time in beat_times:
frame = int(beat_time * self.fps) + 1
# Slight upward movement
mascot.location.z = 1.0 + (0.1 * intensity)
mascot.keyframe_insert(data_path='location', frame=frame)
# Return to rest position
rest_frame = frame + 5
mascot.location.z = 1.0
mascot.keyframe_insert(data_path='location', frame=rest_frame)
print(f"[OK] Gesture animation generated ({len(beat_times)} beats)")
def create_lyrics_text(self):
"""
Create production-quality animated text overlays for lyrics.
Returns:
List of text objects
"""
if not self.config.get('animation', {}).get('enable_lyrics', True):
print("Lyrics disabled in config")
return []
print("Creating professional lyrics text...")
timed_words = self.prep_data.get('timed_words', [])
if not timed_words:
print(" WARNING: No lyrics data available")
return []
lyrics_style = self.config.get('animation', {}).get('lyrics_style', 'bounce')
text_objects = []
# Get material settings from config
materials_config = self.config.get('materials', {})
text_mat_config = materials_config.get('text', {})
# Create a text object for each word
for i, word_data in enumerate(timed_words):
word = word_data['word']
start_time = word_data['start']
end_time = word_data['end']
# Create text object - position in front and below mascot for visibility
# Camera is at (0, -6, 1) looking at mascot at (0, 0, 1)
# Text should be closer to camera (more negative Y) and lower on screen (lower Z)
# This puts text in the lower third of the frame, standard for subtitles
y_position = -2.0 # Closer to camera than mascot for better visibility
z_position = 0.2 # Below mascot center (mascot at z=1, this is ~0.8 below)
bpy.ops.object.text_add(location=(0, y_position, z_position))
text_obj = bpy.context.object
text_obj.data.body = word.upper() # Uppercase for impact
text_obj.data.align_x = 'CENTER'
text_obj.data.align_y = 'CENTER'
text_obj.name = f"Lyric_{word}"
# Professional 3D text settings
if lyrics_style == 'professional':
# Add 3D extrusion
text_obj.data.extrude = 0.15 # Depth
text_obj.data.bevel_depth = 0.02 # Smooth edges
text_obj.data.bevel_resolution = 3 # Bevel smoothness
# Font size
text_obj.data.size = 0.8
# Optional: Use a nicer font if available
# text_obj.data.font = bpy.data.fonts.load("/path/to/font.ttf")
else:
# Standard 3D text
text_obj.data.extrude = 0.1
text_obj.data.bevel_depth = 0.01
text_obj.data.size = 0.6
# Create professional emission/glossy material
mat = bpy.data.materials.new(name=f"TextMaterial_{i}")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
# Clear default nodes
nodes.clear()
# Create shader nodes
output_node = nodes.new('ShaderNodeOutputMaterial')
output_node.location = (400, 0)
if text_mat_config.get('type') == 'emission_glossy':
# Mix emission and glossy for glowing metallic text
mix_shader = nodes.new('ShaderNodeMixShader')
mix_shader.location = (200, 0)
mix_shader.inputs['Fac'].default_value = 0.7 # 70% emission, 30% glossy
# Emission shader (glow)
emission = nodes.new('ShaderNodeEmission')
emission.location = (0, 100)
emission.inputs['Strength'].default_value = text_mat_config.get('emission_strength', 2.0)
# Get accent color from style config
accent_color = self.config.get('style', {}).get('colors', {}).get('accent', [0.95, 0.85, 0.3])
if len(accent_color) == 3:
emission.inputs['Color'].default_value = (*accent_color, 1.0)
# Glossy shader (reflective)
glossy = nodes.new('ShaderNodeBsdfGlossy')
glossy.location = (0, -100)
glossy.inputs['Roughness'].default_value = text_mat_config.get('roughness', 0.1)
glossy.inputs['Color'].default_value = (*accent_color, 1.0)
# Connect nodes
links.new(emission.outputs['Emission'], mix_shader.inputs[1])
links.new(glossy.outputs['BSDF'], mix_shader.inputs[2])
links.new(mix_shader.outputs['Shader'], output_node.inputs['Surface'])
else:
# Simple emission shader
emission = nodes.new('ShaderNodeEmission')
emission.location = (0, 0)
emission.inputs['Strength'].default_value = 2.0
emission.inputs['Color'].default_value = (1.0, 1.0, 0.3, 1.0) # Yellow
links.new(emission.outputs['Emission'], output_node.inputs['Surface'])
# Assign material
if text_obj.data.materials:
text_obj.data.materials[0] = mat
else:
text_obj.data.materials.append(mat)
# Initially hide
text_obj.hide_render = True
text_obj.hide_viewport = True
# Animate visibility and effects
start_frame = int(start_time * self.fps) + 1
end_frame = int(end_time * self.fps) + 1
# Show at start
text_obj.hide_render = False
text_obj.hide_viewport = False
text_obj.keyframe_insert(data_path='hide_render', frame=start_frame)
text_obj.keyframe_insert(data_path='hide_viewport', frame=start_frame)
# Animate based on style
if lyrics_style == 'professional':
# Fade in + scale + subtle rotation
text_obj.scale = (0.1, 0.1, 0.1)
text_obj.keyframe_insert(data_path='scale', frame=start_frame)
# Grow to full size
grow_frame = start_frame + 5
text_obj.scale = (1.0, 1.0, 1.0)
text_obj.keyframe_insert(data_path='scale', frame=grow_frame)
# Subtle pulse during display
mid_frame = (start_frame + end_frame) // 2
text_obj.scale = (1.1, 1.1, 1.1)
text_obj.keyframe_insert(data_path='scale', frame=mid_frame)
# Return to normal
text_obj.scale = (1.0, 1.0, 1.0)
text_obj.keyframe_insert(data_path='scale', frame=end_frame - 3)
elif lyrics_style == 'bounce':
# Original bounce effect
text_obj.scale = (0.5, 0.5, 0.5)
text_obj.keyframe_insert(data_path='scale', frame=start_frame)
mid_frame = start_frame + 3
text_obj.scale = (1.2, 1.2, 1.2)
text_obj.keyframe_insert(data_path='scale', frame=mid_frame)
text_obj.scale = (1.0, 1.0, 1.0)
text_obj.keyframe_insert(data_path='scale', frame=mid_frame + 2)
# Hide at end
text_obj.hide_render = True
text_obj.hide_viewport = True
text_obj.keyframe_insert(data_path='hide_render', frame=end_frame)
text_obj.keyframe_insert(data_path='hide_viewport', frame=end_frame)
text_objects.append(text_obj)
print(f"[OK] Created {len(text_objects)} professional lyric text objects")
print(f" Style: {lyrics_style}")
print(f" Material: emission + glossy with PBR properties")
return text_objects
def animate_lights_to_beats(self, lights):
"""
Animate lights to pulse with beats.
Args:
lights: List of light objects
"""
if not self.config.get('effects', {}).get('lights', {}).get('flashes', {}).get('enabled', True):
print("Light flashes disabled in config")
return
print("Animating lights to beats...")
beat_times = self.prep_data.get('beats', {}).get('beat_times', [])
if not beat_times:
return
for light in lights:
base_energy = light.data.energy
for beat_time in beat_times:
frame = int(beat_time * self.fps) + 1
# Flash brighter
light.data.energy = base_energy * 2
light.data.keyframe_insert(data_path='energy', frame=frame)
# Return to normal
light.data.energy = base_energy
light.data.keyframe_insert(data_path='energy', frame=frame + 3)
print(f"[OK] Lights animated to {len(beat_times)} beats")
def setup_render_settings(self):
"""Configure production-quality render engine and output settings."""
print("Configuring render settings...")
video_config = self.config.get('video', {})
# Render engine - normalize config names to Blender names
engine_config = video_config.get('render_engine', 'EEVEE')
engine_map = {
'EEVEE': 'BLENDER_EEVEE',
'BLENDER_EEVEE': 'BLENDER_EEVEE',
'CYCLES': 'CYCLES'
}
engine = engine_map.get(engine_config, 'BLENDER_EEVEE')
self.scene.render.engine = engine
print(f" Engine: {engine}")
# Samples
samples = video_config.get('samples', 128)
if engine_config == 'EEVEE' or engine == 'BLENDER_EEVEE':
self.scene.eevee.taa_render_samples = samples
# EEVEE quality settings
self.scene.eevee.use_gtao = True # Ambient occlusion
self.scene.eevee.use_bloom = True # Bloom
self.scene.eevee.use_ssr = True # Screen space reflections
self.scene.eevee.use_ssr_refraction = True
self.scene.eevee.use_volumetric_shadows = True
elif engine_config == 'CYCLES' or engine == 'CYCLES':
self.scene.cycles.samples = samples
# Cycles quality settings
self.scene.cycles.use_adaptive_sampling = True
self.scene.cycles.adaptive_threshold = 0.01
# GPU acceleration if available
if video_config.get('use_gpu', True):
try:
self.scene.cycles.device = 'GPU'
print(" GPU rendering enabled")
except:
print(" GPU not available, using CPU")
# Denoising
if video_config.get('use_denoising', False):
try:
self.scene.cycles.use_denoising = True
denoiser = video_config.get('denoiser', 'OPTIX')
if hasattr(self.scene.cycles, 'denoiser'):
try:
self.scene.cycles.denoiser = denoiser
print(f" Denoiser: {denoiser}")
except:
print(" Using default denoiser")
except Exception as e:
print(f" Denoising not available: {e}")
self.scene.cycles.use_denoising = False
else:
# Explicitly disable denoising
self.scene.cycles.use_denoising = False
print(" Denoising disabled")
# Persistent data for faster rendering
if video_config.get('persistent_data', True):
self.scene.render.use_persistent_data = True
print(f" Samples: {samples}")
# Motion blur (production feature)
if video_config.get('motion_blur', False):
self.scene.render.use_motion_blur = True
shutter = video_config.get('motion_blur_shutter', 0.5)
self.scene.render.motion_blur_shutter = shutter
print(f" Motion blur: enabled (shutter {shutter})")
# Output path
frames_dir = self.config.get('output', {}).get('frames_dir', 'outputs/frames')
os.makedirs(frames_dir, exist_ok=True)
self.scene.render.filepath = os.path.join(frames_dir, 'frame_####.png')
self.scene.render.image_settings.file_format = 'PNG'
self.scene.render.image_settings.color_mode = 'RGBA'
self.scene.render.image_settings.color_depth = '16' # 16-bit for better quality
self.scene.render.image_settings.compression = 15 # PNG compression
# Film settings (transparency, etc.)
self.scene.render.film_transparent = False # Opaque background for now
print(f"[OK] Render settings configured")
print(f" Output: {self.scene.render.filepath}")
def setup_compositor(self):
"""Setup production-quality compositor with DOF, bloom, color grading, etc."""
compositor_config = self.config.get('compositor', {})
if not compositor_config.get('enabled', False):
print("Compositor disabled in config")
return
print("Setting up production compositor...")
# Enable compositor
self.scene.use_nodes = True
self.scene.render.use_compositing = True
# Enable depth pass for DOF
view_layer = self.scene.view_layers[0]
view_layer.use_pass_z = True
nodes = self.scene.node_tree.nodes
links = self.scene.node_tree.links
# Clear existing nodes
nodes.clear()
# Create render layers node (source)
render_layers = nodes.new('CompositorNodeRLayers')
render_layers.location = (0, 0)
current_node = render_layers
current_output = 'Image'
x_offset = 250
# Depth of Field (DOF)
dof_config = compositor_config.get('dof', {})
if dof_config.get('enabled', False):
print(f" Adding DOF (f-stop: {dof_config.get('f_stop', 2.8)})")
defocus = nodes.new('CompositorNodeDefocus')
defocus.location = (x_offset, 0)
defocus.use_zbuffer = True
defocus.f_stop = dof_config.get('f_stop', 2.8)
defocus.blur_max = 100
defocus.threshold = 1.0
# Connect
links.new(current_node.outputs[current_output], defocus.inputs['Image'])
links.new(render_layers.outputs['Depth'], defocus.inputs['Z'])
current_node = defocus
current_output = 'Image'
x_offset += 250
# Also configure camera DOF
camera = self.scene.camera
if camera and camera.data:
camera.data.dof.use_dof = True
camera.data.dof.aperture_fstop = dof_config.get('f_stop', 2.8)
camera.data.dof.focus_distance = dof_config.get('focus_distance', 5.0)
# Bloom (glare node)
bloom_config = compositor_config.get('bloom', {})
if bloom_config.get('enabled', False):
print(f" Adding bloom (threshold: {bloom_config.get('threshold', 0.8)})")
glare = nodes.new('CompositorNodeGlare')
glare.location = (x_offset, 0)
glare.glare_type = 'FOG_GLOW' # Bloom-like effect
glare.threshold = bloom_config.get('threshold', 0.8)
glare.size = int(bloom_config.get('radius', 6.5))
glare.quality = 'HIGH'
# Mix with original image
mix = nodes.new('CompositorNodeMixRGB')
mix.location = (x_offset + 200, 0)
mix.blend_type = 'ADD'
mix.inputs['Fac'].default_value = bloom_config.get('intensity', 0.05)
links.new(current_node.outputs[current_output], glare.inputs['Image'])
links.new(current_node.outputs[current_output], mix.inputs[1])
links.new(glare.outputs['Image'], mix.inputs[2])
current_node = mix
current_output = 'Image'
x_offset += 450
# Color Grading
color_config = compositor_config.get('color_grading', {})
if color_config.get('enabled', False):
print(" Adding color grading")
# Hue/Saturation/Value for saturation
hsv = nodes.new('CompositorNodeHueSat')
hsv.location = (x_offset, 100)
hsv.inputs['Saturation'].default_value = color_config.get('saturation', 1.15)
links.new(current_node.outputs[current_output], hsv.inputs['Image'])
# Color Balance for temperature
color_balance = nodes.new('CompositorNodeColorBalance')
color_balance.location = (x_offset, -100)
temp = color_config.get('temperature', 1.05)
# Warm tint (more red/yellow)
if temp > 1.0:
color_balance.lift = (1.0, 0.95, 0.85)
color_balance.gamma = (1.0, 0.98, 0.92)
elif temp < 1.0:
# Cool tint (more blue)
color_balance.lift = (0.85, 0.95, 1.0)
color_balance.gamma = (0.92, 0.98, 1.0)
links.new(hsv.outputs['Image'], color_balance.inputs['Image'])
# Brightness/Contrast
bright_contrast = nodes.new('CompositorNodeBrightContrast')
bright_contrast.location = (x_offset + 200, 0)
bright_contrast.inputs['Contrast'].default_value = color_config.get('contrast', 1.1) - 1.0 # Blender uses 0.0 as default
bright_contrast.inputs['Bright'].default_value = 0.0
links.new(color_balance.outputs['Image'], bright_contrast.inputs['Image'])
# Gamma
gamma_node = nodes.new('CompositorNodeGamma')
gamma_node.location = (x_offset + 400, 0)
gamma_node.inputs['Gamma'].default_value = color_config.get('gamma', 1.0)
links.new(bright_contrast.outputs['Image'], gamma_node.inputs['Image'])
current_node = gamma_node
current_output = 'Image'
x_offset += 600
# Vignette
vignette_config = compositor_config.get('vignette', {})
if vignette_config.get('enabled', False):
print(f" Adding vignette (amount: {vignette_config.get('amount', 0.3)})")
# Create ellipse mask
ellipse = nodes.new('CompositorNodeEllipseMask')
ellipse.location = (x_offset, -300)
ellipse.width = 0.95
ellipse.height = 0.95
# Blur the mask
blur = nodes.new('CompositorNodeBlur')
blur.location = (x_offset + 200, -300)
blur.size_x = 50
blur.size_y = 50
blur.use_extended_bounds = True
links.new(ellipse.outputs['Mask'], blur.inputs['Image'])
# Invert mask (darken edges)
invert = nodes.new('CompositorNodeInvert')
invert.location = (x_offset + 400, -300)
links.new(blur.outputs['Image'], invert.inputs['Color'])
# Mix with main image
mix_vignette = nodes.new('CompositorNodeMixRGB')
mix_vignette.location = (x_offset + 250, 0)
mix_vignette.blend_type = 'MULTIPLY'
mix_vignette.inputs['Fac'].default_value = vignette_config.get('amount', 0.3)
links.new(current_node.outputs[current_output], mix_vignette.inputs[1])
links.new(invert.outputs['Color'], mix_vignette.inputs[2])
current_node = mix_vignette
current_output = 'Image'
x_offset += 500
# Film Grain
grain_config = compositor_config.get('film_grain', {})