source: trunk/gui/scripts/vtkglyphviewer.tcl @ 5184

Last change on this file since 5184 was 5184, checked in by ldelgass, 10 years ago

s/wmap/amap/

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