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

Last change on this file since 3405 was 3405, checked in by gah, 10 years ago

fix to streamlines to (again) display mulitple fields from a single VTK file

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