source: branches/blt4_trunk/gui/scripts/vtksurfaceviewer.tcl @ 6210

Last change on this file since 6210 was 6210, checked in by dkearney, 9 years ago

merging r6137 - r6209 from trunk to branches/blt4_trunk

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