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

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

Remove unused member var

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