forked from simboden/BVtkNodes
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathconverters.py
2050 lines (1721 loc) · 65.9 KB
/
converters.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
from .core import l # Import logging
from .core import *
from .cache import BVTKCache
import bmesh
from vtk.util import numpy_support
try:
import pyopenvdb
with_pyopenvdb = True
except ImportError:
l.warning("pyopenvdb was not found (this is normal)")
with_pyopenvdb = False
# -----------------------------------------------------------------------------
# Converters from VTK to Blender
# -----------------------------------------------------------------------------
# Mesh Converters
# -----------------------------------------------------------------------------
class BVTK_Node_VTKToBlender(Node, BVTK_Node):
"""Legacy node for converting output from VTK Node to Blender Mesh Object.
Note: Not upgraded to new core.py. Superceded by VTK To Blender Mesh Node.
"""
bl_idname = "BVTK_Node_VTKToBlenderType" # type name
bl_label = "VTK To Blender" # label for nice name display
m_Name: bpy.props.StringProperty(name="Name", default="mesh")
smooth: bpy.props.BoolProperty(name="Smooth", default=False)
generate_material: bpy.props.BoolProperty(name="Generate Material", default=False)
def start_scan(self, context):
if context:
if self.auto_update:
bpy.ops.node.bvtk_auto_update_scan(
node_name=self.name, tree_name=context.space_data.node_tree.name
)
auto_update: bpy.props.BoolProperty(default=False, update=start_scan)
def m_properties(self):
return ["m_Name", "smooth", "generate_material"]
def m_connections(self):
return (["input"], [], [], [])
def draw_buttons(self, context, layout):
layout.prop(self, "m_Name")
layout.prop(self, "auto_update", text="Auto update")
layout.prop(self, "smooth", text="Smooth")
layout.prop(self, "generate_material")
layout.separator()
layout.operator("node.bvtk_node_update", text="update").node_path = node_path(
self
)
def update_cb(self):
"""Update node color bar and update Blender object"""
input_node, vtkobj = self.get_input_node("input")
color_mapper = None
if input_node and input_node.bl_idname == "BVTK_Node_ColorMapperType":
color_mapper = input_node
color_mapper.update() # setting auto range
input_node, vtkobj = input_node.get_input_node("input")
if vtkobj:
vtkobj = resolve_algorithm_output(vtkobj)
vtkdata_to_blender(
vtkobj, self.m_Name, color_mapper, self.smooth, self.generate_material
)
update_3d_view()
def apply_properties(self, vtkobj):
pass
def unwrap_and_color_the_mesh(
ob, vtk_obj, name, color_mapper, bm, generate_material, vimap
):
"""Create UV unwrap corresponding to a generated color image to color
the mesh. Also generates material if needed.
"""
# Set colors and color legend
if color_mapper and color_mapper.color_by:
texture = color_mapper.get_texture()
# Color Ramp texture_type is 'IMAGE'
image_width = 1000
img = image_from_ramp(texture.color_ramp, texture.name, image_width)
# Color legend
vrange = (color_mapper.min, color_mapper.max)
if color_mapper.lut:
create_lut(name, vrange, 6, texture, h=color_mapper.height)
# Generate UV maps to get coloring either by points or faces
bm.verts.index_update()
bm.faces.index_update()
if len(color_mapper.color_by) < 3:
return error_text
type_letter = color_mapper.color_by[0]
array_name = color_mapper.color_by[2:]
if type_letter == "P" or type_letter == "p":
bm, val = point_unwrap(bm, vtk_obj, array_name, vrange, vimap)
if val:
return val
elif type_letter == "C" or type_letter == "c":
bm, val = face_unwrap(bm, vtk_obj, array_name, vrange)
if val:
return val
else:
return error_text
# Generate default material if wanted
if generate_material and color_mapper and color_mapper.color_by:
create_material(ob, texture.name)
elif generate_material:
create_material(ob, None)
def vtkdata_to_blender(
data, name, color_mapper=None, smooth=False, generate_material=False
):
"""Convert VTK data to Blender mesh object, using optionally
given color mapper and normal smoothing. Optionally generates default
material, which includes also color information if color_mapper is given.
Note: This is the original implementation and does not consider
VTK cell types (vertex semantics) in conversion, so it works best
with polygon generators like vtkGeometryFilter.
"""
if not data:
l.error("no data!")
return
if issubclass(data.__class__, vtk.vtkImageData):
imgdata_to_blender(data, name)
return
me, ob = mesh_and_object(name)
if me.is_editmode:
bpy.ops.object.mode_set(mode="OBJECT", toggle=False)
err = 0 # Number of errors encountered
bm = bmesh.new()
# bm.from_mesh(me) # fill it in from a Mesh
# Get vertices
data_p = data.GetPoints()
verts = [bm.verts.new(data_p.GetPoint(i)) for i in range(data.GetNumberOfPoints())]
# Loop over cells to create edges and faces
for i in range(data.GetNumberOfCells()):
data_pi = data.GetCell(i).GetPointIds()
# Error is raised if a face already exists. Count errors.
try:
face_verts = [
verts[data_pi.GetId(x)] for x in range(data_pi.GetNumberOfIds())
]
# Remove last vert if it is same as first vert
if face_verts[-1] == face_verts[0]:
face_verts = face_verts[0:-1]
if len(face_verts) == 2:
e = bm.edges.new(face_verts)
else:
f = bm.faces.new(face_verts)
f.smooth = smooth
except:
err += 1
if err:
l.error("number of errors: " + str(err))
# Set normals
point_normals = data.GetPointData().GetNormals()
cell_normals = data.GetCellData().GetNormals()
if cell_normals:
bm.faces.ensure_lookup_table()
for i in range(len(bm.faces)):
bm.faces[i].normal = cell_normals.GetTuple(i)
if point_normals:
for i in range(len(verts)):
verts[i].normal = point_normals.GetTuple(i)
# Set colors and color legend
unwrap_and_color_the_mesh(ob, data, name, color_mapper, bm, generate_material)
bm.to_mesh(me) # store bmesh to mesh
l.info("conversion successful, verts = " + str(len(verts)))
class BVTK_Node_VTKToBlenderMesh(Node, BVTK_Node):
"""New surface mesh coverter node. Convert output from a VTK Node to a
Blender Mesh Object. Converts linear VTK cell types into a boundary mesh.
"""
bl_idname = "BVTK_Node_VTKToBlenderMeshType" # type name
bl_label = "VTK To Blender Mesh" # label for nice name display
m_Name: bpy.props.StringProperty(
name="Name", default="mesh", update=BVTK_Node.outdate_vtk_status
)
create_all_verts: bpy.props.BoolProperty(
name="Create All Verts", default=False, update=BVTK_Node.outdate_vtk_status
)
create_edges: bpy.props.BoolProperty(
name="Create Edges", default=True, update=BVTK_Node.outdate_vtk_status
)
create_faces: bpy.props.BoolProperty(
name="Create Faces", default=True, update=BVTK_Node.outdate_vtk_status
)
smooth: bpy.props.BoolProperty(
name="Smooth", default=False, update=BVTK_Node.outdate_vtk_status
)
recalc_norms: bpy.props.BoolProperty(
name="Recalculate Normals", default=False, update=BVTK_Node.outdate_vtk_status
)
generate_material: bpy.props.BoolProperty(
name="Generate Material", default=False, update=BVTK_Node.outdate_vtk_status
)
motion_blur: bpy.props.BoolProperty(
name="Motion Blur", default=False, update=BVTK_Node.outdate_vtk_status
)
motion_blur_by: bpy.props.StringProperty(
default="", name="Motion Blur By", update=BVTK_Node.outdate_vtk_status
)
motion_blur_time_step: bpy.props.FloatProperty(
default=1.0,name="Time Step for Motion Blur",update=BVTK_Node.outdate_vtk_status
)
def motion_blur_by_enum_generator(self, context=None):
"""Enum list generator for motion_blur property.
Generate array items available for coloring.
"""
items = [("None", "Empty (clear value)", "Empty (clear value)", ENUM_ICON, 0)]
(
input_node,
vtk_output_obj,
vtk_connection,
) = self.get_input_node_and_output_vtk_objects()
if vtk_output_obj:
if hasattr(vtk_output_obj, "GetPointData"):
p_data = vtk_output_obj.GetPointData()
p_descr = "Color by point data using "
for i in range(p_data.GetNumberOfArrays()):
arr_name = str(p_data.GetArrayName(i))
if p_data.GetArray(i).GetNumberOfComponents() != 3:
continue
items.append(
(
"P_" + arr_name,
arr_name,
p_descr + arr_name + " array",
"VERTEXSEL",
len(items),
)
)
return items
def motion_blur_set_value(self, context=None):
"""Set value of motion_blur_set_value using value from EnumProperty"""
if self.motion_blur_property_list == "None":
self.motion_blur_by = ""
else:
self.motion_blur_by = str(self.motion_blur_property_list)
motion_blur_property_list: bpy.props.EnumProperty(
items=motion_blur_by_enum_generator, update=motion_blur_set_value, name="Choices"
)
def m_properties(self):
return [
"m_Name",
"create_all_verts",
"create_edges",
"create_faces",
"smooth",
"recalc_norms",
"generate_material",
"motion_blur",
"motion_blur_by",
"motion_blur_time_step",
]
def m_connections(self):
return (["input"], [], [], [])
def draw_buttons_special(self, context, layout):
"""Custom draw buttons function, to show force update button. Force
update is sometimes necessary for e.g. vtkPlane when using
Blender object for specifying the plane. Changing Blender
object properties does not trigger property outdating for
nodes, so user must have an option for force updating the
upstream pipeline.
"""
layout.prop(self, "m_Name")
layout.prop(self, "create_all_verts")
layout.prop(self, "create_edges")
layout.prop(self, "create_faces")
layout.prop(self, "smooth")
layout.prop(self, "recalc_norms")
layout.prop(self, "generate_material")
layout.prop(self, "motion_blur")
if self.motion_blur:
row = layout.row(align=True)
row.prop(self, "motion_blur_by")
row.prop(self, "motion_blur_property_list", icon_only=True)
layout.prop(self,"motion_blur_time_step")
layout.operator("node.bvtk_node_force_update_upstream").node_path = node_path(
self
)
def apply_properties_special(self):
"""Generate Blender mesh object from VTK object"""
(
input_node,
vtk_output_obj,
vtk_connection,
) = self.get_input_node_and_output_vtk_objects()
color_mapper = None
if input_node and input_node.bl_idname == "BVTK_Node_ColorMapperType":
color_mapper = input_node
val = vtkdata_to_blender_mesh(
vtk_output_obj,
self.m_Name,
smooth=self.smooth,
create_all_verts=self.create_all_verts,
create_edges=self.create_edges,
create_faces=self.create_faces,
recalc_norms=self.recalc_norms,
generate_material=self.generate_material,
color_mapper=color_mapper,
motion_blur=self.motion_blur,
motion_blur_array_name = self.motion_blur_by,
motion_blur_time_step = self.motion_blur_time_step,
)
if val:
self.ui_message = val
return "error"
update_3d_view()
return "up-to-date"
def init_vtk(self):
self.set_vtk_status("out-of-date")
return None
def map_elements(vals, slist):
"""Create list of elements (possibly recursing into embedded lists)
with same structure as index list slist, where each element has
been mapped to a value in vals.
"""
dlist = []
for elem in slist:
if isinstance(elem, list):
dlist.append(map_elements(vals, elem))
else:
dlist.append(vals[elem])
return dlist
def add_verts_to_facelist(verts, facelist):
"""Help function to check and add verts to facelist"""
if len(set(verts)) > 2:
facelist.append(verts)
else:
l.debug("Skipping face, not enough unique verts: " + str(verts))
return facelist
def vtk_cell_to_edges_and_faces(cell_type, vis, polyfacelist):
"""Create lists of edge vertices and face vertices from argument VTK
cell type and VTK vertex ids. Polyfacelist is face stream for polyhedrons.
"""
# List of VTK cell types:
# https://vtk.org/doc/nightly/html/vtkCellType_8h_source.html
# https://lorensen.github.io/VTKExamples/site/VTKFileFormats/
def get_polyhedron_fis(polyfacelist):
"""Generate face vertex indices (fis) from argument polyhedron face
stream list
"""
# https://vtk.org/Wiki/VTK/Polyhedron_Support
next_number_is_vertex_count = True
fis = [] # list of vertex index lists, to be generated here
for n in polyfacelist[1:]:
if next_number_is_vertex_count:
numVerts = n
next_number_is_vertex_count = False
vertlist = []
else:
vertlist.append(n)
if len(vertlist) == numVerts:
fis.append(vertlist)
next_number_is_vertex_count = True
return fis
# Generate edge vertex lists and face vertex lists for each cell type
if cell_type < 3: # VTK_VERTEX or VTK_POLY_VERTEX are ignored here
return [None], [None]
elif cell_type == 3: # VTK_LINE
return [vis], [None]
elif cell_type == 4: # VTK_POLY_LINE
edgelist = [[vis[i], vis[i + 1]] for i in range(len(vis) - 1)]
return edgelist, [None]
elif cell_type == 5: # VTK_TRIANGLE
return [None], [vis]
elif cell_type == 6: # VTK_TRIANGLE_STRIP
facelist = []
from math import floor
# Pairwise triangle generation to get correct normal directions
for i in range(0, floor(len(vis) / 2), 2):
verts = [vis[i], vis[i + 1], vis[i + 2]]
facelist = add_verts_to_facelist(verts, facelist)
verts = [vis[i + 1], vis[i + 3], vis[i + 2]]
facelist = add_verts_to_facelist(verts, facelist)
# Last odd triangle
if len(vis) % 2 == 1:
verts = [vis[-3], vis[-2], vis[-1]]
facelist = add_verts_to_facelist(verts, facelist)
return [None], facelist
elif cell_type == 7: # VTK_POLYGON
return [None], [vis]
elif cell_type == 8: # VTK_PIXEL
return [None], [[vis[0], vis[1], vis[3], vis[2]]]
elif cell_type == 9: # VTK_QUAD
return [None], [vis]
elif cell_type == 10: # VTK_TETRA
fis = [[0, 2, 1], [0, 1, 3], [1, 2, 3], [0, 3, 2]]
facelist = map_elements(vis, fis)
return [None], facelist
elif cell_type == 11: # VTK_VOXEL
fis = [
[0, 1, 5, 4],
[0, 4, 6, 2],
[4, 5, 7, 6],
[1, 3, 7, 5],
[0, 2, 3, 1],
[6, 7, 3, 2],
]
facelist = map_elements(vis, fis)
return [None], facelist
elif cell_type == 12: # VTK_HEXAHEDRON
fis = [
[0, 3, 2, 1],
[0, 1, 5, 4],
[1, 2, 6, 5],
[2, 3, 7, 6],
[3, 0, 4, 7],
[7, 4, 5, 6],
]
facelist = map_elements(vis, fis)
return [None], facelist
elif cell_type == 13: # VTK_WEDGE (=prism)
fis = [[0, 1, 2], [0, 3, 4, 1], [1, 4, 5, 2], [2, 5, 3, 0], [3, 5, 4]]
facelist = map_elements(vis, fis)
return [None], facelist
elif cell_type == 14: # VTK_PYRAMID
fis = [[0, 3, 2, 1], [0, 4, 3], [3, 4, 2], [2, 4, 1], [1, 4, 0]]
facelist = map_elements(vis, fis)
return [None], facelist
elif cell_type == 15: # VTK_PENTAGONAL_PRISM
fis = [
[0, 1, 2, 3, 4],
[0, 5, 6, 1],
[1, 6, 7, 2],
[2, 7, 8, 3],
[3, 8, 9, 4],
[4, 9, 5, 0],
[9, 8, 7, 6, 5],
]
facelist = map_elements(vis, fis)
return [None], facelist
elif cell_type == 16: # VTK_HEXAGONAL_PRISM
fis = [
[0, 1, 2, 3, 4, 5],
[0, 6, 7, 1],
[1, 7, 8, 2],
[2, 8, 9, 3],
[3, 9, 10, 4],
[4, 10, 11, 5],
[5, 11, 6, 0],
[11, 10, 9, 8, 7, 6],
]
facelist = map_elements(vis, fis)
return [None], facelist
elif cell_type == 42: # VTK_POLYHEDRON
facelist = get_polyhedron_fis(polyfacelist)
return [None], facelist
else:
raise ValueError("Unsupported VTK cell type %d" % cell_type)
def process_cell_edge(edges, verts):
"""Add argument cell edge verts to edges dictionary"""
key = str(sorted(verts))
edges[key] = verts
return edges
def process_cell_face(faces, verts):
"""Add (or remove) argument cell face verts to (from) faces dictionary"""
# First make sure first vertex is not repeated at end
if verts[0] == verts[-1]:
verts = verts[0:-1]
# Discard face if same vertices are used many times.
# At least vtkContourFilter can produce such bad triangles.
if not (sorted(verts) == sorted(set(verts))):
l.debug("Discarding illegal face (verts %s)" % str(verts))
return faces
key = str(sorted(verts))
if key not in faces:
faces[key] = verts
else:
faces.pop(key)
return faces
def edges_and_faces_to_bmesh(
edges,
faces,
vcoords,
smooth,
bm,
create_all_verts,
create_edges,
create_faces,
recalc_norms,
):
"""Add argument verts, edges and faces using vertex coordinates
vcoords to bmesh bm.
"""
vertmap = {} # dictionary to map from VTK vertex index to BMVert
vimap = {} # map from bmesh vertex index to VTK vertex index
viset = set() # set to store added VTK vertex indices for fast access
def add_vert(vi, vertmap, vcoords, bm):
"""Add vertex index vi to bmesh if vertex is not there already"""
if vi not in vertmap:
v = bm.verts.new(vcoords[vi])
vertmap[vi] = v
def add_vi(vi, vimap, viset):
"""Add index of vertex to map from bmesh vertex index to VTK vertex index"""
if vi in viset:
return
i = len(vimap)
vimap[i] = vi
viset.add(vi)
# Create BMVerts
if create_all_verts:
for vi in range(len(vcoords)):
add_vert(vi, vertmap, vcoords, bm)
add_vi(vi, vimap, viset)
# Create BMEdges
if create_edges:
for vi1, vi2 in edges.values():
add_vert(vi1, vertmap, vcoords, bm)
add_vert(vi2, vertmap, vcoords, bm)
add_vi(vi1, vimap, viset)
add_vi(vi2, vimap, viset)
bm.edges.new([vertmap[vi1], vertmap[vi2]])
# Create BMFaces
for vis in faces.values():
if len(set(vis)) < 3:
l.debug("Skipping face with verts " + str(vis))
continue
for vi in vis:
add_vert(vi, vertmap, vcoords, bm)
add_vi(vi, vimap, viset)
f = bm.faces.new(map_elements(vertmap, vis))
f.smooth = smooth
if not create_faces:
bmesh.ops.delete(bm, geom=bm.faces, context="FACES_ONLY")
if not create_edges and not create_faces:
bmesh.ops.delete(bm, geom=bm.edges, context="EDGES_FACES")
if recalc_norms:
bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
else:
# Force normal updates. Without normal updates use of smooth
# option will result in surfaces being rendered as black.
for f in bm.faces:
f.normal_update()
for v in bm.verts:
v.normal_update()
return vimap
def vtkdata_to_blender_mesh(
vtk_obj,
name,
create_all_verts=False,
create_edges=True,
create_faces=True,
color_mapper=None,
smooth=False,
recalc_norms=False,
generate_material=False,
motion_blur=False,
motion_blur_array_name=None,
motion_blur_time_step=1.0,
):
"""Convert linear and polyhedron VTK cells into a boundary Blender
surface mesh object.
"""
from mathutils import Vector
if not vtk_obj:
return "No VTK object on input"
if issubclass(vtk_obj.__class__, vtk.vtkImageData):
imgdata_to_blender(vtk_obj, name)
return
me, ob = mesh_and_object(name)
if me.is_editmode:
bpy.ops.object.mode_set(mode="OBJECT", toggle=False)
# Initialize the Basis shape key for mesh motion blur
if motion_blur and not ob.data.shape_keys:
ob.shape_key_add(name="Basis", from_mix=False)
# Get all VTK vertex coordinates
data_p = vtk_obj.GetPoints()
vcoords = [data_p.GetPoint(i) for i in range(vtk_obj.GetNumberOfPoints())]
faces = {} # dictionary of boundary face vertices to be created
edges = {} # dictionary of non-face edges to be created
# Process all VTK cells
for i in range(vtk_obj.GetNumberOfCells()):
data_pi = vtk_obj.GetCell(i).GetPointIds()
vert_ids = [data_pi.GetId(x) for x in range(data_pi.GetNumberOfIds())]
cell_type = vtk_obj.GetCell(i).GetCellType()
polyfacelist = []
# Polyhedrons need additional polyfacelist (face stream in VTK terminology)
# https://vtk.org/Wiki/VTK/Polyhedron_Support
if cell_type == 42:
fs = vtk.vtkIdList()
vtk_obj.GetFaceStream(i, fs)
polyfacelist = [fs.GetId(ind) for ind in range(fs.GetNumberOfIds())]
edge_vis, face_vis = vtk_cell_to_edges_and_faces(
cell_type, vert_ids, polyfacelist
)
# l.debug("cell %d: edge_vis: %s" % (i, str(edge_vis))
# + " face_vis: %s" % str(face_vis))
for vis in edge_vis:
if vis == None:
continue
edges = process_cell_edge(edges, vis)
for vis in face_vis:
if vis == None:
continue
faces = process_cell_face(faces, vis)
# Create mesh from remaining faces
bm = bmesh.new()
vimap = edges_and_faces_to_bmesh(
edges,
faces,
vcoords,
smooth,
bm,
create_all_verts,
create_edges,
create_faces,
recalc_norms,
)
val = unwrap_and_color_the_mesh(
ob, vtk_obj, name, color_mapper, bm, generate_material, vimap
)
# Mesh motion blur
if motion_blur:
nFrame = bpy.context.scene.frame_current
l.debug("Set up motion blur for frame %d" % nFrame)
if ((not bm.verts.layers.shape.keys()) or \
(not "key_blur" in bm.verts.layers.shape.keys())):
key_shape = bm.verts.layers.shape.new("key_blur")
else:
key_shape = bm.verts.layers.shape["key_blur"]
if len(motion_blur_array_name) < 3:
return "Motion blur array name is wrong (minimum 3 letters)"
array_data = get_vtk_array_data(vtk_obj, motion_blur_array_name[2:], array_type=motion_blur_array_name[0])
if not array_data:
return "Did not find point array %r" % motion_blur_array_name[2:]
array_data = numpy_support.vtk_to_numpy(array_data)
# Calculate shape key coordinates
for i, bv in enumerate(bm.verts):
bv[key_shape] = bv.co + motion_blur_time_step * Vector(array_data[i])
bm.to_mesh(me)
# Add keyframes to shape key Value parameter to animate motion blur
if motion_blur:
ob.data.shape_keys.animation_data_clear()
kb = ob.data.shape_keys.key_blocks["key_blur"]
kb.value = 1.0
kb.keyframe_insert("value", frame=nFrame+1)
kb.value = 0.0
kb.keyframe_insert("value", frame=nFrame)
# Set FCurve interpolation to linear (default is bezier).
# Setting kb.interpolation="KEY_LINEAR" does not produce linear interpolation.
ob.data.shape_keys.animation_data.action.fcurves[0].keyframe_points[0].interpolation='LINEAR'
ob.data.shape_keys.animation_data.action.fcurves[0].keyframe_points[1].interpolation='LINEAR'
bpy.context.scene.cycles.use_motion_blur = True
bpy.context.scene.eevee.use_motion_blur = True
# Must use "Start on Frame" Position for motion blur to avoid frame changes
bpy.context.scene.cycles.motion_blur_position = "START"
bpy.context.scene.eevee.motion_blur_position = "START"
bpy.context.scene.view_layers.update()
if val:
start_info = "Coloring failed,"
else:
start_info = "Conversion successful,"
l.info(
start_info
+ " verts:%d" % len(bm.verts)
+ " edges:%d" % len(bm.edges)
+ " faces:%d" % len(bm.faces)
)
return val
# -----------------------------------------------------------------------------
# Particle converter
# -----------------------------------------------------------------------------
class BVTK_OT_InitializeParticleSystem(bpy.types.Operator):
"""Operator to initialize Blender Particle system for VTK To Blender
Particles node.
"""
bl_idname = "node.bvtk_initialize_particle_system"
bl_label = "Initialize Particles"
def execute(self, context):
nSystems = 0
for node_group in bpy.data.node_groups:
for node in node_group.nodes:
if node.bl_idname == "BVTK_Node_VTKToBlenderParticlesType":
nSystems += 1
zero_particle_system(node)
self.report({"INFO"}, "Initialized %d Particle Systems." % nSystems)
return {"FINISHED"}
def zero_particle_system(node):
"""Reinitialize Blender Particle System for argument node"""
obname = node.ob_name
glyph_obname = node.glyph_name
np = node.np
# Delete existing any old object
if obname in bpy.data.objects:
bpy.context.view_layer.objects.active = bpy.data.objects[obname]
mesh = bpy.data.objects[obname].data
bpy.ops.object.mode_set(mode="OBJECT")
bpy.ops.object.select_all(action="DESELECT")
bpy.data.objects[obname].select_set(True)
bpy.ops.object.particle_system_remove()
bpy.ops.object.parent_clear()
bpy.ops.object.delete()
bpy.data.meshes.remove(mesh)
# Reset material on glyph object, get material
matname = obname + "_material"
if node.generate_material:
glyph_ob = bpy.data.objects[node.glyph_name]
mat = reset_particle_material(glyph_ob, matname)
else:
mat = bpy.data.materials[matname]
mesh_data = bpy.data.meshes.new(obname)
ob = bpy.data.objects.new(obname, mesh_data)
bpy.context.scene.collection.objects.link(ob)
bpy.context.view_layer.objects.active = bpy.data.objects[obname]
ob.select_set(True)
# Must have some geometry from where to emit particles
bpy.ops.object.mode_set(mode="EDIT")
bpy.ops.mesh.primitive_cube_add(size=1e-6) # TODO: Improve
bpy.ops.object.mode_set(mode="OBJECT")
# Set glyph material to particles object
bpy.ops.object.material_slot_add()
ob.active_material = mat
# Add and parent particle system
bpy.ops.object.particle_system_add()
bpy.ops.object.select_all(action="DESELECT")
bpy.data.objects[glyph_obname].select_set(True)
bpy.ops.object.parent_set()
ob.particle_systems[0].settings.count = np
ob.particle_systems[0].settings.frame_start = 0
ob.particle_systems[0].settings.frame_end = 0
ob.particle_systems[0].settings.lifetime = 1000000
ob.particle_systems[0].settings.physics_type = "NO"
ob.particle_systems[0].settings.render_type = "OBJECT"
ob.particle_systems[0].settings.particle_size = 1.0
ob.particle_systems[0].settings.instance_object = bpy.data.objects[glyph_obname]
ob.particle_systems[0].settings.emit_from = "VERT"
ob.particle_systems[0].settings.normal_factor = 0.0
# ob.particle_systems[0].settings.object_align_factor[1] = 1.0
ob.show_instancer_for_viewport = True
class BVTK_Node_VTKToBlenderParticles(Node, BVTK_Node):
"""Convert output from VTK Node to Blender Particle System"""
bl_idname = "BVTK_Node_VTKToBlenderParticlesType" # type name
bl_label = "VTK To Blender Particles" # label for nice name display
ob_name: bpy.props.StringProperty(
name="Name", default="particles", update=BVTK_Node.outdate_vtk_status
)
glyph_name: bpy.props.StringProperty(
name="Glyph Name", default="glyph", update=BVTK_Node.outdate_vtk_status
)
vec_name: bpy.props.StringProperty(
name="Direction Vector Array Name",
default="",
update=BVTK_Node.outdate_vtk_status,
)
scale_name: bpy.props.StringProperty(
name="Scale Value or Name", default="", update=BVTK_Node.outdate_vtk_status
)
color_name: bpy.props.StringProperty(
name="Color Value Array Name", default="", update=BVTK_Node.outdate_vtk_status
)
np: bpy.props.IntProperty(
name="Particle Count", default=1000, min=1, update=BVTK_Node.outdate_vtk_status
)
generate_material: bpy.props.BoolProperty(
name="Generate Material", default=True, update=BVTK_Node.outdate_vtk_status
)
# Data storage for point data from VTK
from typing import List
locs: List[float]
scales: List[float]
color_values: List[float]
quats: List[float]
nParticles: float
def m_properties(self):
return [
"ob_name",
"glyph_name",
"vec_name",
"scale_name",
"color_name",
"np",
"generate_material",
]
def m_connections(self):
return (["input"], [], [], [])
def draw_buttons_special(self, context, layout):
layout.prop(self, "ob_name")
layout.prop(self, "glyph_name")
layout.prop(self, "vec_name")
layout.prop(self, "scale_name")
layout.prop(self, "color_name")
layout.prop(self, "np")
layout.prop(self, "generate_material")
layout.operator("node.bvtk_initialize_particle_system", text="Initialize")
def update_particle_system(self, depsgraph):
"""Updates Blender Particle System from point data in vtkPolyData"""
(
input_node,
vtk_output_obj,
vtk_connection,
) = self.get_input_node_and_output_vtk_objects()
if not vtk_output_obj:
return
l.debug("Updating Particle System for Object %r" % self.ob_name)
if not vtk_output_obj:
l.error("No vtkdata!")
return
if not issubclass(vtk_output_obj.__class__, vtk.vtkPolyData):
l.error("Data is not vtkPolyData!")
return
npoints = get_vtk_particle_data(self, vtk_output_obj)
if npoints == 0:
return
vtkdata_to_blender_particles(self, depsgraph)
update_3d_view()
def apply_properties_special(self):
warning_text = warn_if_not_exist_object(self.glyph_name)
if warning_text:
self.ui_message = warning_text
return "error"
# Note: update_particle_system is called from on_frame_change
# and not here, because it requires depsgraph.
return "up-to-date"
def init_vtk(self):
self.set_vtk_status("out-of-date")
return None
def truncate_or_pad_list(slist, n):
"""Truncate or pad the argument list slist to contain exacly n entries"""
# Truncate
length = len(slist)
if length >= n:
return slist[0:n]
# Pad
if type(slist[0]) is list:
element = [0.0 * i for i in slist[0]]
elif type(slist[0]) is tuple:
element = tuple([0.0 * i for i in slist[0]])
else:
element = 0.0
newlist = list(slist)
for i in range(n - length):
newlist.append(element)
return newlist
def get_array_data(pointdata, array_name):
"""Return vtkArray from VTK point data for given array name"""
narrays = pointdata.GetNumberOfArrays()
if narrays == 0:
return None
array_names = [pointdata.GetArrayName(i) for i in range(narrays)]
if array_name not in array_names:
return None
arrdata = pointdata.GetArray(array_names.index(array_name))
return arrdata
def color_scale(vals):
"""Scale list of values to 0.0 <= x <= 1.0"""
minval = min(vals)
maxval = max(vals)
# Force a small difference to avoid div by zero
if maxval <= minval:
minval = 0.99999 * minval
maxval = 1.00001 * minval
return [(v - minval) / (maxval - minval) for v in vals]
def get_vtk_particle_data(self, vtkdata):
"""Get lists of particle properties from vtkPolyData and store those
to self storage variables.
"""
n = vtkdata.GetNumberOfPoints()