source: branches/1.3/gui/scripts/vtksurfaceviewer.tcl @ 4759

Last change on this file since 4759 was 4759, checked in by ldelgass, 6 years ago

merge r4756:4758 from trunk

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