This repository has been archived by the owner on Jul 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
__init__.py
1792 lines (1501 loc) · 68.3 KB
/
__init__.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': 'BlendNet - distributed cloud render',
'author': 'www.state-of-the-art.io',
'version': (0, 4, 0),
'warning': 'development version',
'blender': (2, 80, 0),
'location': 'Properties --> Render --> BlendNet Render',
'description': 'Allows to easy allocate resources in cloud and '
'run the cycles rendering with getting preview '
'and results',
'wiki_url': 'https://github.com/state-of-the-art/BlendNet/wiki',
'tracker_url': 'https://github.com/state-of-the-art/BlendNet/issues',
'category': 'Render',
}
if 'bpy' in locals():
import importlib
importlib.reload(BlendNet)
importlib.reload(blend_file)
else:
from . import (
BlendNet,
)
from .BlendNet import blend_file
import os
import time
import tempfile
from datetime import datetime
import bpy
from bpy.props import (
BoolProperty,
IntProperty,
StringProperty,
EnumProperty,
PointerProperty,
CollectionProperty,
)
class BlendNetAddonPreferences(bpy.types.AddonPreferences):
bl_idname = __package__
resource_provider: EnumProperty(
name = 'Provider',
description = 'Engine to provide resources for rendering',
items = BlendNet.addon.getProvidersEnumItems,
update = lambda self, context: BlendNet.addon.selectProvider(self.resource_provider),
)
blendnet_show_panel: BoolProperty(
name = 'Show BlendNet',
description = 'Show BlendNet render panel',
default = True,
)
# Advanced
blender_dist: EnumProperty(
name = 'Blender dist',
description = 'Blender distributive to use on manager/agents. '
'By default it\'s set to the current blender version and if '
'you want to change it - you will deal with the custom URL',
items = BlendNet.addon.fillAvailableBlenderDists,
update = lambda self, context: BlendNet.addon.updateBlenderDistProp(self.blender_dist),
)
blender_dist_url: StringProperty(
name = 'Blender dist URL',
description = 'URL to download the blender distributive',
default = '',
)
blender_dist_checksum: StringProperty(
name = 'Blender dist checksum',
description = 'Checksum of the distributive to validate the binary',
default = '',
)
blender_dist_custom: BoolProperty(
name = 'Custom dist URL',
description = 'Use custom url instead the automatic one',
default = False,
update = lambda self, context: BlendNet.addon.updateBlenderDistProp(),
)
session_id: StringProperty(
name = 'Session ID',
description = 'Identifier of the session and allocated resources. '
'It is used to properly find your resources in the GCP '
'project and separate your resources from the other ones. '
'Warning: Please be careful with this option and don\'t '
'change it if you don\'t know what it\'s doing',
maxlen = 12,
update = lambda self, context: BlendNet.addon.genSID(self, 'session_id'),
)
manager_instance_type: EnumProperty(
name = 'Manager size',
description = 'Selected manager instance size',
items = BlendNet.addon.fillAvailableInstanceTypesManager,
)
manager_ca_path: StringProperty(
name = 'CA certificate',
description = 'Certificate Authority certificate pem file location',
subtype = 'FILE_PATH',
default = '',
)
manager_address: StringProperty(
name = 'Address',
description = 'If you using the existing Manager service put address here '
'(it will be automatically created otherwise)',
default = '',
)
manager_port: IntProperty(
name = 'Port',
description = 'TLS tcp port to communicate Addon with Manager service',
min = 1,
max = 65535,
default = 8443,
)
manager_user: StringProperty(
name = 'User',
description = 'HTTP Basic Auth username (will be generated if empty)',
maxlen = 32,
default = 'blendnet-manager',
)
manager_password: StringProperty(
name = 'Password',
description = 'HTTP Basic Auth password (will be generated if empty)',
subtype = 'PASSWORD',
maxlen = 128,
default = '',
update = lambda self, context: BlendNet.addon.hidePassword(self, 'manager_password'),
)
manager_agent_instance_type: EnumProperty(
name = 'Agent size',
description = 'Selected agent instance size',
items = BlendNet.addon.fillAvailableInstanceTypesAgent,
)
manager_agents_max: IntProperty(
name = 'Agents max',
description = 'Maximum number of agents in Manager\'s pool',
min = 1,
max = 65535,
default = 3,
)
agent_use_cheap_instance: BoolProperty(
name = 'Use cheap VM',
description = 'Use cheap instances to save money',
default = True,
)
agent_cheap_multiplier: EnumProperty(
name = 'Cheap multiplier',
description = 'Way to choose the price to get a cheap VM. '
'Some providers allows to choose the maximum price for the instance '
'and it could be calculated from the ondemand (max) price multiplied by this value.',
items = BlendNet.addon.getCheapMultiplierList,
)
agent_port: IntProperty(
name = 'Port',
description = 'TLS tcp port to communicate Manager with Agent service',
min = 1,
max = 65535,
default = 9443,
)
agent_user: StringProperty(
name = 'User',
description = 'HTTP Basic Auth username (will be generated if empty)',
maxlen = 32,
default = 'blendnet-agent',
)
agent_password: StringProperty(
name = 'Password',
description = 'HTTP Basic Auth password (will be generated if empty)',
subtype = 'PASSWORD',
maxlen = 128,
default = '',
update = lambda self, context: BlendNet.addon.hidePassword(self, 'agent_password'),
)
# Hidden
show_advanced: BoolProperty(
name = 'Advanced Properties',
description = 'Show/Hide the advanced properties',
default = False,
)
manager_password_hidden: StringProperty(
subtype = 'PASSWORD',
update = lambda self, context: BlendNet.addon.genPassword(self, 'manager_password_hidden'),
)
agent_password_hidden: StringProperty(
subtype = 'PASSWORD',
update = lambda self, context: BlendNet.addon.genPassword(self, 'agent_password_hidden'),
)
def draw(self, context):
layout = self.layout
# Provider
box = layout.box()
row = box.row()
split = box.split(factor=0.8)
split.prop(self, 'resource_provider')
info = BlendNet.addon.getProviderDocs(self.resource_provider).split('\n')
for line in info:
if line.startswith('Help: '):
split.operator('wm.url_open', text='How to setup', icon='HELP').url = line.split(': ', 1)[-1]
provider_settings = BlendNet.addon.getProviderSettings()
for key, data in provider_settings.items():
path = 'provider_' + self.resource_provider + '_' + key
if not path in self.__class__.__annotations__:
print('ERROR: Unable to find provider setting:', path)
continue
if path not in self or self[path] is None:
self[path] = data.get('value')
box.prop(self, path)
messages = BlendNet.addon.getProviderMessages(self.resource_provider)
for msg in messages:
box.label(text=msg, icon='ERROR')
if not BlendNet.addon.checkProviderIsSelected():
err = BlendNet.addon.getProviderDocs(self.resource_provider).split('\n')
for line in err:
box.label(text=line.strip(), icon='ERROR')
return
if self.resource_provider != 'local':
box = box.box()
box.label(text='Collected cloud info:')
provider_info = BlendNet.addon.getProviderInfo(context)
if 'ERRORS' in provider_info:
for err in provider_info['ERRORS']:
box.label(text=err, icon='ERROR')
for key, value in provider_info.items():
if key == 'ERRORS':
continue
split = box.split(factor=0.5)
split.label(text=key, icon='DOT')
split.label(text=value)
# Advanced properties panel
advanced_icon = 'TRIA_RIGHT' if not self.show_advanced else 'TRIA_DOWN'
box = layout.box()
box.prop(self, 'show_advanced', emboss=False, icon=advanced_icon)
if self.show_advanced:
if self.resource_provider != 'local':
row = box.row()
row.prop(self, 'session_id')
row = box.row(align=True)
row.prop(self, 'blender_dist_custom', text='')
if not self.blender_dist_custom:
row.prop(self, 'blender_dist')
else:
row.prop(self, 'blender_dist_url')
box.row().prop(self, 'blender_dist_checksum')
box_box = box.box()
box_box.label(text='Manager')
if self.resource_provider != 'local':
row = box_box.row()
row.prop(self, 'manager_instance_type', text='Type')
row = box_box.row()
price = BlendNet.addon.getManagerPriceBG(self.manager_instance_type, context)
if price[0] < 0.0:
row.label(text='WARNING: Unable to find price for the type "%s": %s' % (
self.manager_instance_type, price[1]
), icon='ERROR')
else:
row.label(text='Calculated price: ~%s/Hour (%s)' % (round(price[0], 12), price[1]))
if self.resource_provider == 'local':
row = box_box.row()
row.use_property_split = True
row.prop(self, 'manager_address')
row = box_box.row()
row.use_property_split = True
row.prop(self, 'manager_ca_path')
row = box_box.row()
row.use_property_split = True
row.prop(self, 'manager_port')
row = box_box.row()
row.use_property_split = True
row.prop(self, 'manager_user')
row = box_box.row()
row.use_property_split = True
row.prop(self, 'manager_password')
box_box = box.box()
box_box.label(text='Agent')
if self.resource_provider != 'local':
row = box_box.row()
row.prop(self, 'agent_use_cheap_instance')
if 'Cheap instances not available' in provider_info.get('ERRORS', []):
row.enabled = False
else:
row.prop(self, 'agent_cheap_multiplier')
row = box_box.row()
row.enabled = not BlendNet.addon.isManagerCreated()
row.prop(self, 'manager_agent_instance_type', text='Agents type')
row.prop(self, 'manager_agents_max', text='Agents max')
row = box_box.row()
price = BlendNet.addon.getAgentPriceBG(self.manager_agent_instance_type, context)
if price[0] < 0.0:
row.label(text='ERROR: Unable to find price for the type "%s": %s' % (
self.manager_agent_instance_type, price[1]
), icon='ERROR')
else:
row.label(text='Calculated combined price: ~%s/Hour (%s)' % (
round(price[0] * self.manager_agents_max, 12), price[1]
))
min_price = BlendNet.addon.getMinimalCheapPriceBG(self.manager_agent_instance_type, context)
if min_price > 0.0:
row = box_box.row()
row.label(text='Minimal combined price: ~%s/Hour' % (
round(min_price * self.manager_agents_max, 12),
))
if price[0] <= min_price:
row = box_box.row()
row.label(text='ERROR: Selected cheap price is lower than minimal one', icon='ERROR')
row = box_box.row()
row.use_property_split = True
row.prop(self, 'agent_port')
row = box_box.row()
row.use_property_split = True
row.prop(self, 'agent_user')
row = box_box.row()
row.use_property_split = True
row.prop(self, 'agent_password')
class BlendNetSceneSettings(bpy.types.PropertyGroup):
scene_memory_req: IntProperty(
name = 'Scene RAM to render',
description = 'Required memory to render the scene in GB',
min = 0,
max = 65535,
default = 0,
)
@classmethod
def register(cls):
bpy.types.Scene.blendnet = PointerProperty(
name = 'BlendNet Settings',
description = 'BlendNet scene settings',
type = cls
)
@classmethod
def unregister(cls):
if hasattr(bpy.types.Scene, 'blendnet'):
del bpy.types.Scene.blendnet
class BlendNetManagerTask(bpy.types.PropertyGroup):
'''Class contains the manager task information'''
name: StringProperty()
create_time: StringProperty()
start_time: StringProperty()
end_time: StringProperty()
state: StringProperty()
done: StringProperty()
received: StringProperty()
class BlendNetSessionProperties(bpy.types.PropertyGroup):
manager_tasks: CollectionProperty(
name = 'Manager tasks',
description = 'Contains all the tasks that right now is available '
'on manager',
type = BlendNetManagerTask,
)
manager_tasks_idx: IntProperty(default=0)
status: StringProperty(
name = 'BlendNet status',
description = 'BlendNet is performing some operation',
default = 'idle',
)
@classmethod
def register(cls):
bpy.types.WindowManager.blendnet = PointerProperty(
name = 'BlendNet Session Properties',
description = 'Just current status of process for internal use',
type = cls,
)
@classmethod
def unregister(cls):
if hasattr(bpy.types.WindowManager, 'blendnet'):
del bpy.types.WindowManager.blendnet
class BlendNetToggleManager(bpy.types.Operator):
bl_idname = 'blendnet.togglemanager'
bl_label = ''
bl_description = 'Start/Stop manager instance'
_timer = None
_last_run = 0
@classmethod
def poll(cls, context):
return context.window_manager.blendnet.status == 'idle' or BlendNet.addon.isManagerStarted()
def invoke(self, context, event):
wm = context.window_manager
BlendNet.addon.toggleManager()
if BlendNet.addon.isManagerStarted():
self.report({'INFO'}, 'BlendNet stopping Manager instance...')
wm.blendnet.status = 'Manager stopping...'
else:
self.report({'INFO'}, 'BlendNet starting Manager instance...')
wm.blendnet.status = 'Manager starting...'
if context.area:
context.area.tag_redraw()
wm.modal_handler_add(self)
self._timer = wm.event_timer_add(5.0, window=context.window)
return {'RUNNING_MODAL'}
def modal(self, context, event):
if event.type != 'TIMER' or self._last_run + 4.5 > time.time():
return {'PASS_THROUGH'}
self._last_run = time.time()
return self.execute(context)
def execute(self, context):
wm = context.window_manager
if wm.blendnet.status == 'Manager starting...':
if not BlendNet.addon.isManagerStarted():
return {'PASS_THROUGH'}
self.report({'INFO'}, 'BlendNet Manager started')
wm.blendnet.status = 'Manager connecting...'
if context.area:
context.area.tag_redraw()
BlendNet.addon.requestManagerInfo(context)
elif wm.blendnet.status == 'Manager stopping...':
if not BlendNet.addon.isManagerStopped():
return {'PASS_THROUGH'}
if wm.blendnet.status == 'Manager connecting...':
if not BlendNet.addon.requestManagerInfo(context):
return {'PASS_THROUGH'}
self.report({'INFO'}, 'BlendNet Manager connected')
if self._timer is not None:
wm.event_timer_remove(self._timer)
wm.blendnet.status = 'idle'
if context.area:
context.area.tag_redraw()
return {'FINISHED'}
class BlendNetDestroyManager(bpy.types.Operator):
bl_idname = 'blendnet.destroymanager'
bl_label = ''
bl_description = 'Destroy manager instance'
@classmethod
def poll(cls, context):
return BlendNet.addon.isManagerStopped()
def invoke(self, context, event):
BlendNet.addon.destroyManager()
self.report({'INFO'}, 'BlendNet destroy Manager instance...')
return {'FINISHED'}
class BlendNetTaskPreviewOperation(bpy.types.Operator):
bl_idname = 'blendnet.taskpreview'
bl_label = 'Open preview'
bl_description = 'Show the render for the currently selected task'
@classmethod
def poll(cls, context):
bn = context.window_manager.blendnet
return len(bn.manager_tasks) > bn.manager_tasks_idx
def _findRenderResultArea(self, context):
for window in context.window_manager.windows:
if window.scene != context.scene:
continue
for area in window.screen.areas:
if area.type != 'IMAGE_EDITOR':
continue
if area.spaces.active.image.type == 'RENDER_RESULT':
return area
return None
def invoke(self, context, event):
# Show the preview of the render if not open
if not self._findRenderResultArea(context):
bpy.ops.render.view_show('INVOKE_DEFAULT')
# Save the original render engine to run render on BlendNet
original_render_engine = context.scene.render.engine
context.scene.render.engine = __package__
# Start the render process
self.result = bpy.ops.render.render('INVOKE_DEFAULT')
# Restore the original scene engine
time.sleep(1.0)
if context.scene.render.engine == __package__:
context.scene.render.engine = original_render_engine
return {'FINISHED'}
class BlendNetRunTaskOperation(bpy.types.Operator):
bl_idname = 'blendnet.runtask'
bl_label = 'Run Task'
bl_description = 'Run Manager task using BlendNet resources'
is_animation: BoolProperty(
name = 'Animation',
description = 'Runs animation rendering instead of just a still image rendering',
default = False
)
_timer = None
_project_file: None # temp blend project file to ensure it will not be changed
_frame: 0 # current/start frame depends on animation
_frame_to: 0 # end frame for animation
_frame_orig: 0 # to restore the current frame after animation processing
_task_name: None # store task name to retry later
@classmethod
def poll(cls, context):
return BlendNet.addon.isManagerActive()
def _findRenderResultArea(self, context):
for window in context.window_manager.windows:
if window.scene != context.scene:
continue
for area in window.screen.areas:
if area.type != 'IMAGE_EDITOR':
continue
if area.spaces.active.image.type == 'RENDER_RESULT':
return area
def init(self, context):
'''Initializes the execution'''
if not bpy.data.filepath:
self.report({'ERROR'}, 'Unable to render not saved project. Please save it somewhere.')
return {'CANCELLED'}
# Fix and verify the blendfile dependencies
bads = blend_file.getDependencies(bpy.path.abspath('//'), os.path.abspath(''))[1]
if bads:
self.report({'ERROR'}, 'Found some bad dependencies - please fix them before run: %s' % (bads,))
return {'CANCELLED'}
# Saving project to the same directory
try:
self._project_file = bpy.data.filepath + '_blendnet.blend'
bpy.ops.wm.save_as_mainfile(
filepath = self._project_file,
check_existing = False,
compress = True,
copy = True,
)
except Exception as e:
self.report({'ERROR'}, 'Unable to save the "_blendnet.blend" project file: %s' % (e,))
return {'CANCELLED'}
if self.is_animation:
self._frame = context.scene.frame_start
self._frame_to = context.scene.frame_end
self._frame_orig = context.scene.frame_current
else:
self._frame = context.scene.frame_current
self._task_name = None
context.window_manager.modal_handler_add(self)
self._timer = context.window_manager.event_timer_add(0.1, window=context.window)
return {'RUNNING_MODAL'}
def invoke(self, context, event):
return self.init(context)
def modal(self, context, event):
if event.type != 'TIMER':
return {'PASS_THROUGH'}
# Waiting for manager
if not BlendNet.addon.isManagerActive():
return {'PASS_THROUGH'}
return self.execute(context)
def execute(self, context):
scene = context.scene
wait = False
if not hasattr(self, '_frame'):
wait = True # The execute is running directly, so run in fg
if 'CANCELLED' in self.init(context):
self.report({'ERROR'}, 'Unable to init task preparation')
return {'CANCELLED'}
scene.frame_current = self._frame
fname = bpy.path.basename(bpy.data.filepath)
if not self._task_name:
# If the operation is not completed - reuse the same task name
d = datetime.utcnow().strftime('%y%m%d%H%M')
self._task_name = '%s%s-%d-%s' % (
BlendNet.addon.getTaskProjectPrefix(),
d, scene.frame_current,
BlendNet.addon.genRandomString(3)
)
print('DEBUG: Uploading task "%s" to the manager' % self._task_name)
# Prepare list of files need to be uploaded
deps, bads = blend_file.getDependencies(bpy.path.abspath('//'), os.path.abspath(''))
if bads:
self.report({'ERROR'}, 'Found some bad dependencies - please fix them before run: %s' % (bads,))
return {'CANCELLED'}
deps_map = dict([ (rel, bpy.path.abspath(rel)) for rel in deps ])
deps_map['//'+fname] = self._project_file
# Run the dependencies upload background process
BlendNet.addon.managerTaskUploadFiles(self._task_name, deps_map)
# Slow down the check process
if self._timer is not None:
context.window_manager.event_timer_remove(self._timer)
self._timer = context.window_manager.event_timer_add(3.0, window=context.window)
status = BlendNet.addon.managerTaskUploadFilesStatus()
if wait:
for retry in range(1, 10):
status = BlendNet.addon.managerTaskUploadFilesStatus()
if not status:
break
time.sleep(1.0)
if status:
self.report({'INFO'}, 'Uploading process for task %s: %s' % (self._task_name, status))
return {'PASS_THROUGH'}
# Configuring the task
print('INFO: Configuring task "%s"' % self._task_name)
self.report({'INFO'}, 'Configuring task "%s"' % (self._task_name,))
samples = None
if hasattr(scene.cycles, 'progressive'):
# For blender < 3.0.0
if scene.cycles.progressive == 'PATH':
samples = scene.cycles.samples
elif scene.cycles.progressive == 'BRANCHED_PATH':
samples = scene.cycles.aa_samples
else:
samples = scene.cycles.samples
if hasattr(scene.cycles, 'use_square_samples'):
# For blender < 3.0.0
# Addon need to pass the actual samples number to the manager
if scene.cycles.use_square_samples:
samples *= samples
# Where the compose result will be stored on the Addon side
compose_filepath = scene.render.frame_path()
if scene.render.filepath.startswith('//'):
# It's relative to blend project path
compose_filepath = bpy.path.relpath(compose_filepath)
cfg = {
'samples': samples,
'frame': scene.frame_current,
'project': fname,
'use_compositing_nodes': scene.render.use_compositing,
'compose_filepath': compose_filepath,
'project_path': bpy.path.abspath('//'), # To resolve the project parent paths like `//../..`
'cwd_path': os.path.abspath(''), # Current working directory to resolve relative paths like `../dir/file.txt`
}
if not BlendNet.addon.managerTaskConfig(self._task_name, cfg):
self.report({'WARNING'}, 'Unable to config the task "%s", let\'s retry...' % (self._task_name,))
return {'PASS_THROUGH'}
# Running the task
self.report({'INFO'}, 'Running task "%s"' % self._task_name)
if not BlendNet.addon.managerTaskRun(self._task_name):
self.report({'WARNING'}, 'Unable to start the task "%s", let\'s retry...' % (self._task_name,))
return {'PASS_THROUGH'}
self.report({'INFO'}, 'Task "%s" marked as ready to start' % (self._task_name,))
# Ok, task is started - we can clean the name
self._task_name = None
if self.is_animation:
if self._frame < self._frame_to:
# Not all the frames are processed
self._frame += 1
return {'PASS_THROUGH'}
# Restore the original current frame
scene.frame_current = self._frame_orig
# Removing no more required temp blend file
os.remove(self._project_file)
if self._timer is not None:
context.window_manager.event_timer_remove(self._timer)
return {'FINISHED'}
class TASKS_UL_list(bpy.types.UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
self.use_filter_sort_alpha = True
if self.layout_type in {'DEFAULT', 'COMPACT'}:
split = layout.split(factor=0.7)
split.label(text=item.name)
split.label(text=('%s:%s' % (item.state[0], item.done)) if item.done and item.state != 'COMPLETED' else item.state)
elif self.layout_type in {'GRID'}:
pass
class BlendNetGetNodeLogOperation(bpy.types.Operator):
bl_idname = 'blendnet.getnodelog'
bl_label = 'Get Node Log'
bl_description = 'Show the node (instance) log data'
node_id: StringProperty(
name = 'Node ID',
description = 'ID of the node/instance to get the log',
default = ''
)
@classmethod
def poll(cls, context):
return True
def invoke(self, context, event):
wm = context.window_manager
data = BlendNet.addon.getNodeLog(self.node_id)
if not data:
self.report({'WARNING'}, 'No log data retreived for ' + self.node_id)
return {'CANCELLED'}
if data == 'NOT IMPLEMENTED':
self.report({'WARNING'}, 'Not implemented for the current provider')
return {'CANCELLED'}
prefix = self.node_id
def drawPopup(self, context):
layout = self.layout
if BlendNet.addon.showLogWindow(prefix, data):
layout.label(text='''Don't forget to unlink the file if you '''
'''don't want it to stay in blend file.''')
else:
layout.label(text='Unable to show the log window', icon='ERROR')
wm.popup_menu(drawPopup, title='Log for'+prefix, icon='INFO')
return {'FINISHED'}
class BlendNetGetAddonLogOperation(bpy.types.Operator):
bl_idname = 'blendnet.getaddonlog'
bl_label = 'Get BlendNet Addon Log'
bl_description = 'Show the running BlendNet addon log information'
@classmethod
def poll(cls, context):
return True
def invoke(self, context, event):
wm = context.window_manager
out = BlendNet.addon.getAddonLog()
prefix = 'addon'
if not out:
self.report({'ERROR'}, 'No log data found for ' + prefix)
return {'CANCELLED'}
data = []
line = ''
for t, l in out.items():
if not l.endswith('\n'):
line += l
continue
time_str = datetime.fromtimestamp(round(float(t), 3)).strftime('%y.%m.%d %H:%M:%S.%f')
data.append(time_str + '\t' + line + l)
line = ''
if line:
data.append('{not completed line}\t' + line)
data = ''.join(data)
def drawPopup(self, context):
layout = self.layout
if BlendNet.addon.showLogWindow(prefix, data):
layout.label(text='Don\'t forget to unlink the file if you don\'t want it to stay in blend file.')
else:
layout.label(text='Unable to show the log window', icon='ERROR')
wm.popup_menu(drawPopup, title='Log for ' + prefix, icon='INFO')
return {'FINISHED'}
class BlendNetGetServiceLogOperation(bpy.types.Operator):
bl_idname = 'blendnet.getservicelog'
bl_label = 'Get Service Log'
bl_description = 'Show the service (daemon) log data'
agent_name: StringProperty(
name = 'Name of Agent',
description = 'Name of Agent (or Manager by default) to get the log from',
default = ''
)
@classmethod
def poll(cls, context):
return True
def invoke(self, context, event):
wm = context.window_manager
out = {}
if self.agent_name:
out = BlendNet.addon.agentGetLog(self.agent_name)
else:
out = BlendNet.addon.managerGetLog()
prefix = self.agent_name if self.agent_name else BlendNet.addon.getResources(context).get('manager', {}).get('name')
if not out:
self.report({'ERROR'}, 'No log data retreived for ' + prefix)
return {'CANCELLED'}
data = []
line = ''
for t, l in out.items():
if not l.endswith('\n'):
line += l
continue
time_str = datetime.fromtimestamp(round(float(t), 3)).strftime('%y.%m.%d %H:%M:%S.%f')
data.append(time_str + '\t' + line + l)
line = ''
if line:
data.append('{not completed line}\t' + line)
data = ''.join(data)
def drawPopup(self, context):
layout = self.layout
if BlendNet.addon.showLogWindow(prefix, data):
layout.label(text='Don\'t forget to unlink the file if you don\'t want it to stay in blend file.')
else:
layout.label(text='Unable to show the log window', icon='ERROR')
wm.popup_menu(drawPopup, title='Log for' + prefix, icon='INFO')
return {'FINISHED'}
class BlendNetTaskInfoOperation(bpy.types.Operator):
bl_idname = 'blendnet.taskinfo'
bl_label = 'Task info'
bl_description = 'Show the current task info panel'
@classmethod
def poll(cls, context):
bn = context.window_manager.blendnet
return len(bn.manager_tasks) > bn.manager_tasks_idx
def invoke(self, context, event):
wm = context.window_manager
def drawPopup(self, context):
layout = self.layout
task_name = wm.blendnet.manager_tasks[wm.blendnet.manager_tasks_idx].name
data = BlendNet.addon.managerTaskStatus(task_name)
if not data:
return
keys = BlendNet.addon.naturalSort(data.keys())
for key in keys:
if key == 'result':
layout.label(text='%s:' % (key,))
for k in data[key]:
layout.label(text=' %s: %s' % (k, data[key][k]))
elif key == 'state_error_info':
layout.label(text='%s:' % (key,), icon='ERROR')
for it in data[key]:
if isinstance(it, dict):
for k, v in it.items():
layout.label(text=' %s: %s' % (k, v))
else:
layout.label(text=' ' + str(it))
else:
layout.label(text='%s: %s' % (key, data[key]))
task_name = wm.blendnet.manager_tasks[wm.blendnet.manager_tasks_idx].name
wm.popup_menu(drawPopup, title='Task info for "%s"' % task_name, icon='INFO')
return {'FINISHED'}
class BlendNetTaskMessagesOperation(bpy.types.Operator):
bl_idname = 'blendnet.taskmessages'
bl_label = 'Show task messages'
bl_description = 'Show the task execution messages'
@classmethod
def poll(cls, context):
bn = context.window_manager.blendnet
if len(bn.manager_tasks) <= bn.manager_tasks_idx:
return False
task_state = bn.manager_tasks[bn.manager_tasks_idx].state
return task_state not in {'CREATED', 'PENDING'}
def invoke(self, context, event):
wm = context.window_manager
task_name = wm.blendnet.manager_tasks[wm.blendnet.manager_tasks_idx].name
out = BlendNet.addon.managerTaskMessages(task_name)
if not out:
self.report({'ERROR'}, 'No task messages found for "%s"' % (task_name,))
return {'CANCELLED'}
data = []
keys = BlendNet.addon.naturalSort(out.keys())
for key in keys:
data.append(key)
if not out[key]:
continue
for line in out[key]:
data.append(' ' + line)
data = '\n'.join(data)
prefix = task_name + 'messages'
def drawPopup(self, context):
layout = self.layout
if BlendNet.addon.showLogWindow(prefix, data):
layout.label(text='Don\'t forget to unlink the file if you don\'t want it to stay in blend file.')
else:
layout.label(text='Unable to show the log window', icon='ERROR')
wm.popup_menu(drawPopup, title='Task messages for "%s"' % (task_name,), icon='TEXT')
return {'FINISHED'}
class BlendNetTaskDetailsOperation(bpy.types.Operator):
bl_idname = 'blendnet.taskdetails'
bl_label = 'Show task details'
bl_description = 'Show the task execution details'
@classmethod
def poll(cls, context):
bn = context.window_manager.blendnet
if len(bn.manager_tasks) <= bn.manager_tasks_idx:
return False
task_state = bn.manager_tasks[bn.manager_tasks_idx].state
return task_state not in {'CREATED', 'PENDING'}
def invoke(self, context, event):
wm = context.window_manager
task_name = wm.blendnet.manager_tasks[wm.blendnet.manager_tasks_idx].name
out = BlendNet.addon.managerTaskDetails(task_name)
if not out:
self.report({'ERROR'}, 'No task details found for "%s"' % (task_name,))
return {'CANCELLED'}
data = []
keys = BlendNet.addon.naturalSort(out.keys())
for key in keys:
data.append(key)
if not out[key]:
continue
for line in out[key]:
data.append(' ' + str(line))
data = '\n'.join(data)