forked from CDAT/cdat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDV3DPlot.py
More file actions
1376 lines (1187 loc) · 58.8 KB
/
DV3DPlot.py
File metadata and controls
1376 lines (1187 loc) · 58.8 KB
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
'''
Created on Apr 30, 2014
@author: tpmaxwel
'''
from ColorMapManager import *
from ButtonBarWidget import *
import vtk, traceback, time, threading
MIN_LINE_LEN = 150
VTK_NOTATION_SIZE = 10
PlotButtonNames = [ 'XSlider', 'YSlider', 'ZSlider', 'ToggleSurfacePlot', 'ToggleVolumePlot' ]
def addState( values, state ):
state_val = 'vcs.on' if ( state == 1 ) else 'vcs.off'
for index, val in enumerate(values):
if val in [ "vcs.on", "vcs.off" ]:
values[ index ] = state_val
return
values.append( state_val )
class AnimationStepper:
def __init__( self, target ):
self.target = target
def startAnimation(self):
self.target.startAnimation()
def stopAnimation(self):
self.target.stopAnimation()
def ffmpeg( movie, rootFileName ):
cmd = 'ffmpeg -y -b:v 1024k '
# bitrate = 1024
# rate = 10
# options=''
cmd += '-i %s%%d.png' % ( rootFileName )
# cmd += ' -r %s ' % rate
# cmd += ' -b:v %sk' % bitrate
# cmd += ' ' + options
cmd += ' ' + movie
print "Exec: ", cmd
o = os.popen(cmd).read()
return o
def saveAnimation( saveDir, animation_frames ):
writer = vtk.vtkFFMPEGWriter()
movie = os.path.join( saveDir, "movie.avi" )
writer.SetFileName( movie )
print "Saving recorded animation to %s" % movie; sys.stdout.flush()
writer.SetBitRate(1024*1024*30)
writer.SetBitRateTolerance(1024*1024*3)
writer.SetInputData( animation_frames[0] )
writer.Start()
for index, frame in enumerate( animation_frames ):
writer.SetInputData(frame)
writer.Write()
time.sleep(0.0)
writer.End()
def saveAnimationFFMpeg( animation_frames, saveDir ):
rootFileName = os.path.join( saveDir, "frame-" )
files = []
print " Saving animation (%d frames) to '%s'" % ( len( animation_frames ) , saveDir ); sys.stdout.flush()
for index, frame in enumerate( animation_frames ):
writer = vtk.vtkPNGWriter()
writer.SetInputData(frame)
fname = "%s%d.png" % ( rootFileName, index )
writer.SetFileName( fname )
writer.Update()
writer.Write()
files.append( fname )
time.sleep( 0.0 )
ffmpeg( os.path.join( saveDir, "movie.avi" ), rootFileName )
for f in files: os.remove(f)
print "Done saving animation"; sys.stdout.flush()
class SaveAnimation():
def __init__( self, frames, **args ):
self.animation_frames = list( frames )
self.rootDirName = args.get( 'root_name', "~/.uvcdat/animation" )
print "Init SaveAnimationThread, nframes = %d" % len( self.animation_frames )
def getUnusedDirName( self ):
for index in range( 100000 ):
dir_name = os.path.expanduser( '-'.join( [ self.rootDirName, str(index) ]) )
if not os.path.exists(dir_name):
os.mkdir( dir_name, 0755 )
return dir_name
def run(self):
nframes = len( self.animation_frames )
if nframes > 0:
saveDir = self.getUnusedDirName()
t = threading.Thread(target=saveAnimation, args = ( saveDir, self.animation_frames ))
t.daemon = True
t.start()
self.animation_frames = []
class TextDisplayMgr:
def __init__( self, renderer ):
self.renderer = renderer
# def setTextPosition(self, textActor, pos, size=[400,20] ):
# # vp = self.renderer.GetSize()
# # vpos = [ pos[i]*vp[i] for i in [0,1] ]
# # textActor.GetPositionCoordinate().SetValue( vpos[0], vpos[1] )
# textActor.SetPosition( 0.2, 0.5 )
# textActor.SetWidth( 0.6 )
# textActor.SetHeight( 0.08 )
# # textActor.GetPosition2Coordinate().SetValue( vpos[0] + size[0], vpos[1] + size[1] )
def getTextActor( self, aid, text, **args ):
if text == None: return
textActor = self.getProp( 'vtkTextActor', aid )
if textActor == None:
textActor = self.createTextActor( aid, **args )
self.renderer.AddViewProp( textActor )
textActor.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport ()
textActor.GetPosition2Coordinate().SetCoordinateSystemToNormalizedViewport ()
textActor.GetPositionCoordinate().SetValue( .3, .9, 0 )
textActor.GetPosition2Coordinate().SetValue( .98, .98, 0 )
# textActor.SetWidth( 0.6 )
# textActor.SetHeight( 0.08 )
text_lines = text.split('\n')
linelen = len(text_lines[0])
if linelen < MIN_LINE_LEN: text += (' '*(MIN_LINE_LEN-linelen))
text += '.'
textActor.SetInput( text )
textActor.Modified()
return textActor
def getProp( self, ptype, pid = None ):
try:
props = self.renderer.GetViewProps()
nitems = props.GetNumberOfItems()
for iP in range(nitems):
prop = props.GetItemAsObject(iP)
if prop.IsA( ptype ):
if not pid or (prop.id == pid):
return prop
except:
pass
return None
def createTextActor( self, aid, **args ):
textActor = vtk.vtkTextActor()
# textActor.SetTextScaleModeToViewport()
# textActor.SetTextScaleMode( vtk.vtkTextActor.TEXT_SCALE_MODE_PROP )
# textActor.SetMaximumLineHeight( 0.005 )
# print dir( textActor )
# textActor.ScaledTextOn()
textActor.SetTextScaleModeToProp()
textprop = textActor.GetTextProperty()
textprop.SetColor( *args.get( 'color', ( VTK_FOREGROUND_COLOR[0], VTK_FOREGROUND_COLOR[1], VTK_FOREGROUND_COLOR[2] ) ) )
textprop.SetOpacity ( args.get( 'opacity', 1.0 ) )
textprop.SetFontSize( 8 )
if args.get( 'bold', False ): textprop.BoldOn()
else: textprop.BoldOff()
textprop.ItalicOff()
textprop.ShadowOff()
textprop.SetJustificationToLeft()
textprop.SetVerticalJustificationToBottom()
textActor.VisibilityOff()
textActor.id = aid
return textActor
class DV3DPlot():
NoModifier = 0
ShiftModifier = 1
CtrlModifier = 2
AltModifier = 3
LEFT_BUTTON = 0
RIGHT_BUTTON = 1
sliceAxes = [ 'x', 'y', 'z' ]
AnimationTimerType = 9
AnimationEventId = 9
AnimationExternalEventId = 10
def __init__( self, **args ):
self.ParameterValueChanged = SIGNAL( 'ParameterValueChanged' )
self.type = args.get( 'gmname', 'default').lower()
self.activate_display=args.get('display',True)
self.renderer = None
self.parameter_initializing = False
self.useDepthPeeling = False
self.record_animation = False
self.animation_frames = []
self.renderWindowInteractor = None
self.inputSpecs = {}
self.logoActor = None
self.logoVisible = True
self.logoRepresentation = None
self.setAnimationStepper( AnimationStepper )
self.labelBuff = ""
self.resizingWindow = False
self.textDisplayMgr = None
if self.activate_display:
self.createRenderWindow( **args )
self.cameraOrientation = {}
self.maxStageHeight = 100.0
self.observerTargets = set()
self.currTime = None
self.xcenter = 100.0
self.xwidth = 300.0
self.ycenter = 0.0
self.ywidth = 180.0
self.cfgManager = ConfigManager( **args )
self.buttonBarHandler = ButtonBarHandler( self.cfgManager, **args )
self.plot_attributes = args.get( 'plot_attributes', {} )
self.plotConstituents = { 'Slice' : 'SliceRoundRobin', 'Volume' : 'ToggleVolumePlot', 'Surface' : 'ToggleSurfacePlot' }
self.topo = PlotType.Planar
self.configuring = False
self.animating = False
self.activated = False
# self.buttons = {}
self.renderWindowSize = None
self.renderWindowInitSize = None
self.animationTimerId = -1
self.isAltMode = False
self.createColormap = True
self.colormapManagers= {}
self.colormapWidget = None
self.widgetsVisible = True
self.colormapWindowSize = None
self.keyPressHandlers = {}
interactionButtons = self.getInteractionButtons()
interactionButtons.addSliderButton( names=['BasemapOpacity'], key='B', toggle=True, label='Basemap Opacity', sliderLabels='Basemap Opacity', interactionHandler=self.processBasemapOpacityCommand, range_bounds=[ 0.0, 1.0 ], initValue= 0.5 )
interactionButtons.addSliderButton( names=['VerticalScaling'], key='Z', toggle=True, label='Vertical Scaling', sliderLabels='Vertical Scale', interactionHandler=self.processVerticalScalingCommand, range_bounds=[ 0.02, 20.0 ], initValue= 1.0 )
interactionButtons.addConfigButton( names=['ChooseColormap'], key='m', toggle=True, interactionHandler=self.processChooseColormapCommand, initValue=[ 'jet', False, False ] )
interactionButtons.addConfigButton( names=['ToggleClipping'], key='X', toggle=True, parents=['ToggleVolumePlot', 'ToggleSurfacePlot'], interactionHandler=self.processToggleClippingCommand )
interactionButtons.addConfigButton( names=['Colorbar'], key='b', toggle=True, label='Show Colorbar', interactionHandler=self.processShowColorbarCommand )
interactionButtons.addSliderButton( names=['Animation'], key='a', toggle=True, label='Animation', sliderLabels='Speed (Step Delay)', interactionHandler=self.processAnimationCommand, range_bounds=[ 0.0, 2.0 ], initValue=0.0 )
cameraFunction = self.cfgManager.getConfigurableFunction( 'Camera', interactionHandler=self.processCameraCommand )
self.addKeyPressHandler( 'r', self.resetCamera )
self.addKeyPressHandler( 'q', self.quit )
self.addKeyPressHandler( 'Q', self.quit )
self.addKeyPressHandler( 's', self.saveState )
self.addKeyPressHandler( 'p', self.printParameterValues )
self.addKeyPressHandler( 'w', self.toggleWidgetVisibility )
self.addKeyPressHandler( 't', self.createTest )
def toggleWidgetVisibility( self, **args ):
print " Toggle Widget Visibility: ", str( args )
self.widgetsVisible = not self.widgetsVisible
if self.widgetsVisible: self.showWidgets()
else: self.hideWidgets()
def createTest(self, **args ):
ctestFunction = self.createCTestFunction()
print " Create CTest: \n", ctestFunction
def setAnimationStepper( self, stepper_class ):
self.animationStepper = stepper_class(self)
def applyAction( self, action ):
print "Applying action: ", str(action)
def getControlBar(self, config_function, build_args, **args ):
control_bar = self.buttonBarHandler.createControlBar( config_function.cfg_state, self.renderWindowInteractor, build_args, position = ( 0.55, 0.08 ), **args )
control_bar.reposition()
return control_bar
def getConstituentSelectionBar(self, config_function, build_args, **args ):
args[ 'toggle' ] = True
control_bar = self.buttonBarHandler.createControlBar( config_function.cfg_state, self.renderWindowInteractor, build_args, position = ( 0.7, 0.07 ), **args )
control_bar.reposition()
activations = [ ( cname, True, 1 if self.isConstituentConfigEnabled(cname) else 0 ) for cname in build_args[0] ]
control_bar.changeButtonActivations( activations )
return control_bar
def getConstituentSelectionButton(self, config_function, build_args, position, **args ):
control_bar = self.buttonBarHandler.createControlBar( config_function.cfg_state, self.renderWindowInteractor, build_args, position = position, **args )
control_bar.reposition()
return control_bar
def processConfigParameterChange( self, parameter, val_key = None ):
# values = parameter.getValue(val_key)
# if values == None: values = parameter.getValues()
# if not hasattr( values, '__iter__' ): values = [ values ]
# state = parameter.getState()
# if state <> None: addState( values, state )
values = parameter.values
active_constituents = self.getActiveConstituentNames()
argList = [ parameter.name, parameter.ptype, str(values), active_constituents ]
self.ParameterValueChanged( argList )
def getActiveConstituentNames(self):
active_constituents = []
for cname in self.plotConstituents.keys():
if self.isConstituentConfigEnabled(cname):
active_constituents.append( cname )
return active_constituents
def processConfigStateChange( self, parameter ):
argList = [ parameter.name, parameter.ptype, str( parameter.getValue('state') ) ]
self.ParameterValueChanged( argList )
def addKeyPressHandler( self, key, handler ):
handlers = self.keyPressHandlers.setdefault( key, [] )
handlers.append( handler )
def refresh(self):
self.onWindowModified()
def onClosing(self, cell ):
#print " ------> Closing!"
self.stopAnimation()
if self.cfgManager.parent:
self.cfgManager.parent.clear( cell )
self.terminate()
self.renderer.RemoveAllViewProps()
self.clearReferrents()
if self.renderWindowInteractor <> None:
self.renderWindowInteractor.TerminateApp()
# pipeline = DV3DPipelineHelper.getPipeline( cell_address, sheetName )
# if pipeline == None: pipeline = self.getCurrentPipeline()
# if pipeline: UVCDATGuiConfigFunction.clearModules( pipeline )
# IVModuleConfigurationDialog.reset()
# StandardGrid.clear_cache()
# self.cellWidget = None
# self.builtCellWidget = False
def terminate( self ):
pass
def quit( self, **args ):
self.saveState()
self.onClosing(None)
eventArgs = args.get( 'args', None )
if eventArgs and ( eventArgs[1] == 'Q' ):
sys.exit( 0 )
def stepAnimation(self, **args):
if self.record_animation: self.captureFrame()
def stepAnimationSignal(self):
self.renderWindowInteractor.SetTimerEventId( self.AnimationExternalEventId )
self.renderWindowInteractor.SetTimerEventType( self.AnimationTimerType )
self.renderWindowInteractor.InvokeEvent('TimerEvent')
def processTimerEvent(self, caller, event):
eid = caller.GetTimerEventId ()
etype = caller.GetTimerEventType()
# print "processTimerEvent: %d %d " % ( eid, etype )
if self.animating and ( etype == self.AnimationTimerType ):
self.runAnimation()
return 1
def getAnimationDelay(self):
plotButtons = self.getInteractionButtons()
cf = plotButtons.getConfigFunction('Animation')
event_duration = 0
if cf <> None:
animation_delay = cf.value.getValues()
event_duration = event_duration + int( animation_delay[0]*1000 )
return event_duration
def runAnimation( self ):
self.stepAnimation( )
self.updateTimer()
def updateTimer( self ):
event_duration = self.getAnimationDelay()
if self.animationTimerId <> -1:
self.renderWindowInteractor.DestroyTimer( self.animationTimerId )
self.animationTimerId = -1
self.renderWindowInteractor.SetTimerEventId( self.AnimationEventId )
self.renderWindowInteractor.SetTimerEventType( self.AnimationTimerType )
self.animationTimerId = self.renderWindowInteractor.CreateOneShotTimer( event_duration )
def captureFrame( self, **args ):
frameCaptureFilter = vtk.vtkWindowToImageFilter()
frameCaptureFilter.SetInput( self.renderWindow )
ignore_alpha = args.get( 'ignore_alpha', True )
if ignore_alpha: frameCaptureFilter.SetInputBufferTypeToRGB()
else: frameCaptureFilter.SetInputBufferTypeToRGBA()
frameCaptureFilter.Update()
output = frameCaptureFilter.GetOutput()
self.animation_frames.append( output )
def saveAnimation(self):
saveAnimationThread = SaveAnimation( self.animation_frames )
self.animation_frames =[]
saveAnimationThread.run()
def changeButtonActivation(self, button_name, activate, state = None ):
button = self.buttonBarHandler.findButton( button_name )
print " ---> change Button Activation[%s], activate = %s, state = %s" % ( button_name, str(activate), str(state) )
if button:
if activate: button.activate()
else: button.deactivate()
if state <> None:
button.setToggleState( state )
def changeButtonActivations(self, activation_list ):
print " ** Change Button Activations: ", str( activation_list )
for activation_spec in activation_list:
self.changeButtonActivation( *activation_spec )
def saveState(self, **args):
self.recordCamera()
self.cfgManager.saveState()
def getStateData(self, **args):
return self.cfgManager.getStateData()
def getConfigurationData(self, **args):
return self.cfgManager.getConfigurationData( **args )
def getConfigurationParms(self, **args):
return self.cfgManager.getConfigurationParms( **args )
# test1 = vcsTest( 'dv3d_slider_test', roi=( -105.0, -15.0, 5.0, 50.0 ), file="geos5-sample.nc", vars = [ 'uwnd' ],
# parameters={'VerticalScaling': 3.0,
# 'ToggleVolumePlot': vcs.off,
# 'ScaleOpacity': [1.0, 1.0],
# 'ToggleSurfacePlot': vcs.off,
# 'ScaleColormap': [-10.0, 10.0, 1],
# 'BasemapOpacity': [0.5],
# 'XSlider': ( -50.0, vcs.on ),
# 'ZSlider': ( 0.0, vcs.on ),
# 'YSlider': ( 20.0, vcs.on ),
# } )
# plot = self.canvas.backend.plotApps[ self.gm ]
def createCTestFunction( self, **args ):
try:
cTestStrs = []
lt = time.localtime(time.time())
mdataStrs = [ '"ctest"' ]
roi = self.cfgManager.getMetadata('roi')
if roi: mdataStrs.append( ' roi=%s' % str( roi ) )
cdmsfile = self.cfgManager.getMetadata('cdmsfile')
filename = os.path.basename(cdmsfile)
mdataStrs.append( ' file="%s"' % filename )
var_list = []
for input_index in range(0,5):
input_ispec = self.getInputSpec( input_index )
if input_ispec == None: break
else:
plist = input_ispec.getMetadata( 'inputVarList' )
if not plist:
pname = input_ispec.getMetadata( 'scalars' )
var_list.append( pname )
else:
for pname in plist:
if ( pname <> '__zeros__' ):
var_list.append( pname )
mdataStrs.append( ' vars=%s' % str(var_list) )
mdataStrs.append( ' type="%s"' % str(self.type) )
template = self.plot_attributes.get( 'template', None )
if template <> None: mdataStrs.append( ' template="%s"' % template )
cTestStrs.append( 'vcsTest( %s,' % ( ','.join(mdataStrs) ) )
self.recordCamera()
parameter_names = set( self.cfgManager.getParameterList() )
parameter_names.update( PlotButtonNames )
cTestStrs.append( '\t\t\t\tparameters = {' )
ignorable_parms = [ 'axes', 'Configure', 'SliceRoundRobin' ]
for param_name in parameter_names:
if not param_name in ignorable_parms:
pval = self.cfgManager.getParameterDescription( param_name, ignorable=['cell','count'] )
if pval: cTestStrs.append( '\t\t\t\t\t"%s": %s,' % ( param_name, pval ) )
cTestStrs.append( '\t\t\t\t\t} )' )
return '\n'.join( cTestStrs )
except Exception, err:
print "Error generating CTestFunction: ", str( err )
traceback.print_exc()
return ""
def printParameterValues( self, **args ):
self.recordCamera()
parameter_names = list( self.cfgManager.getParameterList() ) + PlotButtonNames
for param_name in parameter_names:
pval = self.cfgManager.getParameterValue( param_name )
if pval: print '%s = %s' % ( param_name, pval )
def processKeyPressHandler( self, key, eventArgs ):
# print " processKeyPress: ", str( key )
handlers = self.keyPressHandlers.get( key, [] )
for handler in handlers: handler( args=eventArgs )
return len( handlers )
def processBasemapOpacityCommand( self, args, config_function ):
pass
def processVerticalScalingCommand( self, args, config_function ):
pass
def processCameraCommand( self, args, config_function ):
if args and args[0] == "Init":
# cameraSpecs = config_function.value
self.initCamera()
# print " processCameraCommand: "
def processToggleClippingCommand( self, args, config_function ):
pass
def getRenderer(self):
if self.renderer <> None: return self.renderer
return self.renderWindow.GetRenderers().GetFirstRenderer ()
def processShowColorbarCommand( self, args, config_function = None ):
if args and args[0] == "InitConfig":
constituent = 'Slice'
state = args[1]
cs_button = self.getConstituentSelectionButton( config_function, [ ( self.plotConstituents.keys(), ), self.processColorbarConstituentSelection ], ( 0.9, 0.2) )
if state: cs_button.show()
else: cs_button.hide()
colorbarParameter = self.cfgManager.getParameter( 'Colorbar' )
constituent = colorbarParameter.getValue( 'ConstituentSelected', self.plotConstituents.keys()[0] )
self.toggleColorbarVisibility( constituent, state )
self.processConfigStateChange( config_function.value )
def processColorbarConstituentSelection( self, *args, **kwargs ):
#print " Process Colorbar Constituent Selection: %s " % str( args )
constituent = self.plotConstituents.keys()[ args[2] ]
colorbarParameter = self.cfgManager.getParameter( 'Colorbar' )
colorbarParameter.setValue( 'ConstituentSelected', constituent )
self.toggleColorbarVisibility( constituent, 1 )
def initializePlots(self):
bbar = self.getPlotButtonbar()
if not self.cfgManager.initialized:
button = bbar.getButton( 'ZSlider' )
if button <> None:
button.setButtonState( 1 )
bbar.initializeSliderPosition(0)
bbar.initializeState()
def processChooseColormapCommand( self, args, config_function ):
from ListWidget import ColorbarListWidget
colormapParam = config_function.value
if args and args[0] == "StartConfig":
pass
elif args and args[0] == "Init":
self.parameter_initializing = True
for plotItem in self.plotConstituents.items():
self.setColormap( plotItem[0], config_function.initial_value )
self.parameter_initializing = False
elif args and args[0] == "EndConfig":
self.processConfigParameterChange( colormapParam )
elif args and args[0] == "InitConfig":
state = args[1]
if ( self.colormapWidget == None ): # or self.colormapWidget.checkWindowSizeChange():
self.colormapWidget = ColorbarListWidget( self.renderWindowInteractor )
bbar = args[3]
self.colormapWidget.StateChangedSignal.connect( bbar.processInteractionEvent )
if len( args ) == 1: self.colormapWidget.toggleVisibility()
else: self.colormapWidget.toggleVisibility( state = args[1] )
if self.logoRepresentation is not None:
if state: self.logoWidget.Off()
else: self.logoWidget.On()
elif args and args[0] == "Open":
pass
elif args and args[0] == "Close":
if self.colormapWidget <> None:
self.colormapWidget.hide()
elif args and args[0] == "UpdateConfig":
cmap_data = args[3]
for plotItem in self.plotConstituents.items():
if self.isConstituentConfigEnabled(plotItem[0]):
self.setColormap( plotItem[0], cmap_data )
colormapParam.setValues( cmap_data )
def isConstituentConfigEnabled(self, constituent ):
param = None
for plotItem in self.plotConstituents.items():
if constituent == plotItem[0]: param = self.cfgManager.getParameter( plotItem[1] )
return param.getValue( 'ConfigEnabled', True ) if ( param <> None ) else True
def getInteractionState( self, key ):
for bbar in ButtonBarWidget.getButtonBars():
state = bbar.getInteractionState( key )
if state[0] <> None: return state
return ( None, None, None )
def displayEventType(self, caller, event):
print " --> Event: %s " % event
return 0
def updateAnimationControlBar(self, state, config_function ):
bbar = self.getControlBar( config_function, [ ( "Step", "Run", "Stop" ), self.processAnimationStateChange ], mag=1.4 )
if state == 1:
#print " ** Displaying AnimationControlBar ** "
self.updateTextDisplay( config_function.label )
bbar.show()
if self.animating:
self.changeButtonActivations( [ ( 'Run', False ), ( 'Stop', True ) , ( 'Step', False ) ] )
else:
self.changeButtonActivations( [ ( 'Run', True ), ( 'Stop', False ) , ( 'Step', True ) ] )
else:
bbar.hide()
def processAnimationCommand( self, args, config_function = None ):
# print " processAnimationCommand, args = ", str( args ), ", animating = ", str(self.animating)
runSpeed = config_function.value
if args and args[0] == "StartConfig":
pass
elif args and args[0] == "Init":
pass
elif args and args[0] == "EndConfig":
pass
elif args and args[0] == "InitConfig":
state = args[1]
bbar = self.getControlBar( config_function, [ ( "Step", "Run", "Stop", ( "Record", True ) ), self.processAnimationStateChange ], mag=1.4 )
if state == 1:
self.updateTextDisplay( config_function.label )
bbar.show()
if self.animating:
self.changeButtonActivations( [ ( 'Run', False ), ( 'Stop', True ) , ( 'Step', False ) ] )
else:
self.changeButtonActivations( [ ( 'Run', True ), ( 'Stop', False ) , ( 'Step', True ), ( 'Record', True, 0 ) ] )
else:
bbar.hide()
elif args and args[0] == "Open":
pass
elif args and args[0] == "Close":
pass
elif args and args[0] == "UpdateConfig":
try:
value = args[2].GetValue()
runSpeed.setValue( 0, value )
except Exception, err:
print>>sys.stderr, "Error setting animation run speed: ", str( err )
def processAnimationStateChange( self, button_id, key, state, force = False ):
# print " Process Animation State Change[%s], state = %d " % ( button_id, state )
if button_id == 'Step':
self.stepAnimation()
elif button_id == 'Run':
if self.animationTimerId == -1:
self.changeButtonActivations( [ ( 'Run', False ), ( 'Stop', True ) , ( 'Step', False ) ] )
self.animationStepper.startAnimation()
self.animating = True
elif button_id == 'Stop':
self.animationStepper.stopAnimation()
self.animating = False
elif button_id == 'Record':
self.record_animation = state
print " Set record_animation: " , str( self.record_animation )
if self.record_animation == 0:
self.saveAnimation()
def startAnimation(self):
self.notifyStartAnimation()
self.animating = True
self.runAnimation()
def stopAnimation(self):
self.animating = False
if self.animationTimerId <> -1:
self.animationTimerId = -1
self.renderWindowInteractor.DestroyTimer( self.animationTimerId )
self.saveAnimation()
self.notifyStopAnimation()
def notifyStartAnimation(self):
pass
def notifyStopAnimation(self):
self.changeButtonActivations( [ ( 'Run', True ), ( 'Stop', False ) , ( 'Step', True ) ] )
def setInteractionState(self, caller, event):
interactor = caller.GetInteractor()
key = interactor.GetKeyCode()
keysym = interactor.GetKeySym()
shift = interactor.GetShiftKey()
# print " setInteractionState -- Key Press: %c ( %d: %s ), event = %s " % ( key, ord(key), str(keysym), str( event ) )
alt = ( keysym <> None) and keysym.startswith("Alt")
if alt:
self.isAltMode = True
else:
self.processKeyEvent( key, caller, event )
return 0
def processKeyEvent( self, key, caller=None, event=None, **args ):
interactor = caller.GetInteractor()
keysym = interactor.GetKeySym() if caller else key
ctrl = interactor.GetControlKey() if caller else args.get( 'ctrl', 0 )
eventArgs = [ key, keysym, ctrl ]
if self.processKeyPressHandler( key, eventArgs ):
return 1
else:
return self.onKeyEvent( eventArgs )
#
# if self.onKeyEvent( [ key, keysym, ctrl ] ):
# pass
# else:
# ( state, persisted, guibar ) = self.getInteractionState( key )
# # print " %s Set Interaction State: %s ( currently %s) " % ( str(self.__class__), state, self.InteractionState )
# if state <> None:
# print " ------------------------------------------ setInteractionState, key=%s, state = %s ------------------------------------------ " % (str(key), str(state) )
# guibar.updateInteractionState( state, **args )
# self.isAltMode = False
#
# for button_bar in self.button_bars.values():
# button_bar.processKeyEvent( keysym, ctrl )
# return 0
def onLeftButtonPress( self, caller, event ):
return 0
# istyle = self.renderWindowInteractor.GetInteractorStyle()
# # print "(%s)-LBP: s = %s, nis = %s " % ( getClassName( self ), getClassName(istyle), getClassName(self.navigationInteractorStyle) )
# if not self.finalizeLeveling():
# # shift = caller.GetShiftKey()
# self.currentButton = self.LEFT_BUTTON
# # self.clearInstructions()
# self.UpdateCamera()
# x, y = caller.GetEventPosition()
# self.startConfiguration( x, y, [ 'leveling', 'generic' ] )
# return 0
def onRightButtonPress( self, caller, event ):
# shift = caller.GetShiftKey()
# self.currentButton = self.RIGHT_BUTTON
# # self.clearInstructions()
# self.UpdateCamera()
# x, y = caller.GetEventPosition()
# if self.InteractionState <> None:
# self.startConfiguration( x, y, [ 'generic' ] )
return 0
def onLeftButtonRelease( self, caller, event ):
print " onLeftButtonRelease "
self.currentButton = None
self.recordCamera()
def onRightButtonRelease( self, caller, event ):
print " onRightButtonRelease "
self.currentButton = None
self.recordCamera()
# def updateLevelingEvent( self, caller, event ):
# x, y = caller.GetEventPosition()
# wsize = caller.GetRenderWindow().GetSize()
# self.updateLeveling( x, y, wsize )
#
# def updateLeveling( self, x, y, wsize, **args ):
# if self.configuring:
# configFunct = self.configurableFunctions[ self.InteractionState ]
# if configFunct.type == 'leveling':
# configData = configFunct.update( self.InteractionState, x, y, wsize )
# if configData <> None:
# self.setParameter( configFunct.name, configData )
# textDisplay = configFunct.getTextDisplay()
# if textDisplay <> None: self.updateTextDisplay( textDisplay )
# self.render()
def updateTextDisplay( self, text=None, render=False ):
if text <> None:
self.labelBuff = "%s" % str(text)
label_actor = self.getLabelActor()
if label_actor:
label_actor.ComputeScaledFont( self.renderer )
label_actor.VisibilityOn()
if render: self.render()
def getDisplayText(self):
return self.labelBuff
def getLabelActor(self):
return self.textDisplayMgr.getTextActor( 'label', self.labelBuff, bold = False ) if self.textDisplayMgr else None
def UpdateCamera(self):
pass
def setParameter( self, name, value ):
pass
def getLut( self, constituent, cmap_index=0 ):
colormapManager = self.getColormapManager( constituent, index=cmap_index )
return colormapManager.lut
def updatingColormap( self, cmap_index, colormapManager ):
pass
def addObserver( self, target, event, observer ):
self.observerTargets.add( target )
target.AddObserver( event, observer )
def createRenderer(self, **args ):
background_color = args.get( 'background_color', VTK_BACKGROUND_COLOR )
self.renderer.SetBackground(*background_color)
self.textDisplayMgr = TextDisplayMgr( self.renderer )
self.renderWindowInitSize = args.get( 'window_size', None )
if self.renderWindowInitSize <> None:
self.renderWindow.SetSize( self.renderWindowInitSize )
self.pointPicker = vtk.vtkPointPicker()
self.pointPicker.PickFromListOn()
try: self.pointPicker.SetUseCells(True)
except: print>>sys.stderr, "Warning, vtkPointPicker patch not installed, picking will not work properly."
self.pointPicker.InitializePickList()
self.renderWindowInteractor.SetPicker(self.pointPicker)
self.addObserver( self.renderer, 'ModifiedEvent', self.activateEvent )
self.clipper = vtk.vtkBoxWidget()
self.clipper.RotationEnabledOff()
self.clipper.SetPlaceFactor( 1.0 )
self.clipper.KeyPressActivationOff()
self.clipper.SetInteractor( self.renderWindowInteractor )
self.clipper.SetHandleSize( 0.005 )
self.clipper.SetEnabled( True )
self.clipper.InsideOutOn()
self.clipper.AddObserver( 'StartInteractionEvent', self.startClip )
self.clipper.AddObserver( 'EndInteractionEvent', self.endClip )
self.clipper.AddObserver( 'InteractionEvent', self.executeClip )
self.clipOff()
self.addLogo()
def clipOn(self):
pass
def clipOff(self):
pass
def startClip( self, caller=None, event=None ):
pass
def endClip( self, caller=None, event=None ):
pass
def executeClip( self, caller=None, event=None ):
pass
def isConfigStyle( self, iren ):
return False
# if not iren: return False
# return getClassName( iren.GetInteractorStyle() ) == getClassName( self.configurationInteractorStyle )
def onKeyRelease(self, caller, event):
#print " Key event "
return
def onModified(self, caller, event):
# print " --- Modified Event --- "
return 0
def onAnyEvent(self, caller, event):
print " --- %s Event --- " % str(event)
return 0
def onCameraEvent(self, caller, event):
print " --- %s Event --- " % str(event)
return 0
def onRender(self, caller, event):
# print " --- Render Event --- "
# traceback.print_stack()
return 0
def updateInteractor(self):
return 0
def activateEvent( self, caller, event ):
if not self.activated:
self.renderWindowInteractor.Initialize()
# print "Activating, renderWindowInteractor = ", self.renderWindowInteractor.__class__.__name__
# self.addObserver( self.renderWindowInteractor, 'InteractorEvent', self.displayEventType )
self.addObserver( self.interactorStyle, 'CharEvent', self.setInteractionState )
self.addObserver( self.renderWindowInteractor, 'TimerEvent', self.processTimerEvent )
# self.addObserver( self.renderWindowInteractor, 'CreateTimerEvent', self.processTimerEvent )
# self.addObserver( self.renderWindowInteractor, 'MouseMoveEvent', self.updateLevelingEvent )
self.addObserver( self.interactorStyle, 'KeyReleaseEvent', self.onKeyRelease )
self.addObserver( self.renderWindowInteractor, 'LeftButtonPressEvent', self.onLeftButtonPress )
self.addObserver( self.interactorStyle, 'ModifiedEvent', self.onModified )
self.addObserver( self.renderWindowInteractor, 'RenderEvent', self.onRender )
self.addObserver( self.renderWindowInteractor, 'LeftButtonReleaseEvent', self.onLeftButtonRelease )
self.addObserver( self.renderWindowInteractor, 'RightButtonReleaseEvent', self.onRightButtonRelease )
self.addObserver( self.renderWindowInteractor, 'RightButtonPressEvent', self.onRightButtonPress )
# self.addObserver( self.renderWindowInteractor, 'RenderWindowMessageEvent', self.onAnyEvent )
# self.addObserver( self.renderWindowInteractor, 'ResetCameraEvent', self.onCameraEvent )
# self.addObserver( self.renderWindowInteractor, 'CameraEvent', self.onCameraEvent )
# self.addObserver( self.renderWindowInteractor, 'ResetCameraClippingRangeEvent', self.onAnyEvent )
# self.addObserver( self.renderWindowInteractor, 'ComputeVisiblePropBoundsEvent', self.onAnyEvent )
# self.addObserver( self.renderWindowInteractor, 'AnyEvent', self.onAnyEvent )
# self.animationTestId = self.renderWindowInteractor.CreateRepeatingTimer( 100 )
# cb = TimerCallback()
# self.renderWindowInteractor.AddObserver(vtk.vtkCommand.TimerEvent, cb)
RenderWindow = self.renderWindowInteractor.GetRenderWindow()
# RenderWindow.AddObserver( 'AnyEvent', self.onAnyWindowEvent )
RenderWindow.AddObserver( 'RenderEvent', self.onWindowRenderEvent )
RenderWindow.AddObserver( 'ExitEvent', self.onWindowExit )
self.updateInteractor()
self.activated = True
def buildConfigurationButton(self):
bbar_name = 'Configure'
bbar = self.buttonBarHandler.getButtonBar( bbar_name )
if bbar == None:
bbar = self.buttonBarHandler.createButtonBarWidget( bbar_name, self.renderWindowInteractor )
config_button = bbar.addConfigButton( names=['Configure'], id='Configure', key='g', toggle=True, persist=False, interactionHandler=self.processConfigurationToggle )
bbar.build()
return bbar
def showConfigurationButton(self):
bbar = self.buildConfigurationButton( )
bbar.show()
def buildPlotButtons( self, **args ):
bbar_name = 'Plot'
enable_3d_plots = True
ispec = self.inputSpecs.get( 0 , None )
if ispec is not None:
md = ispec.metadata
plotType = md.get( 'plotType', 'xyz' )
lev = md.get( 'lev', None )
if (lev is None) and (plotType == 'xyz'): enable_3d_plots = False
bbar = self.buttonBarHandler.createButtonBarWidget( bbar_name, self.renderWindowInteractor, position=( 0.0, 0.96) )
self.buttonBarHandler.DefaultGroup = 'SliceRoundRobin'
if (self.type == '3d_vector') or not enable_3d_plots:
sliderLabels= 'Slice Position' if enable_3d_plots else []
b = bbar.addSliderButton( names=['ZSlider'], key='z', visible=enable_3d_plots, toggle=True, group='SliceRoundRobin', sliderLabels=sliderLabels, label="Slicing", state = 1, interactionHandler=self.processSlicingCommand )
vs_button = self.buttonBarHandler.findButton( 'VerticalScaling' )
if vs_button is not None: vs_button.setVisibility( False )
else:
b = bbar.addConfigButton( names=['SliceRoundRobin'], key='p', interactionHandler=bbar.sliceRoundRobin )
b = bbar.addSliderButton( names=['XSlider'], key='x', toggle=True, group='SliceRoundRobin', sliderLabels='X Slice Position', label="Slicing", position=[0,3], interactionHandler=self.processSlicingCommand )
b.addFunctionKey( 'W', 1, Button.FuncToggleStateOff )
b = bbar.addSliderButton( names=['YSlider'], key='y', toggle=True, group='SliceRoundRobin', sliderLabels='Y Slice Position', label="Slicing", position=[1,3], interactionHandler=self.processSlicingCommand )
b.addFunctionKey( 'W', 1, Button.FuncToggleStateOff )
b = bbar.addSliderButton( names=['ZSlider'], key='z', toggle=True, group='SliceRoundRobin', sliderLabels='Z Slice Position', label="Slicing", position=[2,3], interactionHandler=self.processSlicingCommand )
b.addFunctionKey( 'W', 1, Button.FuncToggleStateOff )
b = bbar.addConfigButton( names=['ToggleSurfacePlot'], key='S', children=['IsosurfaceValue'], toggle=True, interactionHandler=self.processSurfacePlotCommand )
b = bbar.addConfigButton( names=['ToggleVolumePlot'], key='v', children=['ScaleTransferFunction'], toggle=True, interactionHandler=self.processVolumePlotCommand )
bbar.build()
def processSurfacePlotCommand( self, args, config_function = None ):
if args and args[0] == "Init":
self.parameter_initializing = True
state = config_function.getState()
if state: self.cfgManager.initialized = True
if config_function.initial_value <> None:
config_function.setState( config_function.initial_value[0] )
state = config_function.getState()
if state: self.toggleIsosurfaceVisibility( state )
self.parameter_initializing = False
elif args and args[0] == "InitConfig":
state = args[1]
self.toggleIsosurfaceVisibility( state )
self.processConfigStateChange( config_function.value )
def processVolumePlotCommand( self, args, config_function = None ):
if args and args[0] == "Init":
self.parameter_initializing = True
state = config_function.getState()
if state: self.cfgManager.initialized = True
if config_function.initial_value <> None:
config_function.setState( config_function.initial_value[0] )
# print " init ToggleVolumePlot: state=%s, cfg=(%s) " % ( str(state), str(config_function.initial_value) )
state = config_function.getState()
state_val = state[0] if hasattr(state, "__iter__") else state
if state_val: self.toggleVolumeVisibility( state_val )
self.parameter_initializing = False
elif args and args[0] == "InitConfig":
state = args[1]
self.toggleVolumeVisibility( state )
self.processConfigStateChange( config_function.value )
def fetchPlotButtons( self ):
bbar1 = self.buttonBarHandler.getButtonBar( 'Plot' )
if bbar1 == None: bbar1 = self.buildPlotButtons()
bbar2 = self.buttonBarHandler.getButtonBar( 'Interaction' )
bbar2.build()
return bbar1
def getPlotButtonbar(self):
return self.buttonBarHandler.getButtonBar( 'Plot' )
def getPlotButtons( self, names ):
bbar = self.buttonBarHandler.getButtonBar( bbar_name )
return [ bbar.getButton( name ) for name in names ] if bbar is not None else []
def toggleCongurationButtons(self, isVisible ):
config_bbars = [ 'Plot', 'Interaction' ]
for bbar_name in config_bbars:
bbar = self.buttonBarHandler.getButtonBar( bbar_name )
if bbar: