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

Last change on this file since 5071 was 5071, checked in by ldelgass, 9 years ago

Isosurface viewer fixes: Fix applying UI settings for opacity, numcontours to
new results. Set font option on gauges: still doesn't seem to get rid of bold
text. Use custom min/max to compute isovlues even when they are range is larger
than the intrinsic data range.

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