-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbl_types.py
774 lines (623 loc) · 26.2 KB
/
bl_types.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
# Nikita Akimov
#
# GitHub
# https://github.com/Korchy/BIS
# Blender types to/from JSON conversion
# Blender types are described with prefix BL
import os
import sys
import bpy
from .file_manager import FileManager
from .TextManager import TextManager
from . import cfg
class BlTypes:
@classmethod
def has_json(cls, instance):
# check if this type described here to get its json
if hasattr(sys.modules[__name__], 'BL' + instance.__class__.__name__):
return True
else:
return False
@classmethod
def to_json(cls, instance, instance_name=None, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
# instance to json
if isinstance(instance, (int, float, bool, set, str)):
# simple type
if instance_name:
return {
instance_name: instance
}
else:
return instance
elif hasattr(sys.modules[__name__], 'BL' + instance.__class__.__name__):
# complex attribute described in ths module
instance_class = getattr(sys.modules[__name__], 'BL' + instance.__class__.__name__)
if instance_name:
return {
instance_name: instance_class.to_json(instance=instance)
}
else:
return instance_class.to_json(instance=instance)
else:
# any other complex type - try co process as unknown complex instance
if cfg.show_debug_err:
print('Not described in BIS bl_types:')
print(
'instance:', instance, ',',
'instance name:', instance_name, ',',
'instance class:', instance.__class__.__name__
)
if instance_name:
return {
instance_name: BLBaseType.to_json(instance=instance)
}
else:
return BLBaseType.to_json(instance=instance)
@classmethod
def complex_to_json(cls, instance, instance_name=None, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
instance_json = {}
# excluded attributes - don't process them (ex: type, select)
excluded_attributes = excluded_attributes if excluded_attributes is not None else []
# first process attributes
# need to be processed first because when changed - change another attributes (ex: mode)
first_attributes = first_attributes if first_attributes is not None else []
first_attributes_filtered = [
attr for attr in first_attributes if
attr not in excluded_attributes
and hasattr(instance, attr)
and getattr(instance, attr) is not None # don't add attributes == None
and not (isinstance(getattr(instance, attr), str) and not getattr(instance, attr)) # don't add attributes == '' (empty string)
and (not instance.is_property_readonly(attr) or cls.has_json(instance=getattr(instance, attr))) # read-only attributes - only complex
]
# get next attributes from instance
next_attributes_filtered = [
attr for attr in dir(instance) if
hasattr(instance, attr)
and not attr.startswith('__')
and not attr.startswith('bl_')
and attr not in excluded_attributes
and attr not in first_attributes_filtered # don't add first_attributes_filtered, added them first manually
and not callable(getattr(instance, attr))
and getattr(instance, attr) is not None # don't add attributes == None
and not (isinstance(getattr(instance, attr), str) and not getattr(instance, attr)) # don't add attributes == '' (empty string)
and (not instance.is_property_readonly(attr) or cls.has_json(instance=getattr(instance, attr))) # read-only attributes - only complex
or attr == 'bl_idname'
]
# all attributes: first - preordered attributes, next - all other attributes
all_attributes = first_attributes_filtered + next_attributes_filtered
# get json
for attr in all_attributes:
instance_json.update(
cls.to_json(instance=getattr(instance, attr), instance_name=attr)
)
return instance_json
@classmethod
def from_json(cls, instance_name, instance_owner, instance_json, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
# fill instance from json
if hasattr(instance_owner, instance_name):
instance = getattr(instance_owner, instance_name)
# print('instance', instance, type(instance), instance_json, instance.__class__.__name__)
# print(
# 'bltypes attribute - ', 'instance name: ', instance_name, ',',
# 'instance class', instance.__class__.__name__, ',',
# 'instance owner', instance_owner, ',',
# 'instance_json', instance_json
# )
if isinstance(instance, (int, float, bool, set, str)):
# simple type
setattr(instance_owner, instance_name, instance_json)
# setattr(instance_owner, instance_name, 'xxx')
elif hasattr(sys.modules[__name__], 'BL' + instance.__class__.__name__):
# complex attribute described in ths module
instance_class = getattr(sys.modules[__name__], 'BL' + instance.__class__.__name__)
instance_class.from_json(
instance_name=instance_name,
instance_owner=instance_owner,
json=instance_json,
attachments_path=attachments_path
)
else:
# any other complex type - try co process as unknown complex instance
if cfg.show_debug_err:
print('Not described in BIS bl_types:')
print(
'instance name: ', instance_name, ',',
'instance class:', instance.__class__.__name__, ',',
'instance owner', instance_owner, ',',
'instance json:', instance_json
)
BLBaseType.from_json(
instance_name=instance_name,
instance_owner=instance_owner,
json=instance_json,
attachments_path=attachments_path,
excluded_attributes=excluded_attributes,
first_attributes=first_attributes
)
@classmethod
def complex_from_json(cls, instance, json, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
if instance:
# instance attributes
# print(
# 'bltypes complex attribute - ',
# 'instance class', instance.__class__.__name__, ',',
# 'json', json
# )
# don't process
excluded_attributes = excluded_attributes if excluded_attributes is not None else []
# first attributes - process first because they influence on other attributes
first_attributes = first_attributes if first_attributes is not None else []
first_attributes_filtered = [
attribute_name for attribute_name in json['instance'] if
attribute_name in first_attributes
]
for attribute_name in first_attributes_filtered:
if hasattr(instance, attribute_name):
cls.from_json(
instance_name=attribute_name,
instance_owner=instance,
instance_json=json['instance'][attribute_name],
attachments_path=attachments_path,
excluded_attributes=excluded_attributes,
first_attributes=first_attributes
)
excluded_attributes += first_attributes_filtered
# for all other node attributes
for attribute_name in json['instance']:
if attribute_name not in excluded_attributes and hasattr(instance, attribute_name):
cls.from_json(
instance_name=attribute_name,
instance_owner=instance,
instance_json=json['instance'][attribute_name],
attachments_path=attachments_path,
excluded_attributes=excluded_attributes,
first_attributes=first_attributes
)
class BLBaseType:
# exclude for all types
# instance to json
_common_excluded_attributes_get = ['bl_idname', 'original', 'rna_type', 'select']
# json to instance
_common_excluded_attributes_set = ['bis_linked_item', 'bl_idname', 'original', 'rna_type', 'select', 'type']
# exclude for current type in child classes
# json to instance
excluded_attributes_get = []
# json to instance
excluded_attributes_set = []
@classmethod
def to_json(cls, instance):
# instance to json call
instance_in_json = {
'class': instance.__class__.__name__,
'instance': cls.instance_to_json(instance=instance)
}
return instance_in_json
@classmethod
def instance_to_json(cls, instance):
# get data from instance and convert them to json
return BlTypes.complex_to_json(
instance=instance,
excluded_attributes=cls.excluded_attr(aim='get')
)
@classmethod
def from_json(cls, instance_name, instance_owner, json, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
# instance from json call
return cls.json_to_instance(
instance_name=instance_name,
instance_owner=instance_owner,
json=json,
attachments_path=attachments_path,
excluded_attributes=excluded_attributes,
first_attributes=first_attributes
)
@classmethod
def json_to_instance(cls, instance_name, instance_owner, json, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
# get data from json and fill instance with that data
return BlTypes.complex_from_json(
instance=getattr(instance_owner, instance_name),
json=json,
attachments_path=attachments_path,
excluded_attributes=cls.excluded_attr(aim='set', additional_exclude=excluded_attributes),
first_attributes=first_attributes
)
@classmethod
def excluded_attr(cls, aim='get', additional_exclude: list = None):
additional_exclude = additional_exclude if additional_exclude is not None else []
if aim == 'get':
return cls._common_excluded_attributes_get + cls.excluded_attributes_get + additional_exclude
else:
return cls._common_excluded_attributes_set + cls.excluded_attributes_set + additional_exclude
class BLbpy_prop_collection(BLBaseType):
@classmethod
def instance_to_json(cls, instance):
json = []
for key, item in instance.items():
item_json = BlTypes.to_json(instance=item)
json.append(item_json)
return json
@classmethod
def json_to_instance(cls, instance_name, instance_owner, json, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
# add new items if not exists
instance = getattr(instance_owner, instance_name)
items_exists = len(instance)
if items_exists < len(json['instance']):
for item_json in json['instance'][items_exists:]:
item_class = None
if hasattr(sys.modules[__name__], 'BL' + item_json['class']):
item_class = getattr(sys.modules[__name__], 'BL' + item_json['class'])
if item_class and hasattr(item_class, 'new_item'):
item_class.new_item(item_owner=instance)
# fill with data
for i, item_json in enumerate(json['instance']):
if i < len(instance):
BlTypes.complex_from_json(
instance=instance[i],
json=item_json,
attachments_path=attachments_path,
excluded_attributes=excluded_attributes,
first_attributes=first_attributes
)
class BLbpy_prop_array(BLBaseType):
@classmethod
def instance_to_json(cls, instance):
json = []
for item in instance:
json.append(item)
return json
@classmethod
def json_to_instance(cls, instance_name, instance_owner, json, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
instance = getattr(instance_owner, instance_name)
if isinstance(json, (int, float, bool, set, str)):
# auto-convert: value to array (for older compatibility)
for item in instance:
item = json
elif json['class'] == 'Vector':
# auto-convert: Vector to array (for older compatibility)
instance[0] = json['instance']['x']
instance[1] = json['instance']['y']
if len(instance) > 2:
instance[2] = json['instance']['z']
else:
# common way - array to array
for i, array_item_json in enumerate(json['instance']):
instance[i] = array_item_json
# class BLNodeOutputFileSlotFile(BLBaseType):
#
# @classmethod
# def instance_to_json(cls, instance):
# # data to json
# json = {
# 'format': BLImageFormatSettings.to_json(instance.format),
# 'path': instance.path,
# 'use_node_format': instance.use_node_format
# }
# return json
#
# @classmethod
# def json_to_instance(cls, instance, json, instance_field=None):
# # data from json
# BLImageFormatSettings.from_json(instance.format, json['format'])
# instance.path = json['path']
# instance.use_node_format = json['use_node_format']
# return instance
#
# @classmethod
# def new_item(cls, node):
# # creates new real item
# context_copy = bpy.context.copy()
# context_copy['node'] = node
# bpy.ops.node.output_file_add_socket(context_copy)
class BLColor(BLBaseType):
@classmethod
def instance_to_json(cls, instance):
# data to json
json = {
'r': instance.r,
'g': instance.g,
'b': instance.b
}
return json
@classmethod
def json_to_instance(cls, instance_name, instance_owner, json, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
instance = getattr(instance_owner, instance_name)
instance.r = json['instance']['r']
instance.g = json['instance']['g']
instance.b = json['instance']['b']
class BLVector(BLBaseType):
@classmethod
def instance_to_json(cls, instance):
# data to json
json = {
'x': instance.x,
'y': instance.y
}
if hasattr(instance, 'z'):
json['z'] = instance.z
return json
@classmethod
def json_to_instance(cls, instance_name, instance_owner, json, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
instance = getattr(instance_owner, instance_name)
instance.x = json['instance']['x']
instance.y = json['instance']['y']
if hasattr(instance, 'z'):
instance.z = json['instance']['z']
# class BLset:
#
# @classmethod
# def to_json(cls, instance):
# # instance to json call
# return list(instance)
#
# @classmethod
# def from_json(cls, json):
# # instance from json call
# return set(json)
class BLObject(BLBaseType):
@classmethod
def instance_to_json(cls, instance):
# data to json
json = {}
if instance:
json['name'] = instance.name
return json
@classmethod
def json_to_instance(cls, instance_name, instance_owner, json, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
# data from json
if 'name' in json['instance'] and json['instance']['name'] in bpy.data.objects:
setattr(instance_owner, instance_name, bpy.data.objects[json['instance']['name']])
# class BLImage(BLBaseType):
#
# excluded_attributes_get = ['pixels', 'filepath_raw'] # exclude for current type
class BLImage(BLBaseType):
@classmethod
def instance_to_json(cls, instance):
# data to json
json = {}
if instance:
# json['source'] = instance.source
# json['filepath'] = os.path.normpath(
# os.path.join(
# os.path.dirname(bpy.data.filepath),
# instance.filepath.replace('//', '')
# )
# )
json['filepath'] = os.path.normpath(
os.path.join(
os.path.dirname(bpy.data.filepath),
os.path.dirname(instance.filepath.replace('//', '')),
FileManager.normalize_file_name(instance.name),
)
)
return json
@classmethod
def json_to_instance(cls, instance_name, instance_owner, json, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
# data from json
# all attachments (images) must be loaded first
if 'filepath' in json['instance'] and json['instance']['filepath']:
image_name = os.path.basename(json['instance']['filepath'])
# find image file
image_path = ''
# print(os.path.join(attachments_path, image_name))
if os.path.exists(os.path.join(attachments_path, image_name)) and \
os.path.isfile(os.path.join(attachments_path, image_name)):
# first look in received attachments
image_path = os.path.join(attachments_path, image_name)
elif os.path.exists(json['instance']['filepath']) and os.path.isfile(json['instance']['filepath']):
# next look by original path
image_path = json['instance']['filepath']
# get image
if image_path:
image = bpy.data.images.load(image_path, check_existing=True)
# image.source = json['instance']['source']
elif image_name in bpy.data.images:
image = bpy.data.images[image_name]
else:
image = None
# set image as attribute
if image:
setattr(instance_owner, instance_name, image)
class BLText(BLBaseType):
@classmethod
def instance_to_json(cls, instance):
# data to json
json = {}
rez = TextManager.to_bis(context=bpy.context, text=instance)
if rez['stat'] == 'OK':
bis_linked_item = {
'storage': TextManager.storage_type(),
'id': rez['data']['id']
}
json['bis_linked_item'] = bis_linked_item
return json
@classmethod
def json_to_instance(cls, instance_name, instance_owner, json, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
# data from json
rez = TextManager.from_bis(context=bpy.context, bis_text_id=json['instance']['bis_linked_item']['id'])
if rez['stat'] == 'OK':
text_item = TextManager.item_by_bis_uid(bis_uid=json['instance']['bis_linked_item']['id'])
if text_item:
setattr(instance_owner, instance_name, text_item)
class BLCurveMapping(BLBaseType):
pass
class BLCurveMap(BLBaseType):
pass
class BLCurveMapPoint(BLBaseType):
@classmethod
def new_item(cls, item_owner):
# creates new item ot this type
return item_owner.new(0.0, 0.0)
class BLColorRamp(BLBaseType):
pass
class BLColorRampElement(BLBaseType):
@classmethod
def new_item(cls, item_owner):
# creates new item ot this type
return item_owner.new(0.0)
class BLTexture(BLBaseType):
@classmethod
def json_to_instance(cls, instance_name, instance_owner, json, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
# data from json
if 'name' in json['instance'] and 'type' in json['instance']:
# create new anyway, because existed could be from other material
new_item = bpy.data.textures.new(name=json['instance']['name'], type=json['instance']['type'])
setattr(instance_owner, instance_name, new_item)
BlTypes.complex_from_json(
instance=new_item,
json=json,
attachments_path=attachments_path
)
class BLBlendTexture(BLTexture):
pass
class BLCloudsTexture(BLTexture):
pass
class BLDistortedNoiseTexture(BLTexture):
pass
# class BLImageTexture(BLTexture):
# pass
class BLMagicTexture(BLTexture):
pass
class BLMarbleTexture(BLTexture):
pass
class BLMusgraveTexture(BLTexture):
pass
class BLNoiseTexture(BLTexture):
pass
class BLStucciTexture(BLTexture):
pass
class BLVoronoiTexture(BLTexture):
pass
class BLWoodTexture(BLTexture):
pass
class BLScene(BLBaseType):
@classmethod
def instance_to_json(cls, instance):
# data to json
json = {}
if instance:
json['name'] = instance.name
return json
@classmethod
def json_to_instance(cls, instance_name, instance_owner, json, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
# data from json
if 'name' in json['instance'] and json['instance']['name'] in bpy.data.scenes:
setattr(instance_owner, instance_name, bpy.data.scenes[json['instance']['name']])
class BLEuler(BLBaseType):
@classmethod
def instance_to_json(cls, instance):
# data to json
json = {}
if instance:
json['order'] = instance.order
json['x'] = instance.x
json['y'] = instance.y
json['z'] = instance.z
return json
@classmethod
def json_to_instance(cls, instance_name, instance_owner, json, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
# data from json
instance = getattr(instance_owner, instance_name)
if hasattr(instance, 'order') and 'order' in json['instance'] and json['instance']['order']:
instance.order = json['instance']['order']
if hasattr(instance, 'x') and 'x' in json['instance']:
instance.x = json['instance']['x']
if hasattr(instance, 'y') and 'y' in json['instance']:
instance.y = json['instance']['y']
if hasattr(instance, 'z') and 'z' in json['instance']:
instance.z = json['instance']['z']
return instance
class BLNodeFrame(BLBaseType):
@classmethod
def instance_to_json(cls, instance):
# data to json
json = {
'bis_node_uid': instance['bis_node_uid'] if 'bis_node_uid' in instance else None
}
return json
class BLFilepath(BLBaseType):
# not a type, used for working with external objects like *.osl, *.ies external files
# instance_to_json works like with a "str" type
# TODO check - maybe need to do as in the BLImage to keep proper external object names
@classmethod
def json_to_instance(cls, instance_name, instance_owner, json, attachments_path=None,
excluded_attributes: list = None, first_attributes: list = None):
# data from json
# all attachments (files) must be loaded first
if json:
file_name = os.path.basename(json)
# find external file
file_path = ''
if os.path.exists(os.path.join(attachments_path, file_name)) and \
os.path.isfile(os.path.join(attachments_path, file_name)):
# first look in received attachments
file_path = os.path.join(attachments_path, file_name)
elif os.path.exists(json) and os.path.isfile(json):
# next look by original path
file_path = json
# get file
if file_path:
setattr(instance_owner, instance_name, file_path)
class BLNodeSocketFloat(BLBaseType):
pass
class BLNodeSocketFloatAngle(BLBaseType):
pass
class BLNodeSocketFloatFactor(BLBaseType):
pass
class BLNodeSocketFloatUnsigned(BLBaseType):
pass
class BLNodeSocketString(BLBaseType):
pass
class BLNodeSocketVector(BLBaseType):
pass
class BLNodeSocketVectorDirection(BLBaseType):
pass
class BLNodeSocketVectorEuler(BLBaseType):
pass
class BLNodeSocketVectorTranslation(BLBaseType):
pass
class BLNodeSocketVectorXYZ(BLBaseType):
pass
class BLNodeSocketColor(BLBaseType):
pass
class BLNodeSocketInt(BLBaseType):
pass
class BLNodeSocketShader(BLBaseType):
pass
class BLNodeSocketInterfaceFloat(BLBaseType):
pass
class BLNodeSocketInterfaceFloatAngle(BLBaseType):
pass
class BLNodeSocketInterfaceFloatFactor(BLBaseType):
pass
class BLNodeSocketInterfaceFloatUnsigned(BLBaseType):
pass
class BLNodeSocketInterfaceInt(BLBaseType):
pass
class BLNodeSocketInterfaceVector(BLBaseType):
pass
class BLNodeSocketInterfaceVectorEuler(BLBaseType):
pass
class BLNodeSocketInterfaceVectorTranslation(BLBaseType):
pass
class BLNodeSocketInterfaceVectorXYZ(BLBaseType):
pass
class BLNodeSocketInterfaceColor(BLBaseType):
pass
class BLNodeSocketInterfaceShader(BLBaseType):
pass