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

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

merge r4756:4758 from trunk

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