-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathVF_autosaveRender.py
2497 lines (2147 loc) · 108 KB
/
VF_autosaveRender.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
bl_info = {
"name": "VF Autosave Render + Output Variables",
"author": "John Einselen - Vectorform LLC, based on work by tstscr(florianfelix)",
"version": (2, 8, 6),
"blender": (3, 2, 0),
"location": "Scene Output Properties > Output Panel > Autosave Render",
"description": "Automatically saves rendered images with custom naming",
"doc_url": "https://github.com/jeinselenVF/VF-BlenderAutosaveRender",
"tracker_url": "https://github.com/jeinselenVF/VF-BlenderAutosaveRender/issues",
"category": "Render"}
# General features
import bpy
from bpy.app.handlers import persistent
import datetime
import time
import json
# File paths
import os
from pathlib import Path
# Variable data
import platform
from re import findall, search, sub, M as multiline
# FFmpeg system access
import subprocess
from shutil import which
# Email notifications
import smtplib
from email.mime.text import MIMEText
# Pushover notifications
import requests
# Format validation lists
IMAGE_FORMATS = (
'BMP',
'IRIS',
'PNG',
'JPEG',
'JPEG2000',
'TARGA',
'TARGA_RAW',
'CINEON',
'DPX',
'OPEN_EXR_MULTILAYER',
'OPEN_EXR',
'HDR',
'TIFF')
IMAGE_EXTENSIONS = (
'bmp',
'rgb',
'png',
'jpg',
'jp2',
'tga',
'cin',
'dpx',
'exr',
'hdr',
'tif')
FFMPEG_FORMATS = (
'BMP',
'PNG',
'JPEG',
'DPX',
'OPEN_EXR',
'TIFF')
# Available variables
# Includes both headers (string starting with "title,") and variables (string with brackets, commas segment multi-variable lines)
variableArray = ["title,Project,SCENE_DATA",
"{project}", "{scene}", "{viewlayer}", "{collection}", "{camera}", "{item}", "{material}", "{node}",
"title,Image,NODE_COMPOSITING",
"{display}", "{colorspace}", "{look}", "{exposure}", "{gamma}", "{curves}", "{compositing}",
"title,Render,SCENE",
"{engine}", "{device}", "{samples}", "{features}", "{duration}", "{rtime}", "{rH},{rM},{rS}",
"title,System,DESKTOP",
"{host}", "{processor}", "{platform}", "{system}", "{release}", "{python}", "{blender}",
"title,Identifier,COPY_ID",
"{date}", "{y},{m},{d}", "{time}", "{H},{M},{S}", "{serial}", "{frame}", "{batch}"]
###########################################################################
# Pre-render function
# •Set render status variables
# •Save start time for calculations
# •Replace output variables
@persistent
def autosave_render_start(scene):
# Save start time in seconds as a string to the addon settings
bpy.context.scene.autosave_render_settings.start_date = str(time.time())
# Set estimated render time active to false (must render at least one frame before estimating time remaining)
bpy.context.scene.autosave_render_settings.estimated_render_time_active = False
# Set video sequence tracking (separate from render active above)
bpy.context.scene.autosave_render_settings.autosave_video_sequence = False
bpy.context.scene.autosave_render_settings.autosave_video_sequence_processing = False
# Track usage of the output serial usage globally to ensure it can be accessed before/after rendering
# Set it to false ahead of processing to ensure no errors occur (usually only if there's a crash of some sort)
bpy.context.scene.autosave_render_settings.output_file_serial_used = False
# Filter output file path if enabled
if bpy.context.preferences.addons['VF_autosaveRender'].preferences.render_output_variables:
# Save original file path
bpy.context.scene.autosave_render_settings.output_file_path = filepath = scene.render.filepath
# Check if the serial variable is used
if '{serial}' in filepath:
filepath = filepath.replace("{serial}", format(bpy.context.scene.autosave_render_settings.output_file_serial, '04'))
bpy.context.scene.autosave_render_settings.output_file_serial_used = True
# Replace scene filepath output with the processed version
scene.render.filepath = replaceVariables(filepath)
# Filter compositing node file path if turned on in the plugin settings and compositing is enabled
if bpy.context.preferences.addons['VF_autosaveRender'].preferences.render_output_variables and bpy.context.scene.use_nodes:
# Iterate through Compositor nodes, adding all file output node path and sub-path variables to a dictionary
node_settings = {}
for node in bpy.context.scene.node_tree.nodes:
# Check if the node is a File Output node
if isinstance(node, bpy.types.CompositorNodeOutputFile):
# Save the base_path property and the file_slots dictionary entry
node_settings[node.name] = {
"base_path": node.base_path,
"file_slots": {}
}
# Replace dynamic variables
if '{serial}' in node.base_path:
bpy.context.scene.autosave_render_settings.output_file_serial_used = True
node.base_path = replaceVariables(node.base_path, serial=bpy.context.scene.autosave_render_settings.output_file_serial)
# Save and then process the sub-path property of each file slot
for i, slot in enumerate(node.file_slots):
node_settings[node.name]["file_slots"][i] = {
"path": slot.path
}
# Replace dynamic variables
if '{serial}' in slot.path:
bpy.context.scene.autosave_render_settings.output_file_serial_used = True
slot.path = replaceVariables(slot.path, serial=bpy.context.scene.autosave_render_settings.output_file_serial)
# Convert the dictionary to JSON format and save to the plugin preferences for safekeeping while rendering
bpy.context.scene.autosave_render_settings.output_file_nodes = json.dumps(node_settings)
###########################################################################
# During render function
# •Remaining render time estimation
@persistent
def autosave_render_estimate(scene):
# Save starting frame (before setting active to true, this should only happen once during a sequence)
if not bpy.context.scene.autosave_render_settings.estimated_render_time_active:
bpy.context.scene.autosave_render_settings.estimated_render_time_frame = bpy.context.scene.frame_current
# If video sequence is inactive and our current frame is not our starting frame, assume we're rendering a sequence
if not bpy.context.scene.autosave_render_settings.autosave_video_sequence and bpy.context.scene.autosave_render_settings.estimated_render_time_frame < bpy.context.scene.frame_current:
bpy.context.scene.autosave_render_settings.autosave_video_sequence = True
# If it's not the last frame, estimate time remaining
if bpy.context.scene.frame_current < bpy.context.scene.frame_end:
bpy.context.scene.autosave_render_settings.estimated_render_time_active = True
# Elapsed time (Current - Render Start)
render_time = time.time() - float(bpy.context.scene.autosave_render_settings.start_date)
# Divide by number of frames completed
render_time /= bpy.context.scene.frame_current - bpy.context.scene.autosave_render_settings.estimated_render_time_frame + 1.0
# Multiply by number of frames assumed unrendered (does not account for previously completed frames beyond the current frame)
render_time *= bpy.context.scene.frame_end - bpy.context.scene.frame_current
# Convert to readable and store
bpy.context.scene.autosave_render_settings.estimated_render_time_value = secondsToReadable(render_time)
# print('Estimated Time Remaining: ' + bpy.context.scene.autosave_render_settings.estimated_render_time_value)
else:
bpy.context.scene.autosave_render_settings.estimated_render_time_active = False
###########################################################################
# Post-render function
# •Compile output video using FFmpeg
# •Autosave final rendered image
# •Reset render status variables
# •Reset output paths with original keywords
# •Send render complete alerts
# •Save log file
@persistent
def autosave_render_end(scene):
# Set estimated render time active to false (render is complete or canceled, estimate display and FFmpeg check is no longer needed)
bpy.context.scene.autosave_render_settings.estimated_render_time_active = False
# Calculate elapsed render time
render_time = round(time.time() - float(bpy.context.scene.autosave_render_settings.start_date), 2)
# Update total render time
bpy.context.scene.autosave_render_settings.total_render_time = bpy.context.scene.autosave_render_settings.total_render_time + render_time
# Output video files if FFmpeg processing is enabled, the command appears to exist, and the image format output is supported
if bpy.context.preferences.addons['VF_autosaveRender'].preferences.ffmpeg_processing and bpy.context.preferences.addons['VF_autosaveRender'].preferences.ffmpeg_exists and bpy.context.scene.render.image_settings.file_format in FFMPEG_FORMATS and bpy.context.scene.autosave_render_settings.autosave_video_sequence:
# Create initial command base
ffmpeg_location = bpy.context.preferences.addons['VF_autosaveRender'].preferences.ffmpeg_location
# Create absolute path and strip trailing spaces
absolute_path = bpy.path.abspath(scene.render.filepath).rstrip()
# Replace frame number placeholder with asterisk or add trailing asterisk
if "#" in absolute_path:
absolute_path = sub(r'#+(?!.*#)', "*", absolute_path)
else:
absolute_path += "*"
# Create input image glob pattern
glob_pattern = '-pattern_type glob -i "' + absolute_path + scene.render.file_extension + '"'
# Create floating point FPS value
fps_float = '-r ' + str(scene.render.fps / scene.render.fps_base)
# ProRes output
if bpy.context.scene.autosave_render_settings.autosave_video_prores:
# Set FFmpeg processing to true so the Image View window can display status
bpy.context.scene.autosave_render_settings.autosave_video_sequence_processing = True
if len(bpy.context.scene.autosave_render_settings.autosave_video_prores_location) > 1:
# Replace with custom string
output_path = bpy.context.scene.autosave_render_settings.autosave_video_prores_location
# Replace dynamic variables
if '{serial}' in output_path:
bpy.context.scene.autosave_render_settings.output_file_serial_used = True
output_path = replaceVariables(output_path, rendertime=render_time, serial=bpy.context.scene.autosave_render_settings.output_file_serial)
# Convert relative path into absolute path for Python and CLI compatibility
output_path = bpy.path.abspath(output_path)
# Create the project subfolder if it doesn't already exist
output_dir = sub(r'[^/]*$', "", output_path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Wrap with FFmpeg settings
output_path = '-y "' + output_path + '"'
# FFmpeg location
ffmpeg_command = ffmpeg_location
# Frame rate
ffmpeg_command += ' ' + fps_float
# Image sequence pattern
ffmpeg_command += ' ' + glob_pattern
# ProRes format
ffmpeg_command += ' -c:v prores -pix_fmt yuv422p10le'
# ProRes profile (Proxy, LT, 422 HQ)
ffmpeg_command += ' -profile:v ' + str(bpy.context.scene.autosave_render_settings.autosave_video_prores_quality)
# Final output settings
ffmpeg_command += ' -vendor apl0 -an -sn'
# Output file path
ffmpeg_command += ' ' + output_path + '.mov'
# Remove any accidental double spaces
ffmpeg_command = sub(r'\s{2,}', " ", ffmpeg_command)
# Print command to the terminal
print('FFmpeg ProRes command:')
print(ffmpeg_command)
print('')
# Run FFmpeg command
try:
subprocess.call(ffmpeg_command, shell=True)
print('')
except Exception as exc:
print(str(exc) + " | Error in VF Autosave Render: failed to process FFmpeg ProRes command")
# MP4 output
if bpy.context.scene.autosave_render_settings.autosave_video_mp4:
# Set FFmpeg processing to true so the Image View window can display status
bpy.context.scene.autosave_render_settings.autosave_video_sequence_processing = True
if len(bpy.context.scene.autosave_render_settings.autosave_video_mp4_location) > 1:
# Replace with custom string
output_path = bpy.context.scene.autosave_render_settings.autosave_video_mp4_location
# Replace dynamic variables
if '{serial}' in output_path:
bpy.context.scene.autosave_render_settings.output_file_serial_used = True
output_path = replaceVariables(output_path, rendertime=render_time, serial=bpy.context.scene.autosave_render_settings.output_file_serial)
# Convert relative path into absolute path for Python and CLI compatibility
output_path = bpy.path.abspath(output_path)
# Create the project subfolder if it doesn't already exist
output_dir = sub(r'[^/]*$', "", output_path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Wrap with FFmpeg settings
output_path = '-y "' + output_path + '"'
# FFmpeg location
ffmpeg_command = ffmpeg_location
# Frame rate
ffmpeg_command += ' ' + fps_float
# Image sequence pattern
ffmpeg_command += ' ' + glob_pattern
# MP4 format
ffmpeg_command += ' -c:v libx264 -preset slow'
# MP4 quality (0-51 from highest to lowest quality)
ffmpeg_command += ' -crf ' + str(bpy.context.scene.autosave_render_settings.autosave_video_mp4_quality)
# Final output settings
ffmpeg_command += ' -pix_fmt yuv420p -movflags rtphint'
# Output file path
ffmpeg_command += ' ' + output_path + '.mp4'
# Remove any accidental double or more spaces
ffmpeg_command = sub(r'\s{2,}', " ", ffmpeg_command)
# Print command to the terminal
print('FFmpeg MP4 command:')
print(ffmpeg_command)
print('')
# Run FFmpeg command
try:
subprocess.call(ffmpeg_command, shell=True)
print('')
except Exception as exc:
print(str(exc) + " | Error in VF Autosave Render: failed to process FFmpeg MP4 command")
# Custom output
if bpy.context.scene.autosave_render_settings.autosave_video_custom:
# Set FFmpeg processing to true so the Image View window can display status
bpy.context.scene.autosave_render_settings.autosave_video_sequence_processing = True
if len(bpy.context.scene.autosave_render_settings.autosave_video_custom_location) > 1:
# Replace with custom string
output_path = bpy.context.scene.autosave_render_settings.autosave_video_custom_location
# Replace dynamic variables
if '{serial}' in output_path:
bpy.context.scene.autosave_render_settings.output_file_serial_used = True
output_path = replaceVariables(output_path, rendertime=render_time, serial=bpy.context.scene.autosave_render_settings.output_file_serial)
# Convert relative path into absolute path for Python and CLI compatibility
output_path = bpy.path.abspath(output_path)
# Create the project subfolder if it doesn't already exist
output_dir = sub(r'[^/]*$', "", output_path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Wrap with FFmpeg settings
output_path = '-y "' + output_path + '"'
# FFmpeg location
ffmpeg_command = ffmpeg_location + ' ' + bpy.context.scene.autosave_render_settings.autosave_video_custom_command
# Replace variables
ffmpeg_command = ffmpeg_command.replace("{fps}", fps_float)
ffmpeg_command = ffmpeg_command.replace("{input}", glob_pattern)
ffmpeg_command = ffmpeg_command.replace("{output}", output_path)
# Remove any accidental double spaces
ffmpeg_command = sub(r'\s{2,}', " ", ffmpeg_command)
# Print command to the terminal
print('FFmpeg custom command:')
print(ffmpeg_command)
print('')
# Run FFmpeg command
try:
subprocess.call(ffmpeg_command, shell=True)
print('')
except Exception as exc:
print(str(exc) + " | Error in VF Autosave Render: failed to process FFmpeg custom command")
# Increment the output serial number if it was used any output path
if bpy.context.scene.autosave_render_settings.output_file_serial_used:
bpy.context.scene.autosave_render_settings.output_file_serial += 1
# Set video sequence status to false
bpy.context.scene.autosave_render_settings.autosave_video_sequence = False
bpy.context.scene.autosave_render_settings.autosave_video_sequence_processing = False
# Restore unprocessed file path if processing is enabled
if bpy.context.preferences.addons['VF_autosaveRender'].preferences.render_output_variables and bpy.context.scene.autosave_render_settings.output_file_path:
scene.render.filepath = bpy.context.scene.autosave_render_settings.output_file_path
# Restore unprocessed node output file path if processing is enabled, compositing is enabled, and a file output node exists with the default node name
if bpy.context.preferences.addons['VF_autosaveRender'].preferences.render_output_variables and bpy.context.scene.use_nodes and len(bpy.context.scene.autosave_render_settings.output_file_nodes) > 2:
# Get the JSON data from the preferences string where it was stashed
json_data = bpy.context.scene.autosave_render_settings.output_file_nodes
# If the JSON data is not empty, deserialize it and restore the node settings
if json_data:
node_settings = json.loads(json_data)
for node_name, node_data in node_settings.items():
node = bpy.context.scene.node_tree.nodes.get(node_name)
if isinstance(node, bpy.types.CompositorNodeOutputFile):
node.base_path = node_data.get("base_path", node.base_path)
file_slots_data = node_data.get("file_slots", {})
for i, slot_data in file_slots_data.items():
slot = node.file_slots[int(i)]
if slot:
slot.path = slot_data.get("path", slot.path)
# Get project name (used by both autosave render and the external log file)
projectname = os.path.splitext(os.path.basename(bpy.data.filepath))[0]
# Autosave render
if (bpy.context.preferences.addons['VF_autosaveRender'].preferences.enable_autosave_render) and bpy.data.filepath:
# Save original file format settings
original_format = scene.render.image_settings.file_format
original_colormode = scene.render.image_settings.color_mode
original_colordepth = scene.render.image_settings.color_depth
# Set up render output formatting with override
if bpy.context.preferences.addons['VF_autosaveRender'].preferences.file_format_override:
file_format = bpy.context.preferences.addons['VF_autosaveRender'].preferences.file_format_global
else:
file_format = bpy.context.scene.autosave_render_settings.file_format
if file_format == 'SCENE':
if original_format not in IMAGE_FORMATS:
print('VF Autosave Render: {} is not an image format. Image not saved.'.format(original_format))
return {'CANCELLED'}
elif file_format == 'JPEG':
scene.render.image_settings.file_format = 'JPEG'
elif file_format == 'PNG':
scene.render.image_settings.file_format = 'PNG'
elif file_format == 'OPEN_EXR':
scene.render.image_settings.file_format = 'OPEN_EXR'
extension = scene.render.file_extension
# Get location variable with override and project path replacement
if bpy.context.preferences.addons['VF_autosaveRender'].preferences.file_location_override:
filepath = bpy.context.preferences.addons['VF_autosaveRender'].preferences.file_location_global
else:
filepath = bpy.context.scene.autosave_render_settings.file_location
# If the file path contains one or fewer characters, replace it with the project path
if len(filepath) <= 1:
filepath = os.path.join(os.path.dirname(bpy.data.filepath), projectname)
# Convert relative path into absolute path for Python compatibility
filepath = bpy.path.abspath(filepath)
# Process elements that aren't available in the global variable replacement
# The autosave serial number and override are separate from the project serial number
serialUsedGlobal = False
serialUsed = False
serialNumber = -1
if '{serial}' in filepath:
if bpy.context.preferences.addons['VF_autosaveRender'].preferences.file_location_override:
serialNumber = bpy.context.preferences.addons['VF_autosaveRender'].preferences.file_serial_global
serialUsedGlobal = True
else:
serialNumber = bpy.context.scene.autosave_render_settings.file_serial
serialUsed = True
# Replace global variables in the output path string
filepath = replaceVariables(filepath, rendertime=render_time, serial=serialNumber)
# Create the project subfolder if it doesn't already exist (otherwise subsequent operations will fail)
if not os.path.exists(filepath):
os.makedirs(filepath)
# Get file name type with override
if bpy.context.preferences.addons['VF_autosaveRender'].preferences.file_name_override:
file_name_type = bpy.context.preferences.addons['VF_autosaveRender'].preferences.file_name_type_global
else:
file_name_type = bpy.context.scene.autosave_render_settings.file_name_type
# Create the output file name string
if file_name_type == 'SERIAL':
# Generate dynamic serial number
# Finds all of the image files that start with projectname in the selected directory
files = [f for f in os.listdir(filepath) if f.startswith(projectname) and f.lower().endswith(IMAGE_EXTENSIONS)]
# Searches the file collection and returns the next highest number as a 4 digit string
def save_number_from_files(files):
highest = -1
if files:
for f in files:
# find filenames that end with four or more digits
suffix = findall(r'\d{4,}$', os.path.splitext(f)[0].split(projectname)[-1], multiline)
if suffix:
if int(suffix[-1]) > highest:
highest = int(suffix[-1])
return format(highest+1, '04')
# Create string with serial number
filename = '{project}-' + save_number_from_files(files)
elif file_name_type == 'DATE':
filename = '{project} {date} {time}'
elif file_name_type == 'RENDER':
filename = '{project} {engine} {duration}'
else:
# Load custom file name with override
if bpy.context.preferences.addons['VF_autosaveRender'].preferences.file_name_override:
filename = bpy.context.preferences.addons['VF_autosaveRender'].preferences.file_name_custom_global
else:
filename = bpy.context.scene.autosave_render_settings.file_name_custom
if '{serial}' in filename:
if bpy.context.preferences.addons['VF_autosaveRender'].preferences.file_location_override:
serialNumber = bpy.context.preferences.addons['VF_autosaveRender'].preferences.file_serial_global
serialUsedGlobal = True
else:
serialNumber = bpy.context.scene.autosave_render_settings.file_serial
serialUsed = True
# Replace global variables in the output name string
filename = replaceVariables(filename, rendertime=render_time, serial=serialNumber)
# Finish local and global serial number updates
if serialUsedGlobal:
bpy.context.preferences.addons['VF_autosaveRender'].preferences.file_serial_global += 1
if serialUsed:
bpy.context.scene.autosave_render_settings.file_serial += 1
# Combine file path and file name using system separator, add extension
filepath = os.path.join(filepath, filename) + extension
# Save image file
image = bpy.data.images['Render Result']
if not image:
print('VF Autosave Render: Render Result not found. Image not saved.')
return {'CANCELLED'}
# Please note that multilayer EXR files are currently unsupported in the Python API - https://developer.blender.org/T71087
image.save_render(filepath, scene=None) # Consider using bpy.context.scene if different compression settings are desired per-scene
# Restore original user settings for render output
scene.render.image_settings.file_format = original_format
scene.render.image_settings.color_mode = original_colormode
scene.render.image_settings.color_depth = original_colordepth
# Render complete notifications, only if the time spent rendering exceeds the minimum time defined in the preferences
if render_time > float(bpy.context.preferences.addons['VF_autosaveRender'].preferences.minimum_time):
if bpy.context.preferences.addons['VF_autosaveRender'].preferences.email_enable:
# Subject line variable replacement
subject = replaceVariables(
bpy.context.preferences.addons['VF_autosaveRender'].preferences.email_subject,
rendertime=render_time,
serial=bpy.context.scene.autosave_render_settings.output_file_serial
)
# Body text variable replacement
message = replaceVariables(
bpy.context.preferences.addons['VF_autosaveRender'].preferences.email_message,
rendertime=render_time,
serial=bpy.context.scene.autosave_render_settings.output_file_serial
)
send_email(subject, message)
if bpy.context.preferences.addons['VF_autosaveRender'].preferences.pushover_enable and len(bpy.context.preferences.addons['VF_autosaveRender'].preferences.pushover_key) == 30 and len(bpy.context.preferences.addons['VF_autosaveRender'].preferences.pushover_app) == 30:
subject = replaceVariables(
bpy.context.preferences.addons['VF_autosaveRender'].preferences.pushover_subject,
rendertime=render_time,
serial=bpy.context.scene.autosave_render_settings.output_file_serial
)
message = replaceVariables(
bpy.context.preferences.addons['VF_autosaveRender'].preferences.pushover_message,
rendertime=render_time,
serial=bpy.context.scene.autosave_render_settings.output_file_serial
)
send_pushover(subject, message)
# MacOS Siri text-to-speech announcement
# Re-check Say location just to be extra-sure (otherwise this is only checked when the add-on is first enable)
bpy.context.preferences.addons[__name__].preferences.check_macos_say_location()
if bpy.context.preferences.addons['VF_autosaveRender'].preferences.macos_say_exists and bpy.context.preferences.addons['VF_autosaveRender'].preferences.macos_say_enable:
message = replaceVariables(
bpy.context.preferences.addons['VF_autosaveRender'].preferences.macos_say_message,
rendertime=render_time,
serial=bpy.context.scene.autosave_render_settings.output_file_serial
)
os.system('say "' + message + '"')
# Save external log file
if bpy.context.preferences.addons['VF_autosaveRender'].preferences.external_render_time:
# Log file settings
logname = bpy.context.preferences.addons['VF_autosaveRender'].preferences.external_log_name
logname = logname.replace("{project}", projectname)
logpath = os.path.join(os.path.dirname(bpy.data.filepath), logname) # Limited to locations local to the project file
logtitle = 'Total Render Time: '
logtime = 0.00
# Get previous time spent rendering, if log file exists, and convert formatted string into seconds
if os.path.exists(logpath):
with open(logpath) as filein:
logtime = filein.read().replace(logtitle, '')
logtime = readableToSeconds(logtime)
# Create log file directory location if it doesn't exist
elif not os.path.exists(os.path.dirname(logpath)): # Safety net just in case a folder was included in the file name entry
os.makedirs(os.path.dirname(logpath))
# Add the latest render time
logtime += float(render_time)
# Convert seconds into formatted string
logtime = secondsToReadable(logtime)
# Write log file
with open(logpath, 'w') as fileout:
fileout.write(logtitle + logtime)
return {'FINISHED'}
###########################################################################
# Variable replacement function
# •Prepopulate data that requires more logic
# •Replace all variables
# •Replaces {duration}{rtime}{rH}{rM}{rS} only if valid 0.0+ float is provided
# •Replaces {serial} only if valid 0+ integer is provided
def replaceVariables(string, rendertime=-1.0, serial=-1):
# Get scene from context
scene = bpy.context.scene
# Get render engine feature sets
if bpy.context.engine == 'BLENDER_WORKBENCH':
renderEngine = 'Workbench'
renderDevice = 'GPU'
renderSamples = scene.display.render_aa
renderFeatures = scene.display.shading.light.title().replace("Matcap", "MatCap") + '+' + scene.display.shading.color_type.title()
elif bpy.context.engine == 'BLENDER_EEVEE':
renderEngine = 'Eevee'
renderDevice = 'GPU'
renderSamples = str(scene.eevee.taa_render_samples) + '+' + str(scene.eevee.sss_samples) + '+' + str(scene.eevee.volumetric_samples)
renderFeaturesArray = []
if scene.eevee.use_gtao:
renderFeaturesArray.append('AO')
if scene.eevee.use_bloom:
renderFeaturesArray.append('Bloom')
if scene.eevee.use_ssr:
renderFeaturesArray.append('SSR')
if scene.eevee.use_motion_blur:
renderFeaturesArray.append('MB' + str(scene.eevee.motion_blur_steps))
renderFeatures = 'None' if len(renderFeaturesArray) == 0 else '+'.join(renderFeaturesArray)
elif bpy.context.engine == 'CYCLES':
renderEngine = 'Cycles'
renderDevice = scene.cycles.device
# Add compute device type if GPU is enabled
# if renderDevice == "GPU":
# renderDevice += '_' + bpy.context.preferences.addons["cycles"].preferences.compute_device_type
renderSamples = str(round(scene.cycles.adaptive_threshold, 4)) + '+' + str(scene.cycles.samples) + '+' + str(scene.cycles.adaptive_min_samples)
renderFeatures = str(scene.cycles.max_bounces) + '+' + str(scene.cycles.diffuse_bounces) + '+' + str(scene.cycles.glossy_bounces) + '+' + str(scene.cycles.transmission_bounces) + '+' + str(scene.cycles.volume_bounces) + '+' + str(scene.cycles.transparent_max_bounces)
elif bpy.context.engine == 'RPR':
renderEngine = 'ProRender'
# Compile array of enabled devices
renderDevicesArray = []
if bpy.context.preferences.addons["rprblender"].preferences.settings.final_devices.cpu_state:
renderDevicesArray.append('CPU')
for gpu in bpy.context.preferences.addons["rprblender"].preferences.settings.final_devices.available_gpu_states:
if gpu:
renderDevicesArray.append('GPU')
renderDevice = 'None' if len(renderDevicesArray) == 0 else '+'.join(renderDevicesArray)
renderSamples = str(scene.rpr.limits.min_samples) + '+' + str(scene.rpr.limits.max_samples) + '+' + str(round(scene.rpr.limits.noise_threshold, 4))
renderFeatures = str(scene.rpr.max_ray_depth) + '+' + str(scene.rpr.diffuse_depth) + '+' + str(scene.rpr.glossy_depth) + '+' + str(scene.rpr.refraction_depth) + '+' + str(scene.rpr.glossy_refraction_depth) + '+' + str(scene.rpr.shadow_depth)
elif bpy.context.engine == 'LUXCORE':
renderEngine = 'LuxCore'
renderDevice = 'CPU' if scene.luxcore.config.device == 'CPU' else 'GPU'
# Samples returns the halt conditions for time, samples, and/or noise threshold
renderSamples = ''
if scene.luxcore.halt.use_time:
renderSamples += str(scene.luxcore.halt.time) + 's'
if scene.luxcore.halt.use_samples:
if len(renderSamples) > 0:
renderSamples += '+'
renderSamples += str(scene.luxcore.halt.samples)
if scene.luxcore.halt.use_noise_thresh:
if len(renderSamples) > 0:
renderSamples += '+'
renderSamples += str(scene.luxcore.halt.noise_thresh) + '+' + str(scene.luxcore.halt.noise_thresh_warmup) + '+' + str(scene.luxcore.halt.noise_thresh_step)
# Features include the number of paths or bounces (depending on engine selected) and denoising if enabled
if scene.luxcore.config.engine == 'PATH':
renderEngine += '-Path'
renderFeatures = str(scene.luxcore.config.path.depth_total) + '+' + str(scene.luxcore.config.path.depth_diffuse) + '+' + str(scene.luxcore.config.path.depth_glossy) + '+' + str(scene.luxcore.config.path.depth_specular)
else:
renderEngine += '-Bidir'
renderFeatures = str(scene.luxcore.config.bidir_path_maxdepth) + '+' + str(scene.luxcore.config.bidir_light_maxdepth)
if scene.luxcore.denoiser.enabled:
renderFeatures += '+' + str(scene.luxcore.denoiser.type)
else:
renderEngine = bpy.context.engine
renderDevice = 'unknown'
renderSamples = 'unknown'
renderFeatures = 'unknown'
# Get conditional project variables Item > Material > Node
projectItem = projectMaterial = projectNode = 'None'
if bpy.context.view_layer.objects.active:
# Set active object name
projectItem = bpy.context.view_layer.objects.active.name
if bpy.context.view_layer.objects.active.active_material:
# Set active material slot name
projectMaterial = bpy.context.view_layer.objects.active.active_material.name
if bpy.context.view_layer.objects.active.active_material.use_nodes and bpy.context.view_layer.objects.active.active_material.node_tree.nodes.active:
if bpy.context.view_layer.objects.active.active_material.node_tree.nodes.active.type == 'TEX_IMAGE' and bpy.context.view_layer.objects.active.active_material.node_tree.nodes.active.image:
# Set active texture node image name
projectNode = bpy.context.view_layer.objects.active.active_material.node_tree.nodes.active.image.name
else:
# Set active node name
projectNode = bpy.context.view_layer.objects.active.active_material.node_tree.nodes.active.name
# Set node name to the Batch Render Target if active and available
if scene.autosave_render_settings.batch_active and scene.autosave_render_settings.batch_type == 'imgs' and bpy.data.materials.get(scene.autosave_render_settings.batch_images_material) and bpy.data.materials[scene.autosave_render_settings.batch_images_material].node_tree.nodes.get(scene.autosave_render_settings.batch_images_node):
projectNode = bpy.data.materials[scene.autosave_render_settings.batch_images_material].node_tree.nodes.get(scene.autosave_render_settings.batch_images_node).image.name
# Remove file extension from image node names (this could be unhelpful when comparing renders with .psd versus .jpg texture sources)
projectNode = sub(r'\.\w{3,4}$', '', projectNode)
# Using "replace" instead of "format" because format fails ungracefully when an exact match isn't found
# Project variables
string = string.replace("{project}", os.path.splitext(os.path.basename(bpy.data.filepath))[0])
string = string.replace("{scene}", scene.name)
string = string.replace("{viewlayer}", bpy.context.view_layer.name)
string = string.replace("{collection}", scene.autosave_render_settings.batch_collection_name if len(scene.autosave_render_settings.batch_collection_name) > 0 else bpy.context.collection.name)
string = string.replace("{camera}", scene.camera.name)
string = string.replace("{item}", projectItem)
string = string.replace("{material}", projectMaterial)
string = string.replace("{node}", projectNode)
# Image variables
sceneOverride = scene.render.image_settings if bpy.context.scene.render.image_settings.color_management == "OVERRIDE" else scene
string = string.replace("{display}", sceneOverride.display_settings.display_device.replace(" ", "").replace(".", ""))
string = string.replace("{viewtransform}", "{colorspace}") # Alternative variable (backwards compatibility may be removed at a later date)
string = string.replace("{colorspace}", "{space}") # Alternative variable (backwards compatibility may be removed at a later date)
string = string.replace("{space}", sceneOverride.view_settings.view_transform.replace(" ", ""))
string = string.replace("{look}", sceneOverride.view_settings.look.replace(" ", "").replace("AgX-", "").replace("FalseColor-", ""))
string = string.replace("{exposure}", str(sceneOverride.view_settings.exposure))
string = string.replace("{gamma}", str(sceneOverride.view_settings.gamma))
string = string.replace("{curves}", "Curves" if sceneOverride.view_settings.use_curve_mapping else "None")
string = string.replace("{compositing}", "Compositing" if scene.use_nodes else "None")
# Rendering variables
string = string.replace("{renderengine}", "{engine}") # Alternative variable (backwards compatibility may be removed at a later date)
string = string.replace("{engine}", renderEngine)
string = string.replace("{device}", renderDevice)
string = string.replace("{samples}", renderSamples)
string = string.replace("{features}", renderFeatures)
if rendertime >= 0.0: # Only enabled if a value is supplied
string = string.replace("{rendertime}", "{duration}") # Alternative variable (backwards compatibility may be removed at a later date)
string = string.replace("{duration}", str(rendertime) + 's')
rH, rM, rS = secondsToStrings(rendertime)
string = string.replace("{rtime}", rH + '-' + rM + '-' + rS)
string = string.replace("{rH}", rH)
string = string.replace("{rM}", rM)
string = string.replace("{rS}", rS)
# System variables
string = string.replace("{host}", platform.node().split('.')[0])
string = string.replace("{processor}", platform.processor()) # Alternate: platform.machine() provides the same information in many cases
string = string.replace("{platform}", platform.platform())
string = string.replace("{system}", platform.system().replace("Darwin", "macOS")) # Alternate: {os}
string = string.replace("{release}", platform.mac_ver()[0] if platform.system() == "Darwin" else platform.release()) # Alternate: {system}
string = string.replace("{python}", platform.python_version())
string = string.replace("{version}", "{blender}") # Alternative variable (backwards compatibility may be removed at a later date)
string = string.replace("{blender}", bpy.app.version_string + '-' + bpy.app.version_cycle)
# Identifier variables
string = string.replace("{date}", datetime.datetime.now().strftime('%Y-%m-%d'))
string = string.replace("{year}", "{y}") # Alternative variable
string = string.replace("{y}", datetime.datetime.now().strftime('%Y'))
string = string.replace("{month}", "{m}") # Alternative variable
string = string.replace("{m}", datetime.datetime.now().strftime('%m'))
string = string.replace("{day}", "{d}") # Alternative variable
string = string.replace("{d}", datetime.datetime.now().strftime('%d'))
string = string.replace("{time}", datetime.datetime.now().strftime('%H-%M-%S'))
string = string.replace("{hour}", "{H}") # Alternative variable
string = string.replace("{H}", datetime.datetime.now().strftime('%H'))
string = string.replace("{minute}", "{M}") # Alternative variable
string = string.replace("{M}", datetime.datetime.now().strftime('%M'))
string = string.replace("{second}", "{S}") # Alternative variable
string = string.replace("{S}", datetime.datetime.now().strftime('%S'))
if serial >= 0: # Only enabled if a value is supplied
string = string.replace("{serial}", format(serial, '04'))
string = string.replace("{frame}", format(scene.frame_current, '04'))
# Consider adding hash-mark support for inserting frames: sub(r'#+(?!.*#)', "", absolute_path)
# Batch variables
string = string.replace("{index}", "{batch}") # Alternative variable (backwards compatibility may be removed at a later date)
string = string.replace("{batch}", format(scene.autosave_render_settings.batch_index, '04'))
return string
###########################################################################
# Time conversion functions (because datetime doesn't like zero-numbered days or hours over 24)
# •Convert float seconds into string as [hour, minute, second] array (hours expand indefinitely, will not roll over into days)
# •Convert float seconds into string in HH:MM:SS.## format (hours expand indefinitely, will not roll over into days)
# •Convert string in HH:MM:SS.## format into float seconds
def secondsToStrings(sec):
seconds, decimals = divmod(float(sec), 1)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
return [
"%d" % (hours),
"%02d" % (minutes),
"%02d.%02d" % (seconds, round(decimals*100))
]
def secondsToReadable(seconds):
h, m, s = secondsToStrings(seconds)
return h + ":" + m + ":" + s
def readableToSeconds(readable):
hours, minutes, seconds = readable.split(':')
return int(hours)*3600 + int(minutes)*60 + float(seconds)
###########################################################################
# Copy string to clipboard
class AutosaveRenderCopyToClipboard(bpy.types.Operator):
"""Copy variable to the clipboard"""
bl_label = "Copy to clipboard"
bl_idname = "vf.autosave_render_copy_to_clipboard"
bl_options = {'REGISTER', 'INTERNAL'}
string: bpy.props.StringProperty()
def invoke(self, context, event):
context.window_manager.clipboard = self.string
# Close the popup panel by temporarily moving the mouse
x, y = event.mouse_x, event.mouse_y
context.window.cursor_warp(10, 10)
move_back = lambda: context.window.cursor_warp(x, y)
bpy.app.timers.register(move_back, first_interval=0.001)
return {'FINISHED'}
###########################################################################
# Notification system functions
# •Send email notification
# •Send Pushover notification
def send_email(subject, message):
try:
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = bpy.context.preferences.addons['VF_autosaveRender'].preferences.email_from
msg['To'] = bpy.context.preferences.addons['VF_autosaveRender'].preferences.email_to
with smtplib.SMTP_SSL(bpy.context.preferences.addons['VF_autosaveRender'].preferences.email_server, bpy.context.preferences.addons['VF_autosaveRender'].preferences.email_port) as smtp_server:
smtp_server.login(bpy.context.preferences.addons['VF_autosaveRender'].preferences.email_from, bpy.context.preferences.addons['VF_autosaveRender'].preferences.email_password)
smtp_server.sendmail(bpy.context.preferences.addons['VF_autosaveRender'].preferences.email_from, bpy.context.preferences.addons['VF_autosaveRender'].preferences.email_to.split(', '), msg.as_string())
except Exception as exc:
print(str(exc) + " | Error in VF Autosave Render: failed to send email notification")
def send_pushover(subject, message):
try:
r = requests.post('https://api.pushover.net/1/messages.json', data = {
"token": bpy.context.preferences.addons['VF_autosaveRender'].preferences.pushover_app,
"user": bpy.context.preferences.addons['VF_autosaveRender'].preferences.pushover_key,
"title": subject,
"message": message
})
if r.status_code == 200:
print(r.text)
if r.status_code == 500:
print('Error in VF Autosave Render: Pushover notification service unavailable')
print(r.text)
else:
print('Error in VF Autosave Render: Pushover URL request failed')
print(r.text)
except Exception as exc:
print(str(exc) + " | Error in VF Autosave Render: failed to send Pushover notification")
###########################################################################
# Global user preferences and UI rendering class
class AutosaveRenderPreferences(bpy.types.AddonPreferences):
bl_idname = __name__
# Global Variables
render_output_variables: bpy.props.BoolProperty(
name='Render Variables',
description='Implements dynamic keywords in the Output directory and Compositing tab "File Output" nodes',
default=True)
# Autosave Images
enable_autosave_render: bpy.props.BoolProperty(
name="Autosave Images",
description="Automatically saves numbered or dated images in a directory alongside the project file or in a custom location",
default=True)
show_autosave_render_overrides: bpy.props.BoolProperty(
name="Global Overrides",
description="Show available global overrides, replacing local project settings",
default=False)
# Override individual project autosave location and file name settings
file_location_override: bpy.props.BoolProperty(
name="Override File Location",
description='Global override for the per-project directory setting',
default=False)
file_location_global: bpy.props.StringProperty(
name="Global File Location",
description="Leave a single forward slash to auto generate folders alongside project files",
default="/",
maxlen=4096,
subtype="DIR_PATH")
file_name_override: bpy.props.BoolProperty(
name="Override File Name",
description='Global override for the per-project autosave file name setting',
default=False)
file_name_type_global: bpy.props.EnumProperty(
name='Global File Name',
description='Autosaves files with the project name and serial number, project name and date, or custom naming pattern',
items=[
('SERIAL', 'Project Name + Serial Number', 'Save files with a sequential serial number'),
('DATE', 'Project Name + Date & Time', 'Save files with the local date and time'),
('RENDER', 'Project Name + Render Engine + Render Time', 'Save files with the render engine and render time'),
('CUSTOM', 'Custom String', 'Save files with a custom string format'),
],
default='SERIAL')
file_name_custom_global: bpy.props.StringProperty(
name="Global Custom String",
description="Format a custom string using the variables listed below",
default="{project}-{serial}",
maxlen=4096)
file_serial_global: bpy.props.IntProperty(
name="Global Serial Number",
description="Current serial number, automatically increments with every render (must be manually updated when installing a plugin update)")
file_format_override: bpy.props.BoolProperty(
name="Override File Format",
description='Global override for the per-project autosave file format setting',
default=False)
file_format_global: bpy.props.EnumProperty(
name='Global File Format',
description='Image format used for the automatically saved render files',
items=[
('SCENE', 'Project Setting', 'Same format as set in output panel'),
('PNG', 'PNG', 'Save as png'),
('JPEG', 'JPEG', 'Save as jpeg'),
('OPEN_EXR', 'OpenEXR', 'Save as exr'),
],
default='PNG')
# Autosave Videos - FFMPEG output processing
ffmpeg_processing: bpy.props.BoolProperty(
name='Autosave Videos',
description='Enables FFmpeg image sequence compilation options in the Output panel',
default=True)
ffmpeg_location: bpy.props.StringProperty(
name="FFmpeg location",
description="System location where the the FFmpeg command line interface is installed",
default="/opt/local/bin/ffmpeg",
maxlen=4096,
update=lambda self, context: self.check_ffmpeg_location())
ffmpeg_location_previous: bpy.props.StringProperty(default="")
ffmpeg_exists: bpy.props.BoolProperty(
name="FFmpeg exists",
description='Stores the existence of FFmpeg at the defined system location',
default=False)
# Validate the ffmpeg location string on value change and plugin registration
def check_ffmpeg_location(self):
# Ensure it points at ffmpeg
if not self.ffmpeg_location.endswith('ffmpeg'):
self.ffmpeg_location = self.ffmpeg_location + 'ffmpeg'
# Test if it's a valid path and replace with valid path if such exists
if self.ffmpeg_location != self.ffmpeg_location_previous:
if which(self.ffmpeg_location) is None:
if which("ffmpeg") is None:
self.ffmpeg_exists = False
else:
self.ffmpeg_location = which("ffmpeg")
self.ffmpeg_exists = True
else:
self.ffmpeg_exists = True
self.ffmpeg_location_previous = self.ffmpeg_location
# Render Time Tracking
show_estimated_render_time: bpy.props.BoolProperty(
name="Show Estimated Render Time",
description='Adds estimated remaining render time display to the image editor menu bar while rendering',
default=True)
show_total_render_time: bpy.props.BoolProperty(
name="Show Project Render Time",
description='Displays the total time spent rendering a project in the output panel',
default=True)
external_render_time: bpy.props.BoolProperty(
name="Save External Render Time Log",
description='Saves the total time spent rendering to an external log file',
default=False)
external_log_name: bpy.props.StringProperty(
name="File Name",
description="Log file name; use {project} for per-project tracking, remove it for per-directory tracking",
default="{project}-TotalRenderTime.txt",
maxlen=4096)
# Render Complete Notifications
minimum_time: bpy.props.IntProperty(
name="Minimum Render Time",
description="Minimum rendering time required before notifications will be enabled, in seconds",
default=300)
# Email notifications
email_enable: bpy.props.BoolProperty(
name='Email Notification',
description='Enable email notifications',
default=False)
email_server: bpy.props.StringProperty(