source: branches/1.4/gui/scripts/vtksurfaceviewer.tcl @ 5187

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

s/styles/style/ (for code consistency), remove unused member variables

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