source: trunk/gui/scripts/vtkisosurfaceviewer.tcl

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

Add point size style option to mesh/surface viewers, some fixes for constant
color option.

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