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

Last change on this file since 5068 was 5068, checked in by ldelgass, 6 years ago

Change uses of SendCmdNoWait? to SendCmd?. We don't currently have (or need) a
true out-of-band send.

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