forked from nortikin/sverchok
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_structure.py
executable file
·1023 lines (821 loc) · 28.8 KB
/
data_structure.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
from functools import reduce
from math import radians
import itertools
import time
import ast
import bpy
from mathutils import Vector, Matrix
from core.update_system import sverchok_update
global bmesh_mapping, per_cache
DEBUG_MODE = False
HEAT_MAP = False
# this is set correctly later.
SVERCHOK_NAME = "sverchok"
#handle for object in node
temp_handle = {}
# cache node group update trees it not used, as i see
# cache_nodes = {}
# cache node group update trees
list_nodes4update = {}
# cache for partial update lists
partial_update_cache = {}
# wifi node data
sv_Vars = {}
# socket cache
socket_data_cache = {}
# for viewer baker node cache
cache_viewer_baker = {}
# note used?
#bmesh_mapping = {}
#per_cache = {}
#####################################################
################### update magic ####################
#####################################################
# is this used?
# i think no
# main update
def read_cnodes(cnode):
global cache_nodes
if cnode not in cache_nodes:
return None
return cache_nodes[cnode]
def write_cnodes(cnode, number):
global cache_nodes
if cnode in cache_nodes:
del cache_nodes[cnode]
cache_nodes[cnode] = number
def clear_cnodes(cnode='ALL'):
global cache_nodes
if cnode == 'ALL':
for i in cache_nodes.items:
del cache_nodes[i]
else:
if read_cnodes(cnode) is not None:
del cache_nodes[cnode]
def initialize_cnodes():
node_name = 'GLOBAL CNODE'
write_cnodes(node_name, 1)
write_cnodes('LOCK UPDATE CNODES', 1)
def check_update_node(node_name, write=False):
numb = read_cnodes(node_name)
etalon = read_cnodes('GLOBAL CNODE')
#print('etalon',etalon)
if numb == etalon:
return False
else:
if write:
write_cnodes(node_name, etalon)
return True
def ini_update_cnode(node_name):
if read_cnodes('LOCK UPDATE CNODES') == 1:
return False
etalon = read_cnodes('GLOBAL CNODE')
if etalon is None:
initialize_cnodes()
etalon = 1
else:
etalon += 1
write_cnodes('GLOBAL CNODE', etalon)
write_cnodes(node_name, etalon)
return True
def is_updated_cnode():
write_cnodes('LOCK UPDATE CNODES', 0)
def lock_updated_cnode():
write_cnodes('LOCK UPDATE CNODES', 1)
#####################################################
################### bmesh magic #####################
#####################################################
def read_bmm(bm_ref):
global bmesh_mapping
if bm_ref not in bmesh_mapping:
return None
return bmesh_mapping[bm_ref]
def write_bmm(bm_ref, bm):
global bmesh_mapping
if bm_ref in bmesh_mapping:
del bmesh_mapping[bm_ref]
bmesh_mapping[bm_ref] = bm
def clear_bmm(bm_ref='ALL'):
global bmesh_mapping
if bm_ref == 'ALL':
for i in bmesh_mapping.items:
del bmesh_mapping[i]
else:
if read_bmm(bm_ref) is not None:
del bmesh_mapping[bm_ref]
#####################################################
################### cache magic #####################
#####################################################
def handle_delete(handle):
if handle in temp_handle:
del temp_handle[handle]
def handle_read(handle):
if not (handle in temp_handle):
return (False, [])
prop = temp_handle[handle]['prop']
return (True, prop)
def handle_write(handle, prop):
if handle in temp_handle:
if prop != temp_handle[handle]['prop']:
handle_delete(handle)
elif not (handle in temp_handle) and handle:
temp_handle[handle] = {"prop": prop}
def handle_check(handle, prop):
if handle in handle_check:
if prop != handle_check[handle]['prop']:
return False
else:
return False
return True
#####################################################
################ list matching magic ################
#####################################################
# creates an infinite iterator
# use with terminating input
def repeat_last(lst):
i = -1
while lst:
i += 1
if len(lst) > i:
yield lst[i]
else:
yield lst[-1]
# longest list matching [[1,2,3,4,5], [10,11]] -> [[1,2,3,4,5], [10,11,11,11,11]]
def match_long_repeat(lsts):
max_l = 0
tmp = []
for l in lsts:
max_l = max(max_l, len(l))
for l in lsts:
if len(l) == max_l:
tmp.append(l)
else:
tmp.append(repeat_last(l))
return list(map(list, zip(*zip(*tmp))))
# longest list matching, cycle [[1,2,3,4,5] ,[10,11]] -> [[1,2,3,4,5] ,[10,11,10,11,10]]
def match_long_cycle(lsts):
max_l = 0
tmp = []
for l in lsts:
max_l = max(max_l, len(l))
for l in lsts:
if len(l) == max_l:
tmp.append(l)
else:
tmp.append(itertools.cycle(l))
return list(map(list, zip(*zip(*tmp))))
# cross matching
# [[1,2], [5,6,7]] -> [[1,1,1,2,2,2], [5,6,7,5,6,7]]
def match_cross(lsts):
return list(map(list, zip(*itertools.product(*lsts))))
# use this one
# cross matching 2, more useful order
# [[1,2], [5,6,7]] ->[[1, 2, 1, 2, 1, 2], [5, 5, 6, 6, 7, 7]]
# but longer and less elegant expression
# performance difference is minimal since number of lists is usually small
def match_cross2(lsts):
return list(reversed(list(map(list, zip(*itertools.product(*reversed(lsts)))))))
# Shortest list decides output length [[1,2,3,4,5], [10,11]] -> [[1,2], [10, 11]]
def match_short(lsts):
return list(map(list, zip(*zip(*lsts))))
# extends list so len(l) == count
def fullList(l, count):
d = count - len(l)
if d > 0:
l.extend([l[-1] for a in range(d)])
return
def sv_zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
# like standard zip but list instead of tuple
sentinel = object()
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield result
#####################################################
################# list levels magic #################
#####################################################
# working with nesting levels
# define data floor
# data from nasting to standart: TO container( objects( lists( floats, ), ), )
def dataCorrect(data, nominal_dept=2):
dept = levelsOflist(data)
output = []
if dept < 2:
return [dept, data]
else:
output = dataStandart(data, dept, nominal_dept)
return output
# from standart data to initial levels: to nasting lists container( objects( lists( nasty_lists( floats, ), ), ), ) это невозможно!
def dataSpoil(data, dept):
if dept:
out = []
for d in data:
out.append([dataSpoil(d, dept-1)])
else:
out = data
return out
# data from nasting to standart: TO container( objects( lists( floats, ), ), )
def dataStandart(data, dept, nominal_dept):
deptl = dept - 1
output = []
for object in data:
if deptl >= nominal_dept:
output.extend(dataStandart(object, deptl, nominal_dept))
else:
output.append(data)
return output
return output
# calc list nesting only in countainment level integer
def levelsOflist(lst):
level = 1
for n in lst:
if n and isinstance(n, (list, tuple)):
level += levelsOflist(n)
return level
return
#####################################################
################### matrix magic ####################
#####################################################
# tools that makes easier to convert data
# from string to matrixes, vertices,
# lists, other and vise versa
def Matrix_listing(prop):
# matrix degenerate
mat_out = []
for i, matrix in enumerate(prop):
unit = []
for k, m in enumerate(matrix):
# [Matrix0, Matrix1, ... ]
unit.append(m[:])
mat_out.append((unit))
return mat_out
def Matrix_generate(prop):
mat_out = []
for i, matrix in enumerate(prop):
unit = Matrix()
for k, m in enumerate(matrix):
# [Matrix0, Matrix1, ... ]
unit[k] = Vector(m)
mat_out.append(unit)
return mat_out
def Matrix_location(prop, list=False):
Vectors = []
for p in prop:
if list:
Vectors.append(p.translation[:])
else:
Vectors.append(p.translation)
return [Vectors]
def Matrix_scale(prop, list=False):
Vectors = []
for p in prop:
if list:
Vectors.append(p.to_scale()[:])
else:
Vectors.append(p.to_scale())
return [Vectors]
# returns (Vector, rotation) utility function for Matrix Destructor. if list is true
# the Vector is decomposed into tuple format.
def Matrix_rotation(prop, list=False):
Vectors = []
for p in prop:
q = p.to_quaternion()
if list:
vec, angle = q.to_axis_angle()
Vectors.append((vec[:], angle))
else:
Vectors.append(q.to_axis_angle())
return [Vectors]
def Vector_generate(prop):
return [[Vector(v) for v in obj] for obj in prop]
def Vector_degenerate(prop):
return [[v[0:3] for v in object] for object in prop]
def Edg_pol_generate(prop):
edg_pol_out = []
if len(prop[0][0]) == 2:
type = 'edg'
elif len(prop[0]) > 2:
type = 'pol'
for ob in prop:
list = []
for p in ob:
list.append(p)
edg_pol_out.append(list)
# [ [(n1,n2,n3), (n1,n7,n9), p, p, p, p...], [...],... ] n = vertexindex
return type, edg_pol_out
def matrixdef(orig, loc, scale, rot, angle, vec_angle=[[]]):
modif = []
for i, de in enumerate(orig):
ma = de.copy()
if loc[0]:
k = min(len(loc[0])-1, i)
mat_tran = de.Translation(loc[0][k])
ma *= mat_tran
if vec_angle[0] and rot[0]:
k = min(len(rot[0])-1, i)
a = min(len(vec_angle[0])-1, i)
vec_a = vec_angle[0][a].normalized()
vec_b = rot[0][k].normalized()
mat_rot = vec_b.rotation_difference(vec_a).to_matrix().to_4x4()
ma = ma * mat_rot
elif rot[0]:
k = min(len(rot[0])-1, i)
a = min(len(angle[0])-1, i)
mat_rot = de.Rotation(radians(angle[0][a]), 4, rot[0][k].normalized())
ma = ma * mat_rot
if scale[0]:
k = min(len(scale[0])-1, i)
scale2 = scale[0][k]
id_m = Matrix.Identity(4)
for j in range(3):
id_m[j][j] = scale2[j]
ma *= id_m
modif.append(ma)
return modif
#####################################################
#################### lists magic ####################
#####################################################
def create_list(x, y):
if type(y) in [list, tuple]:
return reduce(create_list, y, x)
else:
return x.append(y) or x
def preobrazovatel(list_a, levels, level2=1):
list_tmp = []
level = levels[0]
if level > level2:
if type(list_a)in [list, tuple]:
for l in list_a:
if type(l) in [list, tuple]:
tmp = preobrazovatel(l, levels, level2+1)
if type(tmp) in [list, tuple]:
list_tmp.extend(tmp)
else:
list_tmp.append(tmp)
else:
list_tmp.append(l)
elif level == level2:
if type(list_a) in [list, tuple]:
for l in list_a:
if len(levels) == 1:
tmp = preobrazovatel(l, levels, level2+1)
else:
tmp = preobrazovatel(l, levels[1:], level2+1)
list_tmp.append(tmp if tmp else l)
else:
if type(list_a) in [list, tuple]:
list_tmp = reduce(create_list, list_a, [])
return list_tmp
def myZip(list_all, level, level2=0):
if level == level2:
if type(list_all) in [list, tuple]:
list_lens = []
list_res = []
for l in list_all:
if type(l) in [list, tuple]:
list_lens.append(len(l))
else:
list_lens.append(0)
if list_lens == []:
return False
min_len = min(list_lens)
for value in range(min_len):
lt = []
for l in list_all:
lt.append(l[value])
t = list(lt)
list_res.append(t)
return list_res
else:
return False
elif level > level2:
if type(list_all) in [list, tuple]:
list_res = []
list_tr = myZip(list_all, level, level2+1)
if list_tr is False:
list_tr = list_all
t = []
for tr in list_tr:
if type(list_tr) in [list, tuple]:
list_tl = myZip(tr, level, level2+1)
if list_tl is False:
list_tl = list_tr
t.extend(list_tl)
list_res.append(list(t))
return list_res
else:
return False
#####################################################
################### update List join magic ##########
#####################################################
def myZip_2(list_all, level, level2=1):
def create_listDown(list_all, level):
def subDown(list_a, level):
list_b = []
for l2 in list_a:
if type(l2) in [list, tuple]:
list_b.extend(l2)
else:
list_b.append(l2)
if level > 1:
list_b = subDown(list_b, level-1)
return list_b
list_tmp = []
if type(list_all) in [list, tuple]:
for l in list_all:
list_b = subDown(l, level-1)
list_tmp.append(list_b)
else:
list_tmp = list_all
return list_tmp
list_tmp = list_all.copy()
for x in range(level-1):
list_tmp = create_listDown(list_tmp, level)
list_r = []
l_min = []
for el in list_tmp:
if type(el) not in [list, tuple]:
break
l_min.append(len(el))
if l_min == []:
l_min = [0]
lm = min(l_min)
for elm in range(lm):
for el in list_tmp:
list_r.append(el[elm])
list_tmp = list_r
for lev in range(level-1):
list_tmp = [list_tmp]
return list_tmp
def joiner(list_all, level, level2=1):
list_tmp = []
if level > level2:
if type(list_all) in [list, tuple]:
for list_a in list_all:
if type(list_a) in [list, tuple]:
list_tmp.extend(list_a)
else:
list_tmp.append(list_a)
else:
list_tmp = list_all
list_res = joiner(list_tmp, level, level2=level2+1)
list_tmp = [list_res]
if level == level2:
if type(list_all) in [list, tuple]:
for list_a in list_all:
if type(list_a) in [list, tuple]:
list_tmp.extend(list_a)
else:
list_tmp.append(list_a)
else:
list_tmp.append(list_all)
if level < level2:
if type(list_all) in [list, tuple]:
for l in list_all:
list_tmp.append(l)
else:
list_tmp.append(l)
return list_tmp
def wrapper_2(l_etalon, list_a, level):
def subWrap(list_a, level, count):
list_b = []
if level == 1:
if len(list_a) == count:
for l in list_a:
list_b.append([l])
else:
dc = len(list_a)//count
for l in range(count):
list_c = []
for j in range(dc):
list_c.append(list_a[l*dc+j])
list_b.append(list_c)
else:
for l in list_a:
list_b = subWrap(l, level-1, count)
return list_b
def subWrap_2(l_etalon, len_l, level):
len_r = len_l
if type(l_etalon) in [list, tuple]:
len_r = len(l_etalon) * len_l
if level > 1:
len_r = subWrap_2(l_etalon[0], len_r, level-1)
return len_r
len_l = len(l_etalon)
lens_l = subWrap_2(l_etalon, 1, level)
list_tmp = subWrap(list_a, level, lens_l)
for l in range(level-1):
list_tmp = [list_tmp]
return list_tmp
#####################################################
############### debug settings magic ################
#####################################################
def sverchok_debug(mode):
global DEBUG_MODE
DEBUG_MODE = mode
return DEBUG_MODE
def setup_init():
global DEBUG_MODE
global HEAT_MAP
global SVERCHOK_NAME
SVERCHOK_NAME = bpy.types.SverchokPreferences.bl_idname
addon = bpy.context.user_preferences.addons.get(SVERCHOK_NAME)
if addon:
DEBUG_MODE = addon.preferences.show_debug
HEAT_MAP = addon.preferences.heat_map
#####################################################
############### heat map system ################
#####################################################
def heat_map_state(state):
global HEAT_MAP
HEAT_MAP = state
sv_ng = [ng for ng in bpy.data.node_groups if ng.bl_idname == 'SverchCustomTreeType']
if state:
for ng in sv_ng:
color_data = {node.name: (node.color[:], node.use_custom_color) for node in ng.nodes}
if not ng.sv_user_colors:
ng.sv_user_colors = str(color_data)
else:
for ng in sv_ng:
if not ng.sv_user_colors:
print("{0} has no colors".format(ng.name))
continue
color_data = ast.literal_eval(ng.sv_user_colors)
for name, node in ng.nodes.items():
if name in color_data:
color, use = color_data[name]
setattr(node, 'color', color)
setattr(node, 'use_custom_color', use)
ng.sv_user_colors = ""
#####################################################
############### update system magic! ################
#####################################################
def updateNode(self, context):
"""
When a node has changed state and need to call a partial update.
For example a user exposed bpy.prop
"""
global DEBUG_MODE
a = time.perf_counter()
sverchok_update(start_node=self)
b = time.perf_counter()
if DEBUG_MODE:
print("Partial update from node", self.name, "in", round(b-a, 4))
##############################################################
##############################################################
############## changable type of socket magic ################
########### if you have separate socket solution #############
#################### wellcome to provide #####################
##############################################################
##############################################################
# node has to have self veriables:
# self.typ = bpy.props.StringProperty(name='typ', default='')
# self.newsock = bpy.props.BoolProperty(name='newsock', default=False)
# and in update:
# inputsocketname = 'data' # 'data' - name of your input socket, that defines type
# outputsocketname = ['dataTrue','dataFalse'] # 'data...' - are names of your sockets to be changed
# changable_sockets(self, inputsocketname, outputsocketname)
def check_sockets(self, inputsocketname):
if type(self.inputs[inputsocketname].links[0].from_socket) == bpy.types.VerticesSocket:
if self.typ == 'v':
self.newsock = False
else:
self.typ = 'v'
self.newsock = True
if type(self.inputs[inputsocketname].links[0].from_socket) == bpy.types.StringsSocket:
if self.typ == 's':
self.newsock = False
else:
self.typ = 's'
self.newsock = True
if type(self.inputs[inputsocketname].links[0].from_socket) == bpy.types.MatrixSocket:
if self.typ == 'm':
self.newsock = False
else:
self.typ = 'm'
self.newsock = True
return
# cleaning of old not fited
def clean_sockets(self, outputsocketname):
for n in outputsocketname:
if n in self.outputs:
self.outputs.remove(self.outputs[n])
return
# main def for changable sockets type
def changable_sockets(self, inputsocketname, outputsocketname):
if len(self.inputs[inputsocketname].links) > 0:
check_sockets(self, inputsocketname)
if self.newsock:
clean_sockets(self, outputsocketname)
self.newsock = False
if self.typ == 'v':
for n in outputsocketname:
self.outputs.new('VerticesSocket', n, n)
if self.typ == 's':
for n in outputsocketname:
self.outputs.new('StringsSocket', n, n)
if self.typ == 'm':
for n in outputsocketname:
self.outputs.new('MatrixSocket', n, n)
else:
self.newsock = False
return
def get_socket_type(node, inputsocketname):
if type(node.inputs[inputsocketname].links[0].from_socket) == bpy.types.VerticesSocket:
return 'v'
if type(node.inputs[inputsocketname].links[0].from_socket) == bpy.types.StringsSocket:
return 's'
if type(node.inputs[inputsocketname].links[0].from_socket) == bpy.types.MatrixSocket:
return 'm'
def get_socket_type_full(node, inputsocketname):
# this is solution, universal and future proof.
return node.inputs[inputsocketname].links[0].from_socket.bl_idname
# it is real solution, universal
#if type(node.inputs[inputsocketname].links[0].from_socket) == bpy.types.VerticesSocket:
# return 'VerticesSocket'
#if type(node.inputs[inputsocketname].links[0].from_socket) == bpy.types.StringsSocket:
# return 'StringsSocket'
#if type(node.inputs[inputsocketname].links[0].from_socket) == bpy.types.MatrixSocket:
# return 'MatrixSocket'
###########################################
# Multysocket magic / множественный сокет #
###########################################
# utility function for handling n-inputs, for usage see Test1.py
# for examples see ListJoin2, LineConnect, ListZip
# min parameter sets minimum number of sockets
# setup two variables in Node class
# create Fixed inputs socket, the multi socket will not change anything
# below min
# base_name = StringProperty(default='Data ')
# multi_socket_type = StringProperty(default='StringsSocket')
def multi_socket(node, min=1, start=0, breck=False, output=False):
'''
min - integer, minimal number of sockets, at list 1 needed
start - integer, starting socket.
breck - boolean, adding brecket to nmae of socket x[0] x[1] x[2] etc
output - integer, deal with output, if>0 counts number of outputs multy sockets
base name added in separated node in self.base_name = 'some_name', i.e. 'x', 'data'
node.multi_socket_type - type of socket, added in self.multi_socket_type
as one of three sverchok types 'StringsProperty', 'MatricesProperty', 'VerticesProperty'
'''
#probably incorrect state due or init or change of inputs
# do nothing
if not len(node.inputs):
return
if min < 1:
min = 1
if not output:
if node.inputs[-1].links:
length = start + len(node.inputs)
if breck:
name = node.base_name + '[' + str(length) + ']'
else:
name = node.base_name + str(length)
node.inputs.new(node.multi_socket_type, name, name)
else:
while len(node.inputs) > min and not node.inputs[-2].links:
node.inputs.remove(node.inputs[-1])
else:
lenod = len(node.outputs)
if lenod < output:
length = output-lenod
for n in range(length):
if breck:
name = node.base_name + '[' + str(n+lenod-1) + ']'
else:
name = node.base_name + str(n+lenod-1)
node.outputs.new(node.multi_socket_type, name, name)
else:
while len(node.outputs) > output:
node.outputs.remove(node.outputs[-1])
#####################################
# node and socket id functions #
#####################################
# socket.name is not unique... identifier is
def socket_id(socket):
#return hash(socket)
return hash(socket.id_data.name+socket.node.name+socket.identifier)
# For when need a key for use with dict in node
# create a string property like this.
# n_id = StringProperty(default='')
# And a copy function
# def copy(self,node)
# self.n_id=''
# the always use like this
# n_id = node_id(self)
# node_dict[n_id]['key']
def node_id(node):
if not node.n_id:
node.n_id = str(hash(node) ^ hash(time.monotonic()))
return node.n_id
#####################################
# socket data cache #
#####################################
def SvGetSocketAnyType(self, socket, deepcopy=True):
out = SvGetSocket(socket, deepcopy)
if out:
return out
else:
return []
def SvSetSocketAnyType(self, socket_name, out):
SvSetSocket(self.outputs[socket_name], out)
return
# faster than builtin deep copy for us.
# useful for our limited case
# we should be able to specify vectors here to get them create
# or stop destroying them when in vector socket.
def sv_deep_copy(lst):
if isinstance(lst, (list, tuple)):
if lst and not isinstance(lst[0], (list, tuple)):
return lst[:]
return [sv_deep_copy(l) for l in lst]
return lst
# Build string for showing in socket label
def SvGetSocketInfo(socket):
def build_info(data):
if not data:
return str(data)
#if isinstance(data,list):
#return '['+build_info(data[0])
#elif isinstance(data,tuple):
#return '('+build_info(data[0])
else:
return str(data)
global socket_data_cache
ng = socket.id_data.name
if socket.is_output:
s_id = socket_id(socket)
elif socket.links:
s_id = socket_id(socket.links[0].from_socket)
else:
return ''
if ng in socket_data_cache:
if s_id in socket_data_cache[ng]:
data = socket_data_cache[ng][s_id]
if data:
return str(len(data))
return ''
def SvSetSocket(socket, out):
global socket_data_cache
if not socket.is_output:
print("Warning, setting input socket")
s_id = socket_id(socket)
s_ng = socket.id_data.name
if s_ng not in socket_data_cache:
socket_data_cache[s_ng] = {}
socket_data_cache[s_ng][s_id] = out
def SvGetSocket(socket, deepcopy=True):
global socket_data_cache
global DEBUG_MODE
if socket.links:
other = socket.links[0].from_socket
s_id = socket_id(other)
s_ng = other.id_data.name
if s_ng not in socket_data_cache:
return None
if s_id in socket_data_cache[s_ng]:
out = socket_data_cache[s_ng][s_id]
if deepcopy:
return sv_deep_copy(out)
else: