-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvtk_utils.py
executable file
·2085 lines (1541 loc) · 70.6 KB
/
vtk_utils.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
import warnings
import numpy as np
from scipy.special import sph_harm
import matplotlib.pyplot as plt
from scipy.spatial.transform import Rotation as R
import sys
import os
import config
from vtk.util import numpy_support
import PIL
import vtk
import LUT_utils
import interactor_utils
import physics_utils
def vtk_render():
phi, theta = np.mgrid[0:2*np.pi:config.granularity*1j, 0:np.pi:config.granularity*1j]
# print(globals()["savename"])
r = physics_utils.calculate_r(config.A, config.B2, config.M2, config.B3, config.M3, config.B4, config.M4, theta, phi)
if config.secondary_scalar is not None:
r += (config.secondary_scalar.T) * config.h3
config.initial_values=dict()
config.initial_values.update({'A':config.A, 'b2':config.B2, 'b3':config.B3, 'b4':config.B4, 'm2':config.M2, 'm3':config.M3, 'm4':config.M4})
print('press \'r\' to reset camera')
print('press \'o\' to toggle orthogonal projection')
print('press \'w\' to render as wireframe')
print('press \'s\' to render as surface')
print('press \'i\' to change display type (flat, smooth, reflective)')
print('press \'e\' or \'q\' to exit')
nuclear_shape = add_spherical_function(r, add_gridlines=False, secondary_scalars=config.secondary_scalar, colormap=config.colormap)
# nuclear_shape = add_textures_to_actor(nuclear_shape[list(nuclear_shape.keys())[0]], material='treadplate')
actor_dict = dict()
actor_dict.update({'shape': nuclear_shape})
render_window = render(actors=actor_dict)
return render_window
def write_gltf(source, verbose=True):
savename = config.savename
if verbose:
print('Writing GLTF to %s' % savename)
try:
exporter = vtk.vtkGLTFExporter()
except AttributeError:
print('Gltf exporting is not supported in your version of VTK, try updating')
exporter.SetInput(source)
exporter.InlineDataOn()
exporter.SaveNormalOn()
exporter.SetFileName(savename)
exporter.Update()
exporter.Write()
if verbose:
print('File written')
def colorbar(actor,
interactor=None,
title='Radius',
orientation='vertical',
return_widget=True,
total_ticks=10,
background=True,
opacity=1.0):
"""[Adds a colorbar to the interactor]
Arguments:
interactor {[VTK Interactor]} -- [the interactor used by VTK]
title {[string]} -- [the title of the colorbar]
mapper {[VTK mapper]} -- [the VTK mapper used to grab color values]
Keyword Arguments:
orientation {str} -- [orientation of the colorbar] (default: {'vertical'})
return_widget {bool} -- [returns the colorbar as a widget instead] (default: {True})
Returns:
[type] -- [description]
"""
print('adding colorbar')
if type(actor) == vtk.vtkScalarBarActor:
scalar_bar = actor
else:
scalar_bar = vtk.vtkScalarBarActor()
scalar_bar.SetLookupTable(actor.GetMapper().GetLookupTable())
# print(scalar_bar)
# print(sorted(dir(scalar_bar)))
scalar_bar.GetLabelTextProperty().SetColor(0.0, 0.0, 0.0)
scalar_bar.GetLabelTextProperty().SetFontFamilyToArial()
scalar_bar.GetLabelTextProperty().ItalicOff()
# scalar_bar.GetLabelTextProperty().ShadowOff()
# scalar_bar.GetLabelTextProperty().FrameOn()
scalar_bar.GetLabelTextProperty().SetShadowOffset(0,0)
scalar_bar.GetLabelTextProperty().GetShadowColor((1,1,1))#.SetValue(1,1,1)
# scalar_bar.GetLabelTextProperty().SetBackgroundOpacity(0.5)
# scalar_bar.GetLabelTextProperty().SetBackgroundColor(1.0, 1.0, 1.0)
# print('SHADOW', scalar_bar.GetLabelTextProperty().GetShadow())
scalar_bar.SetTitle(title)
scalar_bar.GetTitleTextProperty().SetColor(0.0, 0.0, 0.0)
# scalar_bar.SetUnconstrainedFontSize(40)
scalar_bar.GetTitleTextProperty().SetFontFamilyToArial()
scalar_bar.GetTitleTextProperty().ShadowOff()
scalar_bar.GetTitleTextProperty().ItalicOff()
scalar_bar.AnnotationTextScalingOn()
scalar_bar.SetVerticalTitleSeparation(10)
scalar_bar.UseOpacityOff()
scalar_bar.Modified()
# print(dir(scalar_bar))
if orientation == 'Horizontal':
scalar_bar.SetOrientationToHorizontal()
else:
scalar_bar.SetOrientationToVertical()
scalar_bar.SetWidth(0.1)
# scalar_bar.SetHeight(0.1)
scalar_bar.SetVisibility(1)
scalar_bar.SetNumberOfLabels(total_ticks)
scalar_bar.UseOpacityOn()
if background:
scalar_bar.DrawBackgroundOn()
scalar_bar.GetBackgroundProperty().SetOpacity(opacity)
# scalar_bar.SetWidth(10)
scalar_bar.SetBarRatio(0.85)
# create the scalar_bar_widget
if return_widget:
global scalar_bar_widget
scalar_bar_widget = vtk.vtkScalarBarWidget()
scalar_bar_widget.SetInteractor(interactor)
scalar_bar_widget.SetScalarBarActor(scalar_bar)
scalar_bar_widget.On()
scalar_bar_widget.ResizableOn()
# print(scalar_bar, scalar_bar_widget)
return scalar_bar_widget
return scalar_bar
def read_texture(filename, file_type='jpg', useSRGB=False):
if file_type == '.png':
color = vtk.vtkPNGReader()
if file_type == '.jpg':
color = vtk.vtkJPEGReader()
elif file_type == '.tiff':
warnings.warn('TIFF images may produce odd effects, JPEGs or PNGs are recommended')
color = vtk.vtkTIFFReader()
elif file_type == '.tif':
warnings.warn('TIFF images may produce odd effects, JPEGs or PNGs are recommended')
color = vtk.vtkTIFFReader()
color.SetFileName(filename)
color_texture = vtk.vtkTexture()
color_texture.SetInputConnection(color.GetOutputPort())
if useSRGB:
color_texture.UseSRGBColorSpaceOn()
return color_texture
def read_texture_directory(folder_path, color=None, texture_size=[1024,1024], fallback_ORM=[128,0,0], fallback_normals=[128,128, 255], fallback_height=128):
file_type = '.jpg'
if color is None:
albedofile = folder_path + os.sep + "albedo" + file_type
else:
albedofile = folder_path + os.sep + color + file_type
if not os.path.isfile(albedofile):
file_type = '.png'
if color is None:
albedofile = folder_path + os.sep + "albedo" + file_type
else:
albedofile = folder_path + os.sep + color + file_type
if not os.path.isfile(albedofile):
file_type = '.tif'
if color is None:
albedofile = folder_path + os.sep + "albedo" + file_type
else:
albedofile = folder_path + os.sep + color + file_type
if not os.path.isfile(albedofile):
print('can\'t find textures in directory:', folder_path)
albedo_texture = read_texture(albedofile, useSRGB=True, file_type=file_type)
normalfile = folder_path + os.sep + "normal" + file_type
heightfile = folder_path + os.sep + "height" + file_type
emissivefile = folder_path + os.sep + "emissive" + file_type
ormfile = folder_path + os.sep + "orm" + file_type
a = np.array(PIL.Image.open(albedofile))
if np.ndim(a) == 3:
a = a[:,:,0]
texture_size = a.shape
if os.path.isfile(ormfile):
orm_texture = read_texture(ormfile, file_type=file_type)
else:
print('Can\'t find ORM file, assuming seperate Occlusion, Roughness & Metalicity')
occlusionfile = folder_path + os.sep + "ao" + file_type
roughnessfile = folder_path + os.sep + "roughness" + file_type
specularfile = folder_path + os.sep + "specular" + file_type
metalfile = folder_path + os.sep + "metallic" + file_type
if os.path.isfile(occlusionfile):
o = np.array(PIL.Image.open(occlusionfile))
if np.ndim(o) == 3:
o = o[:,:,0]
else:
print('Occlusion file not found, using fallback value: %f' % fallback_ORM[0])
o = np.ones(texture_size) * fallback_ORM[0]
if os.path.isfile(roughnessfile):
r = np.array(PIL.Image.open(roughnessfile))
if np.ndim(r) == 3:
r = r[:,:,0]
elif os.path.isfile(specularfile):
r = 1 - np.array(PIL.Image.open(specularfile))
if np.ndim(r) == 3:
r = r[:,:,0]
print(r)
else:
print('Roughness file not found, using fallback value: %f' % fallback_ORM[1])
r = np.ones(texture_size) * fallback_ORM[1]
if os.path.isfile(metalfile):
m = np.array(PIL.Image.open(metalfile))
if np.ndim(m) == 3:
m = m[:,:,0]
else:
print('Metalicity file not found, using fallback value: %f' % fallback_ORM[2])
m = np.ones(texture_size) * fallback_ORM[2]
orm = np.dstack([o,r,m])
orm_image = PIL.Image.fromarray(orm.astype(np.uint8))
print('saving new ORM texture to %s' % ormfile)
orm_image.save(ormfile)
orm_texture = read_texture(ormfile, file_type=file_type)
if os.path.isfile(normalfile):
normal_texture = read_texture(normalfile, file_type=file_type)
else:
print('Normal file not found, creating fallback')
normal_array = np.ones([*a.shape, 3]) * fallback_normals
normal_image = PIL.Image.fromarray(normal_array.astype(np.uint8))
normal_image.save(normalfile)
normal_texture = read_texture(normalfile, file_type=file_type)
texture_dict = dict()
texture_dict.update({'albedo':albedo_texture})
texture_dict.update({'normal':normal_texture})
texture_dict.update({'ORM':orm_texture})
if os.path.isfile(heightfile):
height_texture = read_texture(heightfile, useSRGB=True, file_type=file_type)
texture_dict.update({'height':height_texture})
else:
pass
if os.path.isfile(emissivefile):
emissive_texture = read_texture(emissivefile, useSRGB=True, file_type=file_type)
texture_dict.update({'emissive':emissive_texture})
else:
pass
return texture_dict
def generate_texture_coords(uResolution, vResolution, pd):
"""
Generate u, v texture coordinates on a parametric surface.
:param uResolution: u resolution
:param vResolution: v resolution
:param pd: The polydata representing the surface.
:return: The polydata with the texture coordinates added.
"""
print('Can\'t find texture coordinates, making new ones')
numPts = pd.GetNumberOfPoints()
if ((uResolution is None) or (vResolution is None)):
limit = int(np.floor(np.sqrt(numPts)))
uResolution = limit
vResolution = limit
elif numPts < (uResolution * vResolution):
limit = int(np.floor(np.sqrt(numPts)))
warnings.warn('Texture coords set too high, setting both to: %i' % limit)
uResolution = limit
vResolution = limit
u0 = 1.0
v0 = 0.0
du = 1.0 / (uResolution - 1)
dv = 1.0 / (vResolution - 1)
tCoords = vtk.vtkFloatArray()
tCoords.SetNumberOfComponents(2)
tCoords.SetNumberOfTuples(numPts)
tCoords.SetName('Texture Coordinates')
ptId = 0
u = u0
for i in range(0, uResolution):
v = v0
for j in range(0, vResolution):
tc = [u, v]
# print(ptId, tc)
tCoords.SetTuple(ptId, tc)
v += dv
ptId += 1
u -= du
pd.GetPointData().SetTCoords(tCoords)
return pd, tCoords
def add_textures_to_actor(actor, material=None, texture_dir='textures', color=None, occlusion=0.5, roughness=1, metallic=1, normal_scale=1, height_scale=0.01, emissive=(1,1,1), uResolution=None, vResolution=None, use_heightmap=False, method='vtk', texture_scale=(1,1,1), verbose=False):
fallback_ORM = np.asarray([occlusion, roughness, metallic]) * 255
# actor.GetProperty().SetInterpolationToPBR()
tex = actor.GetTexture()
if tex is None:
print('reading textures from', texture_dir + os.sep + material)
if material is not None:
texture_dict = read_texture_directory(texture_dir + os.sep + material, fallback_ORM=fallback_ORM, color=color)
else:
texture_dict = read_texture_directory(texture_dir, fallback_ORM=fallback_ORM, color=color)
# if (('height' in texture_dict) and (use_heightmap)):
# if material is not None:
# filepath = texture_dir + material + '/height.jpg'
# else:
# filepath = texture_dir + 'height.jpg'
# reader = vtk.vtkJPEGReader()
# if not os.path.isfile(filepath):
# if material is not None:
# filepath = texture_dir + material + '/height.png'
# else:
# filepath = texture_dir + 'height.png'
# reader = vtk.vtkPNGReader()
# if not os.path.isfile(filepath):
# if material is not None:
# filepath = texture_dir + material + '/height.tiff'
# else:
# filepath = texture_dir + 'height.tiff'
# reader = vtk.vtkTIFFReader()
# if verbose:
# print('Height displacement enabled, using %s' % filepath)
# reader.SetFileName(filepath)
# reader.Update()
# image_extents = np.asarray(reader.GetDataExtent())
# image_size = np.asarray([image_extents[1] - image_extents[0], image_extents[3] - image_extents[2], image_extents[5] - image_extents[4]])
# current_tocoords = actor.GetMapper().GetInput().GetPointData().GetTCoords()
# # print('Current Coordinates', current_tocoords)
# if current_tocoords is not None:
# mapper = actor.GetMapper()
# probe_points = vtk.vtkPoints()
# # print(current_tocoords)
# # print(image_size)
# probe_points.SetNumberOfPoints(current_tocoords.GetNumberOfTuples())
# # print(probe_points.GetDataType())
# # print(dir(probe_points))
# np_coords = numpy_support.vtk_to_numpy(current_tocoords)
# n_0 = np.zeros([current_tocoords.GetNumberOfTuples(),1])
# new_coords = numpy_support.numpy_to_vtk(np.hstack([np_coords, n_0]) * image_size)
# # probe_points.SetNumberOfComponents(new_coords.GetNumberOfComponents())
# probe_points.SetData(new_coords)
# probe_poly = vtk.vtkPolyData()
# probe_poly.SetPoints(probe_points)
# else:
# pd = generate_texture_coords(uResolution, vResolution, actor.GetMapper().GetInput())
# tcoords = pd.GetPointData().GetTCoords()
# probe_points = vtk.vtkPoints()
# probe_points.SetNumberOfPoints(tcoords.GetNumberOfValues())
# np_coords = numpy_support.vtk_to_numpy(tcoords)
# n_0 = np.zeros([tcoords.GetNumberOfTuples(),1])
# probe_points.SetData(numpy_support.numpy_to_vtk(np.hstack([np_coords, n_0]) * image_size))
# probe_poly = vtk.vtkPolyData()
# probe_poly.SetPoints(probe_points)
# current_tocoords = probe_poly
# probes = vtk.vtkProbeFilter()
# probes.SetSourceData(reader.GetOutput())
# probes.SetInputData(probe_poly)
# probes.Update()
# actor.GetMapper().GetInput().GetPointData().SetScalars(probes.GetOutput().GetPointData().GetScalars())
# warp = vtk.vtkWarpScalar()
# warp.SetInputData(actor.GetMapper().GetInput())
# warp.SetScaleFactor(height_scale)
# warp.Update()
# mapper = vtk.vtkPolyDataMapper()
# mapper.SetInputConnection(warp.GetOutputPort())
# mapper.GetInput().GetPointData().SetScalars(None)
# smoothing_passes = 1
# if smoothing_passes is not None:
# if verbose:
# print('Smoothing mesh, may take a while')
# smooth_loop = vtk.vtkSmoothPolyDataFilter()
# smooth_loop.SetNumberOfIterations(smoothing_passes)
# smooth_loop.SetRelaxationFactor(0.5)
# smooth_loop.BoundarySmoothingOn()
# smooth_loop.SetInputData(mapper.GetInput())
# smooth_loop.Update()
# mapper = vtk.vtkPolyDataMapper()
# mapper.SetInputConnection(smooth_loop.GetOutputPort())
# # tcoords_np = numpy_support.vtk_to_numpy(current_tocoords)
# # print(tcoords_np.shape)
# # plt.figure()
# # plt.scatter(tcoords_np[:,0], tcoords_np[:,1])
# # plt.show()
# else:
# # # print(actor)
# # current_tocoords = actor.GetMapper().GetInput().GetPointData().GetTCoords()
# # tcoords_np = numpy_support.vtk_to_numpy(current_tocoords)
# # # print(tcoords_np)
# # plt.figure()
# # plt.scatter(tcoords_np[:,0], tcoords_np[:,1])
# # plt.show()
# # print('current texture coordinates', current_tocoords)
mapper = actor.GetMapper()
current_tcoords = mapper.GetInput().GetCellData().GetTCoords()
if current_tcoords is None:
pd, tcords = generate_texture_coords(uResolution, vResolution, mapper.GetInput())
# tangents = vtk.vtkPolyDataTangents()
# tangents.SetComputePointTangents(True)
# tangents.SetComputeCellTangents(True)
# tangents.SetInputData(pd)
# tangents.Update()
mapper.SetInputData(pd)
# mapper.SetInputConnection(tangents.GetOutputPort())
mapper.GetInput().GetPointData().SetTCoords(tcords)
mapper.GetInput().GetCellData().SetTCoords(tcords)
mapper.Modified()
# print(tcords)
else:
pass
# actor.SetMapper(mapper)
if tex is None:
actor.GetProperty().SetRoughness(roughness)
actor.GetProperty().SetMetallic(metallic)
actor.GetProperty().SetOcclusionStrength(occlusion)
actor.GetProperty().SetNormalScale(normal_scale)
actor.GetProperty().SetEmissiveFactor(emissive)
actor.SetTexture(texture_dict['albedo'])
# actor.GetProperty().SetBaseColorTexture(texture_dict['albedo'])
actor.GetProperty().SetNormalTexture(texture_dict['normal'])
actor.GetProperty().SetORMTexture(texture_dict['ORM'])
if 'emissive' in texture_dict:
actor.GetProperty().SetEmissiveTexture(texture_dict['emissive'])
return actor
def ReadCubeMap(folderRoot, fileRoot, ext, key, flip_axis=1):
"""
Read the cube map.
:param folderRoot: The folder where the cube maps are stored.
:param fileRoot: The root of the individual cube map file names.
:param ext: The extension of the cube map files.
:param key: The key to data used to build the full file name.
:return: The cubemap texture.
"""
# A map of cube map naming conventions and the corresponding file name
# components.
fileNames = {
0: ['right', 'left', 'top', 'bottom', 'front', 'back'],
1: ['posx', 'negx', 'posy', 'negy', 'posz', 'negz'],
2: ['px', 'nx', 'py', 'ny', 'pz', 'nz'],
3: ['0', '1', '2', '3', '4', '5']}
if key in fileNames:
fns = fileNames[key]
else:
print('ReadCubeMap(): invalid key, unable to continue.')
sys.exit()
texture = vtk.vtkTexture()
texture.CubeMapOn()
texture.MipmapOn()
texture.InterpolateOn()
# Build the file names.
for i in range(0, len(fns)):
fns[i] = folderRoot + fileRoot + fns[i] + ext
if not os.path.isfile(fns[i]):
print('Nonexistent texture file:', fns[i])
return texture
i = 0
for fn in fns:
# Read the images
readerFactory = vtk.vtkImageReader2Factory()
imgReader = readerFactory.CreateImageReader2(fn)
imgReader.SetFileName(fn)
if flip_axis is not None:
flip = vtk.vtkImageFlip()
flip.SetInputConnection(imgReader.GetOutputPort())
flip.SetFilteredAxis(flip_axis) # flip y axis
texture.SetInputConnection(i, flip.GetOutputPort(0))
else:
texture.SetInputConnection(i, imgReader.GetOutputPort())
i += 1
return texture
class SliderProperties:
tube_width = 0.005
slider_length = 0.01
slider_width = 0.01
end_cap_length = 0.01
end_cap_width = 0.01
title_height = 0.025
label_height = 0.020
minimum_value = -3.0
maximum_value = 3.0
initial_value = 0.0
tube_length = 0.18
p1 = np.asarray([0.02, 0.05])
p2 = p1 + np.asarray([tube_length, 0])
title = None
title_color = 'Black'
label_color = 'Black'
value_color = 'DarkSlateGray'
slider_color = 'Red'
selected_color = 'Lime'
bar_color = 'DarkSlateGray'
bar_ends_color = 'Black'
initial_values=None
def make_slider(properties, slider_name=None):
colors = vtk.vtkNamedColors()
slider = vtk.vtkSliderRepresentation2D()
slider.SetMinimumValue(properties.minimum_value)
slider.SetMaximumValue(properties.maximum_value)
slider.SetValue(properties.initial_value)
slider.SetTitleText(properties.title)
slider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
slider.GetPoint1Coordinate().SetValue(properties.p1[0], properties.p1[1])
slider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
slider.GetPoint2Coordinate().SetValue(properties.p2[0], properties.p2[1])
slider.SetTubeWidth(properties.tube_width)
slider.SetSliderLength(properties.slider_length)
slider.SetSliderWidth(properties.slider_width)
slider.SetEndCapLength(properties.end_cap_length)
slider.SetEndCapWidth(properties.end_cap_width)
slider.SetTitleHeight(properties.title_height)
slider.SetLabelHeight(properties.label_height)
# Set the color properties
# Change the color of the title.
slider.GetTitleProperty().SetColor(colors.GetColor3d(properties.title_color))
# Change the color of the label.
slider.GetTitleProperty().SetColor(colors.GetColor3d(properties.label_color))
# Change the color of the bar.
slider.GetTubeProperty().SetColor(colors.GetColor3d(properties.bar_color))
# Change the color of the ends of the bar.
slider.GetCapProperty().SetColor(colors.GetColor3d(properties.bar_ends_color))
# Change the color of the knob that slides.
slider.GetSliderProperty().SetColor(colors.GetColor3d(properties.slider_color))
# Change the color of the knob when the mouse is held on it.
slider.GetSelectedProperty().SetColor(colors.GetColor3d(properties.selected_color))
# Change the color of the text displaying the value.
slider.GetLabelProperty().SetColor(colors.GetColor3d(properties.value_color))
slider_widget = vtk.vtkSliderWidget()
slider_widget.SetRepresentation(slider)
if slider_name is None:
slider_name = 'slider-%i' % np.random.randint(10000,9000000)
# print(dir(slider_widget))
slider_widget.SetObjectName(slider_name)
return slider_widget
class SliderCallback:
def __init__(self, initial_value=None):
self.value = initial_value
def _extract_values(self, sliders):
A = int(sliders['A'].GetRepresentation().GetValue())
b2 = sliders['Beta 2'].GetRepresentation().GetValue()
b3 = sliders['Beta 3'].GetRepresentation().GetValue()
b4 = sliders['Beta 4'].GetRepresentation().GetValue()
m2 = int(sliders['m2'].GetRepresentation().GetValue())
m3 = int(sliders['m3'].GetRepresentation().GetValue())
m4 = int(sliders['m4'].GetRepresentation().GetValue())
# print(A, b2, b3, b4, m2, m3, m4)
return A, b2, b3, b4, m2, m3, m4
def __call__(self, caller, ev):
slider_widget = caller
value = slider_widget.GetRepresentation().GetValue()
self.value = value
A, b2, b3, b4, m2, m3, m4 = self._extract_values(sliders)
update_surface(A, b2, m2, b3, m3, b4, m4)
# print(dir(scalar_bar_widget))
def update_surface(A, b2, m2, b3, m3, b4, m4):
r = physics_utils.calculate_r(A, b2, m2, b3, m3, b4, m4, mesh_granularity=config.granularity)
if config.secondary_scalar is not None:
r += (config.secondary_scalar.T) * config.h3
old_shape = renderer.GetActors().GetItemAsObject(0)
actors = renderer.GetActors()
add_spherical_function(r, add_gridlines=False, original_actor=old_shape, secondary_scalars=config.secondary_scalar, colormap=config.colormap)
actors.InitializeObjectBase()
actors.InitTraversal()
source_actor = None
axes_actor = None
total_actors = actors.GetNumberOfItems()
for j in range(total_actors):
actor = actors.GetNextActor()
# print(type(actor), total_actors)
if isinstance(actor, vtk.vtkOpenGLActor):
sourcename = actor.GetObjectName()
# print('sourcename', sourcename)
if sourcename is not None:
if sourcename.startswith('surface'):
source_actor = actor
if source_actor is not None:
if isinstance(actor, vtk.vtkCubeAxesActor):
axes_actor = actor
actor.SetBounds(source_actor.GetBounds())
if config.add_axes and (axes_actor is None):
axes = make_axes(source_actor, renderer)
renderer.AddActor(axes)
elif (not config.add_axes) and (axes_actor is not None):
axes_actor.SetVisibility(0)
elif (config.add_axes) and (axes_actor is not None):
axes_actor.SetVisibility(1)
renderer.Modified()
scalar_bar_widget.GetScalarBarActor().SetLookupTable(source_actor.GetMapper().GetLookupTable())
scalar_bar_widget.Modified()
return source_actor
def export_button_callback(widget, event):
renwin = widget.GetCurrentRenderer().GetRenderWindow()
write_gltf(renwin)
return
def reset_button_callback(widget, event):
value = widget.GetRepresentation().GetState()
reset_sliders(renderer)
A = config.A
b2 = config.B2
b3 = config.B3
b4 = config.B4
m2 = config.M2
m3 = config.M3
m4 = config.M4
update_surface(A, b2, m2, b3, m3, b4, m4)
return
def dark_button_callback(widget, event):
value = widget.GetRepresentation().GetState()
if value == 1:
config.dark_mode = True
print('Dark mode enabled')
else:
config.dark_mode = False
print('Dark mode disabled')
sliders = config.sliders
A = int(sliders['A'].GetRepresentation().GetValue())
b2 = sliders['Beta 2'].GetRepresentation().GetValue()
b3 = sliders['Beta 3'].GetRepresentation().GetValue()
b4 = sliders['Beta 4'].GetRepresentation().GetValue()
m2 = int(sliders['m2'].GetRepresentation().GetValue())
m3 = int(sliders['m3'].GetRepresentation().GetValue())
m4 = int(sliders['m4'].GetRepresentation().GetValue())
update_surface(A, b2, m2, b3, m3, b4, m4)
return
def axes_button_callback(widget, event):
value = widget.GetRepresentation().GetState()
if value == 1:
config.add_axes = True
print('Axes enabled')
else:
config.add_axes = False
print('Axes disabled')
sliders = config.sliders
A = int(sliders['A'].GetRepresentation().GetValue())
b2 = sliders['Beta 2'].GetRepresentation().GetValue()
b3 = sliders['Beta 3'].GetRepresentation().GetValue()
b4 = sliders['Beta 4'].GetRepresentation().GetValue()
m2 = int(sliders['m2'].GetRepresentation().GetValue())
m3 = int(sliders['m3'].GetRepresentation().GetValue())
m4 = int(sliders['m4'].GetRepresentation().GetValue())
surface = update_surface(A, b2, m2, b3, m3, b4, m4)
def render_style_button_callback(widget, event):
value = widget.GetRepresentation().GetState()
if value == 0:
smoothing = 'flat'
elif value == 1:
smoothing = 'smooth'
elif value == 2:
smoothing = 'pbr'
print('Setting smoothing to %s' % smoothing)
actors = renderer.GetActors()
actors.InitializeObjectBase()
actors.InitTraversal()
total_actors = actors.GetNumberOfItems()
for j in range(total_actors):
actor = actors.GetNextActor()
actor_name = actor.GetObjectName()
if actor_name is not None:
if actor_name.startswith('surface'):
if smoothing == 'smooth':
actor.GetProperty().SetInterpolationToGouraud()
elif smoothing == 'pbr':
actor.GetProperty().SetMetallic(1)
actor.GetProperty().SetRoughness(0)
actor.GetProperty().SetInterpolationToPBR()
else:
actor.GetProperty().SetInterpolationToFlat()
return
def add_button(interactor, renderer, callback, icon_path_1, icon_path_2=None, position=[0.05, 0.05], initial_state=True, icon_path_3=None):
r1 = vtk.vtkPNGReader()
r1.SetFileName(icon_path_1)
r1.Update()
if icon_path_2 is None:
icon_path_2 = icon_path_1
r2 = vtk.vtkPNGReader()
r2.SetFileName(icon_path_2)
r2.Update()
buttonRepresentation = vtk.vtkTexturedButtonRepresentation2D()
if icon_path_3 is not None:
total_states = 3
r3 = vtk.vtkPNGReader()
r3.SetFileName(icon_path_3)
r3.Update()
else:
total_states = 2
buttonRepresentation.SetNumberOfStates(total_states)
buttonRepresentation.SetButtonTexture(0, r1.GetOutput())
buttonRepresentation.SetButtonTexture(1, r2.GetOutput())
if icon_path_3 is not None:
buttonRepresentation.SetButtonTexture(2, r3.GetOutput())
buttonWidget = vtk.vtkButtonWidget()
buttonWidget.SetInteractor(interactor)
buttonWidget.SetRepresentation(buttonRepresentation)
# print(initial_state)
if initial_state is not False:
if initial_state is True:
buttonWidget.GetRepresentation().SetState(1)
else:
buttonWidget.GetRepresentation().SetState(initial_state)
else:
buttonWidget.GetRepresentation().SetState(0)
# // Place the widget. Must be done after a render so that the
# // viewport is defined..
# // Here the widget placement is in normalized display coordinates.
upperRight = vtk.vtkCoordinate()
upperRight.SetCoordinateSystemToNormalizedDisplay()
upperRight.SetValue(position[0], position[1])
bds = np.zeros(6)
sz = 50.0
bds[0] = upperRight.GetComputedDisplayValue(renderer)[0] - sz
bds[1] = bds[0] + sz
bds[2] = upperRight.GetComputedDisplayValue(renderer)[1] - sz
bds[3] = bds[2] + sz
bds[4] = bds[5] = 0.0
# // Scale to 1, default is .5
buttonRepresentation.SetPlaceFactor(1)
buttonRepresentation.PlaceWidget(bds)
buttonWidget.AddObserver(vtk.vtkCommand.StateChangedEvent, callback)
buttonWidget.On()
return buttonWidget
def reset_sliders(renderer):
sliders = config.sliders
sliders['A'].GetRepresentation().SetValue(config.A)
sliders['A'].Modified()
sliders['Beta 2'].GetRepresentation().SetValue(config.B2)
sliders['Beta 2'].Modified()
sliders['Beta 3'].GetRepresentation().SetValue(config.B3)
sliders['Beta 3'].Modified()
sliders['Beta 4'].GetRepresentation().SetValue(config.B4)
sliders['Beta 4'].Modified()
sliders['m2'].GetRepresentation().SetValue(config.M2)
sliders['m2'].Modified()
sliders['m3'].GetRepresentation().SetValue(config.M3)
sliders['m3'].Modified()
sliders['m4'].GetRepresentation().SetValue(config.M4)
sliders['m4'].Modified()
renderer.Render()
def add_sliders(interactor, renderer):
global sliders
sliders = dict()
initial_values = config.initial_values