source: branches/uiuc_vtk_viewers/gui/scripts/vtkisosurfaceviewer.tcl @ 5033

Last change on this file since 5033 was 5033, checked in by dkearney, 10 years ago

adding a -validatecommand to gauge.tcl so people can add their own validation
to the widget

using gauge widgets for the min/max fields in the settings tab of the
isosurface viewer instead of entry widgets so we can take advantage of input
validation and tooltip cues. tied the min/max editor values, that are above and
below the legend colormap, to the min/max gauge widgets so they all change at
the same time and read the same values. I think there is still a problem if the
min equals the max value, the legend will still show the same value above and
below the colormap. there may also be a race condition when first setting the
min and max gauge widget values because validation occurs. if the data's min is
greater than the default max of 1 (not sure where this comes from yet) or if
the data max is less than the default min of 0 (not sure where this comes from
either) then an error will be raised.

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