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

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

merge r4765 from trunk

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