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

Last change on this file since 4447 was 4431, checked in by ldelgass, 10 years ago

Merge trunk fixes

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