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

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

Don't call update from viewer ctors. This causes an error in the init order
where FieldResult::add is called from ResultViewer? before the viewer's ctor
has completed.

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