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

Last change on this file since 3550 was 3550, checked in by ldelgass, 11 years ago

Reset camera *after* orienting, so zoom reset can use the correct view direction

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