forked from p2or/blender-loom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loom.py
3229 lines (2660 loc) · 125 KB
/
loom.py
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
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
import bpy
import re
import os
import errno
import subprocess
import blend_render_info
from sys import platform
from bpy_extras.io_utils import ImportHelper
from numpy import arange, around, isclose
from itertools import count, groupby
import rna_keymap_ui
import webbrowser
bl_info = {
"name": "Loom",
"description": "Image sequence rendering, encoding and playback",
"author": "Christian Brinkmann (p2or)",
"version": (0, 5),
"blender": (2, 81, 0),
"location": "Render Menu or Render Panel (optional)",
"warning": "", # used for warning icon and text in addons panel
"wiki_url": "https://github.com/p2or/blender-loom",
"tracker_url": "https://github.com/p2or/blender-loom/issues",
"support": "COMMUNITY",
"category": "Render"
}
# -------------------------------------------------------------------
# Preferences & Scene Properties
# -------------------------------------------------------------------
class LoomPreferences(bpy.types.AddonPreferences):
bl_idname = __name__
terminal: bpy.props.EnumProperty(
name="Terminal",
items=(
("win-default", "Windows Default Terminal", "", 1),
("osx-default", "OSX Default Terminal", "", 2),
("x-terminal-emulator", "X Terminal Emulator", "", 3),
("xfce4-terminal", "Xfce4 Terminal", "", 4),
("xterm", "xterm", "", 5)))
xterm_flag: bpy.props.BoolProperty(
name="Use Xterm (Terminal Fallback)",
description="Serves as fallback for OSX and others",
default=False)
bash_file: bpy.props.StringProperty(
name="Bash file",
description = "Filepath to temporary bash or bat file")
bash_flag: bpy.props.BoolProperty(
name="Force Bash File",
description="Force using bash file instead of individual arguments",
default=False)
render_dialog_width: bpy.props.IntProperty(
name="Render Dialog Width",
description = "Width of Image Sequence Render Dialog",
subtype='PIXEL',
default=450, min=400)
encode_dialog_width: bpy.props.IntProperty(
name="Encoding Dialog Width",
description = "Width of Encoding Dialog",
subtype='PIXEL',
default=650, min=400)
log_render: bpy.props.BoolProperty(
name="Logging (Required for Playback)",
description="If enabled render output properties will be saved",
default=True)
log_render_limit: bpy.props.IntProperty(
name="Log Limit",
default=3)
playblast_flag: bpy.props.BoolProperty(
name="Playblast (Experimental)",
description="Playback rendered sequences",
default=False)
user_player: bpy.props.BoolProperty(
name="Default Animation Player",
description="Use default player (User Preferences > File > Animation Player)",
default=False)
display_ui: bpy.props.BoolProperty(
name="Display Buttons in Render Panel",
description = "Displays Buttons in Render Panel",
default=False)
ffmpeg_path: bpy.props.StringProperty(
name="FFmpeg Binary",
description="Path to ffmpeg",
maxlen=1024,
subtype='FILE_PATH')
default_codec: bpy.props.StringProperty(
name="User Codec",
description = "Default user codec")
batch_dialog_width: bpy.props.IntProperty(
name="Batch Dialog Width",
description="Width of Batch Render Dialog",
subtype='PIXEL',
default=650, min=600, max=1800)
batch_dialog_rows: bpy.props.IntProperty(
name="Number of Rows",
description="Number of Rows",
min=7, max=40,
default=12)
batch_paths_flag: bpy.props.BoolProperty(
name="Display File Paths",
description="Display File paths")
batch_path_col_width: bpy.props.FloatProperty(
name="Path Column Width",
description="Width of path column in list",
default=0.6, min=0.3, max=0.8)
batch_name_col_width: bpy.props.FloatProperty(
name="Name Column Width",
description="Width of name column in list",
default=0.45, min=0.3, max=0.8)
render_background: bpy.props.BoolProperty(
name="Render in Background",
description="Do not activate the Console",
default=False)
def draw(self, context):
split_width = 0.4
layout = self.layout
box = layout.box()
split = box.split(factor=split_width)
col = split.column()
if bpy.app.version < (2, 80, 0): col.prop(self, "display_ui")
col.prop(self, "playblast_flag")
up = col.column()
up.prop(self, "user_player")
up.enabled = self.playblast_flag
col = split.column()
col.prop(self, "render_dialog_width")
col.prop(self, "encode_dialog_width")
col.prop(self, "batch_dialog_width")
box = layout.box()
split = box.split(factor=split_width)
col = split.column()
col.label(text="Path to FFmpeg Binary:")
txt = "Force generating .bat file" if platform.startswith('win32') else "Force generating .sh file"
col_sub = col.column()
col_sub.prop(self, "bash_flag", text=txt)
""" OSX specific properties """
if platform.startswith('darwin'):
col_sub.enabled = False
col.prop(self, "render_background")
""" Linux/OSX specific properties """
if not platform.startswith('win32'):
col.prop(self, "xterm_flag")
col = split.column()
col.prop(self, "ffmpeg_path", text="")
sub = col.row(align=True)
txt = "Delete temporary .bat Files" if platform.startswith('win32') else "Delete temporary .sh files"
sub.operator(LOOM_OT_delete_bash_files.bl_idname, text=txt, icon="FILE_SCRIPT")
script_folder = bpy.utils.script_path_user()
sub.operator(LOOM_OT_open_folder.bl_idname, icon="DISK_DRIVE", text="").folder_path = script_folder
""" Hotkey box """
box = layout.box()
split = box.split()
col = split.column()
col.label(text='Hotkeys')
kc_usr = bpy.context.window_manager.keyconfigs.user
km_usr = kc_usr.keymaps.get('Screen')
if not user_keymap_ids: # Ouch, Todo!
for kmi_usr in km_usr.keymap_items:
for km_addon, kmi_addon in addon_keymaps:
if kmi_addon.compare(kmi_usr):
user_keymap_ids.append(kmi_usr.id)
for kmi_usr in km_usr.keymap_items: # user hotkeys by namespace
if kmi_usr.idname.startswith("loom."):
col.context_pointer_set("keymap", km_usr)
rna_keymap_ui.draw_kmi([], kc_usr, km_usr, kmi_usr, col, 0)
row = layout.row()
layout.operator(LOOM_OT_pref_reset.bl_idname, icon='FILE_REFRESH')
class LOOM_OT_pref_reset(bpy.types.Operator):
"""Reset Add-on Preferences"""
bl_idname = "loom.reset_preferences"
bl_label = "Reset Preferences"
bl_options = {"INTERNAL"}
def execute(self, context):
prefs = context.preferences.addons[__name__].preferences
prefs.property_unset("terminal")
prefs.property_unset("xterm_flag")
prefs.property_unset("render_dialog_width")
prefs.property_unset("encode_dialog_width")
prefs.property_unset("bash_flag")
prefs.property_unset("bash_file")
prefs.property_unset("display_ui")
prefs.property_unset("user_player")
prefs.property_unset("log_render")
prefs.property_unset("log_render_limit")
#prefs.property_unset("ffmpeg_path")
prefs.property_unset("default_codec")
prefs.property_unset("playblast_flag")
""" Restore default keys by keymap ids """
kc_usr = context.window_manager.keyconfigs.user
km_usr = kc_usr.keymaps.get('Screen')
for i in user_keymap_ids:
kmi = km_usr.keymap_items.from_id(i)
if kmi:
km_usr.restore_item_to_default(kmi)
#bpy.ops.wm.save_userpref()
return {'FINISHED'}
class LoomRenderCollection(bpy.types.PropertyGroup):
# name: bpy.props.StringProperty()
render_id: bpy.props.IntProperty()
start_time: bpy.props.StringProperty()
start_frame: bpy.props.StringProperty()
end_frame: bpy.props.StringProperty()
file_path: bpy.props.StringProperty()
padded_zeros: bpy.props.IntProperty()
image_format: bpy.props.StringProperty()
class LoomBatchRenderCollection(bpy.types.PropertyGroup):
# name: bpy.props.StringProperty()
rid: bpy.props.IntProperty()
path: bpy.props.StringProperty()
frame_start: bpy.props.IntProperty()
frame_end: bpy.props.IntProperty()
scene: bpy.props.StringProperty()
frames: bpy.props.StringProperty(name="Frames")
encode_flag: bpy.props.BoolProperty(default=False)
input_filter: bpy.props.BoolProperty(default=False)
class LoomSettings(bpy.types.PropertyGroup):
frame_input: bpy.props.StringProperty(
name="Frames to render",
description="Specify a range or single frames to render")
filter_input: bpy.props.BoolProperty(
name="Filter individual elements",
description="Isolate numbers after exclude chars (^, !)",
default=False)
command_line: bpy.props.BoolProperty(
name="Render using Command Line",
description="Send frames to Command Line (background process)",
default=False)
override_threads: bpy.props.BoolProperty(
name="Override CPU thread count",
description="Force to render with specified thread count (CPU)",
default=False)
threads: bpy.props.IntProperty(
name="CPU Threads",
description="Number of CPU threads to use simultaneously while rendering",
min = 1)
sequence_encode: bpy.props.StringProperty(
name="Image Sequence",
description="Image Sequence",
maxlen=1024)
movie_path: bpy.props.StringProperty(
name="Movie",
description="Movie File output path",
maxlen=1024)
lost_frames: bpy.props.StringProperty(
name="Missing Frames",
description="Missing Frames",
default="",
options={'SKIP_SAVE'})
render_collection: bpy.props.CollectionProperty(
name="Render Collection",
type=LoomRenderCollection)
batch_scan_folder: bpy.props.StringProperty(
name="Folder",
description="Folder",
maxlen=1024)
batch_render_idx: bpy.props.IntProperty(
name="Collection Index",
description="Collection Index")
batch_render_coll: bpy.props.CollectionProperty(
name="Batch Render Collection",
type=LoomBatchRenderCollection)
# -------------------------------------------------------------------
# UI Operators
# -------------------------------------------------------------------
class LOOM_OT_render_threads(bpy.types.Operator):
"""Set all available threads"""
bl_idname = "loom.available_threads"
bl_label = "Reset Threads"
bl_description = "Set to all available threads"
bl_options = {'INTERNAL'}
def execute(self, context):
from multiprocessing import cpu_count
context.scene.loom.threads = cpu_count()
self.report({'INFO'}, "Set to core maximum")
return {'FINISHED'}
class LOOM_OT_render_full_scale(bpy.types.Operator):
"""Set Resolution Percentage Scale to 100%"""
bl_idname = "loom.full_scale"
bl_label = "Full Scale"
bl_description = "Set Resolution Percentage Scale to 100%"
bl_options = {'INTERNAL'}
def execute(self, context): #context.area.tag_redraw()
context.scene.render.resolution_percentage = 100
return {'FINISHED'}
class LOOM_OT_timeline_props(bpy.types.Operator):
"""Set timeline range, steps & threads from UI"""
bl_idname = "loom.timeline_properties"
bl_label = "Timeline UI Properties"
bl_description = "Set range based on Timeline"
bl_options = {'INTERNAL'}
def execute(self, context):
scn = context.scene
lum = scn.loom
timeline_range = "{start}-{end}".format(start=scn.frame_start, end=scn.frame_end)
timeline_inc = "{range}x{inc}".format(range=timeline_range, inc=scn.frame_step)
lum.frame_input = timeline_inc if scn.frame_step != 1 else timeline_range
return {'FINISHED'}
class LOOM_OT_verify_frames(bpy.types.Operator):
"""Display all frames & the current render location"""
bl_idname = "loom.verify_frames"
bl_label = "Verify Input Frames"
bl_description = "Report all Frames that are going to be rendered"
bl_options = {'INTERNAL'}
frame_input = None
def execute(self, context):
scn = context.scene
folder = os.path.realpath(bpy.path.abspath(scn.render.filepath))
if self.frame_input:
self.report({'INFO'}, ("{} {} [{}] will be rendered to {}".format(
len(self.frame_input),
"Frame" if len(self.frame_input) == 1 else "Frames",
', '.join('{}'.format(i) for i in self.frame_input),
folder)))
else:
self.report({'INFO'}, "No frames specified")
return {'FINISHED'}
def invoke(self, context, event):
lum = context.scene.loom
self.frame_input = filter_frames(
lum.frame_input, context.scene.frame_step, lum.filter_input)
return self.execute(context)
class LOOM_OT_render_dialog(bpy.types.Operator):
"""Render Image Sequence UI"""
bl_idname = "loom.render_dialog"
bl_label = "Render Image Sequence"
bl_description = "Render Image Sequence"
bl_options = {'REGISTER'}
show_errors: bpy.props.BoolProperty(
name="Show Errors",
description="Displays Errors and Warnings",
default=False,
options={'SKIP_SAVE'})
@classmethod
def poll(cls, context):
return not context.scene.render.is_movie_format
def check(self, context):
return True
def write_permission(self, folder): # Hacky, but ok for now
# https://stackoverflow.com/q/2113427/3091066
try: # os.access(os.path.realpath(bpy.path.abspath(out_folder)), os.W_OK)
pf = os.path.join(folder, "permission.txt")
fh = open(pf, 'w')
fh.close()
os.remove(pf)
return True
except:
return False
def execute(self, context):
prefs = context.preferences.addons[__name__].preferences
scn = context.scene
lum = scn.loom
filter_individual_numbers = lum.filter_input
user_input = lum.frame_input
""" Error handling """
user_error = False
if not self.options.is_invoke:
user_error = True
if not bpy.data.is_saved:
self.report({'ERROR'}, "Blend-file not saved.")
user_error = True
if not context.scene.camera:
self.report({'ERROR'}, "No camera in scene.")
user_error = True
if not user_input and not any(char.isdigit() for char in user_input):
self.report({'ERROR'}, "No frames to render.")
user_error = True
out_folder, out_filename = os.path.split(scn.render.filepath)
if not self.write_permission(os.path.realpath(bpy.path.abspath(out_folder))):
self.report({'ERROR'}, "Specified output folder does not exist (permission denied)")
user_error = True
if user_error: #bpy.ops.loom.render_dialog('INVOKE_DEFAULT')
return {"CANCELLED"}
""" Start rendering headless or within the UI as usual """
if lum.command_line:
bpy.ops.loom.render_terminal(
frames = user_input,
threads = lum.threads,
isolate_numbers = filter_individual_numbers)
else:
bpy.ops.render.image_sequence(
frames = user_input,
isolate_numbers = filter_individual_numbers,
render_silent = False)
return {"FINISHED"}
def invoke(self, context, event):
scn = context.scene
lum = scn.loom
prefs = context.preferences.addons[__name__].preferences
if not lum.is_property_set("frame_input") or not lum.frame_input:
bpy.ops.loom.timeline_properties()
if not prefs.is_property_set("terminal") or not prefs.terminal:
bpy.ops.loom.verify_terminal()
if not lum.is_property_set("threads") or not lum.threads:
lum.threads = scn.render.threads # *.5
return context.window_manager.invoke_props_dialog(self,
width=(prefs.render_dialog_width*context.preferences.system.pixel_size))
def draw(self, context):
scn = context.scene
lum = scn.loom
prefs = context.preferences.addons[__name__].preferences
layout = self.layout # layout.label(text="Render Image Sequence")
split = layout.split(factor=.17)
col = split.column(align=True)
col.label(text="Frames:")
col = split.column(align=True)
sub = col.row(align=True) #GHOST_ENABLED
sub.operator(LOOM_OT_timeline_props.bl_idname, icon='PREVIEW_RANGE', text="")
sub.prop(lum, "frame_input", text="")
sub.prop(lum, "filter_input", icon='FILTER', icon_only=True)
#sub.prop(lum, "filter_keyframes", icon='SPACE2', icon_only=True)
sub.operator(LOOM_OT_verify_frames.bl_idname, icon='GHOST_ENABLED', text="") #SEQ_LUMA_WAVEFORM
# Display Mode seems gone
if getattr(scn.render, "display_mode", None):
split = layout.split(factor=.17)
col = split.column(align=True)
col.active = not lum.command_line
col.label(text="Display:")
col = split.column(align=True)
sub = col.row(align=True)
sub.active = not lum.command_line
sub.prop(scn.render, "display_mode", text="")
sub.prop(scn.render, "use_lock_interface", icon_only=True)
row = layout.row(align=True)
row.prop(lum, "command_line", text="Render using Command Line")
if scn.render.resolution_percentage < 100:
row.prop(self, "show_errors", text="", icon='SCRIPT' if self.show_errors else "REC", emboss=False)
else:
row.operator(LOOM_OT_help.bl_idname, icon='HELP', text="", emboss=False)
#row.prop(self, "show_errors", icon='SCRIPT' if self.selection else "HELP", text="", emboss=False)
if lum.command_line:
row = layout.row(align=True)
row.prop(lum, "override_threads", icon='PARTICLE_DATA', icon_only=True)
thr_elem = row.row(align=True)
thr_elem.active = bool(lum.command_line and lum.override_threads)
thr_elem.prop(lum, "threads")
thr_elem.operator(LOOM_OT_render_threads.bl_idname, icon='LOOP_BACK', text="")
#thr_elem.prop(lum, "extra_terminal", icon='CONSOLE', icon_only=True)
if self.show_errors:
res_percentage = scn.render.resolution_percentage
if res_percentage < 100:
row = layout.row()
row.label(text="Warning: Resolution Percentage Scale is set to {}%".format(res_percentage))
row.operator(LOOM_OT_render_full_scale.bl_idname, icon="RECOVER_AUTO", text="", emboss=False)
class LOOM_OT_render_input_dialog(bpy.types.Operator):
"""Allows to pass custom numbers and ranges to the render dialog"""
bl_idname = "loom.render_input_dialog"
bl_label = "Render Frames"
bl_description = "Open up Render Image Sequence dialog"
bl_options = {'INTERNAL'}
frame_input: bpy.props.StringProperty()
def execute(self, context):
if self.frame_input:
context.scene.loom.frame_input = self.frame_input
bpy.ops.loom.render_dialog('INVOKE_DEFAULT')
return {'FINISHED'}
else:
return {'CANCELLED'}
class LOOM_OT_selected_keys_dialog(bpy.types.Operator):
"""Render selected keys of the dopesheet or graph editor"""
bl_idname = "loom.render_selected_keys"
bl_label = "Render Selected Keyframes"
bl_description = "Render selected Keyframes in the Timeline, Graph Editor or Dopesheet"
bl_options = {'REGISTER'}
def int_filter(self, flt):
try:
return int(flt)
except ValueError:
return None
def rangify_frames(self, frames):
""" Converts a list of integers to range string [1,2,3] -> '1-3' """
G=(list(x) for _,x in groupby(frames, lambda x,c=count(): next(c)-x))
return ",".join("-".join(map(str,(g[0],g[-1])[:len(g)])) for g in G)
def selected_ctrl_points(self, context):
""" Returns all selected keys in dopesheet """
# There is a select flag for the handles:
# key.select_left_handle & key.select_right_handle
ctrl_points = set()
for action in bpy.data.actions:
for channel in action.fcurves:
#if channel.select:
for key in channel.keyframe_points:
if key.select_control_point:
ctrl_points.add(key.co.x)
return sorted(ctrl_points)
def channel_ctrl_points(self, context):
"""Returns all keys of selected channels in dopesheet"""
ctrl_points = set()
for action in bpy.data.actions:
for channel in action.fcurves:
if channel.select: #print(action, channel.group)
for key in channel.keyframe_points:
ctrl_points.add(key.co.x)
return sorted(ctrl_points)
def selected_gpencil_frames(self, context):
""" Returns all selected grease pencil frames """
ctrl_points = set()
for o in context.scene.objects:
if o.type == 'GPENCIL':
for l in o.data.layers:
for f in l.frames:
if f.select:
ctrl_points.add(f.frame_number)
return sorted(ctrl_points)
@classmethod
def poll(cls, context):
editors = ('DOPESHEET_EDITOR', 'GRAPH_EDITOR', 'TIMELINE')
return context.space_data.type in editors and \
not context.scene.render.is_movie_format
def execute(self, context):
space = context.space_data #print (space.type)
selected_keys = None
if space.type == 'DOPESHEET_EDITOR':
mode = context.space_data.mode
if mode == 'GPENCIL':
selected_keys = self.selected_gpencil_frames(context)
elif mode == 'MASK':
# bpy.data.masks['Mask'].animation_data is empty
self.report({'ERROR'}, "Not implemented.")
return {"CANCELLED"}
elif mode == 'CACHEFILE':
self.report({'ERROR'}, "Not implemented.")
return {"CANCELLED"}
else: # Mode can be: DOPESHEET, ACTION, 'SHAPEKEY'
selected_keys = self.selected_ctrl_points(context)
elif space.type == 'GRAPH_EDITOR':
selected_keys = self.selected_ctrl_points(context)
if not selected_keys:
self.report({'ERROR'}, "No keyframes to render.")
return {"CANCELLED"}
""" Return integers whenever possible """
int_frames = [self.int_filter(frame) for frame in selected_keys]
frames = selected_keys if None in int_frames else int_frames
bpy.ops.loom.render_input_dialog(frame_input=self.rangify_frames(frames))
return {'FINISHED'}
class LOOM_OT_selected_makers_dialog(bpy.types.Operator):
"""Render selected markers of the dopesheet or timeline"""
bl_idname = "loom.render_selected_markers"
bl_label = "Render Selected Markers"
bl_description = "Render selected Markers in the Timeline or Dopesheet"
bl_options = {'REGISTER'}
def rangify_frames(self, frames):
""" Converts a list of integers to range string [1,2,3] -> '1-3' """
G=(list(x) for _,x in groupby(frames, lambda x,c=count(): next(c)-x))
return ",".join("-".join(map(str,(g[0],g[-1])[:len(g)])) for g in G)
@classmethod
def poll(cls, context):
editors = ('DOPESHEET_EDITOR', 'TIMELINE')
return context.space_data.type in editors and \
not context.scene.render.is_movie_format
def execute(self, context):
selected_markers = sorted(m.frame for m in context.scene.timeline_markers if m.select)
if not selected_markers:
self.report({'ERROR'}, "No markers to render.")
return {"CANCELLED"}
bpy.ops.loom.render_input_dialog(frame_input=self.rangify_frames(selected_markers))
return {'FINISHED'}
def codec_callback(scene, context):
codec = [
('PRORES422', "Apple ProRes 422", ""),
('PRORES422HQ', "Apple ProRes 422 HQ", ""),
('PRORES422LT', "Apple ProRes 422 LT", ""),
('PRORES422PR', "Apple ProRes 422 Proxy", ""),
('PRORES4444', "Apple ProRes 4444", ""),
('PRORES4444XQ', "Apple ProRes 4444 XQ", ""),
('DNXHD422-08-036', "Avid DNxHD 422 8-bit 36Mbit", ""),
('DNXHD422-08-145', "Avid DNxHD 422 8-bit 145Mbit", ""),
('DNXHD422-08-145', "Avid DNxHD 422 8-bit 220Mbit", ""),
('DNXHD422-10-185', "Avid DNxHD 422 10-bit 185Mbit", ""),
#('DNXHD422-10-440', "Avid DNxHD 422 10-bit 440Mbit", ""),
#('DNXHD444-10-350', "Avid DNxHD 422 10-bit 440Mbit", ""),
('DNXHR-444', "Avid DNxHR 444 10bit", ""),
('DNXHR-HQX', "Avid DNxHR HQX 10bit", ""),
('DNXHR-HQ', "Avid DNxHR HQ 8bit", ""),
('DNXHR-SQ', "Avid DNxHR SQ 8bit", "")
]
return codec
def colorspace_callback(scene, context):
colorspace = [
('iec61966_2_1', "sRGB", ""),
('bt709', "rec709", ""),
('gamma22', "Gamma 2.2", ""),
('gamma28', "Gamma 2.8", ""),
('linear', "Linear", "")
]
return colorspace
class LOOM_MT_display_settings(bpy.types.Menu):
bl_label = "Loom Batch Display Settings"
bl_idname = "LOOM_MT_display_settings"
def draw(self, context):
prefs = context.preferences.addons[__name__].preferences
layout = self.layout
layout.label(text="Display Settings", icon="COLOR")
layout.separator()
layout.prop(prefs, "batch_paths_flag")
layout.prop(prefs, "batch_dialog_rows")
if prefs.batch_paths_flag:
layout.prop(prefs, "batch_path_col_width")
else:
layout.prop(prefs, "batch_name_col_width")
layout.operator("loom.batch_dialog_reset_display", icon="ANIM")
class LOOM_UL_batch_list(bpy.types.UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
prefs = context.preferences.addons[__name__].preferences
if prefs.batch_paths_flag:
split = layout.split(factor=prefs.batch_path_col_width, align=True)
split_left = split.split(factor=0.08)
split_left.label(text="{:02d}".format(index+1))
#split_left.prop(item, "path", text="", emboss=False, icon='FILE_BLEND')
split_left.label(text=item.path, icon='FILE_BLEND')
else:
split = layout.split(factor=prefs.batch_name_col_width, align=True)
split_left = split.split(factor=0.1)
#split_left.label(text="{:02d}".format(index+1))
split_left.operator("loom.batch_default_frames", text="{:02d}".format(index+1), emboss=False).item_id = index
split_left.label(text=item.name, icon='FILE_BLEND')
split_right = split.split(factor=.99)
row = split_right.row(align=True)
row.operator("loom.batch_default_frames", icon="PREVIEW_RANGE", text="").item_id = index
row.prop(item, "frames", text="") #, icon='IMAGEFILE'
#row = split_right.row(align=True) #row.prop(item, "input_filter", text="", icon='FILTER')
row.prop(item, "input_filter", text="", icon='FILTER')
row.operator("loom.batch_verify_input", text="", icon='GHOST_ENABLED').item_id = index
#if prefs.ffmpeg_path:
row.prop(item, "encode_flag", text="", icon='FILE_MOVIE')
def invoke(self, context, event):
pass
class LOOM_OT_batch_dialog(bpy.types.Operator):
"""Loom Batch Render Dialog"""
bl_idname = "loom.batch_render_dialog"
bl_label = "Loom Batch"
bl_options = {'REGISTER'}
colorspace: bpy.props.EnumProperty(
name="Colorspace",
description="colorspace",
items=colorspace_callback)
codec: bpy.props.EnumProperty(
name="Codec",
description="Codec",
items=codec_callback)
fps: bpy.props.IntProperty(
name="Frame Rate",
description="Frame Rate",
default=25, min=1)
terminal: bpy.props.BoolProperty(
name="Terminal Instance",
description="Render in new Terminal Instance",
default=True)
shutdown: bpy.props.BoolProperty(
name="Shutdown",
description="Shutdown when done",
default=False)
def determine_type(self, val):
#val = ast.literal_eval(s)
if (isinstance(val, int)):
return ("chi")
elif (isinstance(val, float)):
return ("chf")
if val in ["true", "false"]:
return ("chb")
else:
return ("chs")
def pack_multiple_cmds(self, dct):
rna_lst = []
for key, args in dct.items():
for i in args:
rna_lst.append({"idc": key, "name": self.determine_type(i), "value": str(i)})
return rna_lst
def pack_arguments(self, lst):
return [{"idc": 0, "name": self.determine_type(i), "value": str(i)} for i in lst]
def write_permission(self, folder): # Hacky, but ok for now
# https://stackoverflow.com/q/2113427/3091066
try: # os.access(os.path.realpath(bpy.path.abspath(out_folder)), os.W_OK)
pf = os.path.join(folder, "permission.txt")
fh = open(pf, 'w')
fh.close()
os.remove(pf)
return True
except:
return False
def missing_frames(self, frames):
return sorted(set(range(frames[0], frames[-1] + 1)).difference(frames))
def verify_app(self, cmd):
try:
subprocess.call(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except OSError as e:
if e.errno == errno.ENOENT:
return False
return True
@classmethod
def poll(cls, context):
return True
def execute(self, context):
prefs = context.preferences.addons[__name__].preferences
lum = context.scene.loom
black_list = []
""" Error handling """
user_error = False
ffmpeg_error = False
if not bool(lum.batch_render_coll):
self.report({'ERROR'}, "No files to render.")
user_error = True
for item in lum.batch_render_coll:
if not item.frames and not any(char.isdigit() for char in item.frames):
self.report({'ERROR'}, "{} [wrong frame input]".format(item.name))
user_error = True
if not os.path.isfile(item.path):
self.report({'ERROR'}, "{} does not exist anymore".format(item.name))
user_error = True
""" encode errors """
if item.encode_flag:
""" Verify ffmpeg """
if not prefs.ffmpeg_path:
if self.verify_app(["ffmpeg", "-h"]):
prefs.ffmpeg_path = "ffmpeg"
else:
ffmpeg_error = True
elif prefs.ffmpeg_path and prefs.ffmpeg_path != "ffmpeg":
if not os.path.isabs(prefs.ffmpeg_path) or prefs.ffmpeg_path.startswith('//'):
ffmpeg_bin = os.path.realpath(bpy.path.abspath(prefs.ffmpeg_path))
if os.path.isfile(ffmpeg_bin):
prefs.ffmpeg_path = ffmpeg_bin
if not self.verify_app([prefs.ffmpeg_path, "-h"]):
ffmpeg_error = True
""" verify frames """
frames_user = filter_frames(frame_input=item.frames, filter_individual=item.input_filter)
if self.missing_frames(frames_user):
black_list.append(item.name)
info = "Encoding {} will be skipped [Missing Frames]".format(item.name)
self.report({'INFO'}, info)
out_folder, out_filename = os.path.split(item.path)
if not self.write_permission(os.path.realpath(bpy.path.abspath(out_folder))):
self.report({'ERROR'}, "Specified output folder does not exist (permission denied)")
user_error = True
if len(black_list) > 1:
self.report({'ERROR'}, "Can not encode: {} (missing frames)".format(", ".join(black_list)))
user_error = True
if user_error or ffmpeg_error:
if ffmpeg_error:
self.report({'ERROR'}, "Path to ffmpeg binary not set in Addon preferences")
bpy.ops.loom.batch_render_dialog('INVOKE_DEFAULT')
return {"CANCELLED"}
cli_arg_dict = {}
for c, item in enumerate(lum.batch_render_coll):
python_expr = ("import bpy;" +\
"bpy.ops.render.image_sequence(" +\
"frames='{fns}', isolate_numbers={iel}," +\
"render_silent={cli});" +\
"bpy.ops.wm.save_as_mainfile(filepath=bpy.data.filepath)").format(
fns=item.frames,
iel=item.input_filter,
cli=True)
cli_args = [bpy.app.binary_path, "-b", item.path, "--python-expr", python_expr]
cli_arg_dict[c] = cli_args
coll_len = len(cli_arg_dict)
for c, item in enumerate(lum.batch_render_coll):
if item.encode_flag and item.name not in black_list:
python_expr = ("import bpy;" +\
"seq_path=bpy.context.scene.render.frame_path(frame=1);" +\
#"seq_path=bpy.context.scene.render.filepath;" +\
"bpy.ops.loom.encode_sequence(" +\
"sequence=seq_path, terminal_instance=False, pause=False)")
cli_args = [bpy.app.binary_path, "-b", item.path, "--python-expr", python_expr]
cli_arg_dict[c+coll_len] = cli_args
""" Start headless batch encoding """
bpy.ops.loom.run_terminal(
#debug_arguments=True,
binary="",
terminal_instance=self.terminal,
argument_collection=self.pack_multiple_cmds(cli_arg_dict),
bash_name="loom-batch-temp",
force_bash=True,
shutdown=self.shutdown)
return {'FINISHED'}
def invoke(self, context, event):
prefs = context.preferences.addons[__name__].preferences
return context.window_manager.invoke_props_dialog(self,
width=(prefs.batch_dialog_width*context.preferences.system.pixel_size))
def check(self, context):
return True
def draw(self, context):
prefs = context.preferences.addons[__name__].preferences
scn = context.scene
lum = scn.loom
layout = self.layout
row = layout.row()
row.template_list(
listtype_name = "LOOM_UL_batch_list",
list_id = "",
dataptr = lum,
propname = "batch_render_coll",
active_dataptr = lum,
active_propname = "batch_render_idx",
#rows=prefs.batch_dialog_rows
)
col = row.column(align=True)
col.operator("loom.batch_select_blends", icon='ZOOM_IN', text="")
col.operator("loom.batch_dialog_action", icon='ZOOM_OUT', text="").action = 'REMOVE'
col.menu("LOOM_MT_display_settings", icon='DOWNARROW_HLT', text="")
col.separator()
col.separator()
col.operator("loom.batch_dialog_action", icon='TRIA_UP', text="").action = 'UP'
col.operator("loom.batch_dialog_action", icon='TRIA_DOWN', text="").action = 'DOWN'
row = layout.row(align=True)
row = row.column(align=True)
row.operator("loom.batch_scandir_blends", icon='ZOOM_SELECTED') #VIEWZOOM
col = row.row(align=True)
col.operator("loom.batch_remove_doubles", text="Remove Duplicates", icon="SEQ_SPLITVIEW")
col.operator("loom.batch_clear_list", text="Clear List", icon="PANEL_CLOSE")
if any(i.encode_flag for i in lum.batch_render_coll):
row = layout.row()
row.separator()
split_perc = 0.3