source: branches/1.3/gui/scripts/vtkisosurfaceviewer.tcl @ 5181

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

merge r5157:5158 from trunk (surfaceviewer)

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