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

Last change on this file since 4736 was 4736, checked in by ldelgass, 7 years ago

merge r4735 from trunk

File size: 83.2 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_version"  [$dataobj hints toolRevision]
984                    lappend info "tool_title"    [$dataobj hints toolTitle]
985                    lappend info "dataset_label" [$dataobj hints label]
986                    lappend info "dataset_size"  $length
987                    lappend info "dataset_tag"   $tag
988                    SendCmd "clientinfo [list $info]"
989                }
990                SendCmd "dataset add $tag data follows $length"
991                append _outbuf $bytes
992                set _datasets($tag) 1
993                SetObjectStyle $dataobj $comp
994            }
995            lappend _obj2datasets($dataobj) $tag
996            if { [info exists _obj2ovride($dataobj-raise)] } {
997                # Setting dataset visible enables outline
998                # and glyphs
999                SendCmd "dataset visible 1 $tag"
1000            }
1001        }
1002    }
1003
1004    if { $_first != "" } {
1005        $itk_component(field) choices delete 0 end
1006        $itk_component(fieldmenu) delete 0 end
1007        array unset _fields
1008        set _curFldName ""
1009        foreach cname [$_first components] {
1010            foreach fname [$_first fieldnames $cname] {
1011                if { [info exists _fields($fname)] } {
1012                    continue
1013                }
1014                foreach { label units components } \
1015                    [$_first fieldinfo $fname] break
1016                $itk_component(field) choices insert end "$fname" "$label"
1017                $itk_component(fieldmenu) add radiobutton -label "$label" \
1018                    -value $label -variable [itcl::scope _curFldLabel] \
1019                    -selectcolor red \
1020                    -activebackground $itk_option(-plotbackground) \
1021                    -activeforeground $itk_option(-plotforeground) \
1022                    -font "Arial 8" \
1023                    -command [itcl::code $this Combo invoke]
1024                set _fields($fname) [list $label $units $components]
1025                if { $_curFldName == "" } {
1026                    set _curFldName $fname
1027                    set _curFldLabel $label
1028                }
1029            }
1030        }
1031        $itk_component(field) value $_curFldLabel
1032    }
1033    InitSettings -glyphoutline
1034        #-cutplanevisible
1035    if { $_reset } {
1036        # These are settings that rely on a dataset being loaded.
1037        InitSettings \
1038            -glyphlighting \
1039            -field \
1040            -glyphedges -glyphlighting -glyphopacity \
1041            -glyphwireframe
1042
1043        #-cutplanexposition -cutplaneyposition -cutplanezposition \
1044            -cutplanexvisible -cutplaneyvisible -cutplanezvisible \
1045            -cutplanepreinterp
1046
1047        Zoom reset
1048        foreach axis { x y z } {
1049            # Another problem fixed by a <view>. We looking into a data
1050            # object for the name of the axes. This should be global to
1051            # the viewer itself.
1052            set label [$_first hints ${axis}label]
1053            if { $label == "" } {
1054                set label [string toupper $axis]
1055            }
1056            # May be a space in the axis label.
1057            SendCmd [list axis name $axis $label]
1058        }
1059        if { [array size _fields] < 2 } {
1060            catch {blt::table forget $itk_component(field) $itk_component(field_l)}
1061        }
1062        set _reset 0
1063    }
1064
1065    # Actually write the commands to the server socket.  If it fails, we don't
1066    # care.  We're finished here.
1067    blt::busy hold $itk_component(hull)
1068    StopBufferingCommands;              # Turn off buffering and send commands.
1069    blt::busy release $itk_component(hull)
1070}
1071
1072# ----------------------------------------------------------------------
1073# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1074#
1075# Returns a list of server IDs for the current datasets being displayed.  This
1076# is normally a single ID, but it might be a list of IDs if the current data
1077# object has multiple components.
1078# ----------------------------------------------------------------------
1079itcl::body Rappture::VtkGlyphViewer::CurrentDatasets {args} {
1080    set flag [lindex $args 0]
1081    switch -- $flag {
1082        "-all" {
1083            if { [llength $args] > 1 } {
1084                error "CurrentDatasets: can't specify dataobj after \"-all\""
1085            }
1086            set dlist [get -objects]
1087        }
1088        "-visible" {
1089            if { [llength $args] > 1 } {
1090                set dlist {}
1091                set args [lrange $args 1 end]
1092                foreach dataobj $args {
1093                    if { [info exists _obj2ovride($dataobj-raise)] } {
1094                        lappend dlist $dataobj
1095                    }
1096                }
1097            } else {
1098                set dlist [get -visible]
1099            }
1100        }           
1101        default {
1102            set dlist $args
1103        }
1104    }
1105    set rlist ""
1106    foreach dataobj $dlist {
1107        foreach comp [$dataobj components] {
1108            set tag $dataobj-$comp
1109            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1110                lappend rlist $tag
1111            }
1112        }
1113    }
1114    return $rlist
1115}
1116
1117# ----------------------------------------------------------------------
1118# USAGE: Zoom in
1119# USAGE: Zoom out
1120# USAGE: Zoom reset
1121#
1122# Called automatically when the user clicks on one of the zoom
1123# controls for this widget.  Changes the zoom for the current view.
1124# ----------------------------------------------------------------------
1125itcl::body Rappture::VtkGlyphViewer::Zoom {option} {
1126    switch -- $option {
1127        "in" {
1128            set _view(zoom) [expr {$_view(zoom)*1.25}]
1129            SendCmd "camera zoom $_view(zoom)"
1130        }
1131        "out" {
1132            set _view(zoom) [expr {$_view(zoom)*0.8}]
1133            SendCmd "camera zoom $_view(zoom)"
1134        }
1135        "reset" {
1136            array set _view {
1137                qw     0.853553
1138                qx     -0.353553
1139                qy     0.353553
1140                qz     0.146447
1141                zoom   1.0
1142                xpan   0
1143                ypan   0
1144            }
1145            if { $_first != "" } {
1146                set location [$_first hints camera]
1147                if { $location != "" } {
1148                    array set _view $location
1149                }
1150            }
1151            set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1152            $_arcball quaternion $q
1153            DoRotate
1154            SendCmd "camera reset"
1155        }
1156    }
1157}
1158
1159itcl::body Rappture::VtkGlyphViewer::PanCamera {} {
1160    set x $_view(xpan)
1161    set y $_view(ypan)
1162    SendCmd "camera pan $x $y"
1163}
1164
1165# ----------------------------------------------------------------------
1166# USAGE: Rotate click <x> <y>
1167# USAGE: Rotate drag <x> <y>
1168# USAGE: Rotate release <x> <y>
1169#
1170# Called automatically when the user clicks/drags/releases in the
1171# plot area.  Moves the plot according to the user's actions.
1172# ----------------------------------------------------------------------
1173itcl::body Rappture::VtkGlyphViewer::Rotate {option x y} {
1174    switch -- $option {
1175        "click" {
1176            $itk_component(view) configure -cursor fleur
1177            set _click(x) $x
1178            set _click(y) $y
1179        }
1180        "drag" {
1181            if {[array size _click] == 0} {
1182                Rotate click $x $y
1183            } else {
1184                set w [winfo width $itk_component(view)]
1185                set h [winfo height $itk_component(view)]
1186                if {$w <= 0 || $h <= 0} {
1187                    return
1188                }
1189
1190                if {[catch {
1191                    # this fails sometimes for no apparent reason
1192                    set dx [expr {double($x-$_click(x))/$w}]
1193                    set dy [expr {double($y-$_click(y))/$h}]
1194                }]} {
1195                    return
1196                }
1197                if { $dx == 0 && $dy == 0 } {
1198                    return
1199                }
1200                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1201                EventuallyRotate $q
1202                set _click(x) $x
1203                set _click(y) $y
1204            }
1205        }
1206        "release" {
1207            Rotate drag $x $y
1208            $itk_component(view) configure -cursor ""
1209            catch {unset _click}
1210        }
1211        default {
1212            error "bad option \"$option\": should be click, drag, release"
1213        }
1214    }
1215}
1216
1217itcl::body Rappture::VtkGlyphViewer::Pick {x y} {
1218    foreach tag [CurrentDatasets -visible] {
1219        SendCmdNoSplash "dataset getscalar pixel $x $y $tag"
1220    }
1221}
1222
1223# ----------------------------------------------------------------------
1224# USAGE: $this Pan click x y
1225#        $this Pan drag x y
1226#        $this Pan release x y
1227#
1228# Called automatically when the user clicks on one of the zoom
1229# controls for this widget.  Changes the zoom for the current view.
1230# ----------------------------------------------------------------------
1231itcl::body Rappture::VtkGlyphViewer::Pan {option x y} {
1232    switch -- $option {
1233        "set" {
1234            set w [winfo width $itk_component(view)]
1235            set h [winfo height $itk_component(view)]
1236            set x [expr $x / double($w)]
1237            set y [expr $y / double($h)]
1238            set _view(xpan) [expr $_view(xpan) + $x]
1239            set _view(ypan) [expr $_view(ypan) + $y]
1240            PanCamera
1241            return
1242        }
1243        "click" {
1244            set _click(x) $x
1245            set _click(y) $y
1246            $itk_component(view) configure -cursor hand1
1247        }
1248        "drag" {
1249            if { ![info exists _click(x)] } {
1250                set _click(x) $x
1251            }
1252            if { ![info exists _click(y)] } {
1253                set _click(y) $y
1254            }
1255            set w [winfo width $itk_component(view)]
1256            set h [winfo height $itk_component(view)]
1257            set dx [expr ($_click(x) - $x)/double($w)]
1258            set dy [expr ($_click(y) - $y)/double($h)]
1259            set _click(x) $x
1260            set _click(y) $y
1261            set _view(xpan) [expr $_view(xpan) - $dx]
1262            set _view(ypan) [expr $_view(ypan) - $dy]
1263            PanCamera
1264        }
1265        "release" {
1266            Pan drag $x $y
1267            $itk_component(view) configure -cursor ""
1268        }
1269        default {
1270            error "unknown option \"$option\": should set, click, drag, or release"
1271        }
1272    }
1273}
1274
1275# ----------------------------------------------------------------------
1276# USAGE: InitSettings <what> ?<value>?
1277#
1278# Used internally to update rendering settings whenever parameters
1279# change in the popup settings panel.  Sends the new settings off
1280# to the back end.
1281# ----------------------------------------------------------------------
1282itcl::body Rappture::VtkGlyphViewer::InitSettings { args } {
1283    foreach spec $args {
1284        if { [info exists _settings($_first${spec})] } {
1285            # Reset global setting with dataobj specific setting
1286            set _settings($spec) $_settings($_first${spec})
1287        }
1288        AdjustSetting $spec
1289    }
1290}
1291
1292#
1293# AdjustSetting --
1294#
1295#    Changes/updates a specific setting in the widget.  There are
1296#    usually user-setable option.  Commands are sent to the render
1297#    server.
1298#
1299itcl::body Rappture::VtkGlyphViewer::AdjustSetting {what {value ""}} {
1300    if { ![isconnected] } {
1301        return
1302    }
1303    switch -- $what {
1304        "-background" {
1305            set bgcolor [$itk_component(background) value]
1306            array set fgcolors {
1307                "black" "white"
1308                "white" "black"
1309                "grey"  "black"
1310            }
1311            configure -plotbackground $bgcolor \
1312                -plotforeground $fgcolors($bgcolor)
1313            $itk_component(view) delete "legend"
1314            DrawLegend
1315        }
1316        "-axesvisible" {
1317            set bool $_settings($what)
1318            SendCmd "axis visible all $bool"
1319        }
1320        "-axislabels" {
1321            set bool $_settings($what)
1322            SendCmd "axis labels all $bool"
1323        }
1324        "-axisminorticks" {
1325            set bool $_settings($what)
1326            SendCmd "axis minticks all $bool"
1327        }
1328        "-xgrid" - "-ygrid" - "-zgrid" {
1329            set axis [string tolower [string range $what 1 1]]
1330            set bool $_settings($what)
1331            SendCmd "axis grid $axis $bool"
1332        }
1333        "-axismode" {
1334            set mode [$itk_component(axisMode) value]
1335            set mode [$itk_component(axisMode) translate $mode]
1336            set _settings($what) $mode
1337            SendCmd "axis flymode $mode"
1338        }
1339        "-cutplaneedges" {
1340            set bool $_settings($what)
1341            SendCmd "cutplane edges $bool"
1342        }
1343        "-cutplanevisible" {
1344            set bool $_settings($what)
1345            SendCmd "cutplane visible $bool"
1346        }
1347        "-cutplanewireframe" {
1348            set bool $_settings($what)
1349            SendCmd "cutplane wireframe $bool"
1350        }
1351        "-cutplanelighting" {
1352            set bool $_settings($what)
1353            SendCmd "cutplane lighting $bool"
1354        }
1355        "-cutplaneopacity" {
1356            set val $_settings($what)
1357            set sval [expr { 0.01 * double($val) }]
1358            SendCmd "cutplane opacity $sval"
1359        }
1360        "-cutplanepreinterp" {
1361            set bool $_settings($what)
1362            SendCmd "cutplane preinterp $bool"
1363        }
1364        "-cutplanexvisible" - "-cutplaneyvisible" - "-cutplanezvisible" {
1365            set axis [string tolower [string range $what 9 9]]
1366            set bool $_settings($what)
1367            if { $bool } {
1368                $itk_component(${axis}position) configure -state normal \
1369                    -troughcolor white
1370            } else {
1371                $itk_component(${axis}position) configure -state disabled \
1372                    -troughcolor grey82
1373            }
1374            SendCmd "cutplane axis $axis $bool"
1375        }
1376        "-cutplanexposition" - "-cutplaneyposition" - "-cutplanezposition" {
1377            set axis [string tolower [string range $what 9 9]]
1378            set pos [expr $_settings($what) * 0.01]
1379            SendCmd "cutplane slice ${axis} ${pos}"
1380            set _cutplanePending 0
1381        }
1382        "-colormap" {
1383            set _changed($what) 1
1384            StartBufferingCommands
1385            set color [$itk_component(colormap) value]
1386            set _settings($what) $color
1387            if { $color == "none" } {
1388                if { $_settings(-colormapvisible) } {
1389                    SendCmd "glyphs colormode constant {}"
1390                    set _settings(-colormapvisible) 0
1391                }
1392            } else {
1393                if { !$_settings(-colormapvisible) } {
1394                    SendCmd "glyphs colormode $_colorMode $_curFldName"
1395                    set _settings(-colormapvisible) 1
1396                }
1397                SetCurrentColormap $color
1398            }
1399            StopBufferingCommands
1400            EventuallyRequestLegend
1401        }
1402        "-glyphwireframe" {
1403            set bool $_settings($what)
1404            SendCmd "glyphs wireframe $bool"
1405        }
1406        "-glyphvisible" {
1407            set bool $_settings($what)
1408            SendCmd "glyphs visible $bool"
1409            if { $bool } {
1410                Rappture::Tooltip::for $itk_component(glyphs) \
1411                    "Hide the glyph"
1412            } else {
1413                Rappture::Tooltip::for $itk_component(glyphs) \
1414                    "Show the glyph"
1415            }
1416            DrawLegend
1417        }
1418        "-glyphlighting" {
1419            set bool $_settings($what)
1420            SendCmd "glyphs lighting $bool"
1421        }
1422        "-glyphedges" {
1423            set bool $_settings($what)
1424            SendCmd "glyphs edges $bool"
1425        }
1426        "-glyphoutline" {
1427            set bool $_settings($what)
1428            SendCmd "outline visible $bool"
1429        }
1430        "-glyphopacity" {
1431            set val $_settings($what)
1432            set sval [expr { 0.01 * double($val) }]
1433            SendCmd "glyphs opacity $sval"
1434        }
1435        "-glyphscale" {
1436            set val $_settings($what)
1437            if { [string is double $val] } {
1438                SendCmd "glyphs gscale $val"
1439            }
1440        }
1441        "-field" {
1442            set label [$itk_component(field) value]
1443            set fname [$itk_component(field) translate $label]
1444            set _settings($what) $fname
1445            if { [info exists _fields($fname)] } {
1446                foreach { label units components } $_fields($fname) break
1447                if { $components > 1 } {
1448                    set _colorMode vmag
1449                } else {
1450                    set _colorMode scalar
1451                }
1452                set _curFldName $fname
1453                set _curFldLabel $label
1454            } else {
1455                puts stderr "unknown field \"$fname\""
1456                return
1457            }
1458            #if { ![info exists _limits($_curFldName)] } {
1459            #    SendCmd "dataset maprange all"
1460            #} else {
1461            #    SendCmd "dataset maprange explicit $_limits($_curFldName) $_curFldName"
1462            #}
1463            #SendCmd "cutplane colormode $_colorMode $_curFldName"
1464            SendCmd "glyphs colormode $_colorMode $_curFldName"
1465            DrawLegend
1466        }
1467        "-legendvisible" {
1468            if { !$_settings($what) } {
1469                $itk_component(view) delete legend
1470            }
1471            DrawLegend
1472        }
1473        default {
1474            error "don't know how to fix $what"
1475        }
1476    }
1477}
1478
1479#
1480# RequestLegend --
1481#
1482#    Request a new legend from the server.  The size of the legend
1483#    is determined from the height of the canvas. 
1484#
1485# This should be called when
1486#    1.  A new current colormap is set.
1487#    2.  Window is resized.
1488#    3.  The limits of the data have changed.  (Just need a redraw).
1489#    4.  Number of glyph have changed. (Just need a redraw).
1490#    5.  Legend becomes visible (Just need a redraw).
1491#
1492itcl::body Rappture::VtkGlyphViewer::RequestLegend {} {
1493    set _legendPending 0
1494    set font "Arial 8"
1495    set w 12
1496    set lineht [font metrics $font -linespace]
1497    # color ramp height = (canvas height) - (min and max value lines) - 2
1498    set h [expr {$_height - 2 * ($lineht + 2)}]
1499
1500    set fname $_curFldName
1501    if { [string match "component*" $fname] } {
1502        set title ""
1503    } else {
1504        if { [info exists _fields($fname)] } {
1505            foreach { title units } $_fields($fname) break
1506            if { $units != "" } {
1507                set title [format "%s (%s)" $title $units]
1508            }
1509        } else {
1510            set title $fname
1511        }
1512    }
1513    # If there's a title too, substract one more line
1514    if { $title != "" } {
1515        incr h -$lineht
1516    }
1517    if { $h < 1 } {
1518        return
1519    }
1520    # Set the legend on the first heightmap dataset.
1521    if { $_currentColormap != ""  } {
1522        set cmap $_currentColormap
1523        SendCmdNoWait "legend $cmap $_colorMode $_curFldName {} $w $h 0"
1524    }
1525}
1526
1527# ----------------------------------------------------------------------
1528# CONFIGURATION OPTION: -plotbackground
1529# ----------------------------------------------------------------------
1530itcl::configbody Rappture::VtkGlyphViewer::plotbackground {
1531    if { [isconnected] } {
1532        set rgb [Color2RGB $itk_option(-plotbackground)]
1533        SendCmd "screen bgcolor $rgb"
1534    }
1535}
1536
1537# ----------------------------------------------------------------------
1538# CONFIGURATION OPTION: -plotforeground
1539# ----------------------------------------------------------------------
1540itcl::configbody Rappture::VtkGlyphViewer::plotforeground {
1541    if { [isconnected] } {
1542        set rgb [Color2RGB $itk_option(-plotforeground)]
1543        SendCmd "axis color all $rgb"
1544        SendCmd "outline color $rgb"
1545        #SendCmd "cutplane color $rgb"
1546    }
1547}
1548
1549itcl::body Rappture::VtkGlyphViewer::BuildGlyphTab {} {
1550
1551    set fg [option get $itk_component(hull) font Font]
1552    #set bfg [option get $itk_component(hull) boldFont Font]
1553
1554    set inner [$itk_component(main) insert end \
1555        -title "Glyph Settings" \
1556        -icon [Rappture::icon volume-on]]
1557    $inner configure -borderwidth 4
1558
1559    checkbutton $inner.glyphs \
1560        -text "Glyphs" \
1561        -variable [itcl::scope _settings(-glyphvisible)] \
1562        -command [itcl::code $this AdjustSetting -glyphvisible] \
1563        -font "Arial 9"
1564
1565    checkbutton $inner.wireframe \
1566        -text "Wireframe" \
1567        -variable [itcl::scope _settings(-glyphwireframe)] \
1568        -command [itcl::code $this AdjustSetting -glyphwireframe] \
1569        -font "Arial 9"
1570
1571    checkbutton $inner.lighting \
1572        -text "Enable Lighting" \
1573        -variable [itcl::scope _settings(-glyphlighting)] \
1574        -command [itcl::code $this AdjustSetting -glyphlighting] \
1575        -font "Arial 9"
1576
1577    checkbutton $inner.edges \
1578        -text "Edges" \
1579        -variable [itcl::scope _settings(-glyphedges)] \
1580        -command [itcl::code $this AdjustSetting -glyphedges] \
1581        -font "Arial 9"
1582
1583    checkbutton $inner.outline \
1584        -text "Outline" \
1585        -variable [itcl::scope _settings(-glyphoutline)] \
1586        -command [itcl::code $this AdjustSetting -glyphoutline] \
1587        -font "Arial 9"
1588
1589    checkbutton $inner.legend \
1590        -text "Legend" \
1591        -variable [itcl::scope _settings(-legendvisible)] \
1592        -command [itcl::code $this AdjustSetting -legendvisible] \
1593        -font "Arial 9"
1594
1595    label $inner.background_l -text "Background" -font "Arial 9"
1596    itk_component add background {
1597        Rappture::Combobox $inner.background -width 10 -editable no
1598    }
1599    $inner.background choices insert end \
1600        "black"              "black"            \
1601        "white"              "white"            \
1602        "grey"               "grey"             
1603
1604    $itk_component(background) value $_settings(-background)
1605    bind $inner.background <<Value>> [itcl::code $this AdjustSetting -background]
1606
1607    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1608    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1609        -variable [itcl::scope _settings(-glyphopacity)] \
1610        -width 10 \
1611        -showvalue off \
1612        -command [itcl::code $this AdjustSetting -glyphopacity]
1613
1614    label $inner.gscale_l -text "Scale factor" -font "Arial 9"
1615    ::scale $inner.gscale -from 1 -to 100 -orient horizontal \
1616        -variable [itcl::scope _settings(-glyphscale)] \
1617        -width 10 \
1618        -showvalue off \
1619        -command [itcl::code $this AdjustSetting -glyphscale]
1620    Rappture::Tooltip::for $inner.gscale "Set scaling multiplier (or constant size)"
1621
1622    itk_component add field_l {
1623        label $inner.field_l -text "Color By" -font "Arial 9"
1624    } {
1625        ignore -font
1626    }
1627    itk_component add field {
1628        Rappture::Combobox $inner.field -width 10 -editable no
1629    }
1630    bind $inner.field <<Value>> \
1631        [itcl::code $this AdjustSetting -field]
1632
1633    label $inner.colormap_l -text "Colormap" -font "Arial 9"
1634    itk_component add colormap {
1635        Rappture::Combobox $inner.colormap -width 10 -editable no
1636    }
1637
1638    $inner.colormap choices insert end [GetColormapList]
1639    $itk_component(colormap) value "BCGYR"
1640    bind $inner.colormap <<Value>> \
1641        [itcl::code $this AdjustSetting -colormap]
1642
1643    blt::table $inner \
1644        0,0 $inner.field_l      -anchor w -pady 2  \
1645        0,1 $inner.field        -anchor w -pady 2  -fill x \
1646        1,0 $inner.colormap_l   -anchor w -pady 2  \
1647        1,1 $inner.colormap     -anchor w -pady 2  -fill x \
1648        3,0 $inner.background_l -anchor w -pady 2 \
1649        3,1 $inner.background   -anchor w -pady 2  -fill x \
1650        5,0 $inner.wireframe    -anchor w -pady 2 -cspan 2 \
1651        6,0 $inner.lighting     -anchor w -pady 2 -cspan 2 \
1652        7,0 $inner.edges        -anchor w -pady 2 -cspan 2 \
1653        8,0 $inner.outline      -anchor w -pady 2 -cspan 2 \
1654        9,0 $inner.legend       -anchor w -pady 2 \
1655        10,0 $inner.opacity_l   -anchor w -pady 2 \
1656        10,1 $inner.opacity     -fill x   -pady 2 -fill x \
1657
1658    blt::table configure $inner r* c* -resize none
1659    blt::table configure $inner r11 c1 -resize expand
1660}
1661
1662itcl::body Rappture::VtkGlyphViewer::BuildAxisTab {} {
1663
1664    set fg [option get $itk_component(hull) font Font]
1665    #set bfg [option get $itk_component(hull) boldFont Font]
1666
1667    set inner [$itk_component(main) insert end \
1668        -title "Axis Settings" \
1669        -icon [Rappture::icon axis2]]
1670    $inner configure -borderwidth 4
1671
1672    checkbutton $inner.visible \
1673        -text "Axes" \
1674        -variable [itcl::scope _settings(-axesvisible)] \
1675        -command [itcl::code $this AdjustSetting -axesvisible] \
1676        -font "Arial 9"
1677
1678    checkbutton $inner.labels \
1679        -text "Axis Labels" \
1680        -variable [itcl::scope _settings(-axislabels)] \
1681        -command [itcl::code $this AdjustSetting -axislabels] \
1682        -font "Arial 9"
1683    label $inner.grid_l -text "Grid" -font "Arial 9"
1684    checkbutton $inner.xgrid \
1685        -text "X" \
1686        -variable [itcl::scope _settings(-xgrid)] \
1687        -command [itcl::code $this AdjustSetting -xgrid] \
1688        -font "Arial 9"
1689    checkbutton $inner.ygrid \
1690        -text "Y" \
1691        -variable [itcl::scope _settings(-ygrid)] \
1692        -command [itcl::code $this AdjustSetting -ygrid] \
1693        -font "Arial 9"
1694    checkbutton $inner.zgrid \
1695        -text "Z" \
1696        -variable [itcl::scope _settings(-zgrid)] \
1697        -command [itcl::code $this AdjustSetting -zgrid] \
1698        -font "Arial 9"
1699    checkbutton $inner.minorticks \
1700        -text "Minor Ticks" \
1701        -variable [itcl::scope _settings(-axisminorticks)] \
1702        -command [itcl::code $this AdjustSetting -axisminorticks] \
1703        -font "Arial 9"
1704
1705    label $inner.mode_l -text "Mode" -font "Arial 9"
1706
1707    itk_component add axisMode {
1708        Rappture::Combobox $inner.mode -width 10 -editable no
1709    }
1710    $inner.mode choices insert end \
1711        "static_triad"    "static" \
1712        "closest_triad"   "closest" \
1713        "furthest_triad"  "farthest" \
1714        "outer_edges"     "outer"         
1715    $itk_component(axisMode) value $_settings(-axismode)
1716    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting -axismode]
1717
1718    blt::table $inner \
1719        0,0 $inner.visible    -anchor w -cspan 4 \
1720        1,0 $inner.labels     -anchor w -cspan 4 \
1721        2,0 $inner.minorticks -anchor w -cspan 4 \
1722        4,0 $inner.grid_l     -anchor w \
1723        4,1 $inner.xgrid      -anchor w \
1724        4,2 $inner.ygrid      -anchor w \
1725        4,3 $inner.zgrid      -anchor w \
1726        5,0 $inner.mode_l     -anchor w -padx { 2 0 } \
1727        5,1 $inner.mode       -fill x   -cspan 3
1728
1729    blt::table configure $inner r* c* -resize none
1730    blt::table configure $inner r7 c6 -resize expand
1731    blt::table configure $inner r3 -height 0.125i
1732}
1733
1734itcl::body Rappture::VtkGlyphViewer::BuildCameraTab {} {
1735    set inner [$itk_component(main) insert end \
1736        -title "Camera Settings" \
1737        -icon [Rappture::icon camera]]
1738    $inner configure -borderwidth 4
1739
1740    label $inner.view_l -text "view" -font "Arial 9"
1741    set f [frame $inner.view]
1742    foreach side { front back left right top bottom } {
1743        button $f.$side  -image [Rappture::icon view$side] \
1744            -command [itcl::code $this SetOrientation $side]
1745        Rappture::Tooltip::for $f.$side "Change the view to $side"
1746        pack $f.$side -side left
1747    }
1748
1749    blt::table $inner \
1750        0,0 $inner.view_l -anchor e -pady 2 \
1751        0,1 $inner.view -anchor w -pady 2
1752    blt::table configure $inner r0 -resize none
1753
1754    set labels { qx qy qz qw xpan ypan zoom }
1755    set row 1
1756    foreach tag $labels {
1757        label $inner.${tag}label -text $tag -font "Arial 9"
1758        entry $inner.${tag} -font "Arial 9"  -bg white \
1759            -textvariable [itcl::scope _view($tag)]
1760        bind $inner.${tag} <KeyPress-Return> \
1761            [itcl::code $this camera set ${tag}]
1762        blt::table $inner \
1763            $row,0 $inner.${tag}label -anchor e -pady 2 \
1764            $row,1 $inner.${tag} -anchor w -pady 2
1765        blt::table configure $inner r$row -resize none
1766        incr row
1767    }
1768    checkbutton $inner.ortho \
1769        -text "Orthographic Projection" \
1770        -variable [itcl::scope _view(ortho)] \
1771        -command [itcl::code $this camera set ortho] \
1772        -font "Arial 9"
1773    blt::table $inner \
1774            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
1775    blt::table configure $inner r$row -resize none
1776    incr row
1777
1778    blt::table configure $inner c* -resize none
1779    blt::table configure $inner c2 -resize expand
1780    blt::table configure $inner r$row -resize expand
1781}
1782
1783itcl::body Rappture::VtkGlyphViewer::BuildCutplaneTab {} {
1784
1785    set fg [option get $itk_component(hull) font Font]
1786   
1787    set inner [$itk_component(main) insert end \
1788        -title "Cutplane Settings" \
1789        -icon [Rappture::icon cutbutton]]
1790
1791    $inner configure -borderwidth 4
1792
1793    checkbutton $inner.visible \
1794        -text "Cutplanes" \
1795        -variable [itcl::scope _settings(-cutplanevisible)] \
1796        -command [itcl::code $this AdjustSetting -cutplanevisible] \
1797        -font "Arial 9"
1798
1799    checkbutton $inner.wireframe \
1800        -text "Wireframe" \
1801        -variable [itcl::scope _settings(-cutplanewireframe)] \
1802        -command [itcl::code $this AdjustSetting -cutplanewireframe] \
1803        -font "Arial 9"
1804
1805    checkbutton $inner.lighting \
1806        -text "Enable Lighting" \
1807        -variable [itcl::scope _settings(-cutplanelighting)] \
1808        -command [itcl::code $this AdjustSetting -cutplanelighting] \
1809        -font "Arial 9"
1810
1811    checkbutton $inner.edges \
1812        -text "Edges" \
1813        -variable [itcl::scope _settings(-cutplaneedges)] \
1814        -command [itcl::code $this AdjustSetting -cutplaneedges] \
1815        -font "Arial 9"
1816
1817    checkbutton $inner.preinterp \
1818        -text "Interpolate Scalars" \
1819        -variable [itcl::scope _settings(-cutplanepreinterp)] \
1820        -command [itcl::code $this AdjustSetting -cutplanepreinterp] \
1821        -font "Arial 9"
1822
1823    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1824    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1825        -variable [itcl::scope _settings(-cutplaneopacity)] \
1826        -width 10 \
1827        -showvalue off \
1828        -command [itcl::code $this AdjustSetting -cutplaneopacity]
1829    $inner.opacity set $_settings(-cutplaneopacity)
1830
1831    # X-value slicer...
1832    itk_component add xbutton {
1833        Rappture::PushButton $inner.xbutton \
1834            -onimage [Rappture::icon x-cutplane-red] \
1835            -offimage [Rappture::icon x-cutplane-red] \
1836            -command [itcl::code $this AdjustSetting -cutplanexvisible] \
1837            -variable [itcl::scope _settings(-cutplanexvisible)] \
1838    }
1839    Rappture::Tooltip::for $itk_component(xbutton) \
1840        "Toggle the X-axis cutplane on/off"
1841    $itk_component(xbutton) select
1842    itk_component add xposition {
1843        ::scale $inner.xval -from 100 -to 0 \
1844            -width 10 -orient vertical -showvalue yes \
1845            -borderwidth 1 -highlightthickness 0 \
1846            -command [itcl::code $this EventuallySetCutplane x] \
1847            -variable [itcl::scope _settings(-cutplanexposition)] \
1848            -foreground red2 -font "Arial 9 bold"
1849    } {
1850        usual
1851        ignore -borderwidth -highlightthickness -foreground -font -background
1852    }
1853    # Set the default cutplane value before disabling the scale.
1854    $itk_component(xposition) set 50
1855    $itk_component(xposition) configure -state disabled
1856    Rappture::Tooltip::for $itk_component(xposition) \
1857        "@[itcl::code $this Slice tooltip x]"
1858
1859    # Y-value slicer...
1860    itk_component add ybutton {
1861        Rappture::PushButton $inner.ybutton \
1862            -onimage [Rappture::icon y-cutplane-green] \
1863            -offimage [Rappture::icon y-cutplane-green] \
1864            -command [itcl::code $this AdjustSetting -cutplaneyvisible] \
1865            -variable [itcl::scope _settings(-cutplaneyvisible)] \
1866    }
1867    Rappture::Tooltip::for $itk_component(ybutton) \
1868        "Toggle the Y-axis cutplane on/off"
1869    $itk_component(ybutton) select
1870
1871    itk_component add yposition {
1872        ::scale $inner.yval -from 100 -to 0 \
1873            -width 10 -orient vertical -showvalue yes \
1874            -borderwidth 1 -highlightthickness 0 \
1875            -command [itcl::code $this EventuallySetCutplane y] \
1876            -variable [itcl::scope _settings(-cutplaneyposition)] \
1877            -foreground green3 -font "Arial 9 bold"
1878    } {
1879        usual
1880        ignore -borderwidth -highlightthickness -foreground -font
1881    }
1882    Rappture::Tooltip::for $itk_component(yposition) \
1883        "@[itcl::code $this Slice tooltip y]"
1884    # Set the default cutplane value before disabling the scale.
1885    $itk_component(yposition) set 50
1886    $itk_component(yposition) configure -state disabled
1887
1888    # Z-value slicer...
1889    itk_component add zbutton {
1890        Rappture::PushButton $inner.zbutton \
1891            -onimage [Rappture::icon z-cutplane-blue] \
1892            -offimage [Rappture::icon z-cutplane-blue] \
1893            -command [itcl::code $this AdjustSetting -cutplanezvisible] \
1894            -variable [itcl::scope _settings(-cutplanezvisible)] \
1895    } {
1896        usual
1897        ignore -foreground
1898    }
1899    Rappture::Tooltip::for $itk_component(zbutton) \
1900        "Toggle the Z-axis cutplane on/off"
1901    $itk_component(zbutton) select
1902
1903    itk_component add zposition {
1904        ::scale $inner.zval -from 100 -to 0 \
1905            -width 10 -orient vertical -showvalue yes \
1906            -borderwidth 1 -highlightthickness 0 \
1907            -command [itcl::code $this EventuallySetCutplane z] \
1908            -variable [itcl::scope _settings(-cutplanezposition)] \
1909            -foreground blue3 -font "Arial 9 bold"
1910    } {
1911        usual
1912        ignore -borderwidth -highlightthickness -foreground -font
1913    }
1914    $itk_component(zposition) set 50
1915    $itk_component(zposition) configure -state disabled
1916    Rappture::Tooltip::for $itk_component(zposition) \
1917        "@[itcl::code $this Slice tooltip z]"
1918
1919    blt::table $inner \
1920        0,0 $inner.visible   -anchor w -pady 2 -cspan 3 \
1921        1,0 $inner.lighting  -anchor w -pady 2 -cspan 3 \
1922        2,0 $inner.wireframe -anchor w -pady 2 -cspan 3 \
1923        3,0 $inner.edges     -anchor w -pady 2 -cspan 3 \
1924        4,0 $inner.preinterp -anchor w -pady 2 -cspan 3 \
1925        5,0 $inner.opacity_l -anchor w -pady 2 -cspan 1 \
1926        5,1 $inner.opacity   -fill x   -pady 2 -cspan 3 \
1927        6,0 $inner.xbutton   -anchor w -padx 2 -pady 2 \
1928        7,0 $inner.ybutton   -anchor w -padx 2 -pady 2 \
1929        8,0 $inner.zbutton   -anchor w -padx 2 -pady 2 \
1930        6,1 $inner.xval      -fill y -rspan 4 \
1931        6,2 $inner.yval      -fill y -rspan 4 \
1932        6,3 $inner.zval      -fill y -rspan 4 \
1933
1934    blt::table configure $inner r* c* -resize none
1935    blt::table configure $inner r9 c4 -resize expand
1936}
1937
1938#
1939#  camera --
1940#
1941itcl::body Rappture::VtkGlyphViewer::camera {option args} {
1942    switch -- $option {
1943        "show" {
1944            puts [array get _view]
1945        }
1946        "set" {
1947            set who [lindex $args 0]
1948            set x $_view($who)
1949            set code [catch { string is double $x } result]
1950            if { $code != 0 || !$result } {
1951                return
1952            }
1953            switch -- $who {
1954                "ortho" {
1955                    if {$_view(ortho)} {
1956                        SendCmd "camera mode ortho"
1957                    } else {
1958                        SendCmd "camera mode persp"
1959                    }
1960                }
1961                "xpan" - "ypan" {
1962                    PanCamera
1963                }
1964                "qx" - "qy" - "qz" - "qw" {
1965                    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1966                    $_arcball quaternion $q
1967                    EventuallyRotate $q
1968                }
1969                "zoom" {
1970                    SendCmd "camera zoom $_view(zoom)"
1971                }
1972             }
1973        }
1974    }
1975}
1976
1977itcl::body Rappture::VtkGlyphViewer::GetVtkData { args } {
1978    set bytes ""
1979    foreach dataobj [get] {
1980        foreach cname [$dataobj components] {
1981            set tag $dataobj-$cname
1982            set contents [$dataobj vtkdata $cname]
1983            append bytes "$contents\n"
1984        }
1985    }
1986    return [list .vtk $bytes]
1987}
1988
1989itcl::body Rappture::VtkGlyphViewer::GetImage { args } {
1990    if { [image width $_image(download)] > 0 &&
1991         [image height $_image(download)] > 0 } {
1992        set bytes [$_image(download) data -format "jpeg -quality 100"]
1993        set bytes [Rappture::encoding::decode -as b64 $bytes]
1994        return [list .jpg $bytes]
1995    }
1996    return ""
1997}
1998
1999itcl::body Rappture::VtkGlyphViewer::BuildDownloadPopup { popup command } {
2000    Rappture::Balloon $popup \
2001        -title "[Rappture::filexfer::label downloadWord] as..."
2002    set inner [$popup component inner]
2003    label $inner.summary -text "" -anchor w
2004    radiobutton $inner.vtk_button -text "VTK data file" \
2005        -variable [itcl::scope _downloadPopup(format)] \
2006        -font "Arial 9 " \
2007        -value vtk 
2008    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
2009    radiobutton $inner.image_button -text "Image File" \
2010        -variable [itcl::scope _downloadPopup(format)] \
2011        -font "Arial 9 " \
2012        -value image
2013    Rappture::Tooltip::for $inner.image_button \
2014        "Save as digital image."
2015
2016    button $inner.ok -text "Save" \
2017        -highlightthickness 0 -pady 2 -padx 3 \
2018        -command $command \
2019        -compound left \
2020        -image [Rappture::icon download]
2021
2022    button $inner.cancel -text "Cancel" \
2023        -highlightthickness 0 -pady 2 -padx 3 \
2024        -command [list $popup deactivate] \
2025        -compound left \
2026        -image [Rappture::icon cancel]
2027
2028    blt::table $inner \
2029        0,0 $inner.summary -cspan 2  \
2030        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2031        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2032        4,1 $inner.cancel -width .9i -fill y \
2033        4,0 $inner.ok -padx 2 -width .9i -fill y
2034    blt::table configure $inner r3 -height 4
2035    blt::table configure $inner r4 -pady 4
2036    raise $inner.image_button
2037    $inner.vtk_button invoke
2038    return $inner
2039}
2040
2041itcl::body Rappture::VtkGlyphViewer::SetObjectStyle { dataobj comp } {
2042    # Parse style string.
2043    set tag $dataobj-$comp
2044    array set style {
2045        -color BCGYR
2046        -edgecolor black
2047        -edges 0
2048        -gscale 1
2049        -lighting 1
2050        -linewidth 1.0
2051        -normscale 1
2052        -opacity 1.0
2053        -orientGlyphs 1
2054        -outline 0
2055        -ptsize 1.0
2056        -quality 1
2057        -scaleMode "vmag"
2058        -shape "arrow"
2059        -wireframe 0
2060    }
2061    set numComponents [$dataobj numComponents $comp]
2062    if {$numComponents == 3} {
2063        set style(-shape) "arrow"
2064        set style(-orientGlyphs) 1
2065        set style(-scaleMode) "vmag"
2066    } else {
2067        set style(-shape) "sphere"
2068        set style(-orientGlyphs) 0
2069        set style(-scaleMode) "scalar"
2070    }
2071    array set style [$dataobj style $comp]
2072    if { $dataobj != $_first } {
2073        set style(-opacity) 1
2074    }
2075    if 0 {
2076    SendCmd "cutplane add $tag"
2077    SendCmd "cutplane visible 0 $tag"
2078    }
2079    # This is too complicated.  We want to set the colormap, number of
2080    # glyph and opacity for the dataset.  They can be the default values,
2081    # the style hints loaded with the dataset, or set by user controls.  As
2082    # datasets get loaded, they first use the defaults that are overidden
2083    # by the style hints.  If the user changes the global controls, then that
2084    # overrides everything else.  I don't know what it means when global
2085    # controls are specified as style hints by each dataset.  It complicates
2086    # the code to handle aberrant cases.
2087
2088    if { $_changed(-glyphopacity) } {
2089        set style(-opacity) [expr $_settings(-glyphopacity) * 0.01]
2090    }
2091    if { $_changed(-colormap) } {
2092        set style(-color) $_settings(-colormap)
2093    }
2094    if { $_currentColormap == "" } {
2095        $itk_component(colormap) value $style(-color)
2096    }
2097
2098    SendCmd "outline add $tag"
2099    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
2100    SendCmd "outline visible $style(-outline) $tag"
2101    set _settings(-glyphoutline) $style(-outline)
2102
2103    SendCmd "glyphs add $style(-shape) $tag"
2104    SendCmd "glyphs edges $style(-edges) $tag"
2105    set _settings(-glyphedges) $style(-edges)
2106
2107    # normscale=1 and gscale=1 are defaults
2108    if {$style(-normscale) != 1} {
2109        SendCmd "glyphs normscale $style(-normscale) $tag"
2110    }
2111    if {$style(-gscale) != 1} {
2112        SendCmd "glyphs gscale $style(-gscale) $tag"
2113    }
2114
2115    # constant color only used if colormode set to constant
2116    SendCmd "glyphs color [Color2RGB $itk_option(-plotforeground)] $tag"
2117    # Omitting field name for gorient and smode commands
2118    # defaults to active scalars or vectors depending on mode
2119    SendCmd "glyphs gorient $style(-orientGlyphs) {} $tag"
2120    SendCmd "glyphs smode $style(-scaleMode) {} $tag"
2121    SendCmd "glyphs quality $style(-quality) $tag"
2122    SendCmd "glyphs lighting $style(-lighting) $tag"
2123    set _settings(-glyphlighting) $style(-lighting)
2124    SendCmd "glyphs linecolor [Color2RGB $style(-edgecolor)] $tag"
2125    SendCmd "glyphs linewidth $style(-linewidth) $tag"
2126    SendCmd "glyphs ptsize $style(-ptsize) $tag"
2127    SendCmd "glyphs opacity $style(-opacity) $tag"
2128    set _settings(-glyphopacity) [expr $style(-opacity) * 100.0]
2129    SetCurrentColormap $style(-color)
2130    SendCmd "glyphs wireframe $style(-wireframe) $tag"
2131    set _settings(-glyphwireframe) $style(-wireframe)
2132}
2133
2134itcl::body Rappture::VtkGlyphViewer::IsValidObject { dataobj } {
2135    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2136        return 0
2137    }
2138    return 1
2139}
2140
2141#
2142# EnterLegend --
2143#
2144itcl::body Rappture::VtkGlyphViewer::EnterLegend { x y } {
2145    SetLegendTip $x $y
2146}
2147
2148#
2149# MotionLegend --
2150#
2151itcl::body Rappture::VtkGlyphViewer::MotionLegend { x y } {
2152    Rappture::Tooltip::tooltip cancel
2153    set c $itk_component(view)
2154    set cw [winfo width $c]
2155    set ch [winfo height $c]
2156    if { $x >= 0 && $x < $cw && $y >= 0 && $y < $ch } {
2157        SetLegendTip $x $y
2158    }
2159}
2160
2161#
2162# LeaveLegend --
2163#
2164itcl::body Rappture::VtkGlyphViewer::LeaveLegend { } {
2165    Rappture::Tooltip::tooltip cancel
2166    .rappturetooltip configure -icon ""
2167}
2168
2169#
2170# SetLegendTip --
2171#
2172itcl::body Rappture::VtkGlyphViewer::SetLegendTip { x y } {
2173    set fname $_curFldName
2174    set c $itk_component(view)
2175    set w [winfo width $c]
2176    set h [winfo height $c]
2177
2178    set font "Arial 8"
2179    set lineht [font metrics $font -linespace]
2180   
2181    set ih [image height $_image(legend)]
2182    set iy [expr $y - ($lineht + 2)]
2183
2184    if { [string match "component*" $fname] } {
2185        set title ""
2186    } else {
2187        if { [info exists _fields($fname)] } {
2188            foreach { title units } $_fields($fname) break
2189            if { $units != "" } {
2190                set title [format "%s (%s)" $title $units]
2191            }
2192        } else {
2193            set title $fname
2194        }
2195    }
2196    # If there's a legend title, increase the offset by the line height.
2197    if { $title != "" } {
2198        incr iy -$lineht
2199    }
2200    # Make a swatch of the selected color
2201    if { [catch { $_image(legend) get 10 $iy } pixel] != 0 } {
2202        return
2203    }
2204    if { ![info exists _image(swatch)] } {
2205        set _image(swatch) [image create photo -width 24 -height 24]
2206    }
2207    set color [eval format "\#%02x%02x%02x" $pixel]
2208    $_image(swatch) put black  -to 0 0 23 23
2209    $_image(swatch) put $color -to 1 1 22 22
2210    .rappturetooltip configure -icon $_image(swatch)
2211
2212    # Compute the value of the point
2213    if { [info exists _limits($_curFldName)] } {
2214        foreach { vmin vmax } $_limits($_curFldName) break
2215        set t [expr 1.0 - (double($iy) / double($ih-1))]
2216        set value [expr $t * ($vmax - $vmin) + $vmin]
2217    } else {
2218        set value 0.0
2219    }
2220    set tx [expr $x + 15]
2221    set ty [expr $y - 5]
2222    Rappture::Tooltip::text $c [format "$title %g" $value]
2223    Rappture::Tooltip::tooltip show $c +$tx,+$ty   
2224}
2225
2226# ----------------------------------------------------------------------
2227# USAGE: Slice move x|y|z <newval>
2228#
2229# Called automatically when the user drags the slider to move the
2230# cut plane that slices 3D data.  Gets the current value from the
2231# slider and moves the cut plane to the appropriate point in the
2232# data set.
2233# ----------------------------------------------------------------------
2234itcl::body Rappture::VtkGlyphViewer::Slice {option args} {
2235    switch -- $option {
2236        "move" {
2237            set axis [lindex $args 0]
2238            set newval [lindex $args 1]
2239            if {[llength $args] != 2} {
2240                error "wrong # args: should be \"Slice move x|y|z newval\""
2241            }
2242            set newpos [expr {0.01*$newval}]
2243            SendCmd "cutplane slice $axis $newpos"
2244        }
2245        "tooltip" {
2246            set axis [lindex $args 0]
2247            set val [$itk_component(${axis}position) get]
2248            return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2249        }
2250        default {
2251            error "bad option \"$option\": should be axis, move, or tooltip"
2252        }
2253    }
2254}
2255
2256#
2257# ReceiveLegend --
2258#
2259#    Invoked automatically whenever the "legend" command comes in from
2260#    the rendering server.  Indicates that binary image data with the
2261#    specified <size> will follow.
2262#
2263itcl::body Rappture::VtkGlyphViewer::ReceiveLegend { colormap title min max size } {
2264    #puts stderr "ReceiveLegend colormap=$colormap title=$title range=$min,$max size=$size"
2265    set _title $title
2266    regsub {\(mag\)} $title "" _title
2267    if { [IsConnected] } {
2268        set bytes [ReceiveBytes $size]
2269        if { ![info exists _image(legend)] } {
2270            set _image(legend) [image create photo]
2271        }
2272        $_image(legend) configure -data $bytes
2273        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2274        if { [catch {DrawLegend} errs] != 0 } {
2275            global errorInfo
2276            puts stderr "errs=$errs errorInfo=$errorInfo"
2277        }
2278    }
2279}
2280
2281#
2282# DrawLegend --
2283#
2284#    Draws the legend in the own canvas on the right side of the plot area.
2285#
2286itcl::body Rappture::VtkGlyphViewer::DrawLegend {} {
2287    set fname $_curFldName
2288    set c $itk_component(view)
2289    set w [winfo width $c]
2290    set h [winfo height $c]
2291    set font "Arial 8"
2292    set lineht [font metrics $font -linespace]
2293   
2294    if { [string match "component*" $fname] } {
2295        set title ""
2296    } else {
2297        if { [info exists _fields($fname)] } {
2298            foreach { title units } $_fields($fname) break
2299            if { $units != "" } {
2300                set title [format "%s (%s)" $title $units]
2301            }
2302        } else {
2303            set title $fname
2304        }
2305    }
2306    set x [expr $w - 2]
2307    if { !$_settings(-legendvisible) } {
2308        $c delete legend
2309        return
2310    }
2311    if { [$c find withtag "legend"] == "" } {
2312        set y 2
2313        # If there's a legend title, create a text item for the title.
2314        $c create text $x $y \
2315            -anchor ne \
2316            -fill $itk_option(-plotforeground) -tags "title legend" \
2317            -font $font
2318        if { $title != "" } {
2319            incr y $lineht
2320        }
2321        $c create text $x $y \
2322            -anchor ne \
2323            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2324            -font $font
2325        incr y $lineht
2326        $c create image $x $y \
2327            -anchor ne \
2328            -image $_image(legend) -tags "colormap legend"
2329        $c create rectangle $x $y 1 1 \
2330            -fill "" -outline "" -tags "sensor legend"
2331        $c create text $x [expr {$h-2}] \
2332            -anchor se \
2333            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2334            -font $font
2335        $c bind sensor <Enter> [itcl::code $this EnterLegend %x %y]
2336        $c bind sensor <Leave> [itcl::code $this LeaveLegend]
2337        $c bind sensor <Motion> [itcl::code $this MotionLegend %x %y]
2338    }
2339    set x2 $x
2340    set iw [image width $_image(legend)]
2341    set ih [image height $_image(legend)]
2342    set x1 [expr $x2 - ($iw*12)/10]
2343
2344    $c bind title <ButtonPress> [itcl::code $this Combo post]
2345    $c bind title <Enter> [itcl::code $this Combo activate]
2346    $c bind title <Leave> [itcl::code $this Combo deactivate]
2347    # Reset the item coordinates according the current size of the plot.
2348    $c itemconfigure title -text $title
2349    if { [info exists _limits($_curFldName)] } {
2350        foreach { vmin vmax } $_limits($_curFldName) break
2351        $c itemconfigure vmin -text [format %g $vmin]
2352        $c itemconfigure vmax -text [format %g $vmax]
2353    }
2354    set y 2
2355    # If there's a legend title, move the title to the correct position
2356    if { $title != "" } {
2357        $c itemconfigure title -text $title
2358        $c coords title $x $y
2359        incr y $lineht
2360        $c raise title
2361    }
2362    $c coords vmax $x $y
2363    incr y $lineht
2364    $c coords colormap $x $y
2365    $c coords sensor [expr $x - $iw] $y $x [expr $y + $ih]
2366    $c raise sensor
2367    $c coords vmin $x [expr {$h - 2}]
2368}
2369
2370# ----------------------------------------------------------------------
2371# USAGE: _dropdown post
2372# USAGE: _dropdown unpost
2373# USAGE: _dropdown select
2374#
2375# Used internally to handle the dropdown list for this combobox.  The
2376# post/unpost options are invoked when the list is posted or unposted
2377# to manage the relief of the controlling button.  The select option
2378# is invoked whenever there is a selection from the list, to assign
2379# the value back to the gauge.
2380# ----------------------------------------------------------------------
2381itcl::body Rappture::VtkGlyphViewer::Combo {option} {
2382    set c $itk_component(view)
2383    switch -- $option {
2384        post {
2385            foreach { x1 y1 x2 y2 } [$c bbox title] break
2386            set cw [winfo width $itk_component(view)]
2387            set mw [winfo reqwidth $itk_component(fieldmenu)]
2388            set x1 [expr $cw - $mw]
2389            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2390            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2391            tk_popup $itk_component(fieldmenu) $x $y
2392        }
2393        activate {
2394            $c itemconfigure title -fill red
2395        }
2396        deactivate {
2397            $c itemconfigure title -fill $itk_option(-plotforeground)
2398        }
2399        invoke {
2400            $itk_component(field) value $_curFldLabel
2401            AdjustSetting -field
2402        }
2403        default {
2404            error "bad option \"$option\": should be post, unpost, select"
2405        }
2406    }
2407}
2408
2409#
2410# SetCurrentColormap --
2411#
2412itcl::body Rappture::VtkGlyphViewer::SetCurrentColormap { name } {
2413    # Keep track of the colormaps that we build.
2414    if { ![info exists _colormaps($name)] } {
2415        BuildColormap $name
2416        set _colormaps($name) 1
2417    }
2418    set _currentColormap $name
2419    SendCmd "glyphs colormap $_currentColormap"
2420}
2421
2422#
2423# BuildColormap --
2424#
2425#    Build the designated colormap on the server.
2426#
2427itcl::body Rappture::VtkGlyphViewer::BuildColormap { name } {
2428    set cmap [ColorsToColormap $name]
2429    if { [llength $cmap] == 0 } {
2430        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
2431    }
2432    set wmap "0.0 1.0 1.0 1.0"
2433    SendCmd "colormap add $name { $cmap } { $wmap }"
2434}
2435
2436itcl::body Rappture::VtkGlyphViewer::SetOrientation { side } {
2437    array set positions {
2438        front "1 0 0 0"
2439        back  "0 0 1 0"
2440        left  "0.707107 0 -0.707107 0"
2441        right "0.707107 0 0.707107 0"
2442        top   "0.707107 -0.707107 0 0"
2443        bottom "0.707107 0.707107 0 0"
2444    }
2445    foreach name { qw qx qy qz } value $positions($side) {
2446        set _view($name) $value
2447    }
2448    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2449    $_arcball quaternion $q
2450    SendCmd "camera orient $q"
2451    SendCmd "camera reset"
2452    set _view(xpan) 0
2453    set _view(ypan) 0
2454    set _view(zoom) 1.0
2455}
Note: See TracBrowser for help on using the repository browser.