source: trunk/gui/scripts/vtksurfaceviewer.tcl

Last change on this file was 6461, checked in by ldelgass, 8 years ago

Add point size style option to mesh/surface viewers, some fixes for constant
color option.

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