source: trunk/gui/scripts/vtkisosurfaceviewer.tcl @ 6148

Last change on this file since 6148 was 6148, checked in by ldelgass, 8 years ago

more cleanups

File size: 110.6 KB
Line 
1# -*- mode: tcl; indent-tabs-mode: nil -*-
2# ----------------------------------------------------------------------
3#  COMPONENT: vtkisosurfaceviewer - Vtk 3D contour object viewer
4#
5#  It connects to the Vtkvis server running on a rendering farm,
6#  transmits data, and displays the results.
7# ======================================================================
8#  AUTHOR:  Michael McLennan, Purdue University
9#  Copyright (c) 2004-2016  HUBzero Foundation, LLC
10#
11#  See the file "license.terms" for information on usage and
12#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13# ======================================================================
14package require Itk
15package require BLT
16#package require Img
17
18option add *VtkIsosurfaceViewer.width 4i widgetDefault
19option add *VtkIsosurfaceViewer*cursor crosshair widgetDefault
20option add *VtkIsosurfaceViewer.height 4i widgetDefault
21option add *VtkIsosurfaceViewer.foreground black widgetDefault
22option add *VtkIsosurfaceViewer.controlBackground gray widgetDefault
23option add *VtkIsosurfaceViewer.controlDarkBackground #999999 widgetDefault
24option add *VtkIsosurfaceViewer.plotBackground black widgetDefault
25option add *VtkIsosurfaceViewer.plotForeground white widgetDefault
26option add *VtkIsosurfaceViewer.font \
27    -*-helvetica-medium-r-normal-*-12-* widgetDefault
28
29# must use this name -- plugs into Rappture::resources::load
30proc VtkIsosurfaceViewer_init_resources {} {
31    Rappture::resources::register \
32        vtkvis_server Rappture::VtkIsosurfaceViewer::SetServerList
33}
34
35itcl::class Rappture::VtkIsosurfaceViewer {
36    inherit Rappture::VisViewer
37
38    itk_option define -plotforeground plotForeground Foreground ""
39    itk_option define -plotbackground plotBackground Background ""
40
41    constructor { args } {
42        Rappture::VisViewer::constructor
43    } {
44        # defined below
45    }
46    destructor {
47        # defined below
48    }
49    public proc SetServerList { namelist } {
50        Rappture::VisViewer::SetServerList "vtkvis" $namelist
51    }
52    public method add {dataobj {settings ""}}
53    public method camera {option args}
54    public method delete {args}
55    public method disconnect {}
56    public method download {option args}
57    public method get {args}
58    public method isconnected {}
59    public method parameters {title args} {
60        # do nothing
61    }
62    public method scale {args}
63
64    # The following methods are only used by this class.
65    private method AdjustSetting {what {value ""}}
66    private method BuildAxisTab {}
67    private method BuildCameraTab {}
68    private method BuildColormap { name }
69    private method BuildCutplanesTab {}
70    private method BuildDownloadPopup { widget command }
71    private method BuildIsosurfaceTab {}
72    private method Connect {}
73    private method CurrentDatasets {args}
74    private method DisableMouseRotationBindings {}
75    private method Disconnect {}
76    private method DoChangeContourLevels {}
77    private method DoResize {}
78    private method DoRotate {}
79    private method DrawLegend {}
80    private method EnterLegend { x y }
81    private method EventuallyChangeContourLevels {}
82    private method EventuallyRequestLegend {}
83    private method EventuallyResize { w h }
84    private method EventuallyRotate { q }
85    private method EventuallySetCutplane { axis args }
86    private method GenerateContourList {}
87    private method GetImage { args }
88    private method GetVtkData { args }
89    private method InitSettings { args }
90    private method IsValidObject { dataobj }
91    private method LeaveLegend {}
92    private method LegendB1Motion {status x y}
93    private method LegendPointToValue { x y }
94    private method LegendProbeSingleContour { x y }
95    private method LegendRangeAction { option args }
96    private method LegendRangeValidate { widget which value }
97    private method LegendTitleAction { option }
98    private method MotionLegend { x y }
99    private method MouseOver2Which {}
100    private method Pan {option x y}
101    private method PanCamera {}
102    private method Pick {x y}
103    private method QuaternionToView { q } {
104        foreach { _view(-qw) _view(-qx) _view(-qy) _view(-qz) } $q break
105    }
106    private method Rebuild {}
107    private method ReceiveDataset { args }
108    private method ReceiveImage { args }
109    private method ReceiveLegend { colormap title vmin vmax size }
110    private method RequestLegend {}
111    private method Rotate {option x y}
112    private method SetCurrentColormap { color }
113    private method SetCurrentFieldName { dataobj }
114    private method SetLegendTip { x y }
115    private method SetMinMaxGauges { min max }
116    private method SetObjectStyle { dataobj comp }
117    private method SetOrientation { side }
118    private method SetupMouseRotationBindings {}
119    private method SetupMousePanningBindings {}
120    private method SetupKeyboardBindings {}
121    private method Slice {option args}
122    private method ToggleCustomRange { args }
123    private method ViewToQuaternion {} {
124        return [list $_view(-qw) $_view(-qx) $_view(-qy) $_view(-qz)]
125    }
126    private method Zoom {option}
127
128    private variable _arcball ""
129
130    private variable _dlist ""     ;    # list of data objects
131    private variable _obj2ovride   ;    # maps dataobj => style override
132    private variable _datasets     ;    # contains all the dataobj-component
133                                   ;    # datasets in the server
134    private variable _colormaps    ;    # contains all the colormaps
135                                   ;    # in the server.
136    # The name of the current colormap used.  The colormap is global to all
137    # heightmaps displayed.
138    private variable _currentColormap ""
139    private variable _currentNumContours -1
140
141    private variable _click        ;    # info used for rotate operations
142    private variable _limits       ;    # autoscale min/max for all axes
143    private variable _view         ;    # view params for 3D view
144    private variable _settings
145    private variable _changed
146    private variable _reset 1;          # Connection to server has been reset.
147
148    private variable _first ""     ;    # This is the topmost dataset.
149    private variable _start 0
150    private variable _title ""
151    private variable _isolines
152    private variable _contourList
153    private variable _currentLimits ""
154    private variable _widget
155    private variable _width 0
156    private variable _height 0
157    private variable _resizePending 0
158    private variable _legendPending 0
159    private variable _rotatePending 0
160    private variable _cutplanePending 0
161    private variable _field      ""
162    private variable _colorMode "scalar";   # Mode of colormap (vmag or scalar)
163    private variable _fields
164    private variable _curFldName ""
165    private variable _curFldLabel ""
166    private variable _mouseOver "";     # what called LegendRangeAction, vmin or vmax
167    private variable _customRangeClick 1;   # what called ToggleCustomRange
168
169    private common _downloadPopup;      # download options from popup
170    private common _hardcopy
171}
172
173itk::usual VtkIsosurfaceViewer {
174    keep -background -foreground -cursor -font
175    keep -plotbackground -plotforeground
176}
177
178# ----------------------------------------------------------------------
179# CONSTRUCTOR
180# ----------------------------------------------------------------------
181itcl::body Rappture::VtkIsosurfaceViewer::constructor {args} {
182    set _serverType "vtkvis"
183
184    #DebugOn
185    EnableWaitDialog 900
186
187    # Rebuild event
188    $_dispatcher register !rebuild
189    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
190
191    # Resize event
192    $_dispatcher register !resize
193    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
194
195    # Legend event
196    $_dispatcher register !legend
197    $_dispatcher dispatch $this !legend "[itcl::code $this RequestLegend]; list"
198
199    # Rotate event
200    $_dispatcher register !rotate
201    $_dispatcher dispatch $this !rotate "[itcl::code $this DoRotate]; list"
202
203    # Contour levels event
204    $_dispatcher register !contours
205    $_dispatcher dispatch $this !contours \
206        "[itcl::code $this DoChangeContourLevels]; list"
207
208    # X-Cutplane event
209    $_dispatcher register !xcutplane
210    $_dispatcher dispatch $this !xcutplane \
211        "[itcl::code $this AdjustSetting -xcutplaneposition]; list"
212
213    # Y-Cutplane event
214    $_dispatcher register !ycutplane
215    $_dispatcher dispatch $this !ycutplane \
216        "[itcl::code $this AdjustSetting -ycutplaneposition]; list"
217
218    # Z-Cutplane event
219    $_dispatcher register !zcutplane
220    $_dispatcher dispatch $this !zcutplane \
221        "[itcl::code $this AdjustSetting -zcutplaneposition]; list"
222
223    #
224    # Populate parser with commands handle incoming requests
225    #
226    $_parser alias image [itcl::code $this ReceiveImage]
227    $_parser alias legend [itcl::code $this ReceiveLegend]
228    $_parser alias dataset [itcl::code $this ReceiveDataset]
229
230    # Initialize the view to some default parameters.
231    array set _view {
232        -ortho    0
233        -qw       0.853553
234        -qx       -0.353553
235        -qy       0.353553
236        -qz       0.146447
237        -xpan     0
238        -ypan     0
239        -zoom     1.0
240    }
241    set _arcball [blt::arcball create 100 100]
242    $_arcball quaternion [ViewToQuaternion]
243
244    array set _contourList {
245        numLevels       10
246        reqValues       ""
247        updatePending   0
248        values          ""
249    }
250    array set _settings {
251        -axesvisible            1
252        -axislabels             1
253        -axisminorticks         1
254        -axismode               "static"
255        -background             black
256        -colormap               BCGYR
257        -colormapvisible        1
258        -customrange            0
259        -customrangemin         0
260        -customrangemax         1
261        -cutplaneedges          0
262        -cutplanelighting       1
263        -cutplaneopacity        1.0
264        -cutplanepreinterp      1
265        -cutplanesvisible       0
266        -cutplanewireframe      0
267        -field                  "Default"
268        -isolinecolor           white
269        -isosurfaceedges        0
270        -isosurfacelighting     1
271        -isosurfaceopacity      0.6
272        -isosurfacevisible      1
273        -isosurfacewireframe    0
274        -legendvisible          1
275        -numcontours            10
276        -outline                0
277        -xcutplaneposition      50
278        -xcutplanevisible       1
279        -xgrid                  0
280        -ycutplaneposition      50
281        -ycutplanevisible       1
282        -ygrid                  0
283        -zcutplaneposition      50
284        -zcutplanevisible       1
285        -zgrid                  0
286    }
287    array set _changed {
288        -colormap               0
289        -cutplaneedges          0
290        -cutplanelighting       0
291        -cutplaneopacity        0
292        -cutplanepreinterp      0
293        -cutplanesvisible       0
294        -cutplanewireframe      0
295        -isosurfaceedges        0
296        -isosurfacelighting     0
297        -isosurfaceopacity      0
298        -isosurfacevisible      0
299        -isosurfacewireframe    0
300        -numcontours            0
301        -outline                0
302        -xcutplaneposition      0
303        -xcutplanevisible       0
304        -ycutplaneposition      0
305        -ycutplanevisible       0
306        -zcutplaneposition      0
307        -zcutplanevisible       0
308    }
309    array set _widget {
310        -isosurfaceopacity      60
311        -cutplaneopacity        100
312    }
313
314    itk_component add view {
315        canvas $itk_component(plotarea).view \
316            -highlightthickness 0 -borderwidth 0
317    } {
318        usual
319        ignore -highlightthickness -borderwidth -background
320    }
321
322    itk_component add fieldmenu {
323        menu $itk_component(plotarea).menu -bg black -fg white -relief flat \
324            -tearoff 0
325    } {
326        usual
327        ignore -background -foreground -relief -tearoff
328    }
329
330    # add an editor for adjusting the legend min and max values
331    itk_component add editor {
332        Rappture::Editor $itk_interior.editor \
333            -activatecommand [itcl::code $this LegendRangeAction activate] \
334            -validatecommand [itcl::code $this LegendRangeAction validate] \
335            -applycommand [itcl::code $this LegendRangeAction apply]
336    }
337
338    set c $itk_component(view)
339    bind $c <Configure> [itcl::code $this EventuallyResize %w %h]
340    bind $c <4> [itcl::code $this Zoom in 0.25]
341    bind $c <5> [itcl::code $this Zoom out 0.25]
342    bind $c <KeyPress-Left>  [list %W xview scroll 10 units]
343    bind $c <KeyPress-Right> [list %W xview scroll -10 units]
344    bind $c <KeyPress-Up>    [list %W yview scroll 10 units]
345    bind $c <KeyPress-Down>  [list %W yview scroll -10 units]
346    bind $c <Enter> "focus %W"
347    bind $c <Control-F1> [itcl::code $this ToggleConsole]
348
349    # Fix the scrollregion in case we go off screen
350    $c configure -scrollregion [$c bbox all]
351
352    set _map(id) [$c create image 0 0 -anchor nw -image $_image(plot)]
353    set _map(cwidth) -1
354    set _map(cheight) -1
355    set _map(zoom) 1.0
356    set _map(original) ""
357
358    set f [$itk_component(main) component controls]
359    itk_component add reset {
360        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
361            -highlightthickness 0 \
362            -image [Rappture::icon reset-view] \
363            -command [itcl::code $this Zoom reset]
364    } {
365        usual
366        ignore -highlightthickness
367    }
368    pack $itk_component(reset) -side top -padx 2 -pady 2
369    Rappture::Tooltip::for $itk_component(reset) \
370        "Reset the view to the default zoom level"
371
372    itk_component add zoomin {
373        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
374            -highlightthickness 0 \
375            -image [Rappture::icon zoom-in] \
376            -command [itcl::code $this Zoom in]
377    } {
378        usual
379        ignore -highlightthickness
380    }
381    pack $itk_component(zoomin) -side top -padx 2 -pady 2
382    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
383
384    itk_component add zoomout {
385        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
386            -highlightthickness 0 \
387            -image [Rappture::icon zoom-out] \
388            -command [itcl::code $this Zoom out]
389    } {
390        usual
391        ignore -highlightthickness
392    }
393    pack $itk_component(zoomout) -side top -padx 2 -pady 2
394    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
395
396    itk_component add contour {
397        Rappture::PushButton $f.contour \
398            -onimage [Rappture::icon volume-on] \
399            -offimage [Rappture::icon volume-off] \
400            -variable [itcl::scope _settings(-isosurfacevisible)] \
401            -command [itcl::code $this AdjustSetting -isosurfacevisible]
402    }
403    $itk_component(contour) select
404    Rappture::Tooltip::for $itk_component(contour) \
405        "Hide the isosurface"
406    pack $itk_component(contour) -padx 2 -pady 2
407
408    itk_component add cutplane {
409        Rappture::PushButton $f.cutplane \
410            -onimage [Rappture::icon cutbutton] \
411            -offimage [Rappture::icon cutbutton] \
412            -variable [itcl::scope _settings(-cutplanesvisible)] \
413            -command [itcl::code $this AdjustSetting -cutplanesvisible]
414    }
415    Rappture::Tooltip::for $itk_component(cutplane) \
416        "Show the cutplanes"
417    pack $itk_component(cutplane) -padx 2 -pady 2
418
419
420    if { [catch {
421        BuildIsosurfaceTab
422        BuildCutplanesTab
423        BuildAxisTab
424        BuildCameraTab
425    } errs] != 0 } {
426        puts stderr errs=$errs
427    }
428
429    # Legend
430    set _image(legend) [image create photo]
431    itk_component add legend {
432        canvas $itk_component(plotarea).legend -width 50 -highlightthickness 0
433    } {
434        usual
435        ignore -highlightthickness
436        rename -background -plotbackground plotBackground Background
437    }
438
439    # Hack around the Tk panewindow.  The problem is that the requested
440    # size of the 3d view isn't set until an image is retrieved from
441    # the server.  So the panewindow uses the tiny size.
442    set w 10000
443    pack forget $itk_component(view)
444    blt::table $itk_component(plotarea) \
445        0,0 $itk_component(view) -fill both -reqwidth $w
446    blt::table configure $itk_component(plotarea) c1 -resize none
447
448    SetupMouseRotationBindings
449    SetupMousePanningBindings
450    SetupKeyboardBindings
451
452
453    #bind $itk_component(view) <ButtonRelease-3> \
454    #    [itcl::code $this Pick %x %y]
455
456
457    if {[string equal "x11" [tk windowingsystem]]} {
458        # Bindings for zoom via mouse
459        bind $itk_component(view) <4> [itcl::code $this Zoom out]
460        bind $itk_component(view) <5> [itcl::code $this Zoom in]
461    }
462
463    set _image(download) [image create photo]
464
465    eval itk_initialize $args
466
467    Connect
468}
469
470# ----------------------------------------------------------------------
471# DESTRUCTOR
472# ----------------------------------------------------------------------
473itcl::body Rappture::VtkIsosurfaceViewer::destructor {} {
474    Disconnect
475    image delete $_image(plot)
476    image delete $_image(download)
477    catch { blt::arcball destroy $_arcball }
478}
479
480itcl::body Rappture::VtkIsosurfaceViewer::SetupMouseRotationBindings {} {
481    # Bindings for rotation via mouse
482    bind $itk_component(view) <ButtonPress-1> \
483        [itcl::code $this Rotate click %x %y]
484    bind $itk_component(view) <B1-Motion> \
485        [itcl::code $this Rotate drag %x %y]
486    bind $itk_component(view) <ButtonRelease-1> \
487        [itcl::code $this Rotate release %x %y]
488}
489
490itcl::body Rappture::VtkIsosurfaceViewer::DisableMouseRotationBindings {} {
491    # Bindings for rotation via mouse
492    bind $itk_component(view) <ButtonPress-1> ""
493    bind $itk_component(view) <B1-Motion> ""
494    bind $itk_component(view) <ButtonRelease-1> ""
495}
496
497itcl::body Rappture::VtkIsosurfaceViewer::SetupMousePanningBindings {} {
498    # Bindings for panning via mouse
499    bind $itk_component(view) <ButtonPress-2> \
500        [itcl::code $this Pan click %x %y]
501    bind $itk_component(view) <B2-Motion> \
502        [itcl::code $this Pan drag %x %y]
503    bind $itk_component(view) <ButtonRelease-2> \
504        [itcl::code $this Pan release %x %y]
505}
506
507itcl::body Rappture::VtkIsosurfaceViewer::SetupKeyboardBindings {} {
508    # Bindings for panning via keyboard
509    bind $itk_component(view) <KeyPress-Left> \
510        [itcl::code $this Pan set -10 0]
511    bind $itk_component(view) <KeyPress-Right> \
512        [itcl::code $this Pan set 10 0]
513    bind $itk_component(view) <KeyPress-Up> \
514        [itcl::code $this Pan set 0 -10]
515    bind $itk_component(view) <KeyPress-Down> \
516        [itcl::code $this Pan set 0 10]
517    bind $itk_component(view) <Shift-KeyPress-Left> \
518        [itcl::code $this Pan set -2 0]
519    bind $itk_component(view) <Shift-KeyPress-Right> \
520        [itcl::code $this Pan set 2 0]
521    bind $itk_component(view) <Shift-KeyPress-Up> \
522        [itcl::code $this Pan set 0 -2]
523    bind $itk_component(view) <Shift-KeyPress-Down> \
524        [itcl::code $this Pan set 0 2]
525
526    # Bindings for zoom via keyboard
527    bind $itk_component(view) <KeyPress-Prior> \
528        [itcl::code $this Zoom out]
529    bind $itk_component(view) <KeyPress-Next> \
530        [itcl::code $this Zoom in]
531
532    bind $itk_component(view) <Enter> "focus $itk_component(view)"
533}
534
535itcl::body Rappture::VtkIsosurfaceViewer::DoResize {} {
536    if { $_width < 2 } {
537        set _width 500
538    }
539    if { $_height < 2 } {
540        set _height 500
541    }
542    set _start [clock clicks -milliseconds]
543    SendCmd "screen size $_width $_height"
544
545    EventuallyRequestLegend
546    set _resizePending 0
547}
548
549itcl::body Rappture::VtkIsosurfaceViewer::DoChangeContourLevels {} {
550    GenerateContourList
551    SendCmd [list contour3d contourlist $_contourList(values)]
552    SendCmd [list camera reset]
553    DrawLegend
554    set _contourList(updatePending) 0
555}
556
557itcl::body Rappture::VtkIsosurfaceViewer::DoRotate {} {
558    SendCmd "camera orient [ViewToQuaternion]"
559    set _rotatePending 0
560}
561
562itcl::body Rappture::VtkIsosurfaceViewer::EventuallyRequestLegend {} {
563    if { !$_legendPending } {
564        set _legendPending 1
565        $_dispatcher event -idle !legend
566    }
567}
568
569itcl::body Rappture::VtkIsosurfaceViewer::EventuallyResize { w h } {
570    set _width $w
571    set _height $h
572    $_arcball resize $w $h
573    if { !$_resizePending } {
574        set _resizePending 1
575        $_dispatcher event -after 400 !resize
576    }
577}
578
579set rotate_delay 100
580
581itcl::body Rappture::VtkIsosurfaceViewer::EventuallyRotate { q } {
582    QuaternionToView $q
583    if { !$_rotatePending } {
584        set _rotatePending 1
585        global rotate_delay
586        $_dispatcher event -after $rotate_delay !rotate
587    }
588}
589
590itcl::body Rappture::VtkIsosurfaceViewer::EventuallySetCutplane { axis args } {
591    if { !$_cutplanePending } {
592        set _cutplanePending 1
593        $_dispatcher event -after 100 !${axis}cutplane
594    }
595}
596
597itcl::body Rappture::VtkIsosurfaceViewer::EventuallyChangeContourLevels {} {
598    set n $_contourList(numLevels)
599    set _contourList(values) ""
600    if { !$_contourList(updatePending) } {
601        set _contourList(updatePending) 1
602        global rotate_delay
603        $_dispatcher event -after $rotate_delay !contours
604    }
605}
606
607# ----------------------------------------------------------------------
608# USAGE: add <dataobj> ?<settings>?
609#
610# Clients use this to add a data object to the plot.  The optional
611# <settings> are used to configure the plot.  Allowed settings are
612# -color, -brightness, -width, -linestyle, and -raise.
613# ----------------------------------------------------------------------
614itcl::body Rappture::VtkIsosurfaceViewer::add {dataobj {settings ""}} {
615    if { ![$dataobj isvalid] } {
616        return;                         # Object doesn't contain valid data.
617    }
618    array set params {
619        -color auto
620        -width 1
621        -linestyle solid
622        -brightness 0
623        -raise 0
624        -description ""
625        -param ""
626        -type ""
627    }
628    array set params $settings
629    set params(-description) ""
630    set params(-param) ""
631    array set params $settings
632
633    if {$params(-color) == "auto" || $params(-color) == "autoreset"} {
634        # can't handle -autocolors yet
635        set params(-color) black
636    }
637    set pos [lsearch -exact $_dlist $dataobj]
638    if {$pos < 0} {
639        lappend _dlist $dataobj
640    }
641    set _obj2ovride($dataobj-color) $params(-color)
642    set _obj2ovride($dataobj-width) $params(-width)
643    set _obj2ovride($dataobj-raise) $params(-raise)
644    $_dispatcher event -idle !rebuild
645}
646
647# ----------------------------------------------------------------------
648# USAGE: delete ?<dataobj1> <dataobj2> ...?
649#
650# Clients use this to delete a dataobj from the plot.  If no dataobjs
651# are specified, then all dataobjs are deleted.  No data objects are
652# deleted.  They are only removed from the display list.
653# ----------------------------------------------------------------------
654itcl::body Rappture::VtkIsosurfaceViewer::delete {args} {
655    if { [llength $args] == 0} {
656        set args $_dlist
657    }
658    # Delete all specified dataobjs
659    set changed 0
660    foreach dataobj $args {
661        set pos [lsearch -exact $_dlist $dataobj]
662        if { $pos < 0 } {
663            continue;                   # Don't know anything about it.
664        }
665        # Remove it from the dataobj list.
666        set _dlist [lreplace $_dlist $pos $pos]
667        array unset _obj2ovride $dataobj-*
668        array unset _settings $dataobj-*
669        set changed 1
670    }
671    # If anything changed, then rebuild the plot
672    if { $changed } {
673        $_dispatcher event -idle !rebuild
674    }
675}
676
677# ----------------------------------------------------------------------
678# USAGE: get ?-objects?
679# USAGE: get ?-visible?
680# USAGE: get ?-image view?
681#
682# Clients use this to query the list of objects being plotted, in
683# order from bottom to top of this result.  The optional "-image"
684# flag can also request the internal images being shown.
685# ----------------------------------------------------------------------
686itcl::body Rappture::VtkIsosurfaceViewer::get {args} {
687    if {[llength $args] == 0} {
688        set args "-objects"
689    }
690
691    set op [lindex $args 0]
692    switch -- $op {
693        "-objects" {
694            # put the dataobj list in order according to -raise options
695            set dlist {}
696            foreach dataobj $_dlist {
697                if { ![IsValidObject $dataobj] } {
698                    continue
699                }
700                if {[info exists _obj2ovride($dataobj-raise)] &&
701                    $_obj2ovride($dataobj-raise)} {
702                    set dlist [linsert $dlist 0 $dataobj]
703                } else {
704                    lappend dlist $dataobj
705                }
706            }
707            return $dlist
708        }
709        "-visible" {
710            set dlist {}
711            foreach dataobj $_dlist {
712                if { ![IsValidObject $dataobj] } {
713                    continue
714                }
715                if { ![info exists _obj2ovride($dataobj-raise)] } {
716                    # No setting indicates that the object isn't visible.
717                    continue
718                }
719                # Otherwise use the -raise parameter to put the object to
720                # the front of the list.
721                if { $_obj2ovride($dataobj-raise) } {
722                    set dlist [linsert $dlist 0 $dataobj]
723                } else {
724                    lappend dlist $dataobj
725                }
726            }
727            return $dlist
728        }
729        -image {
730            if {[llength $args] != 2} {
731                error "wrong # args: should be \"get -image view\""
732            }
733            switch -- [lindex $args end] {
734                view {
735                    return $_image(plot)
736                }
737                default {
738                    error "bad image name \"[lindex $args end]\": should be view"
739                }
740            }
741        }
742        default {
743            error "bad option \"$op\": should be -objects or -image"
744        }
745    }
746}
747
748# ----------------------------------------------------------------------
749# USAGE: scale ?<data1> <data2> ...?
750#
751# Sets the default limits for the overall plot according to the
752# limits of the data for all of the given <data> objects.  This
753# accounts for all objects--even those not showing on the screen.
754# Because of this, the limits are appropriate for all objects as
755# the user scans through data in the ResultSet viewer.
756# ----------------------------------------------------------------------
757itcl::body Rappture::VtkIsosurfaceViewer::scale { args } {
758    foreach dataobj $args {
759        if { ![$dataobj isvalid] } {
760            continue;                   # Object doesn't contain valid data.
761        }
762        foreach axis { x y z } {
763            set lim [$dataobj limits $axis]
764            if { ![info exists _limits($axis)] } {
765                set _limits($axis) $lim
766                continue
767            }
768            foreach {min max} $lim break
769            foreach {amin amax} $_limits($axis) break
770            if { $amin > $min } {
771                set amin $min
772            }
773            if { $amax < $max } {
774                set amax $max
775            }
776            set _limits($axis) [list $amin $amax]
777        }
778        foreach { fname lim } [$dataobj fieldlimits] {
779            if { ![info exists _limits($fname)] } {
780                set _limits($fname) $lim
781
782                # set reasonable defaults for
783                # customrangevmin and customrangevmax
784                foreach {min max} $lim break
785                SetMinMaxGauges $min $max
786                set _settings(-customrangemin) $min
787                set _settings(-customrangemax) $max
788
789                continue
790            }
791            foreach {min max} $lim break
792            foreach {fmin fmax} $_limits($fname) break
793            if { ! $_settings(-customrange) } {
794                SetMinMaxGauges $fmin $fmax
795            }
796            if { $fmin > $min } {
797                set fmin $min
798            }
799            if { $fmax < $max } {
800                set fmax $max
801            }
802            set _limits($fname) [list $fmin $fmax]
803        }
804    }
805}
806
807# ----------------------------------------------------------------------
808# USAGE: download coming
809# USAGE: download controls <downloadCommand>
810# USAGE: download now
811#
812# Clients use this method to create a downloadable representation
813# of the plot.  Returns a list of the form {ext string}, where
814# "ext" is the file extension (indicating the type of data) and
815# "string" is the data itself.
816# ----------------------------------------------------------------------
817itcl::body Rappture::VtkIsosurfaceViewer::download {option args} {
818    switch $option {
819        coming {
820            if {[catch {
821                blt::winop snap $itk_component(plotarea) $_image(download)
822            }]} {
823                $_image(download) configure -width 1 -height 1
824                $_image(download) put #000000
825            }
826        }
827        controls {
828            set popup .vtkviewerdownload
829            if { ![winfo exists .vtkviewerdownload] } {
830                set inner [BuildDownloadPopup $popup [lindex $args 0]]
831            } else {
832                set inner [$popup component inner]
833            }
834            set _downloadPopup(image_controls) $inner.image_frame
835            set num [llength [get]]
836            set num [expr {($num == 1) ? "1 result" : "$num results"}]
837            set word [Rappture::filexfer::label downloadWord]
838            $inner.summary configure -text "$word $num in the following format:"
839            update idletasks            ;# Fix initial sizes
840            return $popup
841        }
842        now {
843            set popup .vtkviewerdownload
844            if {[winfo exists .vtkviewerdownload]} {
845                $popup deactivate
846            }
847            switch -- $_downloadPopup(format) {
848                "image" {
849                    return [$this GetImage [lindex $args 0]]
850                }
851                "vtk" {
852                    return [$this GetVtkData [lindex $args 0]]
853                }
854            }
855            return ""
856        }
857        default {
858            error "bad option \"$option\": should be coming, controls, now"
859        }
860    }
861}
862
863# ----------------------------------------------------------------------
864# USAGE: Connect ?<host:port>,<host:port>...?
865#
866# Clients use this method to establish a connection to a new
867# server, or to reestablish a connection to the previous server.
868# Any existing connection is automatically closed.
869# ----------------------------------------------------------------------
870itcl::body Rappture::VtkIsosurfaceViewer::Connect {} {
871    set _hosts [GetServerList "vtkvis"]
872    if { "" == $_hosts } {
873        return 0
874    }
875    set _reset 1
876    set result [VisViewer::Connect $_hosts]
877    if { $result } {
878        if { $_reportClientInfo }  {
879            # Tell the server the viewer, hub, user and session.
880            # Do this immediately on connect before buffering any commands
881            global env
882
883            set info {}
884            set user "???"
885            if { [info exists env(USER)] } {
886                set user $env(USER)
887            }
888            set session "???"
889            if { [info exists env(SESSION)] } {
890                set session $env(SESSION)
891            }
892            lappend info "version" "$Rappture::version"
893            lappend info "build" "$Rappture::build"
894            lappend info "svnurl" "$Rappture::svnurl"
895            lappend info "installdir" "$Rappture::installdir"
896            lappend info "hub" [exec hostname]
897            lappend info "client" "vtkisosurfaceviewer"
898            lappend info "user" $user
899            lappend info "session" $session
900            SendCmd "clientinfo [list $info]"
901        }
902
903        set w [winfo width $itk_component(view)]
904        set h [winfo height $itk_component(view)]
905        EventuallyResize $w $h
906    }
907    return $result
908}
909
910#
911# isconnected --
912#
913# Indicates if we are currently connected to the visualization server.
914#
915itcl::body Rappture::VtkIsosurfaceViewer::isconnected {} {
916    return [VisViewer::IsConnected]
917}
918
919#
920# disconnect --
921#
922itcl::body Rappture::VtkIsosurfaceViewer::disconnect {} {
923    Disconnect
924    set _reset 1
925}
926
927#
928# Disconnect --
929#
930# Clients use this method to disconnect from the current rendering server.
931#
932itcl::body Rappture::VtkIsosurfaceViewer::Disconnect {} {
933    VisViewer::Disconnect
934
935    $_dispatcher cancel !rebuild
936    $_dispatcher cancel !resize
937    $_dispatcher cancel !rotate
938    $_dispatcher cancel !xcutplane
939    $_dispatcher cancel !ycutplane
940    $_dispatcher cancel !zcutplane
941    $_dispatcher cancel !legend
942    # disconnected -- no more data sitting on server
943    array unset _datasets
944    array unset _colormaps
945}
946
947# ----------------------------------------------------------------------
948# USAGE: ReceiveImage -bytes <size> -type <type> -token <token>
949#
950# Invoked automatically whenever the "image" command comes in from
951# the rendering server.  Indicates that binary image data with the
952# specified <size> will follow.
953# ----------------------------------------------------------------------
954itcl::body Rappture::VtkIsosurfaceViewer::ReceiveImage { args } {
955    array set info {
956        -token "???"
957        -bytes 0
958        -type image
959    }
960    array set info $args
961    set bytes [ReceiveBytes $info(-bytes)]
962    if { $info(-type) == "image" } {
963        if 0 {
964            set f [open "last.ppm" "w"]
965            fconfigure $f -encoding binary
966            puts -nonewline $f $bytes
967            close $f
968        }
969        $_image(plot) configure -data $bytes
970        #set time [clock seconds]
971        #set date [clock format $time]
972        #set w [image width $_image(plot)]
973        #set h [image height $_image(plot)]
974        #puts stderr "$date: received image ${w}x${h} image"
975        if { $_start > 0 } {
976            set finish [clock clicks -milliseconds]
977            #puts stderr "round trip time [expr $finish -$_start] milliseconds"
978            set _start 0
979        }
980    } elseif { $info(type) == "print" } {
981        set tag $this-print-$info(-token)
982        set _hardcopy($tag) $bytes
983    }
984}
985
986#
987# ReceiveDataset --
988#
989itcl::body Rappture::VtkIsosurfaceViewer::ReceiveDataset { args } {
990    if { ![isconnected] } {
991        return
992    }
993    set option [lindex $args 0]
994    switch -- $option {
995        "scalar" {
996            set option [lindex $args 1]
997            switch -- $option {
998                "world" {
999                    foreach { x y z value tag } [lrange $args 2 end] break
1000                }
1001                "pixel" {
1002                    foreach { x y value tag } [lrange $args 2 end] break
1003                }
1004            }
1005        }
1006        "vector" {
1007            set option [lindex $args 1]
1008            switch -- $option {
1009                "world" {
1010                    foreach { x y z vx vy vz tag } [lrange $args 2 end] break
1011                }
1012                "pixel" {
1013                    foreach { x y vx vy vz tag } [lrange $args 2 end] break
1014                }
1015            }
1016        }
1017        "names" {
1018            foreach { name } [lindex $args 1] {
1019                #puts stderr "Dataset: $name"
1020            }
1021        }
1022        default {
1023            error "unknown dataset option \"$option\" from server"
1024        }
1025    }
1026}
1027
1028# ----------------------------------------------------------------------
1029# USAGE: Rebuild
1030#
1031# Called automatically whenever something changes that affects the
1032# data in the widget.  Clears any existing data and rebuilds the
1033# widget to display new data.
1034# ----------------------------------------------------------------------
1035itcl::body Rappture::VtkIsosurfaceViewer::Rebuild {} {
1036    set w [winfo width $itk_component(view)]
1037    set h [winfo height $itk_component(view)]
1038    if { $w < 2 || $h < 2 } {
1039        update
1040        $_dispatcher event -idle !rebuild
1041        return
1042    }
1043
1044    # Turn on buffering of commands to the server.  We don't want to
1045    # be preempted by a server disconnect/reconnect (which automatically
1046    # generates a new call to Rebuild).
1047    StartBufferingCommands
1048
1049    if { $_reset } {
1050        set _width $w
1051        set _height $h
1052        $_arcball resize $w $h
1053        DoResize
1054
1055        # Reset the camera and other view parameters
1056        $_arcball quaternion [ViewToQuaternion]
1057        InitSettings -ortho
1058        DoRotate
1059        PanCamera
1060        set _first ""
1061        InitSettings -background \
1062            -xgrid -ygrid -zgrid -axismode \
1063            -axesvisible -axislabels -axisminorticks
1064        #SendCmd "axis lformat all %g"
1065        StopBufferingCommands
1066        SendCmd "imgflush"
1067        StartBufferingCommands
1068    }
1069    set _first ""
1070    SendCmd "dataset visible 0"
1071    eval scale $_dlist
1072    foreach dataobj [get -objects] {
1073        if { [info exists _obj2ovride($dataobj-raise)] &&  $_first == "" } {
1074            set _first $dataobj
1075            SetCurrentFieldName $dataobj
1076        }
1077        foreach comp [$dataobj components] {
1078            set tag $dataobj-$comp
1079            if { ![info exists _datasets($tag)] } {
1080                set bytes [$dataobj vtkdata $comp]
1081                if 0 {
1082                    set f [open "/tmp/isosurface.vtk" "w"]
1083                    fconfigure $f -translation binary -encoding binary
1084                    puts -nonewline $f $bytes
1085                    close $f
1086                }
1087                set length [string length $bytes]
1088                if { $_reportClientInfo }  {
1089                    set info {}
1090                    lappend info "tool_id"       [$dataobj hints toolid]
1091                    lappend info "tool_name"     [$dataobj hints toolname]
1092                    lappend info "tool_title"    [$dataobj hints tooltitle]
1093                    lappend info "tool_command"  [$dataobj hints toolcommand]
1094                    lappend info "tool_revision" [$dataobj hints toolrevision]
1095                    lappend info "dataset_label" [$dataobj hints label]
1096                    lappend info "dataset_size"  $length
1097                    lappend info "dataset_tag"   $tag
1098                    SendCmd "clientinfo [list $info]"
1099                }
1100                SendCmd "dataset add $tag data follows $length"
1101                SendData $bytes
1102                set _datasets($tag) 1
1103                SetObjectStyle $dataobj $comp
1104            }
1105            if { [info exists _obj2ovride($dataobj-raise)] } {
1106                SendCmd "contour3d visible 1 $tag"
1107            }
1108        }
1109    }
1110
1111    InitSettings -cutplanesvisible -isosurfacevisible -outline
1112    if { $_reset } {
1113        # These are settings that rely on a dataset being loaded.
1114        InitSettings \
1115            -field -range \
1116            -isosurfaceedges -isosurfacelighting -isosurfaceopacity \
1117            -isosurfacewireframe \
1118            -xcutplaneposition -ycutplaneposition -zcutplaneposition \
1119            -xcutplanevisible -ycutplanevisible -zcutplanevisible \
1120            -cutplanepreinterp -numcontours
1121
1122        Zoom reset
1123        foreach axis { x y z } {
1124            set label ""
1125            if { $_first != "" } {
1126                set label [$_first hints ${axis}label]
1127            }
1128            if { $label == "" } {
1129                set label [string toupper $axis]
1130            }
1131            # There may be a space in the axis label.
1132            SendCmd [list axis name $axis $label]
1133        }
1134        if { [array size _fields] < 2 } {
1135            catch {blt::table forget $itk_component(field) $itk_component(field_l)}
1136        }
1137        set _reset 0
1138    }
1139    # Redraw the legend even if we're using the same colormap. The position
1140    # of the isolines may have changed because the range of data changed.
1141    DrawLegend
1142
1143    # Actually write the commands to the server socket.  If it fails, we don't
1144    # care.  We're finished here.
1145    blt::busy hold $itk_component(hull)
1146    StopBufferingCommands;              # Turn off buffering and send commands.
1147    blt::busy release $itk_component(hull)
1148}
1149
1150# ----------------------------------------------------------------------
1151# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1152#
1153# Returns a list of server IDs for the current datasets being displayed.  This
1154# is normally a single ID, but it might be a list of IDs if the current data
1155# object has multiple components.
1156# ----------------------------------------------------------------------
1157itcl::body Rappture::VtkIsosurfaceViewer::CurrentDatasets {args} {
1158    set flag [lindex $args 0]
1159    switch -- $flag {
1160        "-all" {
1161            if { [llength $args] > 1 } {
1162                error "CurrentDatasets: can't specify dataobj after \"-all\""
1163            }
1164            set dlist [get -objects]
1165        }
1166        "-visible" {
1167            if { [llength $args] > 1 } {
1168                set dlist {}
1169                set args [lrange $args 1 end]
1170                foreach dataobj $args {
1171                    if { [info exists _obj2ovride($dataobj-raise)] } {
1172                        lappend dlist $dataobj
1173                    }
1174                }
1175            } else {
1176                set dlist [get -visible]
1177            }
1178        }
1179        default {
1180            set dlist $args
1181        }
1182    }
1183    set rlist ""
1184    foreach dataobj $dlist {
1185        foreach comp [$dataobj components] {
1186            set tag $dataobj-$comp
1187            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1188                lappend rlist $tag
1189            }
1190        }
1191    }
1192    return $rlist
1193}
1194
1195# ----------------------------------------------------------------------
1196# USAGE: Zoom in
1197# USAGE: Zoom out
1198# USAGE: Zoom reset
1199#
1200# Called automatically when the user clicks on one of the zoom
1201# controls for this widget.  Changes the zoom for the current view.
1202# ----------------------------------------------------------------------
1203itcl::body Rappture::VtkIsosurfaceViewer::Zoom {option} {
1204    switch -- $option {
1205        "in" {
1206            set _view(-zoom) [expr {$_view(-zoom)*1.25}]
1207            SendCmd "camera zoom $_view(-zoom)"
1208        }
1209        "out" {
1210            set _view(-zoom) [expr {$_view(-zoom)*0.8}]
1211            SendCmd "camera zoom $_view(-zoom)"
1212        }
1213        "reset" {
1214            array set _view {
1215                -qw      0.853553
1216                -qx      -0.353553
1217                -qy      0.353553
1218                -qz      0.146447
1219                -xpan    0
1220                -ypan    0
1221                -zoom    1.0
1222            }
1223            if { $_first != "" } {
1224                set location [$_first hints camera]
1225                if { $location != "" } {
1226                    array set _view $location
1227                }
1228            }
1229            $_arcball quaternion [ViewToQuaternion]
1230            DoRotate
1231            SendCmd "camera reset"
1232        }
1233    }
1234}
1235
1236itcl::body Rappture::VtkIsosurfaceViewer::PanCamera {} {
1237    set x $_view(-xpan)
1238    set y $_view(-ypan)
1239    SendCmd "camera pan $x $y"
1240}
1241
1242# ----------------------------------------------------------------------
1243# USAGE: Rotate click <x> <y>
1244# USAGE: Rotate drag <x> <y>
1245# USAGE: Rotate release <x> <y>
1246#
1247# Called automatically when the user clicks/drags/releases in the
1248# plot area.  Moves the plot according to the user's actions.
1249# ----------------------------------------------------------------------
1250itcl::body Rappture::VtkIsosurfaceViewer::Rotate {option x y} {
1251    switch -- $option {
1252        "click" {
1253            $itk_component(view) configure -cursor fleur
1254            set _click(x) $x
1255            set _click(y) $y
1256        }
1257        "drag" {
1258            if {[array size _click] == 0} {
1259                Rotate click $x $y
1260            } else {
1261                set w [winfo width $itk_component(view)]
1262                set h [winfo height $itk_component(view)]
1263                if {$w <= 0 || $h <= 0} {
1264                    return
1265                }
1266
1267                if {[catch {
1268                    # this fails sometimes for no apparent reason
1269                    set dx [expr {double($x-$_click(x))/$w}]
1270                    set dy [expr {double($y-$_click(y))/$h}]
1271                }]} {
1272                    return
1273                }
1274                if { $dx == 0 && $dy == 0 } {
1275                    return
1276                }
1277                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1278                EventuallyRotate $q
1279                set _click(x) $x
1280                set _click(y) $y
1281            }
1282        }
1283        "release" {
1284            Rotate drag $x $y
1285            $itk_component(view) configure -cursor ""
1286            catch {unset _click}
1287        }
1288        default {
1289            error "bad option \"$option\": should be click, drag, release"
1290        }
1291    }
1292}
1293
1294itcl::body Rappture::VtkIsosurfaceViewer::Pick {x y} {
1295    foreach tag [CurrentDatasets -visible] {
1296        SendCmd "dataset getscalar pixel $x $y $tag"
1297    }
1298}
1299
1300# ----------------------------------------------------------------------
1301# USAGE: $this Pan click x y
1302#        $this Pan drag x y
1303#        $this Pan release x y
1304#
1305# Called automatically when the user clicks on one of the zoom
1306# controls for this widget.  Changes the zoom for the current view.
1307# ----------------------------------------------------------------------
1308itcl::body Rappture::VtkIsosurfaceViewer::Pan {option x y} {
1309    switch -- $option {
1310        "set" {
1311            set w [winfo width $itk_component(view)]
1312            set h [winfo height $itk_component(view)]
1313            set x [expr $x / double($w)]
1314            set y [expr $y / double($h)]
1315            set _view(-xpan) [expr $_view(-xpan) + $x]
1316            set _view(-ypan) [expr $_view(-ypan) + $y]
1317            PanCamera
1318            return
1319        }
1320        "click" {
1321            set _click(x) $x
1322            set _click(y) $y
1323            $itk_component(view) configure -cursor hand1
1324        }
1325        "drag" {
1326            if { ![info exists _click(x)] } {
1327                set _click(x) $x
1328            }
1329            if { ![info exists _click(y)] } {
1330                set _click(y) $y
1331            }
1332            set w [winfo width $itk_component(view)]
1333            set h [winfo height $itk_component(view)]
1334            set dx [expr ($_click(x) - $x)/double($w)]
1335            set dy [expr ($_click(y) - $y)/double($h)]
1336            set _click(x) $x
1337            set _click(y) $y
1338            set _view(-xpan) [expr $_view(-xpan) - $dx]
1339            set _view(-ypan) [expr $_view(-ypan) - $dy]
1340            PanCamera
1341        }
1342        "release" {
1343            Pan drag $x $y
1344            $itk_component(view) configure -cursor ""
1345        }
1346        default {
1347            error "unknown option \"$option\": should set, click, drag, or release"
1348        }
1349    }
1350}
1351
1352# ----------------------------------------------------------------------
1353# USAGE: InitSettings <what> ?<value>?
1354#
1355# Used internally to update rendering settings whenever parameters
1356# change in the popup settings panel.  Sends the new settings off
1357# to the back end.
1358# ----------------------------------------------------------------------
1359itcl::body Rappture::VtkIsosurfaceViewer::InitSettings { args } {
1360    foreach spec $args {
1361        if { [info exists _settings($_first${spec})] } {
1362            # Reset global setting with dataobj specific setting
1363            set _settings($spec) $_settings($_first${spec})
1364        }
1365        AdjustSetting $spec
1366    }
1367}
1368
1369#
1370# AdjustSetting --
1371#
1372# Changes/updates a specific setting in the widget.  There are
1373# usually user-setable option.  Commands are sent to the render
1374# server.
1375#
1376itcl::body Rappture::VtkIsosurfaceViewer::AdjustSetting {what {value ""}} {
1377    DebugTrace "Enter"
1378    if { ![isconnected] } {
1379        DebugTrace "Not connected"
1380        return
1381    }
1382    switch -- $what {
1383        "-axesvisible" {
1384            set bool $_settings($what)
1385            SendCmd "axis visible all $bool"
1386        }
1387        "-axislabels" {
1388            set bool $_settings($what)
1389            SendCmd "axis labels all $bool"
1390        }
1391        "-axisminorticks" {
1392            set bool $_settings($what)
1393            SendCmd "axis minticks all $bool"
1394        }
1395        "-axismode" {
1396            set mode [$itk_component(axisMode) value]
1397            set mode [$itk_component(axisMode) translate $mode]
1398            set _settings($what) $mode
1399            SendCmd "axis flymode $mode"
1400        }
1401        "-background" {
1402            set bgcolor [$itk_component(background) value]
1403            array set fgcolors {
1404                "black" "white"
1405                "white" "black"
1406                "grey"  "black"
1407            }
1408            configure -plotbackground $bgcolor \
1409                -plotforeground $fgcolors($bgcolor)
1410            $itk_component(view) delete "legend"
1411            DrawLegend
1412        }
1413        "-cutplaneedges" {
1414            set _changed($what) 1
1415            set bool $_settings($what)
1416            SendCmd "cutplane edges $bool"
1417        }
1418        "-cutplanelighting" {
1419            set _changed($what) 1
1420            set bool $_settings($what)
1421            SendCmd "cutplane lighting $bool"
1422        }
1423        "-cutplaneopacity" {
1424            set _changed($what) 1
1425            set _settings($what) [expr $_widget($what) * 0.01]
1426            SendCmd "cutplane opacity $_settings($what)"
1427        }
1428        "-cutplanepreinterp" {
1429            set _changed($what) 1
1430            set bool $_settings($what)
1431            SendCmd "cutplane preinterp $bool"
1432        }
1433        "-cutplanesvisible" {
1434            set _changed($what) 1
1435            set bool $_settings($what)
1436            SendCmd "cutplane visible 0"
1437            if { $bool } {
1438                foreach tag [CurrentDatasets -visible] {
1439                    SendCmd "cutplane visible $bool $tag"
1440                }
1441            }
1442            if { $bool } {
1443                Rappture::Tooltip::for $itk_component(cutplane) \
1444                    "Hide the cutplanes"
1445            } else {
1446                Rappture::Tooltip::for $itk_component(cutplane) \
1447                    "Show the cutplanes"
1448            }
1449        }
1450        "-cutplanewireframe" {
1451            set _changed($what) 1
1452            set bool $_settings($what)
1453            SendCmd "cutplane wireframe $bool"
1454        }
1455        "-colormap" {
1456            set _changed($what) 1
1457            StartBufferingCommands
1458            set color [$itk_component(colormap) value]
1459            set _settings($what) $color
1460            if { $color == "none" } {
1461                if { $_settings(-colormapvisible) } {
1462                    SendCmd "contour3d colormode constant {}"
1463                    set _settings(-colormapvisible) 0
1464                }
1465            } else {
1466                if { !$_settings(-colormapvisible) } {
1467                    SendCmd "contour3d colormode $_colorMode $_curFldName"
1468                    set _settings(-colormapvisible) 1
1469                }
1470                SetCurrentColormap $color
1471            }
1472            StopBufferingCommands
1473            EventuallyRequestLegend
1474        }
1475        "-field" {
1476            set label [$itk_component(field) value]
1477            set fname [$itk_component(field) translate $label]
1478            set _settings($what) $fname
1479            if { [info exists _fields($fname)] } {
1480                foreach { label units components } $_fields($fname) break
1481                if { $components > 1 } {
1482                    set _colorMode vmag
1483                } else {
1484                    set _colorMode scalar
1485                }
1486                set _curFldName $fname
1487                set _curFldLabel $label
1488            } else {
1489                puts stderr "unknown field \"$fname\""
1490                return
1491            }
1492            SendCmd "dataset scalar $_curFldName"
1493            if { ![info exists _limits($_curFldName)] } {
1494                SendCmd "dataset maprange all"
1495            } else {
1496                if { $_settings(-customrange) } {
1497                    set vmin [$itk_component(min) value]
1498                    set vmax [$itk_component(max) value]
1499                } else {
1500                    foreach { vmin vmax } $_limits($_curFldName) break
1501                    # set the min / max gauges with limits from the field
1502                    # the legend's min and max text will be updated
1503                    # when the legend is redrawn in DrawLegend
1504                    SetMinMaxGauges $vmin $vmax
1505                }
1506                SendCmd "dataset maprange explicit $vmin $vmax $_curFldName"
1507            }
1508            SendCmd "cutplane colormode $_colorMode $_curFldName"
1509            SendCmd "contour3d colormode $_colorMode $_curFldName"
1510            GenerateContourList
1511            SendCmd [list contour3d contourlist $_contourList(values)]
1512            SendCmd "camera reset"
1513            DrawLegend
1514        }
1515        "-isolinecolor" {
1516            set color [$itk_component(isolineColor) value]
1517            set _settings($what) $color
1518            DrawLegend
1519        }
1520        "-isosurfaceedges" {
1521            set _changed($what) 1
1522            set bool $_settings($what)
1523            SendCmd "contour3d edges $bool"
1524        }
1525        "-isosurfacelighting" {
1526            set _changed($what) 1
1527            set bool $_settings($what)
1528            SendCmd "contour3d lighting $bool"
1529        }
1530        "-isosurfaceopacity" {
1531            set _changed($what) 1
1532            set _settings($what) [expr $_widget($what) * 0.01]
1533            SendCmd "contour3d opacity $_settings($what)"
1534        }
1535        "-isosurfacevisible" {
1536            set _changed($what) 1
1537            set bool $_settings($what)
1538            SendCmd "contour3d visible 0"
1539            if { $bool } {
1540                foreach tag [CurrentDatasets -visible] {
1541                    SendCmd "contour3d visible $bool $tag"
1542                }
1543                Rappture::Tooltip::for $itk_component(contour) \
1544                    "Hide the isosurface"
1545            } else {
1546                Rappture::Tooltip::for $itk_component(contour) \
1547                    "Show the isosurface"
1548            }
1549        }
1550        "-isosurfacewireframe" {
1551            set _changed($what) 1
1552            set bool $_settings($what)
1553            SendCmd "contour3d wireframe $bool"
1554        }
1555        "-legendvisible" {
1556            if { !$_settings($what) } {
1557                $itk_component(view) delete legend
1558            }
1559            DrawLegend
1560        }
1561        "-numcontours" {
1562            set _changed($what) 1
1563            set _settings($what) [$itk_component(numcontours) value]
1564            if { $_contourList(numLevels) != $_settings($what) } {
1565                set _contourList(numLevels) $_settings($what)
1566                EventuallyChangeContourLevels
1567            }
1568        }
1569        "-ortho" {
1570            set bool $_view($what)
1571            if { $bool } {
1572                SendCmd "camera mode ortho"
1573            } else {
1574                SendCmd "camera mode persp"
1575            }
1576        }
1577        "-outline" {
1578            set _changed($what) 1
1579            set bool $_settings($what)
1580            SendCmd "outline visible 0"
1581            if { $bool } {
1582                foreach tag [CurrentDatasets -visible] {
1583                    SendCmd "outline visible $bool $tag"
1584                }
1585            }
1586        }
1587        "-range" {
1588            if { $_settings(-customrange) } {
1589                set vmin [$itk_component(min) value]
1590                set vmax [$itk_component(max) value]
1591            } else {
1592                foreach { vmin vmax } $_limits($_curFldName) break
1593            }
1594            GenerateContourList
1595            SendCmd [list contour3d contourlist $_contourList(values)]
1596            SendCmd "dataset maprange explicit $vmin $vmax $_curFldName"
1597            DrawLegend
1598        }
1599        "-xcutplanevisible" - "-ycutplanevisible" - "-zcutplanevisible" {
1600            set _changed($what) 1
1601            set axis [string tolower [string range $what 1 1]]
1602            set bool $_settings($what)
1603            if { $bool } {
1604                $itk_component(${axis}position) configure -state normal \
1605                    -troughcolor white
1606            } else {
1607                $itk_component(${axis}position) configure -state disabled \
1608                    -troughcolor grey82
1609            }
1610            SendCmd "cutplane axis $axis $bool"
1611        }
1612        "-xcutplaneposition" - "-ycutplaneposition" - "-zcutplaneposition" {
1613            set _changed($what) 1
1614            set axis [string tolower [string range $what 1 1]]
1615            set pos [expr $_settings($what) * 0.01]
1616            SendCmd "cutplane slice ${axis} ${pos}"
1617            set _cutplanePending 0
1618        }
1619        "-xgrid" - "-ygrid" - "-zgrid" {
1620            set axis [string tolower [string range $what 1 1]]
1621            set bool $_settings($what)
1622            SendCmd "axis grid $axis $bool"
1623        }
1624        default {
1625            error "don't know how to fix $what"
1626        }
1627    }
1628}
1629
1630#
1631# RequestLegend --
1632#
1633# Request a new legend from the server.  The size of the legend
1634# is determined from the height of the canvas.
1635#
1636# This should be called when
1637#   1.  A new current colormap is set.
1638#   2.  Window is resized.
1639#   3.  The limits of the data have changed.  (Just need a redraw).
1640#   4.  Number of isolines have changed. (Just need a redraw).
1641#   5.  Legend becomes visible (Just need a redraw).
1642#
1643itcl::body Rappture::VtkIsosurfaceViewer::RequestLegend {} {
1644    set _legendPending 0
1645    if { ![info exists _fields($_curFldName)] } {
1646        return
1647    }
1648    set fname $_curFldName
1649    set font "Arial 8"
1650    set lineht [font metrics $font -linespace]
1651    set w 12
1652    set h [expr {$_height - 2 * ($lineht + 2)}]
1653    if { $h < 1 } {
1654        return
1655    }
1656    if { [string match "component*" $fname] } {
1657        set title ""
1658    } else {
1659        if { [info exists _fields($fname)] } {
1660            foreach { title units } $_fields($fname) break
1661            if { $units != "" } {
1662                set title [format "%s (%s)" $title $units]
1663            }
1664        } else {
1665            set title $fname
1666        }
1667    }
1668    # If there's a title too, subtract one more line
1669    if { $title != "" } {
1670        incr h -$lineht
1671    }
1672    # Set the legend on the first dataset.
1673    if { $_currentColormap != "" } {
1674        set cmap $_currentColormap
1675        if { ![info exists _colormaps($cmap)] } {
1676            BuildColormap $cmap
1677            set _colormaps($cmap) 1
1678        }
1679        #SendCmd "legend $cmap scalar $_curFldName {} $w $h 0"
1680        SendCmd "legend2 $cmap $w $h"
1681    }
1682}
1683
1684# ----------------------------------------------------------------------
1685# CONFIGURATION OPTION: -plotbackground
1686# ----------------------------------------------------------------------
1687itcl::configbody Rappture::VtkIsosurfaceViewer::plotbackground {
1688    if { [isconnected] } {
1689        set rgb [Color2RGB $itk_option(-plotbackground)]
1690        SendCmd "screen bgcolor $rgb"
1691    }
1692}
1693
1694# ----------------------------------------------------------------------
1695# CONFIGURATION OPTION: -plotforeground
1696# ----------------------------------------------------------------------
1697itcl::configbody Rappture::VtkIsosurfaceViewer::plotforeground {
1698    if { [isconnected] } {
1699        set rgb [Color2RGB $itk_option(-plotforeground)]
1700        SendCmd "axis color all $rgb"
1701        SendCmd "outline color $rgb"
1702        SendCmd "cutplane color $rgb"
1703    }
1704}
1705
1706itcl::body Rappture::VtkIsosurfaceViewer::BuildIsosurfaceTab {} {
1707
1708    set fg [option get $itk_component(hull) font Font]
1709    #set bfg [option get $itk_component(hull) boldFont Font]
1710
1711    set inner [$itk_component(main) insert end \
1712        -title "Isosurface Settings" \
1713        -icon [Rappture::icon volume-on]]
1714    $inner configure -borderwidth 4
1715
1716    checkbutton $inner.contour \
1717        -text "Isosurfaces" \
1718        -variable [itcl::scope _settings(-isosurfacevisible)] \
1719        -command [itcl::code $this AdjustSetting -isosurfacevisible] \
1720        -font "Arial 9"
1721
1722    checkbutton $inner.wireframe \
1723        -text "Wireframe" \
1724        -variable [itcl::scope _settings(-isosurfacewireframe)] \
1725        -command [itcl::code $this AdjustSetting -isosurfacewireframe] \
1726        -font "Arial 9"
1727
1728    checkbutton $inner.lighting \
1729        -text "Enable Lighting" \
1730        -variable [itcl::scope _settings(-isosurfacelighting)] \
1731        -command [itcl::code $this AdjustSetting -isosurfacelighting] \
1732        -font "Arial 9"
1733
1734    checkbutton $inner.edges \
1735        -text "Edges" \
1736        -variable [itcl::scope _settings(-isosurfaceedges)] \
1737        -command [itcl::code $this AdjustSetting -isosurfaceedges] \
1738        -font "Arial 9"
1739
1740    checkbutton $inner.outline \
1741        -text "Outline" \
1742        -variable [itcl::scope _settings(-outline)] \
1743        -command [itcl::code $this AdjustSetting -outline] \
1744        -font "Arial 9"
1745
1746    checkbutton $inner.legend \
1747        -text "Legend" \
1748        -variable [itcl::scope _settings(-legendvisible)] \
1749        -command [itcl::code $this AdjustSetting -legendvisible] \
1750        -font "Arial 9"
1751
1752    label $inner.linecolor_l -text "Isolines" -font "Arial 9"
1753    itk_component add isolineColor {
1754        Rappture::Combobox $inner.linecolor -width 10 -editable 0
1755    }
1756    $inner.linecolor choices insert end \
1757        "black"              "black"            \
1758        "blue"               "blue"             \
1759        "cyan"               "cyan"             \
1760        "green"              "green"            \
1761        "grey"               "grey"             \
1762        "magenta"            "magenta"          \
1763        "orange"             "orange"           \
1764        "red"                "red"              \
1765        "white"              "white"            \
1766        "none"               "none"
1767
1768    $itk_component(isolineColor) value "white"
1769    bind $inner.linecolor <<Value>> \
1770        [itcl::code $this AdjustSetting -isolinecolor]
1771
1772    label $inner.background_l -text "Background" -font "Arial 9"
1773    itk_component add background {
1774        Rappture::Combobox $inner.background -width 10 -editable 0
1775    }
1776    $inner.background choices insert end \
1777        "black"              "black"            \
1778        "white"              "white"            \
1779        "grey"               "grey"
1780
1781    $itk_component(background) value $_settings(-background)
1782    bind $inner.background <<Value>> \
1783        [itcl::code $this AdjustSetting -background]
1784
1785    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1786    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1787        -variable [itcl::scope _widget(-isosurfaceopacity)] \
1788        -width 10 \
1789        -showvalue off \
1790        -command [itcl::code $this AdjustSetting -isosurfaceopacity]
1791    $inner.opacity set [expr $_settings(-isosurfaceopacity) * 100.0]
1792
1793    itk_component add field_l {
1794        label $inner.field_l -text "Field" -font "Arial 9"
1795    } {
1796        ignore -font
1797    }
1798    itk_component add field {
1799        Rappture::Combobox $inner.field -width 10 -editable 0
1800    }
1801    bind $inner.field <<Value>> \
1802        [itcl::code $this AdjustSetting -field]
1803
1804    label $inner.colormap_l -text "Colormap" -font "Arial 9"
1805    itk_component add colormap {
1806        Rappture::Combobox $inner.colormap -width 10 -editable 0
1807    }
1808    $inner.colormap choices insert end [GetColormapList]
1809
1810    $itk_component(colormap) value "BCGYR"
1811    bind $inner.colormap <<Value>> \
1812        [itcl::code $this AdjustSetting -colormap]
1813
1814    label $inner.numcontours_l -text "Number of Isosurfaces" -font "Arial 9"
1815    itk_component add numcontours {
1816        Rappture::Spinint $inner.numcontours \
1817            -min 0 -max 50 -font "arial 9"
1818    }
1819    $itk_component(numcontours) value $_settings(-numcontours)
1820    bind $itk_component(numcontours) <<Value>> \
1821        [itcl::code $this AdjustSetting -numcontours]
1822
1823
1824    # add widgets for setting a custom range on the legend
1825
1826    itk_component add crange {
1827        checkbutton $inner.crange \
1828            -text "Use Custom Range:" \
1829            -variable [itcl::scope _settings(-customrange)] \
1830            -command [itcl::code $this ToggleCustomRange] \
1831            -font "Arial 9"
1832    }
1833
1834    itk_component add l_min {
1835        label $inner.l_min -text "Min" -font "Arial 9"
1836    }
1837    itk_component add min {
1838        Rappture::Gauge $inner.min -font "Arial 9" \
1839            -validatecommand [itcl::code $this LegendRangeValidate "" vmin]
1840    }
1841    bind $itk_component(min) <<Value>> \
1842        [itcl::code $this AdjustSetting -range]
1843
1844    itk_component add l_max {
1845        label $inner.l_max -text "Max" -font "Arial 9"
1846    }
1847    itk_component add max {
1848        Rappture::Gauge $inner.max -font "Arial 9" \
1849            -validatecommand [itcl::code $this LegendRangeValidate "" vmax]
1850    }
1851    bind $itk_component(max) <<Value>> \
1852        [itcl::code $this AdjustSetting -range]
1853
1854    $itk_component(min) configure -state disabled
1855    $itk_component(max) configure -state disabled
1856
1857
1858    blt::table $inner \
1859        0,0 $inner.field_l      -anchor w -pady 2 \
1860        0,1 $inner.field        -anchor w -pady 2 -fill x \
1861        1,0 $inner.colormap_l   -anchor w -pady 2 \
1862        1,1 $inner.colormap     -anchor w -pady 2 -fill x \
1863        2,0 $inner.linecolor_l  -anchor w -pady 2 \
1864        2,1 $inner.linecolor    -anchor w -pady 2 -fill x \
1865        3,0 $inner.background_l -anchor w -pady 2 \
1866        3,1 $inner.background   -anchor w -pady 2 -fill x \
1867        4,0 $inner.numcontours_l -anchor w -pady 2 \
1868        4,1 $inner.numcontours  -anchor w -pady 2 \
1869        5,0 $inner.wireframe    -anchor w -pady 2 -cspan 2 \
1870        6,0 $inner.lighting     -anchor w -pady 2 -cspan 2 \
1871        7,0 $inner.edges        -anchor w -pady 2 -cspan 2 \
1872        8,0 $inner.outline      -anchor w -pady 2 -cspan 2 \
1873        9,0 $inner.legend       -anchor w -pady 2 \
1874        10,0 $inner.opacity_l   -anchor w -pady 2 \
1875        10,1 $inner.opacity     -fill x   -pady 2 -fill x \
1876        11,0 $inner.crange      -anchor w -pady 2 -cspan 2 \
1877        12,0 $inner.l_min       -anchor w -pady 2 \
1878        12,1 $inner.min         -anchor w -pady 2 -fill x \
1879        13,0 $inner.l_max       -anchor w -pady 2 \
1880        13,1 $inner.max         -anchor w -pady 2 -fill x \
1881
1882    blt::table configure $inner r* c* -resize none
1883    blt::table configure $inner r14 c1 -resize expand
1884}
1885
1886itcl::body Rappture::VtkIsosurfaceViewer::BuildAxisTab {} {
1887
1888    set fg [option get $itk_component(hull) font Font]
1889    #set bfg [option get $itk_component(hull) boldFont Font]
1890
1891    set inner [$itk_component(main) insert end \
1892        -title "Axis Settings" \
1893        -icon [Rappture::icon axis2]]
1894    $inner configure -borderwidth 4
1895
1896    checkbutton $inner.visible \
1897        -text "Axes" \
1898        -variable [itcl::scope _settings(-axesvisible)] \
1899        -command [itcl::code $this AdjustSetting -axesvisible] \
1900        -font "Arial 9"
1901
1902    checkbutton $inner.labels \
1903        -text "Axis Labels" \
1904        -variable [itcl::scope _settings(-axislabels)] \
1905        -command [itcl::code $this AdjustSetting -axislabels] \
1906        -font "Arial 9"
1907    label $inner.grid_l -text "Grid" -font "Arial 9"
1908    checkbutton $inner.xgrid \
1909        -text "X" \
1910        -variable [itcl::scope _settings(-xgrid)] \
1911        -command [itcl::code $this AdjustSetting -xgrid] \
1912        -font "Arial 9"
1913    checkbutton $inner.ygrid \
1914        -text "Y" \
1915        -variable [itcl::scope _settings(-ygrid)] \
1916        -command [itcl::code $this AdjustSetting -ygrid] \
1917        -font "Arial 9"
1918    checkbutton $inner.zgrid \
1919        -text "Z" \
1920        -variable [itcl::scope _settings(-zgrid)] \
1921        -command [itcl::code $this AdjustSetting -zgrid] \
1922        -font "Arial 9"
1923    checkbutton $inner.minorticks \
1924        -text "Minor Ticks" \
1925        -variable [itcl::scope _settings(-axisminorticks)] \
1926        -command [itcl::code $this AdjustSetting -axisminorticks] \
1927        -font "Arial 9"
1928
1929    label $inner.mode_l -text "Mode" -font "Arial 9"
1930
1931    itk_component add axisMode {
1932        Rappture::Combobox $inner.mode -width 10 -editable 0
1933    }
1934    $inner.mode choices insert end \
1935        "static_triad"    "static" \
1936        "closest_triad"   "closest" \
1937        "furthest_triad"  "farthest" \
1938        "outer_edges"     "outer"
1939    $itk_component(axisMode) value $_settings(-axismode)
1940    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting -axismode]
1941
1942    blt::table $inner \
1943        0,0 $inner.visible    -anchor w -cspan 4 \
1944        1,0 $inner.labels     -anchor w -cspan 4 \
1945        2,0 $inner.minorticks -anchor w -cspan 4 \
1946        4,0 $inner.grid_l     -anchor w \
1947        4,1 $inner.xgrid      -anchor w \
1948        4,2 $inner.ygrid      -anchor w \
1949        4,3 $inner.zgrid      -anchor w \
1950        5,0 $inner.mode_l     -anchor w -padx { 2 0 } \
1951        5,1 $inner.mode       -fill x   -cspan 3
1952
1953    blt::table configure $inner r* c* -resize none
1954    blt::table configure $inner r7 c6 -resize expand
1955    blt::table configure $inner r3 -height 0.125i
1956}
1957
1958
1959itcl::body Rappture::VtkIsosurfaceViewer::BuildCameraTab {} {
1960    set inner [$itk_component(main) insert end \
1961        -title "Camera Settings" \
1962        -icon [Rappture::icon camera]]
1963    $inner configure -borderwidth 4
1964
1965    label $inner.view_l -text "view" -font "Arial 9"
1966    set f [frame $inner.view]
1967    foreach side { front back left right top bottom } {
1968        button $f.$side  -image [Rappture::icon view$side] \
1969            -command [itcl::code $this SetOrientation $side]
1970        Rappture::Tooltip::for $f.$side "Change the view to $side"
1971        pack $f.$side -side left
1972    }
1973
1974    blt::table $inner \
1975        0,0 $inner.view_l -anchor e -pady 2 \
1976        0,1 $inner.view -anchor w -pady 2
1977    blt::table configure $inner r0 -resize none
1978
1979    set labels { qx qy qz qw xpan ypan zoom }
1980    set row 1
1981    foreach tag $labels {
1982        label $inner.${tag}label -text $tag -font "Arial 9"
1983        entry $inner.${tag} -font "Arial 9"  -bg white \
1984            -textvariable [itcl::scope _view(-$tag)]
1985        bind $inner.${tag} <Return> \
1986            [itcl::code $this camera set -${tag}]
1987        bind $inner.${tag} <KP_Enter> \
1988            [itcl::code $this camera set -${tag}]
1989        blt::table $inner \
1990            $row,0 $inner.${tag}label -anchor e -pady 2 \
1991            $row,1 $inner.${tag} -anchor w -pady 2
1992        blt::table configure $inner r$row -resize none
1993        incr row
1994    }
1995    checkbutton $inner.ortho \
1996        -text "Orthographic Projection" \
1997        -variable [itcl::scope _view(-ortho)] \
1998        -command [itcl::code $this AdjustSetting -ortho] \
1999        -font "Arial 9"
2000    blt::table $inner \
2001            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
2002    blt::table configure $inner r$row -resize none
2003    incr row
2004
2005    blt::table configure $inner c* -resize none
2006    blt::table configure $inner c2 -resize expand
2007    blt::table configure $inner r$row -resize expand
2008}
2009
2010itcl::body Rappture::VtkIsosurfaceViewer::BuildCutplanesTab {} {
2011
2012    set fg [option get $itk_component(hull) font Font]
2013
2014    set inner [$itk_component(main) insert end \
2015        -title "Cutplane Settings" \
2016        -icon [Rappture::icon cutbutton]]
2017
2018    $inner configure -borderwidth 4
2019
2020    checkbutton $inner.visible \
2021        -text "Cutplanes" \
2022        -variable [itcl::scope _settings(-cutplanesvisible)] \
2023        -command [itcl::code $this AdjustSetting -cutplanesvisible] \
2024        -font "Arial 9"
2025
2026    checkbutton $inner.wireframe \
2027        -text "Wireframe" \
2028        -variable [itcl::scope _settings(-cutplanewireframe)] \
2029        -command [itcl::code $this AdjustSetting -cutplanewireframe] \
2030        -font "Arial 9"
2031
2032    checkbutton $inner.lighting \
2033        -text "Enable Lighting" \
2034        -variable [itcl::scope _settings(-cutplanelighting)] \
2035        -command [itcl::code $this AdjustSetting -cutplanelighting] \
2036        -font "Arial 9"
2037
2038    checkbutton $inner.edges \
2039        -text "Edges" \
2040        -variable [itcl::scope _settings(-cutplaneedges)] \
2041        -command [itcl::code $this AdjustSetting -cutplaneedges] \
2042        -font "Arial 9"
2043
2044    checkbutton $inner.preinterp \
2045        -text "Interpolate Scalars" \
2046        -variable [itcl::scope _settings(-cutplanepreinterp)] \
2047        -command [itcl::code $this AdjustSetting -cutplanepreinterp] \
2048        -font "Arial 9"
2049
2050    label $inner.opacity_l -text "Opacity" -font "Arial 9"
2051    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
2052        -variable [itcl::scope _widget(-cutplaneopacity)] \
2053        -width 10 \
2054        -showvalue off \
2055        -command [itcl::code $this AdjustSetting -cutplaneopacity]
2056    $inner.opacity set [expr $_settings(-cutplaneopacity) * 100.0]
2057
2058    # X-value slicer...
2059    itk_component add xbutton {
2060        Rappture::PushButton $inner.xbutton \
2061            -onimage [Rappture::icon x-cutplane-red] \
2062            -offimage [Rappture::icon x-cutplane-red] \
2063            -command [itcl::code $this AdjustSetting -xcutplanevisible] \
2064            -variable [itcl::scope _settings(-xcutplanevisible)] \
2065    }
2066    Rappture::Tooltip::for $itk_component(xbutton) \
2067        "Toggle the X-axis cutplane on/off"
2068    $itk_component(xbutton) select
2069    itk_component add xposition {
2070        ::scale $inner.xval -from 100 -to 0 \
2071            -width 10 -orient vertical -showvalue 1 \
2072            -borderwidth 1 -highlightthickness 0 \
2073            -command [itcl::code $this EventuallySetCutplane x] \
2074            -variable [itcl::scope _settings(-xcutplaneposition)] \
2075            -foreground red2 -font "Arial 9 bold"
2076    } {
2077        usual
2078        ignore -borderwidth -highlightthickness -foreground -font -background
2079    }
2080    # Set the default cutplane value before disabling the scale.
2081    $itk_component(xposition) set 50
2082    $itk_component(xposition) configure -state disabled
2083    Rappture::Tooltip::for $itk_component(xposition) \
2084        "@[itcl::code $this Slice tooltip x]"
2085
2086    # Y-value slicer...
2087    itk_component add ybutton {
2088        Rappture::PushButton $inner.ybutton \
2089            -onimage [Rappture::icon y-cutplane-green] \
2090            -offimage [Rappture::icon y-cutplane-green] \
2091            -command [itcl::code $this AdjustSetting -ycutplanevisible] \
2092            -variable [itcl::scope _settings(-ycutplanevisible)] \
2093    }
2094    Rappture::Tooltip::for $itk_component(ybutton) \
2095        "Toggle the Y-axis cutplane on/off"
2096    $itk_component(ybutton) select
2097
2098    itk_component add yposition {
2099        ::scale $inner.yval -from 100 -to 0 \
2100            -width 10 -orient vertical -showvalue 1 \
2101            -borderwidth 1 -highlightthickness 0 \
2102            -command [itcl::code $this EventuallySetCutplane y] \
2103            -variable [itcl::scope _settings(-ycutplaneposition)] \
2104            -foreground green3 -font "Arial 9 bold"
2105    } {
2106        usual
2107        ignore -borderwidth -highlightthickness -foreground -font
2108    }
2109    Rappture::Tooltip::for $itk_component(yposition) \
2110        "@[itcl::code $this Slice tooltip y]"
2111    # Set the default cutplane value before disabling the scale.
2112    $itk_component(yposition) set 50
2113    $itk_component(yposition) configure -state disabled
2114
2115    # Z-value slicer...
2116    itk_component add zbutton {
2117        Rappture::PushButton $inner.zbutton \
2118            -onimage [Rappture::icon z-cutplane-blue] \
2119            -offimage [Rappture::icon z-cutplane-blue] \
2120            -command [itcl::code $this AdjustSetting -zcutplanevisible] \
2121            -variable [itcl::scope _settings(-zcutplanevisible)] \
2122    } {
2123        usual
2124        ignore -foreground
2125    }
2126    Rappture::Tooltip::for $itk_component(zbutton) \
2127        "Toggle the Z-axis cutplane on/off"
2128    $itk_component(zbutton) select
2129
2130    itk_component add zposition {
2131        ::scale $inner.zval -from 100 -to 0 \
2132            -width 10 -orient vertical -showvalue 1 \
2133            -borderwidth 1 -highlightthickness 0 \
2134            -command [itcl::code $this EventuallySetCutplane z] \
2135            -variable [itcl::scope _settings(-zcutplaneposition)] \
2136            -foreground blue3 -font "Arial 9 bold"
2137    } {
2138        usual
2139        ignore -borderwidth -highlightthickness -foreground -font
2140    }
2141    $itk_component(zposition) set 50
2142    $itk_component(zposition) configure -state disabled
2143    Rappture::Tooltip::for $itk_component(zposition) \
2144        "@[itcl::code $this Slice tooltip z]"
2145
2146    blt::table $inner \
2147        0,0 $inner.visible   -anchor w -pady 2 -cspan 3 \
2148        1,0 $inner.lighting  -anchor w -pady 2 -cspan 3 \
2149        2,0 $inner.wireframe -anchor w -pady 2 -cspan 3 \
2150        3,0 $inner.edges     -anchor w -pady 2 -cspan 3 \
2151        4,0 $inner.preinterp -anchor w -pady 2 -cspan 3 \
2152        5,0 $inner.opacity_l -anchor w -pady 2 -cspan 1 \
2153        5,1 $inner.opacity   -fill x   -pady 2 -cspan 3 \
2154        6,0 $inner.xbutton   -anchor w -padx 2 -pady 2 \
2155        7,0 $inner.ybutton   -anchor w -padx 2 -pady 2 \
2156        8,0 $inner.zbutton   -anchor w -padx 2 -pady 2 \
2157        6,1 $inner.xval      -fill y -rspan 4 \
2158        6,2 $inner.yval      -fill y -rspan 4 \
2159        6,3 $inner.zval      -fill y -rspan 4 \
2160
2161    blt::table configure $inner r* c* -resize none
2162    blt::table configure $inner r9 c4 -resize expand
2163}
2164
2165#
2166# camera --
2167#
2168itcl::body Rappture::VtkIsosurfaceViewer::camera {option args} {
2169    switch -- $option {
2170        "show" {
2171            puts [array get _view]
2172        }
2173        "set" {
2174            set what [lindex $args 0]
2175            set x $_view($what)
2176            set code [catch { string is double $x } result]
2177            if { $code != 0 || !$result } {
2178                return
2179            }
2180            switch -- $what {
2181                "-ortho" {
2182                    if {$_view($what)} {
2183                        SendCmd "camera mode ortho"
2184                    } else {
2185                        SendCmd "camera mode persp"
2186                    }
2187                }
2188                "-xpan" - "-ypan" {
2189                    PanCamera
2190                }
2191                "-qx" - "-qy" - "-qz" - "-qw" {
2192                    set q [ViewToQuaternion]
2193                    $_arcball quaternion $q
2194                    EventuallyRotate $q
2195                }
2196                "-zoom" {
2197                    SendCmd "camera zoom $_view($what)"
2198                }
2199             }
2200        }
2201    }
2202}
2203
2204itcl::body Rappture::VtkIsosurfaceViewer::GetVtkData { args } {
2205    set bytes ""
2206    foreach dataobj [get] {
2207        foreach cname [$dataobj components] {
2208            set tag $dataobj-$cname
2209            set contents [$dataobj vtkdata $cname]
2210            append bytes "$contents\n"
2211        }
2212    }
2213    return [list .vtk $bytes]
2214}
2215
2216itcl::body Rappture::VtkIsosurfaceViewer::GetImage { args } {
2217    if { [image width $_image(download)] > 0 &&
2218         [image height $_image(download)] > 0 } {
2219        set bytes [$_image(download) data -format "jpeg -quality 100"]
2220        set bytes [Rappture::encoding::decode -as b64 $bytes]
2221        return [list .jpg $bytes]
2222    }
2223    return ""
2224}
2225
2226itcl::body Rappture::VtkIsosurfaceViewer::BuildDownloadPopup { popup command } {
2227    Rappture::Balloon $popup \
2228        -title "[Rappture::filexfer::label downloadWord] as..."
2229    set inner [$popup component inner]
2230    label $inner.summary -text "" -anchor w
2231    radiobutton $inner.vtk_button -text "VTK data file" \
2232        -variable [itcl::scope _downloadPopup(format)] \
2233        -font "Arial 9 " \
2234        -value vtk
2235    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
2236    radiobutton $inner.image_button -text "Image File" \
2237        -variable [itcl::scope _downloadPopup(format)] \
2238        -font "Arial 9 " \
2239        -value image
2240    Rappture::Tooltip::for $inner.image_button \
2241        "Save as digital image."
2242
2243    button $inner.ok -text "Save" \
2244        -highlightthickness 0 -pady 2 -padx 3 \
2245        -command $command \
2246        -compound left \
2247        -image [Rappture::icon download]
2248
2249    button $inner.cancel -text "Cancel" \
2250        -highlightthickness 0 -pady 2 -padx 3 \
2251        -command [list $popup deactivate] \
2252        -compound left \
2253        -image [Rappture::icon cancel]
2254
2255    blt::table $inner \
2256        0,0 $inner.summary -cspan 2  \
2257        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2258        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2259        4,1 $inner.cancel -width .9i -fill y \
2260        4,0 $inner.ok -padx 2 -width .9i -fill y
2261    blt::table configure $inner r3 -height 4
2262    blt::table configure $inner r4 -pady 4
2263    raise $inner.image_button
2264    $inner.vtk_button invoke
2265    return $inner
2266}
2267
2268itcl::body Rappture::VtkIsosurfaceViewer::SetObjectStyle { dataobj comp } {
2269    DebugTrace "Enter"
2270    # Parse style string.
2271    set tag $dataobj-$comp
2272    array set style {
2273        -color                  BCGYR
2274        -cutplaneedges          0
2275        -cutplanelighting       1
2276        -cutplaneopacity        1.0
2277        -cutplanepreinterp      1
2278        -cutplanesvisible       0
2279        -cutplanewireframe      0
2280        -edgecolor              black
2281        -edges                  0
2282        -isosurfacevisible      1
2283        -levels                 10
2284        -lighting               1
2285        -linewidth              1.0
2286        -opacity                0.6
2287        -outline                0
2288        -wireframe              0
2289        -xcutplaneposition      50
2290        -xcutplanevisible       1
2291        -ycutplaneposition      50
2292        -ycutplanevisible       1
2293        -zcutplaneposition      50
2294        -zcutplanevisible       1
2295    }
2296    if { $style(-levels) == 1 } {
2297        set style(-opacity) 1.0
2298    }
2299    array set style [$dataobj style $comp]
2300    #DebugTrace [array get style]
2301
2302    # This is too complicated.  We want to set the colormap, number of
2303    # isolines and opacity for the dataset.  They can be the default values,
2304    # the style hints loaded with the dataset, or set by user controls.  As
2305    # datasets get loaded, they first use the defaults that are overidden
2306    # by the style hints.  If the user changes the global controls, then that
2307    # overrides everything else.  I don't know what it means when global
2308    # controls are specified as style hints by each dataset.  It complicates
2309    # the code to handle aberrant cases.
2310
2311    if { $_changed(-isosurfaceedges) } {
2312        set style(-edges) $_settings(-isosurfaceedges)
2313    }
2314    if { $_changed(-isosurfacelighting) } {
2315        set style(-lighting) $_settings(-isosurfacelighting)
2316    }
2317    if { $_changed(-isosurfaceopacity) } {
2318        set style(-opacity) $_settings(-isosurfaceopacity)
2319    }
2320    if { $_changed(-isosurfacewireframe) } {
2321        set style(-wireframe) $_settings(-isosurfacewireframe)
2322    }
2323    if { $_changed(-numcontours) } {
2324        set style(-levels) $_settings(-numcontours)
2325    }
2326    if { $_changed(-colormap) } {
2327        set style(-color) $_settings(-colormap)
2328    }
2329    if { $_currentColormap == "" } {
2330        SetCurrentColormap $style(-color)
2331        $itk_component(colormap) value $style(-color)
2332    }
2333    if { $_contourList(numLevels) != $style(-levels) } {
2334        if { [llength $style(-levels)] > 1 } {
2335            set _contourList(reqValues) [lsort -real $style(-levels)]
2336        } else {
2337            set _settings(-numcontours) $style(-levels)
2338            $itk_component(numcontours) value $style(-levels)
2339            set _contourList(numLevels) $style(-levels)
2340        }
2341        EventuallyChangeContourLevels
2342    }
2343    foreach setting {-outline -isosurfacevisible -cutplanesvisible \
2344                     -xcutplanevisible -ycutplanevisible -zcutplanevisible \
2345                     -xcutplaneposition -ycutplaneposition -zcutplaneposition \
2346                     -cutplaneedges -cutplanelighting -cutplaneopacity \
2347                     -cutplanepreinterp -cutplanewireframe} {
2348        if {$_changed($setting)} {
2349            # User-modified UI setting overrides style
2350            set style($setting) $_settings($setting)
2351        } else {
2352            # Set UI control to style setting (tool provided or default)
2353            set _settings($setting) $style($setting)
2354        }
2355    }
2356
2357    SendCmd "cutplane add $tag"
2358    SendCmd "cutplane color [Color2RGB $itk_option(-plotforeground)] $tag"
2359    foreach axis {x y z} {
2360        set pos [expr $style(-${axis}cutplaneposition) * 0.01]
2361        set visible $style(-${axis}cutplanevisible)
2362        SendCmd "cutplane slice $axis $pos $tag"
2363        SendCmd "cutplane axis $axis $visible $tag"
2364    }
2365    SendCmd "cutplane edges $style(-cutplaneedges) $tag"
2366    SendCmd "cutplane lighting $style(-cutplanelighting) $tag"
2367    SendCmd "cutplane opacity $style(-cutplaneopacity) $tag"
2368    set _widget(-cutplaneopacity) [expr $style(-cutplaneopacity) * 100]
2369    SendCmd "cutplane preinterp $style(-cutplanepreinterp) $tag"
2370    SendCmd "cutplane wireframe $style(-cutplanewireframe) $tag"
2371    SendCmd "cutplane visible $style(-cutplanesvisible) $tag"
2372
2373    SendCmd "outline add $tag"
2374    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
2375    SendCmd "outline visible $style(-outline) $tag"
2376
2377    GenerateContourList
2378    SendCmd [list contour3d add contourlist $_contourList(values) $tag]
2379    SendCmd "contour3d visible $style(-isosurfacevisible) $tag"
2380    SendCmd "contour3d edges $style(-edges) $tag"
2381    set _settings(-isosurfaceedges) $style(-edges)
2382    #SendCmd "contour3d color [Color2RGB $style(-color)] $tag"
2383    SendCmd "contour3d lighting $style(-lighting) $tag"
2384    set _settings(-isosurfacelighting) $style(-lighting)
2385    SendCmd "contour3d linecolor [Color2RGB $style(-edgecolor)] $tag"
2386    SendCmd "contour3d linewidth $style(-linewidth) $tag"
2387    SendCmd "contour3d opacity $style(-opacity) $tag"
2388    set _settings(-isosurfaceopacity) $style(-opacity)
2389    set _widget(-isosurfaceopacity) [expr $style(-opacity) * 100]
2390    SetCurrentColormap $style(-color)
2391    SendCmd "contour3d wireframe $style(-wireframe) $tag"
2392    set _settings(-isosurfacewireframe) $style(-wireframe)
2393}
2394
2395itcl::body Rappture::VtkIsosurfaceViewer::IsValidObject { dataobj } {
2396    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2397        return 0
2398    }
2399    return 1
2400}
2401
2402#
2403# EnterLegend --
2404#
2405itcl::body Rappture::VtkIsosurfaceViewer::EnterLegend { x y } {
2406    SetLegendTip $x $y
2407}
2408
2409#
2410# MotionLegend --
2411#
2412itcl::body Rappture::VtkIsosurfaceViewer::MotionLegend { x y } {
2413    Rappture::Tooltip::tooltip cancel
2414    set c $itk_component(view)
2415    set cw [winfo width $c]
2416    set ch [winfo height $c]
2417    if { $x >= 0 && $x < $cw && $y >= 0 && $y < $ch } {
2418        SetLegendTip $x $y
2419    }
2420}
2421
2422#
2423# LeaveLegend --
2424#
2425itcl::body Rappture::VtkIsosurfaceViewer::LeaveLegend { } {
2426    Rappture::Tooltip::tooltip cancel
2427    .rappturetooltip configure -icon ""
2428}
2429
2430# ----------------------------------------------------------------------
2431# USAGE: LegendB1Motion press <x> <y>
2432# USAGE: LegendB1Motion motion <x> <y>
2433# USAGE: LegendB1Motion release <x> <y>
2434#
2435# Manage actions for Button 1 presses that happen over the legend.
2436# Pressing mouse Button 1 on the legend sends a command to the
2437# visualization server to show a specific isosurface.
2438# ----------------------------------------------------------------------
2439itcl::body Rappture::VtkIsosurfaceViewer::LegendB1Motion { status x y } {
2440
2441    switch -- $status {
2442        "press" {
2443            DisableMouseRotationBindings
2444            LegendProbeSingleContour $x $y
2445        }
2446        "motion" {
2447            DisableMouseRotationBindings
2448            LegendProbeSingleContour $x $y
2449        }
2450        "release" {
2451            AdjustSetting -range
2452            SetupMouseRotationBindings
2453        }
2454        default {
2455            error "bad option \"$option\": should be one of press, motion, release."
2456        }
2457    }
2458}
2459
2460# ----------------------------------------------------------------------
2461# USAGE: LegendPointToValue <x> <y>
2462#
2463# Convert an x,y point on the legend to a numeric isosurface value.
2464# ----------------------------------------------------------------------
2465itcl::body Rappture::VtkIsosurfaceViewer::LegendPointToValue { x y } {
2466
2467    set fname $_curFldName
2468
2469    set font "Arial 8"
2470    set lineht [font metrics $font -linespace]
2471
2472    set ih [image height $_image(legend)]
2473    set iy [expr $y - ($lineht + 2)]
2474
2475    # Compute the value of the point
2476    if { [info exists _limits($fname)] } {
2477        if { $_settings(-customrange) } {
2478            set vmin [$itk_component(min) value]
2479            set vmax [$itk_component(max) value]
2480        } else {
2481            foreach { vmin vmax } $_limits($fname) break
2482        }
2483        set t [expr 1.0 - (double($iy) / double($ih-1))]
2484        set value [expr $t * ($vmax - $vmin) + $vmin]
2485    } else {
2486        set value 0.0
2487    }
2488    return $value
2489}
2490
2491# ----------------------------------------------------------------------
2492# USAGE: LegendProbeSingleContour <x> <y>
2493#
2494# Calculate the isosurface value for the x,y point and send a commands
2495# to the visualization server to show that isosurface.
2496# ----------------------------------------------------------------------
2497itcl::body Rappture::VtkIsosurfaceViewer::LegendProbeSingleContour { x y } {
2498
2499    set value [LegendPointToValue $x $y]
2500    SendCmd [list contour3d contourlist $value]
2501}
2502
2503#
2504# SetLegendTip --
2505#
2506itcl::body Rappture::VtkIsosurfaceViewer::SetLegendTip { x y } {
2507    set fname $_curFldName
2508    set c $itk_component(view)
2509    set w [winfo width $c]
2510    set h [winfo height $c]
2511
2512    set font "Arial 8"
2513    set lineht [font metrics $font -linespace]
2514
2515    set ih [image height $_image(legend)]
2516    set iy [expr $y - ($lineht + 2)]
2517
2518    if { [string match "component*" $fname] } {
2519        set title ""
2520    } else {
2521        if { [info exists _fields($fname)] } {
2522            foreach { title units } $_fields($fname) break
2523            if { $units != "" } {
2524                set title [format "%s (%s)" $title $units]
2525            }
2526        } else {
2527            set title $fname
2528        }
2529    }
2530    # If there's a legend title, increase the offset by the line height.
2531    if { $title != "" } {
2532        incr iy -$lineht
2533    }
2534    # Make a swatch of the selected color
2535    if { [catch { $_image(legend) get 10 $iy } pixel] != 0 } {
2536        return
2537    }
2538    if { ![info exists _image(swatch)] } {
2539        set _image(swatch) [image create photo -width 24 -height 24]
2540    }
2541    set color [eval format "\#%02x%02x%02x" $pixel]
2542    $_image(swatch) put black  -to 0 0 23 23
2543    $_image(swatch) put $color -to 1 1 22 22
2544    .rappturetooltip configure -icon $_image(swatch)
2545
2546    # Compute the value of the point
2547    set value [LegendPointToValue $x $y]
2548
2549    # Setup the location of the tooltip
2550    set tx [expr $x + 15]
2551    set ty [expr $y - 5]
2552
2553    # Setup the text for the tooltip
2554    if { [info exists _isolines($y)] } {
2555        Rappture::Tooltip::text $c [format "$title %g (isosurface)" $_isolines($y)]
2556    } else {
2557        Rappture::Tooltip::text $c [format "$title %g" $value]
2558    }
2559
2560    # Show the tooltip
2561    Rappture::Tooltip::tooltip show $c +$tx,+$ty
2562}
2563
2564# ----------------------------------------------------------------------
2565# USAGE: Slice move x|y|z <newval>
2566#
2567# Called automatically when the user drags the slider to move the
2568# cut plane that slices 3D data.  Gets the current value from the
2569# slider and moves the cut plane to the appropriate point in the
2570# data set.
2571# ----------------------------------------------------------------------
2572itcl::body Rappture::VtkIsosurfaceViewer::Slice {option args} {
2573    switch -- $option {
2574        "move" {
2575            set axis [lindex $args 0]
2576            set newval [lindex $args 1]
2577            if {[llength $args] != 2} {
2578                error "wrong # args: should be \"Slice move x|y|z newval\""
2579            }
2580            set newpos [expr {0.01*$newval}]
2581            SendCmd "cutplane slice $axis $newpos"
2582        }
2583        "tooltip" {
2584            set axis [lindex $args 0]
2585            set val [$itk_component(${axis}position) get]
2586            return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2587        }
2588        default {
2589            error "bad option \"$option\": should be axis, move, or tooltip"
2590        }
2591    }
2592}
2593
2594#
2595# ReceiveLegend --
2596#
2597# Invoked automatically whenever the "legend" command comes in from
2598# the rendering server.  Indicates that binary image data with the
2599# specified <size> will follow.
2600#
2601itcl::body Rappture::VtkIsosurfaceViewer::ReceiveLegend { colormap title min max size } {
2602    DebugTrace "Enter"
2603    set _title $title
2604    regsub {\(mag\)} $title "" _title
2605    if { [IsConnected] } {
2606        set bytes [ReceiveBytes $size]
2607        if { ![info exists _image(legend)] } {
2608            set _image(legend) [image create photo]
2609        }
2610        $_image(legend) configure -data $bytes
2611        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2612        if { [catch {DrawLegend} errs] != 0 } {
2613            global errorInfo
2614            puts stderr "errs=$errs errorInfo=$errorInfo"
2615        }
2616    }
2617}
2618
2619#
2620# DrawLegend --
2621#
2622# Draws the legend on the canvas on the right side of the plot area.
2623#
2624itcl::body Rappture::VtkIsosurfaceViewer::DrawLegend {} {
2625    set fname $_curFldName
2626    set c $itk_component(view)
2627    set w [winfo width $c]
2628    set h [winfo height $c]
2629    set font "Arial 8"
2630    set lineht [font metrics $font -linespace]
2631
2632    if { [string match "component*" $fname] } {
2633        set title ""
2634    } else {
2635        if { [info exists _fields($fname)] } {
2636            foreach { title units } $_fields($fname) break
2637            if { $units != "" } {
2638                set title [format "%s (%s)" $title $units]
2639            }
2640        } else {
2641            set title $fname
2642        }
2643    }
2644    set x [expr $w - 2]
2645    if { !$_settings(-legendvisible) } {
2646        $c delete legend
2647        return
2648    }
2649    if { [$c find withtag "legend"] == "" } {
2650        set y 2
2651        # If there's a legend title, create a text item for the title.
2652        $c create text $x $y \
2653            -anchor ne \
2654            -fill $itk_option(-plotforeground) -tags "title legend" \
2655            -font $font
2656        if { $title != "" } {
2657            incr y $lineht
2658        }
2659        $c create text $x $y \
2660            -anchor ne \
2661            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2662            -font $font
2663        incr y $lineht
2664        $c create image $x $y \
2665            -anchor ne \
2666            -image $_image(legend) -tags "colormap legend"
2667        $c create rectangle $x $y 1 1 \
2668            -fill "" -outline "" -tags "sensor legend"
2669        $c create text $x [expr {$h-2}] \
2670            -anchor se \
2671            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2672            -font $font
2673        $c bind sensor <Enter> [itcl::code $this EnterLegend %x %y]
2674        $c bind sensor <Leave> [itcl::code $this LeaveLegend]
2675        $c bind sensor <Motion> [itcl::code $this MotionLegend %x %y]
2676#        $c bind sensor <ButtonPress-1>   [itcl::code $this LegendB1Motion press %x %y]
2677#        $c bind sensor <B1-Motion>       [itcl::code $this LegendB1Motion motion %x %y]
2678#        $c bind sensor <ButtonRelease-1> [itcl::code $this LegendB1Motion release %x %y]
2679    }
2680    $c delete isoline
2681    set x2 $x
2682    set iw [image width $_image(legend)]
2683    set ih [image height $_image(legend)]
2684    set x1 [expr $x2 - ($iw*12)/10]
2685    set color $_settings(-isolinecolor)
2686    # Draw the isolines on the legend.
2687    array unset _isolines
2688    if { $color != "none"  && [info exists _limits($_curFldName)] &&
2689         $_settings(-numcontours) > 0 } {
2690
2691        if { $_settings(-customrange) } {
2692            set vmin [$itk_component(min) value]
2693            set vmax [$itk_component(max) value]
2694        } else {
2695            foreach { vmin vmax } $_limits($_curFldName) break
2696        }
2697        set range [expr double($vmax - $vmin)]
2698        if { $range <= 0.0 } {
2699            set range 1.0;              # Min is greater or equal to max.
2700        }
2701        set tags "isoline legend"
2702        set offset [expr 2 + $lineht]
2703        if { $title != "" } {
2704            incr offset $lineht
2705        }
2706        foreach value $_contourList(values) {
2707            set norm [expr 1.0 - (($value - $vmin) / $range)]
2708            set y1 [expr int(round(($norm * $ih) + $offset))]
2709            for { set off 0 } { $off < 3 } { incr off } {
2710                set _isolines([expr $y1 + $off]) $value
2711                set _isolines([expr $y1 - $off]) $value
2712            }
2713            $c create line $x1 $y1 $x2 $y1 -fill $color -tags $tags
2714        }
2715    }
2716
2717    $c bind title <ButtonPress> [itcl::code $this LegendTitleAction post]
2718    $c bind title <Enter> [itcl::code $this LegendTitleAction enter]
2719    $c bind title <Leave> [itcl::code $this LegendTitleAction leave]
2720    # Reset the item coordinates according the current size of the plot.
2721    $c itemconfigure title -text $title
2722    if { [info exists _limits($_curFldName)] } {
2723        if { $_settings(-customrange) } {
2724            set vmin [$itk_component(min) value]
2725            set vmax [$itk_component(max) value]
2726        } else {
2727            foreach { vmin vmax } $_limits($_curFldName) break
2728        }
2729        $c itemconfigure vmin -text [format %g $vmin]
2730        $c itemconfigure vmax -text [format %g $vmax]
2731    }
2732    set y 2
2733    # If there's a legend title, move the title to the correct position
2734    if { $title != "" } {
2735        $c itemconfigure title -text $title
2736        $c coords title $x $y
2737        incr y $lineht
2738        $c raise title
2739    }
2740    $c coords vmax $x $y
2741    incr y $lineht
2742    $c coords colormap $x $y
2743    $c coords sensor [expr $x - $iw] $y $x [expr $y + $ih]
2744    $c raise sensor
2745    $c coords vmin $x [expr {$h - 2}]
2746
2747    $c bind vmin <ButtonPress> [itcl::code $this LegendRangeAction popup vmin]
2748    $c bind vmin <Enter> [itcl::code $this LegendRangeAction enter vmin]
2749    $c bind vmin <Leave> [itcl::code $this LegendRangeAction leave vmin]
2750
2751    $c bind vmax <ButtonPress> [itcl::code $this LegendRangeAction popup vmax]
2752    $c bind vmax <Enter> [itcl::code $this LegendRangeAction enter vmax]
2753    $c bind vmax <Leave> [itcl::code $this LegendRangeAction leave vmax]
2754}
2755
2756# ----------------------------------------------------------------------
2757# USAGE: LegendTitleAction post
2758# USAGE: LegendTitleAction enter
2759# USAGE: LegendTitleAction leave
2760# USAGE: LegendTitleAction save
2761#
2762# Used internally to handle the dropdown list for the fields menu combobox.
2763# The post option is invoked when the field title is pressed to launch the
2764# dropdown. The enter option is invoked when the user mouses over the field
2765# title. The leave option is invoked when the user moves the mouse away
2766# from the field title.  The save option is invoked whenever there is a
2767# selection from the list, to alert the visualization server.
2768# ----------------------------------------------------------------------
2769itcl::body Rappture::VtkIsosurfaceViewer::LegendTitleAction {option} {
2770    set c $itk_component(view)
2771    switch -- $option {
2772        post {
2773            foreach { x1 y1 x2 y2 } [$c bbox title] break
2774            set cw [winfo width $itk_component(view)]
2775            set mw [winfo reqwidth $itk_component(fieldmenu)]
2776            set x1 [expr $cw - $mw]
2777            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2778            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2779            tk_popup $itk_component(fieldmenu) $x $y
2780        }
2781        enter {
2782            $c itemconfigure title -fill red
2783        }
2784        leave {
2785            $c itemconfigure title -fill $itk_option(-plotforeground)
2786        }
2787        save {
2788            $itk_component(field) value $_curFldLabel
2789            AdjustSetting -field
2790        }
2791        default {
2792            error "bad option \"$option\": should be post, enter, leave, save"
2793        }
2794    }
2795}
2796
2797# ----------------------------------------------------------------------
2798# USAGE: LegendRangeValidate <widget> <which> <value>
2799#
2800# Used internally to validate a legend range min/max value.
2801# Returns a boolean value telling if <value> was accepted (1) or rejected (0)
2802# If the value is rejected, a tooltip/warning message is popped up
2803# near the widget that asked for the validation, specified by <widget>
2804#
2805# <widget> is the widget where a tooltip/warning message should show up on
2806# <which> is either "vmin" or "vmax".
2807# <value> is the value to be validated.
2808# ----------------------------------------------------------------------
2809itcl::body Rappture::VtkIsosurfaceViewer::LegendRangeValidate {widget which value} {
2810
2811    #check for a valid value
2812    if {[string is double $value] != 1} {
2813        set msg "should be valid number"
2814        if {$widget != ""} {
2815            Rappture::Tooltip::cue $widget $msg
2816        } else {
2817            # error "bad value \"$value\": $msg"
2818            error $msg
2819        }
2820        return 0
2821    }
2822
2823    switch -- $which {
2824        vmin {
2825            # check for min > max
2826            if {$value > [$itk_component(max) value]} {
2827                set msg "min > max, change max first"
2828                if {$widget != ""} {
2829                    Rappture::Tooltip::cue $widget $msg
2830                } else {
2831                    # error "bad value \"$value\": $msg"
2832                    error $msg
2833                }
2834                return 0
2835            }
2836        }
2837        vmax {
2838            # check for max < min
2839            if {$value < [$itk_component(min) value]} {
2840                set msg "max < min, change min first"
2841                if {$widget != ""} {
2842                    Rappture::Tooltip::cue $widget $msg
2843                } else {
2844                    # error "bad value \"$value\": $msg"
2845                    error $msg
2846                }
2847                return 0
2848            }
2849        }
2850        default {
2851            error "bad option \"$which\": should be vmin, vmax"
2852        }
2853    }
2854}
2855
2856itcl::body Rappture::VtkIsosurfaceViewer::MouseOver2Which {} {
2857    switch -- $_mouseOver {
2858        vmin {
2859            set which min
2860        }
2861        vmax {
2862            set which max
2863        }
2864        default {
2865            error "bad _mouseOver \"$_mouseOver\": should be vmin, vmax"
2866        }
2867    }
2868    return $which
2869}
2870
2871# ----------------------------------------------------------------------
2872# USAGE: LegendRangeAction enter <which>
2873# USAGE: LegendRangeAction leave <which>
2874#
2875# USAGE: LegendRangeAction popup <which>
2876# USAGE: LegendRangeAction activate
2877# USAGE: LegendRangeAction validate <value>
2878# USAGE: LegendRangeAction apply <value>
2879#
2880# Used internally to handle the mouseover and popup entry for the field range
2881# inputs.  The enter option is invoked when the user moves the mouse over the
2882# min or max field range. The leave option is invoked when the user moves the
2883# mouse away from the min or max field range. The popup option is invoked when
2884# the user click's on a field range. The popup option stores internally which
2885# widget is requesting a popup ( in the _mouseOver variable) and calls the
2886# activate command of the widget. The widget's activate command calls back to
2887# this method to get the xywh dimensions of the popup editor. After the user
2888# changes focus or sets the value in the editor, the editor calls this methods
2889# validate and apply options to set the value.
2890# ----------------------------------------------------------------------
2891itcl::body Rappture::VtkIsosurfaceViewer::LegendRangeAction {option args} {
2892    set c $itk_component(view)
2893
2894    switch -- $option {
2895        enter {
2896            set which [lindex $args 0]
2897            $c itemconfigure $which -fill red
2898        }
2899        leave {
2900            set which [lindex $args 0]
2901            $c itemconfigure $which -fill $itk_option(-plotforeground)
2902        }
2903        popup {
2904            DisableMouseRotationBindings
2905            set which [lindex $args 0]
2906            set _mouseOver $which
2907            $itk_component(editor) activate
2908        }
2909        activate {
2910            foreach { x1 y1 x2 y2 } [$c bbox $_mouseOver] break
2911            set which [MouseOver2Which]
2912            set info(text) [$itk_component($which) value]
2913            set info(x) [expr $x1 + [winfo rootx $c]]
2914            set info(y) [expr $y1 + [winfo rooty $c]]
2915            set info(w) [expr $x2 - $x1]
2916            set info(h) [expr $y2 - $y1]
2917            return [array get info]
2918        }
2919        validate {
2920            if {[llength $args] != 1} {
2921                error "wrong # args: should be \"editor validate value\""
2922            }
2923
2924            set value [lindex $args 0]
2925            if {[LegendRangeValidate $itk_component(editor) $_mouseOver $value] == 0} {
2926                return 0
2927            }
2928
2929            # value was good, apply it
2930            # reset the mouse rotation bindings
2931            SetupMouseRotationBindings
2932        }
2933        apply {
2934            if {[llength $args] != 1} {
2935                error "wrong # args: should be \"editor apply value\""
2936            }
2937            set value [string trim [lindex $args 0]]
2938
2939            set which [MouseOver2Which]
2940
2941            # only set custom range if value changed
2942            if {[$itk_component($which) value] != $value} {
2943                # set the flag stating the custom range came from the legend
2944                # change the value in the gauge
2945                # turn on crange to enable the labels and gauges
2946                # call AdjustSetting -range (inside ToggleCustomRange)
2947                # to update drawing and legend
2948                set _customRangeClick 0
2949                $itk_component($which) value $value
2950                $itk_component(crange) select
2951                ToggleCustomRange
2952            }
2953        }
2954        default {
2955            error "bad option \"$option\": should be enter, leave, activate, validate, apply"
2956        }
2957    }
2958}
2959
2960# ----------------------------------------------------------------------
2961# USAGE: ToggleCustomRange
2962#
2963# Called whenever the custom range is turned on or off. Used to save
2964# the custom min and custom max set by the user. When the -customrange
2965# setting is turned on, the range min and range max gauges are set
2966# with the last value set by the user, or the default range if no
2967# previous min and max were set.
2968#
2969# When the custom range is turned on, we check how it was turned on
2970# by querying _customRangeClick. If the variable is 1, this means
2971# the user clicked the crange checkbutton and we should pull the
2972# custom range values from our backup variables. If the variable is 0,
2973# the custom range was enabled through the user manipulating the
2974# min and max value in the legend.
2975# ----------------------------------------------------------------------
2976itcl::body Rappture::VtkIsosurfaceViewer::ToggleCustomRange {args} {
2977    if { ! $_settings(-customrange) } {
2978        # custom range was turned off
2979
2980        # disable the min/max labels and gauge widgets
2981        $itk_component(l_min) configure -state disabled
2982        $itk_component(min) configure -state disabled
2983        $itk_component(l_max) configure -state disabled
2984        $itk_component(max) configure -state disabled
2985
2986        # backup the custom range
2987        set _settings(-customrangemin) [$itk_component(min) value]
2988        set _settings(-customrangemax) [$itk_component(max) value]
2989
2990        # set the gauges to dataset's min and max
2991        foreach { vmin vmax } $_limits($_curFldName) break
2992        SetMinMaxGauges $vmin $vmax
2993    } else {
2994        # custom range was turned on
2995
2996        # enable the min/max labels and gauge widgets
2997        $itk_component(l_min) configure -state normal
2998        $itk_component(min) configure -state normal
2999        $itk_component(l_max) configure -state normal
3000        $itk_component(max) configure -state normal
3001
3002        # if the custom range is being turned on by clicking the
3003        # checkbox, restore the min and max gauges from the backup
3004        # variables. otherwise, new values for the min and max
3005        # widgets will be set later from the legend's editor.
3006        if { $_customRangeClick } {
3007            SetMinMaxGauges $_settings(-customrangemin) $_settings(-customrangemax)
3008        }
3009
3010        # reset the click flag
3011        set _customRangeClick 1
3012    }
3013    AdjustSetting -range
3014}
3015
3016# ----------------------------------------------------------------------
3017# USAGE: SetMinMaxGauges <min> <max>
3018#
3019# Set the min and max gauges in the correct order, avoiding the
3020# error where you try to set the min > max before updating the max or
3021# set the max < min before updating the min.
3022#
3023# There are five range cases to consider with our current range validation.
3024# For example:
3025# [2,3] -> [0,1]       : update min first, max last
3026# [2,3] -> [4,5]       : update max first, min last
3027# [2,3] -> [0,2.5]     : update min or max first
3028# [2,3] -> [2.5,5]     : update min or max first
3029# [2,3] -> [2.25,2.75] : update min or max first
3030#
3031# In 4 of the cases we can update min first and max last, so we only
3032# need to check the case where old max < new min, where we update
3033# max first and min last.
3034# ----------------------------------------------------------------------
3035itcl::body Rappture::VtkIsosurfaceViewer::SetMinMaxGauges {min max} {
3036
3037    if { [$itk_component(max) value] < $min} {
3038        # old max < new min
3039        # shift range toward right
3040        # extend max first, then update min
3041        $itk_component(max) value $max
3042        $itk_component(min) value $min
3043    } else {
3044        # extend min first, then update max
3045        $itk_component(min) value $min
3046        $itk_component(max) value $max
3047    }
3048}
3049
3050#
3051# SetCurrentColormap --
3052#
3053itcl::body Rappture::VtkIsosurfaceViewer::SetCurrentColormap { name } {
3054    # Keep track of the colormaps that we build.
3055    if { ![info exists _colormaps($name)] } {
3056        BuildColormap $name
3057        set _colormaps($name) 1
3058    }
3059    set _currentColormap $name
3060    SendCmd "contour3d colormap $_currentColormap"
3061    SendCmd "cutplane colormap $_currentColormap"
3062}
3063
3064#
3065# BuildColormap --
3066#
3067# Build the designated colormap on the server.
3068#
3069itcl::body Rappture::VtkIsosurfaceViewer::BuildColormap { name } {
3070    set cmap [ColorsToColormap $name]
3071    if { [llength $cmap] == 0 } {
3072        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
3073    }
3074    set amap "0.0 1.0 1.0 1.0"
3075    SendCmd "colormap add $name { $cmap } { $amap }"
3076}
3077
3078itcl::body Rappture::VtkIsosurfaceViewer::SetOrientation { side } {
3079    array set positions {
3080        front "1 0 0 0"
3081        back  "0 0 1 0"
3082        left  "0.707107 0 -0.707107 0"
3083        right "0.707107 0 0.707107 0"
3084        top   "0.707107 -0.707107 0 0"
3085        bottom "0.707107 0.707107 0 0"
3086    }
3087    foreach name { -qw -qx -qy -qz } value $positions($side) {
3088        set _view($name) $value
3089    }
3090    set q [ViewToQuaternion]
3091    $_arcball quaternion $q
3092    SendCmd "camera orient $q"
3093    SendCmd "camera reset"
3094    set _view(-xpan) 0
3095    set _view(-ypan) 0
3096    set _view(-zoom) 1.0
3097}
3098
3099itcl::body Rappture::VtkIsosurfaceViewer::GenerateContourList {} {
3100    if { ![info exists _limits($_curFldName)] } {
3101        puts stderr "no _curFldName"
3102        return ""
3103    }
3104    if { $_contourList(numLevels) < 1 } {
3105        # There are tools that set 0 levels to get cutplanes only
3106        #puts stderr "numLevels < 1"
3107        return ""
3108    }
3109    if { [llength $_contourList(reqValues)] > 1 } {
3110        set values $_contourList(reqValues)
3111    } else {
3112        # if custom range has been set, use the custom min and max
3113        # to generate contour list values
3114        if { $_settings(-customrange) } {
3115            set vmin [$itk_component(min) value]
3116            set vmax [$itk_component(max) value]
3117        } else {
3118            # use the field limits to calculate the contour list values
3119            foreach { vmin vmax } $_limits($_curFldName) break
3120        }
3121
3122        set v [blt::vector create \#auto]
3123        $v seq $vmin $vmax [expr $_contourList(numLevels)+2]
3124        $v delete end 0
3125        set values [$v range 0 end]
3126        blt::vector destroy $v
3127    }
3128    set _contourList(values) $values
3129}
3130
3131itcl::body Rappture::VtkIsosurfaceViewer::SetCurrentFieldName { dataobj } {
3132    set _first $dataobj
3133    $itk_component(field) choices delete 0 end
3134    $itk_component(fieldmenu) delete 0 end
3135    array unset _fields
3136    set _curFldName ""
3137    foreach cname [$_first components] {
3138        foreach fname [$_first fieldnames $cname] {
3139            if { [info exists _fields($fname)] } {
3140                continue
3141            }
3142            foreach { label units components } \
3143                [$_first fieldinfo $fname] break
3144            $itk_component(field) choices insert end "$fname" "$label"
3145            $itk_component(fieldmenu) add radiobutton -label "$label" \
3146                -value $label -variable [itcl::scope _curFldLabel] \
3147                -selectcolor red \
3148                -activebackground $itk_option(-plotbackground) \
3149                -activeforeground $itk_option(-plotforeground) \
3150                -font "Arial 8" \
3151                -command [itcl::code $this LegendTitleAction save]
3152            set _fields($fname) [list $label $units $components]
3153            if { $_curFldName == "" } {
3154                set _curFldName $fname
3155                set _curFldLabel $label
3156            }
3157        }
3158    }
3159    $itk_component(field) value $_curFldLabel
3160    if { $_settings(-customrange) } {
3161        set limits [list [$itk_component(min) value] [$itk_component(max) value]]
3162        SendCmd "dataset maprange explicit $limits $_curFldName"
3163        if { $limits != $_currentLimits } {
3164            set _currentLimits $limits
3165            EventuallyChangeContourLevels
3166        }
3167    } else {
3168        if { ![info exists _limits($_curFldName)] } {
3169            SendCmd "dataset maprange all"
3170        } else {
3171            set limits $_limits($_curFldName)
3172            SendCmd "dataset maprange explicit $limits $_curFldName"
3173            if { $limits != $_currentLimits } {
3174                set _currentLimits $limits
3175                EventuallyChangeContourLevels
3176            }
3177        }
3178    }
3179}
Note: See TracBrowser for help on using the repository browser.