source: trunk/gui/scripts/vtkstreamlinesviewer.tcl @ 3430

Last change on this file since 3430 was 3430, checked in by gah, 12 years ago

fix for sequence of contours

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