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

Last change on this file since 5078 was 5078, checked in by ldelgass, 5 years ago

Isosurface viewer: complete the set of style settings and UI control overrides.

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