source: branches/1.4/gui/scripts/vtkglyphviewer.tcl @ 4941

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

merge r4767 from trunk

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