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

Last change on this file since 3431 was 3431, checked in by gah, 11 years ago

fix for sequence of contours

File size: 84.9 KB
Line 
1# -*- mode: tcl; indent-tabs-mode: nil -*-
2# ----------------------------------------------------------------------
3#  COMPONENT: vtkviewer - Vtk drawing object viewer
4#
5#  It connects to the Vtk server running on a rendering farm,
6#  transmits data, and displays the results.
7# ======================================================================
8#  AUTHOR:  Michael McLennan, Purdue University
9#  Copyright (c) 2004-2012  HUBzero Foundation, LLC
10#
11#  See the file "license.terms" for information on usage and
12#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13# ======================================================================
14package require Itk
15package require BLT
16package require Img
17
18option add *VtkStreamlinesViewer.width 4i widgetDefault
19option add *VtkStreamlinesViewer*cursor crosshair widgetDefault
20option add *VtkStreamlinesViewer.height 4i widgetDefault
21option add *VtkStreamlinesViewer.foreground black widgetDefault
22option add *VtkStreamlinesViewer.controlBackground gray widgetDefault
23option add *VtkStreamlinesViewer.controlDarkBackground #999999 widgetDefault
24option add *VtkStreamlinesViewer.plotBackground black widgetDefault
25option add *VtkStreamlinesViewer.plotForeground white widgetDefault
26option add *VtkStreamlinesViewer.font \
27    -*-helvetica-medium-r-normal-*-12-* widgetDefault
28
29# must use this name -- plugs into Rappture::resources::load
30proc VtkStreamlinesViewer_init_resources {} {
31    Rappture::resources::register \
32        vtkvis_server Rappture::VtkStreamlinesViewer::SetServerList
33}
34
35itcl::class Rappture::VtkStreamlinesViewer {
36    inherit Rappture::VisViewer
37
38    itk_option define -plotforeground plotForeground Foreground ""
39    itk_option define -plotbackground plotBackground Background ""
40
41    constructor { hostlist args } {
42        Rappture::VisViewer::constructor $hostlist
43    } {
44        # defined below
45    }
46    destructor {
47        # defined below
48    }
49    public proc SetServerList { namelist } {
50        Rappture::VisViewer::SetServerList "vtkvis" $namelist
51    }
52    public method add {dataobj {settings ""}}
53    public method camera {option args}
54    public method delete {args}
55    public method disconnect {}
56    public method download {option args}
57    public method get {args}
58    public method isconnected {}
59    public method 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 { title }
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 ResetAxes {}
105    private method SetColormap { dataobj comp }
106    private method ChangeColormap { dataobj comp color }
107    private method SetLegendTip { x y }
108    private method SetObjectStyle { dataobj comp }
109    private method Slice {option args}
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    # Rebuild event
169    $_dispatcher register !rebuild
170    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
171
172    # Resize event
173    $_dispatcher register !resize
174    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
175
176    # Reseed event
177    $_dispatcher register !reseed
178    $_dispatcher dispatch $this !reseed "[itcl::code $this DoReseed]; list"
179
180    # Rotate event
181    $_dispatcher register !rotate
182    $_dispatcher dispatch $this !rotate "[itcl::code $this DoRotate]; list"
183
184    # Legend event
185    $_dispatcher register !legend
186    $_dispatcher dispatch $this !legend "[itcl::code $this RequestLegend]; list"
187
188    # X-Cutplane event
189    $_dispatcher register !xcutplane
190    $_dispatcher dispatch $this !xcutplane \
191        "[itcl::code $this AdjustSetting cutplaneXPosition]; list"
192
193    # Y-Cutplane event
194    $_dispatcher register !ycutplane
195    $_dispatcher dispatch $this !ycutplane \
196        "[itcl::code $this AdjustSetting cutplaneYPosition]; list"
197
198    # Z-Cutplane event
199    $_dispatcher register !zcutplane
200    $_dispatcher dispatch $this !zcutplane \
201        "[itcl::code $this AdjustSetting cutplaneZPosition]; list"
202
203    #
204    # Populate parser with commands handle incoming requests
205    #
206    $_parser alias image [itcl::code $this ReceiveImage]
207    $_parser alias dataset [itcl::code $this ReceiveDataset]
208    $_parser alias legend [itcl::code $this ReceiveLegend]
209    $_parser alias viserror [itcl::code $this ReceiveError]
210
211    array set _outline {
212        id -1
213        afterId -1
214        x1 -1
215        y1 -1
216        x2 -1
217        y2 -1
218    }
219    # Initialize the view to some default parameters.
220    array set _view {
221        qw              0.853553
222        qx              -0.353553
223        qy              0.353553
224        qz              0.146447
225        zoom            1.0
226        xpan            0
227        ypan            0
228        ortho           0
229    }
230    set _arcball [blt::arcball create 100 100]
231    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
232    $_arcball quaternion $q
233
234    array set _settings [subst {
235        axesVisible             1
236        axisLabelsVisible       1
237        axisXGrid               0
238        axisYGrid               0
239        axisZGrid               0
240        cutplaneEdges           0
241        cutplaneLighting        1
242        cutplaneOpacity         100
243        cutplaneVisible         0
244        cutplaneWireframe       0
245        cutplaneXPosition       50
246        cutplaneXVisible        1
247        cutplaneYPosition       50
248        cutplaneYVisible        1
249        cutplaneZPosition       50
250        cutplaneZVisible        1
251        legendVisible           1
252        streamlinesLighting     1
253        streamlinesMode         lines
254        streamlinesNumSeeds     200
255        streamlinesOpacity      100
256        streamlinesScale        1
257        streamlinesSeedsVisible 0
258        streamlinesVisible      1
259        volumeEdges             0
260        volumeLighting          1
261        volumeOpacity           40
262        volumeVisible           1
263        volumeWireframe         0
264    }]
265
266    itk_component add view {
267        canvas $itk_component(plotarea).view \
268            -highlightthickness 0 -borderwidth 0
269    } {
270        usual
271        ignore -highlightthickness -borderwidth  -background
272    }
273
274    itk_component add fieldmenu {
275        menu $itk_component(plotarea).menu -bg black -fg white -relief flat \
276            -tearoff no
277    } {
278        usual
279        ignore -background -foreground -relief -tearoff
280    }
281    set c $itk_component(view)
282    bind $c <Configure> [itcl::code $this EventuallyResize %w %h]
283    bind $c <4> [itcl::code $this Zoom in 0.25]
284    bind $c <5> [itcl::code $this Zoom out 0.25]
285    bind $c <KeyPress-Left>  [list %W xview scroll 10 units]
286    bind $c <KeyPress-Right> [list %W xview scroll -10 units]
287    bind $c <KeyPress-Up>    [list %W yview scroll 10 units]
288    bind $c <KeyPress-Down>  [list %W yview scroll -10 units]
289    bind $c <Enter> "focus %W"
290    bind $c <Control-F1> [itcl::code $this ToggleConsole]
291
292    # Fix the scrollregion in case we go off screen
293    $c configure -scrollregion [$c bbox all]
294
295    set _map(id) [$c create image 0 0 -anchor nw -image $_image(plot)]
296    set _map(cwidth) -1
297    set _map(cheight) -1
298    set _map(zoom) 1.0
299    set _map(original) ""
300
301    set f [$itk_component(main) component controls]
302    itk_component add reset {
303        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
304            -highlightthickness 0 \
305            -image [Rappture::icon reset-view] \
306            -command [itcl::code $this Zoom reset]
307    } {
308        usual
309        ignore -highlightthickness
310    }
311    pack $itk_component(reset) -side top -padx 2 -pady 2
312    Rappture::Tooltip::for $itk_component(reset) "Reset the view to the default zoom level"
313
314    itk_component add zoomin {
315        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
316            -highlightthickness 0 \
317            -image [Rappture::icon zoom-in] \
318            -command [itcl::code $this Zoom in]
319    } {
320        usual
321        ignore -highlightthickness
322    }
323    pack $itk_component(zoomin) -side top -padx 2 -pady 2
324    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
325
326    itk_component add zoomout {
327        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
328            -highlightthickness 0 \
329            -image [Rappture::icon zoom-out] \
330            -command [itcl::code $this Zoom out]
331    } {
332        usual
333        ignore -highlightthickness
334    }
335    pack $itk_component(zoomout) -side top -padx 2 -pady 2
336    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
337
338    itk_component add volume {
339        Rappture::PushButton $f.volume \
340            -onimage [Rappture::icon volume-on] \
341            -offimage [Rappture::icon volume-off] \
342            -variable [itcl::scope _settings(volumeVisible)] \
343            -command [itcl::code $this AdjustSetting volumeVisible]
344    }
345    $itk_component(volume) select
346    Rappture::Tooltip::for $itk_component(volume) \
347        "Don't display the volume"
348    pack $itk_component(volume) -padx 2 -pady 2
349
350    itk_component add streamlines {
351        Rappture::PushButton $f.streamlines \
352            -onimage [Rappture::icon streamlines-on] \
353            -offimage [Rappture::icon streamlines-off] \
354            -variable [itcl::scope _settings(streamlinesVisible)] \
355            -command [itcl::code $this AdjustSetting streamlinesVisible] \
356    }
357    $itk_component(streamlines) select
358    Rappture::Tooltip::for $itk_component(streamlines) \
359        "Toggle the streamlines on/off"
360    pack $itk_component(streamlines) -padx 2 -pady 2
361
362    itk_component add cutplane {
363        Rappture::PushButton $f.cutplane \
364            -onimage [Rappture::icon cutbutton] \
365            -offimage [Rappture::icon cutbutton] \
366            -variable [itcl::scope _settings(cutplaneVisible)] \
367            -command [itcl::code $this AdjustSetting cutplaneVisible]
368    }
369    Rappture::Tooltip::for $itk_component(cutplane) \
370        "Show/Hide cutplanes"
371    pack $itk_component(cutplane) -padx 2 -pady 2
372
373
374    if { [catch {
375        BuildVolumeTab
376        BuildStreamsTab
377        BuildCutplaneTab
378        BuildAxisTab
379        BuildCameraTab
380    } errs] != 0 } {
381        puts stderr errs=$errs
382    }
383    # Legend
384
385    set _image(legend) [image create photo]
386    itk_component add legend {
387        canvas $itk_component(plotarea).legend -width 50 -highlightthickness 0
388    } {
389        usual
390        ignore -highlightthickness
391        rename -background -plotbackground plotBackground Background
392    }
393
394    # Hack around the Tk panewindow.  The problem is that the requested
395    # size of the 3d view isn't set until an image is retrieved from
396    # the server.  So the panewindow uses the tiny size.
397    set w 10000
398    pack forget $itk_component(view)
399    blt::table $itk_component(plotarea) \
400        0,0 $itk_component(view) -fill both -reqwidth $w
401    blt::table configure $itk_component(plotarea) c1 -resize none
402
403    # Bindings for rotation via mouse
404    bind $itk_component(view) <ButtonPress-1> \
405        [itcl::code $this Rotate click %x %y]
406    bind $itk_component(view) <B1-Motion> \
407        [itcl::code $this Rotate drag %x %y]
408    bind $itk_component(view) <ButtonRelease-1> \
409        [itcl::code $this Rotate release %x %y]
410    bind $itk_component(view) <Configure> \
411        [itcl::code $this EventuallyResize %w %h]
412
413    if 0 {
414    bind $itk_component(view) <Configure> \
415        [itcl::code $this EventuallyResize %w %h]
416    }
417    # Bindings for panning via mouse
418    bind $itk_component(view) <ButtonPress-2> \
419        [itcl::code $this Pan click %x %y]
420    bind $itk_component(view) <B2-Motion> \
421        [itcl::code $this Pan drag %x %y]
422    bind $itk_component(view) <ButtonRelease-2> \
423        [itcl::code $this Pan release %x %y]
424
425    bind $itk_component(view) <ButtonRelease-3> \
426        [itcl::code $this Pick %x %y]
427
428    # Bindings for panning via keyboard
429    bind $itk_component(view) <KeyPress-Left> \
430        [itcl::code $this Pan set -10 0]
431    bind $itk_component(view) <KeyPress-Right> \
432        [itcl::code $this Pan set 10 0]
433    bind $itk_component(view) <KeyPress-Up> \
434        [itcl::code $this Pan set 0 -10]
435    bind $itk_component(view) <KeyPress-Down> \
436        [itcl::code $this Pan set 0 10]
437    bind $itk_component(view) <Shift-KeyPress-Left> \
438        [itcl::code $this Pan set -2 0]
439    bind $itk_component(view) <Shift-KeyPress-Right> \
440        [itcl::code $this Pan set 2 0]
441    bind $itk_component(view) <Shift-KeyPress-Up> \
442        [itcl::code $this Pan set 0 -2]
443    bind $itk_component(view) <Shift-KeyPress-Down> \
444        [itcl::code $this Pan set 0 2]
445
446    # Bindings for zoom via keyboard
447    bind $itk_component(view) <KeyPress-Prior> \
448        [itcl::code $this Zoom out]
449    bind $itk_component(view) <KeyPress-Next> \
450        [itcl::code $this Zoom in]
451
452    bind $itk_component(view) <Enter> "focus $itk_component(view)"
453
454    if {[string equal "x11" [tk windowingsystem]]} {
455        # Bindings for zoom via mouse
456        bind $itk_component(view) <4> [itcl::code $this Zoom out]
457        bind $itk_component(view) <5> [itcl::code $this Zoom in]
458    }
459
460    set _image(download) [image create photo]
461
462    eval itk_initialize $args
463    Connect
464    update
465}
466
467# ----------------------------------------------------------------------
468# DESTRUCTOR
469# ----------------------------------------------------------------------
470itcl::body Rappture::VtkStreamlinesViewer::destructor {} {
471    Disconnect
472    image delete $_image(plot)
473    image delete $_image(download)
474    catch { blt::arcball destroy $_arcball }
475}
476
477itcl::body Rappture::VtkStreamlinesViewer::DoResize {} {
478    if { $_width < 2 } {
479        set _width 500
480    }
481    if { $_height < 2 } {
482        set _height 500
483    }
484    set _start [clock clicks -milliseconds]
485    SendCmd "screen size $_width $_height"
486    set _legendPending 1
487    # Must reset camera to have object scaling to take effect.
488    SendCmd "camera reset"
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 streamlinesPalette \
1079            streamlinesLighting \
1080            streamlinesPalette field \
1081            volumeVisible volumeEdges volumeLighting volumeOpacity \
1082            volumeWireframe \
1083            cutplaneVisible \
1084            cutplaneXPosition cutplaneYPosition cutplaneZPosition \
1085            cutplaneXVisible cutplaneYVisible cutplaneZVisible
1086
1087        # FIXME: Don't know exactly why this "imgflush" is needed.
1088        #        But this makes the "camera reset" below to work correctly.
1089        #        I left this in because the axis labels are scaled too big.
1090        SendCmd "imgflush"
1091
1092        # Reset the camera and other view parameters
1093        set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1094        $_arcball quaternion $q
1095        if {$_view(ortho)} {
1096            SendCmd "camera mode ortho"
1097        } else {
1098            SendCmd "camera mode persp"
1099        }
1100        DoRotate
1101        PanCamera
1102        Zoom reset
1103        SendCmd "camera reset"
1104        set _reset 0
1105    }
1106    # Actually write the commands to the server socket.  If it fails, we don't
1107    # care.  We're finished here.
1108    blt::busy hold $itk_component(hull)
1109    StopBufferingCommands
1110    blt::busy release $itk_component(hull)
1111}
1112
1113# ----------------------------------------------------------------------
1114# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1115#
1116# Returns a list of server IDs for the current datasets being displayed.  This
1117# is normally a single ID, but it might be a list of IDs if the current data
1118# object has multiple components.
1119# ----------------------------------------------------------------------
1120itcl::body Rappture::VtkStreamlinesViewer::CurrentDatasets {args} {
1121    set flag [lindex $args 0]
1122    switch -- $flag {
1123        "-all" {
1124            if { [llength $args] > 1 } {
1125                error "CurrentDatasets: can't specify dataobj after \"-all\""
1126            }
1127            set dlist [get -objects]
1128        }
1129        "-visible" {
1130            if { [llength $args] > 1 } {
1131                set dlist {}
1132                set args [lrange $args 1 end]
1133                foreach dataobj $args {
1134                    if { [info exists _obj2ovride($dataobj-raise)] } {
1135                        lappend dlist $dataobj
1136                    }
1137                }
1138            } else {
1139                set dlist [get -visible]
1140            }
1141        }           
1142        default {
1143            set dlist $args
1144        }
1145    }
1146    set rlist ""
1147    foreach dataobj $dlist {
1148        foreach comp [$dataobj components] {
1149            set tag $dataobj-$comp
1150            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1151                lappend rlist $tag
1152            }
1153        }
1154    }
1155    return $rlist
1156}
1157
1158# ----------------------------------------------------------------------
1159# USAGE: Zoom in
1160# USAGE: Zoom out
1161# USAGE: Zoom reset
1162#
1163# Called automatically when the user clicks on one of the zoom
1164# controls for this widget.  Changes the zoom for the current view.
1165# ----------------------------------------------------------------------
1166itcl::body Rappture::VtkStreamlinesViewer::Zoom {option} {
1167    switch -- $option {
1168        "in" {
1169            set _view(zoom) [expr {$_view(zoom)*1.25}]
1170            SendCmd "camera zoom $_view(zoom)"
1171        }
1172        "out" {
1173            set _view(zoom) [expr {$_view(zoom)*0.8}]
1174            SendCmd "camera zoom $_view(zoom)"
1175        }
1176        "reset" {
1177            array set _view {
1178                qw              0.853553
1179                qx              -0.353553
1180                qy              0.353553
1181                qz              0.146447
1182                zoom    1.0
1183                xpan   0
1184                ypan   0
1185            }
1186            SendCmd "camera reset all"
1187            if { $_first != "" } {
1188                set location [$_first hints camera]
1189                if { $location != "" } {
1190                    array set _view $location
1191                }
1192            }
1193            set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1194            $_arcball quaternion $q
1195            DoRotate
1196        }
1197    }
1198}
1199
1200itcl::body Rappture::VtkStreamlinesViewer::PanCamera {} {
1201    set x $_view(xpan)
1202    set y $_view(ypan)
1203    SendCmd "camera pan $x $y"
1204}
1205
1206
1207# ----------------------------------------------------------------------
1208# USAGE: Rotate click <x> <y>
1209# USAGE: Rotate drag <x> <y>
1210# USAGE: Rotate release <x> <y>
1211#
1212# Called automatically when the user clicks/drags/releases in the
1213# plot area.  Moves the plot according to the user's actions.
1214# ----------------------------------------------------------------------
1215itcl::body Rappture::VtkStreamlinesViewer::Rotate {option x y} {
1216    switch -- $option {
1217        "click" {
1218            $itk_component(view) configure -cursor fleur
1219            set _click(x) $x
1220            set _click(y) $y
1221        }
1222        "drag" {
1223            if {[array size _click] == 0} {
1224                Rotate click $x $y
1225            } else {
1226                set w [winfo width $itk_component(view)]
1227                set h [winfo height $itk_component(view)]
1228                if {$w <= 0 || $h <= 0} {
1229                    return
1230                }
1231
1232                if {[catch {
1233                    # this fails sometimes for no apparent reason
1234                    set dx [expr {double($x-$_click(x))/$w}]
1235                    set dy [expr {double($y-$_click(y))/$h}]
1236                }]} {
1237                    return
1238                }
1239                if { $dx == 0 && $dy == 0 } {
1240                    return
1241                }
1242                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1243                EventuallyRotate $q
1244                set _click(x) $x
1245                set _click(y) $y
1246            }
1247        }
1248        "release" {
1249            Rotate drag $x $y
1250            $itk_component(view) configure -cursor ""
1251            catch {unset _click}
1252        }
1253        default {
1254            error "bad option \"$option\": should be click, drag, release"
1255        }
1256    }
1257}
1258
1259itcl::body Rappture::VtkStreamlinesViewer::Pick {x y} {
1260    foreach tag [CurrentDatasets -visible] {
1261        SendCmdNoWait "dataset getscalar pixel $x $y $tag"
1262    }
1263}
1264
1265# ----------------------------------------------------------------------
1266# USAGE: $this Pan click x y
1267#        $this Pan drag x y
1268#        $this Pan release x y
1269#
1270# Called automatically when the user clicks on one of the zoom
1271# controls for this widget.  Changes the zoom for the current view.
1272# ----------------------------------------------------------------------
1273itcl::body Rappture::VtkStreamlinesViewer::Pan {option x y} {
1274    switch -- $option {
1275        "set" {
1276            set w [winfo width $itk_component(view)]
1277            set h [winfo height $itk_component(view)]
1278            set x [expr $x / double($w)]
1279            set y [expr $y / double($h)]
1280            set _view(xpan) [expr $_view(xpan) + $x]
1281            set _view(ypan) [expr $_view(ypan) + $y]
1282            PanCamera
1283            return
1284        }
1285        "click" {
1286            set _click(x) $x
1287            set _click(y) $y
1288            $itk_component(view) configure -cursor hand1
1289        }
1290        "drag" {
1291            if { ![info exists _click(x)] } {
1292                set _click(x) $x
1293            }
1294            if { ![info exists _click(y)] } {
1295                set _click(y) $y
1296            }
1297            set w [winfo width $itk_component(view)]
1298            set h [winfo height $itk_component(view)]
1299            set dx [expr ($_click(x) - $x)/double($w)]
1300            set dy [expr ($_click(y) - $y)/double($h)]
1301            set _click(x) $x
1302            set _click(y) $y
1303            set _view(xpan) [expr $_view(xpan) - $dx]
1304            set _view(ypan) [expr $_view(ypan) - $dy]
1305            PanCamera
1306        }
1307        "release" {
1308            Pan drag $x $y
1309            $itk_component(view) configure -cursor ""
1310        }
1311        default {
1312            error "unknown option \"$option\": should set, click, drag, or release"
1313        }
1314    }
1315}
1316
1317# ----------------------------------------------------------------------
1318# USAGE: InitSettings <what> ?<value>?
1319#
1320# Used internally to update rendering settings whenever parameters
1321# change in the popup settings panel.  Sends the new settings off
1322# to the back end.
1323# ----------------------------------------------------------------------
1324itcl::body Rappture::VtkStreamlinesViewer::InitSettings { args } {
1325    foreach spec $args {
1326        if { [info exists _settings($_first-$spec)] } {
1327            # Reset global setting with dataobj specific setting
1328            set _settings($spec) $_settings($_first-$spec)
1329        }
1330        AdjustSetting $spec
1331    }
1332}
1333
1334#
1335# AdjustSetting --
1336#
1337#       Changes/updates a specific setting in the widget.  There are
1338#       usually user-setable option.  Commands are sent to the render
1339#       server.
1340#
1341itcl::body Rappture::VtkStreamlinesViewer::AdjustSetting {what {value ""}} {
1342    if { ![isconnected] } {
1343        return
1344    }
1345    switch -- $what {
1346        "volumeOpacity" {
1347            set val $_settings(volumeOpacity)
1348            set sval [expr { 0.01 * double($val) }]
1349            SendCmd "polydata opacity $sval"
1350        }
1351        "volumeWireframe" {
1352            set bool $_settings(volumeWireframe)
1353            SendCmd "polydata wireframe $bool"
1354        }
1355        "volumeVisible" {
1356            set bool $_settings(volumeVisible)
1357            SendCmd "polydata visible $bool"
1358            if { $bool } {
1359                Rappture::Tooltip::for $itk_component(volume) \
1360                    "Hide the volume"
1361            } else {
1362                Rappture::Tooltip::for $itk_component(volume) \
1363                    "Show the volume"
1364            }
1365        }
1366        "volumeLighting" {
1367            set bool $_settings(volumeLighting)
1368            SendCmd "polydata lighting $bool"
1369        }
1370        "volumeEdges" {
1371            set bool $_settings(volumeEdges)
1372            SendCmd "polydata edges $bool"
1373        }
1374        "axesVisible" {
1375            set bool $_settings(axesVisible)
1376            SendCmd "axis visible all $bool"
1377        }
1378        "axisLabelsVisible" {
1379            set bool $_settings(axisLabelsVisible)
1380            SendCmd "axis labels all $bool"
1381        }
1382        "axisXGrid" - "axisYGrid" - "axisZGrid" {
1383            set axis [string tolower [string range $what 4 4]]
1384            set bool $_settings($what)
1385            SendCmd "axis grid $axis $bool"
1386        }
1387        "axis-mode" {
1388            set mode [$itk_component(axismode) value]
1389            set mode [$itk_component(axismode) translate $mode]
1390            set _settings($what) $mode
1391            SendCmd "axis flymode $mode"
1392        }
1393        "cutplaneEdges" {
1394            set bool $_settings($what)
1395            SendCmd "cutplane edges $bool"
1396        }
1397        "cutplaneVisible" {
1398            set bool $_settings($what)
1399            SendCmd "cutplane visible $bool"
1400        }
1401        "cutplaneWireframe" {
1402            set bool $_settings($what)
1403            SendCmd "cutplane wireframe $bool"
1404        }
1405        "cutplaneLighting" {
1406            set bool $_settings($what)
1407            SendCmd "cutplane lighting $bool"
1408        }
1409        "cutplaneOpacity" {
1410            set val $_settings($what)
1411            set sval [expr { 0.01 * double($val) }]
1412            SendCmd "cutplane opacity $sval"
1413        }
1414        "cutplaneXVisible" - "cutplaneYVisible" - "cutplaneZVisible" {
1415            set axis [string tolower [string range $what 8 8]]
1416            set bool $_settings($what)
1417            if { $bool } {
1418                $itk_component(${axis}CutScale) configure -state normal \
1419                    -troughcolor white
1420            } else {
1421                $itk_component(${axis}CutScale) configure -state disabled \
1422                    -troughcolor grey82
1423            }
1424            SendCmd "cutplane axis $axis $bool"
1425        }
1426        "cutplaneXPosition" - "cutplaneYPosition" - "cutplaneZPosition" {
1427            set axis [string tolower [string range $what 8 8]]
1428            set pos [expr $_settings($what) * 0.01]
1429            SendCmd "cutplane slice ${axis} ${pos}"
1430            set _cutplanePending 0
1431        }
1432        "streamlinesSeedsVisible" {
1433            set bool $_settings($what)
1434            SendCmd "streamlines seed visible $bool"
1435        }
1436        "streamlinesNumSeeds" {
1437            set density $_settings($what)
1438            EventuallyReseed $density
1439        }
1440        "streamlinesVisible" {
1441            set bool $_settings($what)
1442            SendCmd "streamlines visible $bool"
1443            if { $bool } {
1444                Rappture::Tooltip::for $itk_component(streamlines) \
1445                    "Hide the streamlines"
1446            } else {
1447                Rappture::Tooltip::for $itk_component(streamlines) \
1448                    "Show the streamlines"
1449            }
1450        }
1451        "streamlinesMode" {
1452            set mode [$itk_component(streammode) value]
1453            set _settings(streamlinesMode) $mode
1454            switch -- $mode {
1455                "lines" {
1456                    SendCmd "streamlines lines"
1457                }
1458                "ribbons" {
1459                    SendCmd "streamlines ribbons 3 0"
1460                }
1461                "tubes" {
1462                    SendCmd "streamlines tubes 5 3"
1463                }
1464            }
1465        }
1466        "streamlinesPalette" {
1467            set palette [$itk_component(palette) value]
1468            set _settings(streamlinesPalette) $palette
1469            foreach dataset [CurrentDatasets -visible $_first] {
1470                foreach {dataobj comp} [split $dataset -] break
1471                ChangeColormap $dataobj $comp $palette
1472            }
1473            set _legendPending 1
1474        }
1475        "streamlinesOpacity" {
1476            set val $_settings(streamlinesOpacity)
1477            set sval [expr { 0.01 * double($val) }]
1478            SendCmd "streamlines opacity $sval"
1479        }
1480        "streamlinesScale" {
1481            set val $_settings(streamlinesScale)
1482            set sval [expr { 0.01 * double($val) }]
1483            SendCmd "streamlines scale $sval $sval $sval"
1484        }
1485        "streamlinesLighting" {
1486            set bool $_settings(streamlinesLighting)
1487            SendCmd "streamlines lighting $bool"
1488        }
1489        "field" {
1490            set label [$itk_component(field) value]
1491            set fname [$itk_component(field) translate $label]
1492            set _settings(field) $fname
1493            if { [info exists _fields($fname)] } {
1494                foreach { label units components } $_fields($fname) break
1495                if { $components > 1 } {
1496                    set _colorMode vmag
1497                } else {
1498                    set _colorMode scalar
1499                }
1500                set _curFldName $fname
1501                set _curFldLabel $label
1502            } else {
1503                puts stderr "unknown field \"$fname\""
1504                return
1505            }
1506            # Get the new limits because the field changed.
1507            scale $_dlist
1508            ResetAxes
1509            SendCmd "streamlines colormode $_colorMode ${fname}"
1510            SendCmd "cutplane colormode $_colorMode ${fname}"
1511            set _legendPending 1
1512        }
1513        default {
1514            error "don't know how to fix $what"
1515        }
1516    }
1517}
1518
1519#
1520# RequestLegend --
1521#
1522#       Request a new legend from the server.  The size of the legend
1523#       is determined from the height of the canvas.  It will be rotated
1524#       to be vertical when drawn.
1525#
1526itcl::body Rappture::VtkStreamlinesViewer::RequestLegend {} {
1527    set font "Arial 8"
1528    set lineht [font metrics $font -linespace]
1529    set c $itk_component(legend)
1530    set w 12
1531    set h [expr {$_height - 3 * ($lineht + 2)}]
1532    if { $h < 1} {
1533        return
1534    }
1535    # Set the legend on the first streamlines dataset.
1536    foreach dataset [CurrentDatasets -visible $_first] {
1537        foreach {dataobj comp} [split $dataset -] break
1538        if { [info exists _dataset2style($dataset)] } {
1539            SendCmdNoWait \
1540                "legend $_dataset2style($dataset) $_colorMode $_curFldName {} $w $h 0"
1541            break;
1542        }
1543    }
1544}
1545
1546#
1547# ChangeColormap --
1548#
1549itcl::body Rappture::VtkStreamlinesViewer::ChangeColormap {dataobj comp color} {
1550    set tag $dataobj-$comp
1551    if { ![info exist _style($tag)] } {
1552        error "no initial colormap"
1553    }
1554    array set style $_style($tag)
1555    set style(-color) $color
1556    set _style($tag) [array get style]
1557    SetColormap $dataobj $comp
1558}
1559
1560#
1561# SetColormap --
1562#
1563itcl::body Rappture::VtkStreamlinesViewer::SetColormap { dataobj comp } {
1564    array set style {
1565        -color BCGYR
1566        -levels 6
1567        -opacity 1.0
1568    }
1569    set tag $dataobj-$comp
1570    if { ![info exists _initialStyle($tag)] } {
1571        # Save the initial component style.
1572        set _initialStyle($tag) [$dataobj style $comp]
1573    }
1574
1575    # Override defaults with initial style defined in xml.
1576    array set style $_initialStyle($tag)
1577
1578    if { ![info exists _style($tag)] } {
1579        set _style($tag) [array get style]
1580    }
1581    # Override initial style with current style.
1582    array set style $_style($tag)
1583
1584    set name "$style(-color):$style(-levels):$style(-opacity)"
1585    if { ![info exists _colormaps($name)] } {
1586        BuildColormap $name [array get style]
1587        set _colormaps($name) 1
1588    }
1589    if { ![info exists _dataset2style($tag)] ||
1590         $_dataset2style($tag) != $name } {
1591        SendCmd "streamlines colormap $name $tag"
1592        SendCmd "cutplane colormap $name $tag"
1593        set _dataset2style($tag) $name
1594    }
1595}
1596
1597
1598#
1599# BuildColormap --
1600#
1601itcl::body Rappture::VtkStreamlinesViewer::BuildColormap { name styles } {
1602    array set style $styles
1603    set cmap [ColorsToColormap $style(-color)]
1604    if { [llength $cmap] == 0 } {
1605        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
1606    }
1607    if { ![info exists _settings(volumeOpacity)] } {
1608        set _settings(volumeOpacity) $style(-opacity)
1609    }
1610    set max $_settings(volumeOpacity)
1611
1612    set wmap "0.0 1.0 1.0 1.0"
1613    SendCmd "colormap add $name { $cmap } { $wmap }"
1614}
1615
1616# ----------------------------------------------------------------------
1617# CONFIGURATION OPTION: -plotbackground
1618# ----------------------------------------------------------------------
1619itcl::configbody Rappture::VtkStreamlinesViewer::plotbackground {
1620    if { [isconnected] } {
1621        foreach {r g b} [Color2RGB $itk_option(-plotbackground)] break
1622        SendCmd "screen bgcolor $r $g $b"
1623    }
1624}
1625
1626# ----------------------------------------------------------------------
1627# CONFIGURATION OPTION: -plotforeground
1628# ----------------------------------------------------------------------
1629itcl::configbody Rappture::VtkStreamlinesViewer::plotforeground {
1630    if { [isconnected] } {
1631        foreach {r g b} [Color2RGB $itk_option(-plotforeground)] break
1632        #fix this!
1633        #SendCmd "color background $r $g $b"
1634    }
1635}
1636
1637itcl::body Rappture::VtkStreamlinesViewer::BuildVolumeTab {} {
1638
1639    set fg [option get $itk_component(hull) font Font]
1640    #set bfg [option get $itk_component(hull) boldFont Font]
1641
1642    set inner [$itk_component(main) insert end \
1643        -title "Volume Settings" \
1644        -icon [Rappture::icon volume-on]]
1645    $inner configure -borderwidth 4
1646
1647    checkbutton $inner.volume \
1648        -text "Show Volume" \
1649        -variable [itcl::scope _settings(volumeVisible)] \
1650        -command [itcl::code $this AdjustSetting volumeVisible] \
1651        -font "Arial 9"
1652
1653    checkbutton $inner.wireframe \
1654        -text "Show Wireframe" \
1655        -variable [itcl::scope _settings(volumeWireframe)] \
1656        -command [itcl::code $this AdjustSetting volumeWireframe] \
1657        -font "Arial 9"
1658
1659    checkbutton $inner.lighting \
1660        -text "Enable Lighting" \
1661        -variable [itcl::scope _settings(volumeLighting)] \
1662        -command [itcl::code $this AdjustSetting volumeLighting] \
1663        -font "Arial 9"
1664
1665    checkbutton $inner.edges \
1666        -text "Show Edges" \
1667        -variable [itcl::scope _settings(volumeEdges)] \
1668        -command [itcl::code $this AdjustSetting volumeEdges] \
1669        -font "Arial 9"
1670
1671    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1672    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1673        -variable [itcl::scope _settings(volumeOpacity)] \
1674        -width 10 \
1675        -showvalue off \
1676        -command [itcl::code $this AdjustSetting volumeOpacity]
1677
1678    blt::table $inner \
1679        0,0 $inner.wireframe -anchor w -pady 2 -cspan 2 \
1680        1,0 $inner.lighting  -anchor w -pady 2 -cspan 2 \
1681        2,0 $inner.edges     -anchor w -pady 2 -cspan 3 \
1682        3,0 $inner.opacity_l -anchor w -pady 2 \
1683        3,1 $inner.opacity   -fill x   -pady 2
1684
1685    blt::table configure $inner r* c* -resize none
1686    blt::table configure $inner r4 c1 -resize expand
1687}
1688
1689
1690itcl::body Rappture::VtkStreamlinesViewer::BuildStreamsTab {} {
1691
1692    set fg [option get $itk_component(hull) font Font]
1693    #set bfg [option get $itk_component(hull) boldFont Font]
1694
1695    set inner [$itk_component(main) insert end \
1696        -title "Streams Settings" \
1697        -icon [Rappture::icon streamlines-on]]
1698    $inner configure -borderwidth 4
1699
1700    checkbutton $inner.streamlines \
1701        -text "Show Streamlines" \
1702        -variable [itcl::scope _settings(streamlinesVisible)] \
1703        -command [itcl::code $this AdjustSetting streamlinesVisible] \
1704        -font "Arial 9"
1705   
1706    checkbutton $inner.lighting \
1707        -text "Enable Lighting" \
1708        -variable [itcl::scope _settings(streamlinesLighting)] \
1709        -command [itcl::code $this AdjustSetting streamlinesLighting] \
1710        -font "Arial 9"
1711
1712    checkbutton $inner.seeds \
1713        -text "Show Seeds" \
1714        -variable [itcl::scope _settings(streamlinesSeedsVisible)] \
1715        -command [itcl::code $this AdjustSetting streamlinesSeedsVisible] \
1716        -font "Arial 9"
1717
1718    label $inner.mode_l -text "Mode" -font "Arial 9"
1719    itk_component add streammode {
1720        Rappture::Combobox $inner.mode -width 10 -editable no
1721    }
1722    $inner.mode choices insert end \
1723        "lines"    "lines" \
1724        "ribbons"   "ribbons" \
1725        "tubes"     "tubes"
1726    $itk_component(streammode) value $_settings(streamlinesMode)
1727    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting streamlinesMode]
1728
1729    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1730    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1731        -variable [itcl::scope _settings(streamlinesOpacity)] \
1732        -width 10 \
1733        -showvalue off \
1734        -command [itcl::code $this AdjustSetting streamlinesOpacity]
1735
1736    label $inner.density_l -text "No. Seeds" -font "Arial 9"
1737    ::scale $inner.density -from 1 -to 1000 -orient horizontal \
1738        -variable [itcl::scope _settings(streamlinesNumSeeds)] \
1739        -width 10 \
1740        -showvalue on \
1741        -command [itcl::code $this AdjustSetting streamlinesNumSeeds]
1742
1743    label $inner.scale_l -text "Scale" -font "Arial 9"
1744    ::scale $inner.scale -from 1 -to 100 -orient horizontal \
1745        -variable [itcl::scope _settings(streamlinesScale)] \
1746        -width 10 \
1747        -showvalue off \
1748        -command [itcl::code $this AdjustSetting streamlinesScale]
1749
1750    label $inner.field_l -text "Field" -font "Arial 9"
1751    itk_component add field {
1752        Rappture::Combobox $inner.field -width 10 -editable no
1753    }
1754    bind $inner.field <<Value>> \
1755        [itcl::code $this AdjustSetting field]
1756
1757    label $inner.palette_l -text "Palette" -font "Arial 9"
1758    itk_component add palette {
1759        Rappture::Combobox $inner.palette -width 10 -editable no
1760    }
1761    $inner.palette choices insert end \
1762        "BCGYR"              "BCGYR"            \
1763        "BGYOR"              "BGYOR"            \
1764        "blue"               "blue"             \
1765        "blue-to-brown"      "blue-to-brown"    \
1766        "blue-to-orange"     "blue-to-orange"   \
1767        "blue-to-grey"       "blue-to-grey"     \
1768        "green-to-magenta"   "green-to-magenta" \
1769        "greyscale"          "greyscale"        \
1770        "nanohub"            "nanohub"          \
1771        "rainbow"            "rainbow"          \
1772        "spectral"           "spectral"         \
1773        "ROYGB"              "ROYGB"            \
1774        "RYGCB"              "RYGCB"            \
1775        "brown-to-blue"      "brown-to-blue"    \
1776        "grey-to-blue"       "grey-to-blue"     \
1777        "orange-to-blue"     "orange-to-blue"   
1778
1779    $itk_component(palette) value "BCGYR"
1780    bind $inner.palette <<Value>> \
1781        [itcl::code $this AdjustSetting streamlinesPalette]
1782
1783    blt::table $inner \
1784        0,0 $inner.palette_l   -anchor w -pady 2  \
1785        0,1 $inner.palette     -fill x   -pady 2  \
1786        1,0 $inner.field_l     -anchor w -pady 2  \
1787        1,1 $inner.field       -fill x   -pady 2  \
1788        2,0 $inner.mode_l      -anchor w -pady 2  \
1789        2,1 $inner.mode        -fill x   -pady 2  \
1790        3,0 $inner.opacity_l   -anchor w -pady 2  \
1791        3,1 $inner.opacity     -anchor w -pady 2  \
1792        5,0 $inner.lighting    -anchor w -pady 2 -cspan 2 \
1793        6,0 $inner.seeds       -anchor w -pady 2 -cspan 2 \
1794        7,0 $inner.density_l   -anchor w -pady 2  \
1795        7,1 $inner.density     -fill x   -pady 2  \
1796
1797    blt::table configure $inner r* c* -resize none
1798    blt::table configure $inner r10 c1 c2 -resize expand
1799}
1800
1801itcl::body Rappture::VtkStreamlinesViewer::BuildAxisTab {} {
1802
1803    set fg [option get $itk_component(hull) font Font]
1804    #set bfg [option get $itk_component(hull) boldFont Font]
1805
1806    set inner [$itk_component(main) insert end \
1807        -title "Axis Settings" \
1808        -icon [Rappture::icon axis1]]
1809    $inner configure -borderwidth 4
1810
1811    checkbutton $inner.visible \
1812        -text "Show Axes" \
1813        -variable [itcl::scope _settings(axesVisible)] \
1814        -command [itcl::code $this AdjustSetting axesVisible] \
1815        -font "Arial 9"
1816
1817    checkbutton $inner.labels \
1818        -text "Show Axis Labels" \
1819        -variable [itcl::scope _settings(axisLabelsVisible)] \
1820        -command [itcl::code $this AdjustSetting axisLabelsVisible] \
1821        -font "Arial 9"
1822
1823    checkbutton $inner.xgrid \
1824        -text "Show X Grid" \
1825        -variable [itcl::scope _settings(axisXGrid)] \
1826        -command [itcl::code $this AdjustSetting axisXGrid] \
1827        -font "Arial 9"
1828    checkbutton $inner.ygrid \
1829        -text "Show Y Grid" \
1830        -variable [itcl::scope _settings(axisYGrid)] \
1831        -command [itcl::code $this AdjustSetting axisYGrid] \
1832        -font "Arial 9"
1833    checkbutton $inner.zgrid \
1834        -text "Show Z Grid" \
1835        -variable [itcl::scope _settings(axisZGrid)] \
1836        -command [itcl::code $this AdjustSetting axisZGrid] \
1837        -font "Arial 9"
1838
1839    label $inner.mode_l -text "Mode" -font "Arial 9"
1840
1841    itk_component add axismode {
1842        Rappture::Combobox $inner.mode -width 10 -editable no
1843    }
1844    $inner.mode choices insert end \
1845        "static_triad"    "static" \
1846        "closest_triad"   "closest" \
1847        "furthest_triad"  "furthest" \
1848        "outer_edges"     "outer"         
1849    $itk_component(axismode) value "static"
1850    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting axis-mode]
1851
1852    blt::table $inner \
1853        0,0 $inner.visible -anchor w -cspan 2 \
1854        1,0 $inner.labels  -anchor w -cspan 2 \
1855        2,0 $inner.xgrid   -anchor w -cspan 2 \
1856        3,0 $inner.ygrid   -anchor w -cspan 2 \
1857        4,0 $inner.zgrid   -anchor w -cspan 2 \
1858        5,0 $inner.mode_l  -anchor w -cspan 2 -padx { 2 0 } \
1859        6,0 $inner.mode    -fill x   -cspan 2
1860
1861    blt::table configure $inner r* c* -resize none
1862    blt::table configure $inner r7 c1 -resize expand
1863}
1864
1865
1866itcl::body Rappture::VtkStreamlinesViewer::BuildCameraTab {} {
1867    set inner [$itk_component(main) insert end \
1868        -title "Camera Settings" \
1869        -icon [Rappture::icon camera]]
1870    $inner configure -borderwidth 4
1871
1872    set labels { qx qy qz qw xpan ypan zoom }
1873    set row 0
1874    foreach tag $labels {
1875        label $inner.${tag}label -text $tag -font "Arial 9"
1876        entry $inner.${tag} -font "Arial 9"  -bg white \
1877            -textvariable [itcl::scope _view($tag)]
1878        bind $inner.${tag} <KeyPress-Return> \
1879            [itcl::code $this camera set ${tag}]
1880        blt::table $inner \
1881            $row,0 $inner.${tag}label -anchor e -pady 2 \
1882            $row,1 $inner.${tag} -anchor w -pady 2
1883        blt::table configure $inner r$row -resize none
1884        incr row
1885    }
1886    checkbutton $inner.ortho \
1887        -text "Orthographic Projection" \
1888        -variable [itcl::scope _view(ortho)] \
1889        -command [itcl::code $this camera set ortho] \
1890        -font "Arial 9"
1891    blt::table $inner \
1892            $row,0 $inner.ortho -columnspan 2 -anchor w -pady 2
1893    blt::table configure $inner r$row -resize none
1894    incr row
1895
1896    blt::table configure $inner c0 c1 -resize none
1897    blt::table configure $inner c2 -resize expand
1898    blt::table configure $inner r$row -resize expand
1899}
1900
1901itcl::body Rappture::VtkStreamlinesViewer::BuildCutplaneTab {} {
1902
1903    set fg [option get $itk_component(hull) font Font]
1904   
1905    set inner [$itk_component(main) insert end \
1906        -title "Cutplane Settings" \
1907        -icon [Rappture::icon cutbutton]]
1908
1909    $inner configure -borderwidth 4
1910
1911    checkbutton $inner.visible \
1912        -text "Show Cutplanes" \
1913        -variable [itcl::scope _settings(cutplaneVisible)] \
1914        -command [itcl::code $this AdjustSetting cutplaneVisible] \
1915        -font "Arial 9"
1916
1917    checkbutton $inner.wireframe \
1918        -text "Show Wireframe" \
1919        -variable [itcl::scope _settings(cutplaneWireframe)] \
1920        -command [itcl::code $this AdjustSetting cutplaneWireframe] \
1921        -font "Arial 9"
1922
1923    checkbutton $inner.lighting \
1924        -text "Enable Lighting" \
1925        -variable [itcl::scope _settings(cutplaneLighting)] \
1926        -command [itcl::code $this AdjustSetting cutplaneLighting] \
1927        -font "Arial 9"
1928
1929    checkbutton $inner.edges \
1930        -text "Show Edges" \
1931        -variable [itcl::scope _settings(cutplaneEdges)] \
1932        -command [itcl::code $this AdjustSetting cutplaneEdges] \
1933        -font "Arial 9"
1934
1935    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1936    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1937        -variable [itcl::scope _settings(cutplaneOpacity)] \
1938        -width 10 \
1939        -showvalue off \
1940        -command [itcl::code $this AdjustSetting cutplaneOpacity]
1941    $inner.opacity set $_settings(cutplaneOpacity)
1942
1943    # X-value slicer...
1944    itk_component add xCutButton {
1945        Rappture::PushButton $inner.xbutton \
1946            -onimage [Rappture::icon x-cutplane-red] \
1947            -offimage [Rappture::icon x-cutplane-red] \
1948            -command [itcl::code $this AdjustSetting cutplaneXVisible] \
1949            -variable [itcl::scope _settings(cutplaneXVisible)]
1950    }
1951    Rappture::Tooltip::for $itk_component(xCutButton) \
1952        "Toggle the X-axis cutplane on/off"
1953    $itk_component(xCutButton) select
1954
1955    itk_component add xCutScale {
1956        ::scale $inner.xval -from 100 -to 0 \
1957            -width 10 -orient vertical -showvalue yes \
1958            -borderwidth 1 -highlightthickness 0 \
1959            -command [itcl::code $this EventuallySetCutplane x] \
1960            -variable [itcl::scope _settings(cutplaneXPosition)] \
1961            -foreground red3 -font "Arial 9 bold"
1962    } {
1963        usual
1964        ignore -borderwidth -highlightthickness -foreground -font
1965    }
1966    # Set the default cutplane value before disabling the scale.
1967    $itk_component(xCutScale) set 50
1968    $itk_component(xCutScale) configure -state disabled
1969    Rappture::Tooltip::for $itk_component(xCutScale) \
1970        "@[itcl::code $this Slice tooltip x]"
1971
1972    # Y-value slicer...
1973    itk_component add yCutButton {
1974        Rappture::PushButton $inner.ybutton \
1975            -onimage [Rappture::icon y-cutplane-green] \
1976            -offimage [Rappture::icon y-cutplane-green] \
1977            -command [itcl::code $this AdjustSetting cutplaneYVisible] \
1978            -variable [itcl::scope _settings(cutplaneYVisible)]
1979    }
1980    Rappture::Tooltip::for $itk_component(yCutButton) \
1981        "Toggle the Y-axis cutplane on/off"
1982    $itk_component(yCutButton) select
1983
1984    itk_component add yCutScale {
1985        ::scale $inner.yval -from 100 -to 0 \
1986            -width 10 -orient vertical -showvalue yes \
1987            -borderwidth 1 -highlightthickness 0 \
1988            -command [itcl::code $this EventuallySetCutplane y] \
1989            -variable [itcl::scope _settings(cutplaneYPosition)] \
1990            -foreground green3 -font "Arial 9 bold"
1991    } {
1992        usual
1993        ignore -borderwidth -highlightthickness -foreground -font
1994    }
1995    Rappture::Tooltip::for $itk_component(yCutScale) \
1996        "@[itcl::code $this Slice tooltip y]"
1997    # Set the default cutplane value before disabling the scale.
1998    $itk_component(yCutScale) set 50
1999    $itk_component(yCutScale) configure -state disabled
2000
2001    # Z-value slicer...
2002    itk_component add zCutButton {
2003        Rappture::PushButton $inner.zbutton \
2004            -onimage [Rappture::icon z-cutplane-blue] \
2005            -offimage [Rappture::icon z-cutplane-blue] \
2006            -command [itcl::code $this AdjustSetting cutplaneZVisible] \
2007            -variable [itcl::scope _settings(cutplaneZVisible)]
2008    }
2009    Rappture::Tooltip::for $itk_component(zCutButton) \
2010        "Toggle the Z-axis cutplane on/off"
2011    $itk_component(zCutButton) select
2012
2013    itk_component add zCutScale {
2014        ::scale $inner.zval -from 100 -to 0 \
2015            -width 10 -orient vertical -showvalue yes \
2016            -borderwidth 1 -highlightthickness 0 \
2017            -command [itcl::code $this EventuallySetCutplane z] \
2018            -variable [itcl::scope _settings(cutplaneZPosition)] \
2019            -foreground blue3 -font "Arial 9 bold"
2020    } {
2021        usual
2022        ignore -borderwidth -highlightthickness -foreground -font
2023    }
2024    $itk_component(zCutScale) set 50
2025    $itk_component(zCutScale) configure -state disabled
2026    #$itk_component(zCutScale) configure -state disabled
2027    Rappture::Tooltip::for $itk_component(zCutScale) \
2028        "@[itcl::code $this Slice tooltip z]"
2029
2030    blt::table $inner \
2031        0,0 $inner.lighting             -anchor w -pady 2 -cspan 4 \
2032        1,0 $inner.wireframe            -anchor w -pady 2 -cspan 4 \
2033        2,0 $inner.edges                -anchor w -pady 2 -cspan 4 \
2034        3,0 $inner.opacity_l            -anchor w -pady 2 -cspan 1 \
2035        3,1 $inner.opacity              -fill x   -pady 2 -cspan 3 \
2036        4,0 $itk_component(xCutButton)  -anchor w -padx 2 -pady 2 \
2037        5,0 $itk_component(yCutButton)  -anchor w -padx 2 -pady 2 \
2038        6,0 $itk_component(zCutButton)  -anchor w -padx 2 -pady 2 \
2039        4,1 $itk_component(xCutScale)   -fill y -rspan 4 \
2040        4,2 $itk_component(yCutScale)   -fill y -rspan 4 \
2041        4,3 $itk_component(zCutScale)   -fill y -rspan 4 \
2042
2043    blt::table configure $inner r* c* -resize none
2044    blt::table configure $inner r7 c4 -resize expand
2045}
2046
2047
2048
2049#
2050#  camera --
2051#
2052itcl::body Rappture::VtkStreamlinesViewer::camera {option args} {
2053    switch -- $option {
2054        "show" {
2055            puts [array get _view]
2056        }
2057        "set" {
2058            set who [lindex $args 0]
2059            set x $_view($who)
2060            set code [catch { string is double $x } result]
2061            if { $code != 0 || !$result } {
2062                return
2063            }
2064            switch -- $who {
2065                "ortho" {
2066                    if {$_view(ortho)} {
2067                        SendCmd "camera mode ortho"
2068                    } else {
2069                        SendCmd "camera mode persp"
2070                    }
2071                }
2072                "xpan" - "ypan" {
2073                    PanCamera
2074                }
2075                "qx" - "qy" - "qz" - "qw" {
2076                    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2077                    $_arcball quaternion $q
2078                    EventuallyRotate $q
2079                }
2080                "zoom" {
2081                    SendCmd "camera zoom $_view(zoom)"
2082                }
2083            }
2084        }
2085    }
2086}
2087
2088itcl::body Rappture::VtkStreamlinesViewer::ConvertToVtkData { dataobj comp } {
2089    foreach { x1 x2 xN y1 y2 yN } [$dataobj mesh $comp] break
2090    set values [$dataobj values $comp]
2091    append out "# vtk DataFile Version 2.0 \n"
2092    append out "Test data \n"
2093    append out "ASCII \n"
2094    append out "DATASET STRUCTURED_POINTS \n"
2095    append out "DIMENSIONS $xN $yN 1 \n"
2096    append out "ORIGIN 0 0 0 \n"
2097    append out "SPACING 1 1 1 \n"
2098    append out "POINT_DATA [expr $xN * $yN] \n"
2099    append out "SCALARS field float 1 \n"
2100    append out "LOOKUP_TABLE default \n"
2101    append out [join $values "\n"]
2102    append out "\n"
2103    return $out
2104}
2105
2106
2107itcl::body Rappture::VtkStreamlinesViewer::GetVtkData { args } {
2108    set bytes ""
2109    foreach dataobj [get] {
2110        foreach comp [$dataobj components] {
2111            set tag $dataobj-$comp
2112            #set contents [ConvertToVtkData $dataobj $comp]
2113            set contents [$dataobj blob $comp]
2114            append bytes "$contents\n\n"
2115        }
2116    }
2117    return [list .vtk $bytes]
2118}
2119
2120itcl::body Rappture::VtkStreamlinesViewer::GetImage { args } {
2121    if { [image width $_image(download)] > 0 &&
2122         [image height $_image(download)] > 0 } {
2123        set bytes [$_image(download) data -format "jpeg -quality 100"]
2124        set bytes [Rappture::encoding::decode -as b64 $bytes]
2125        return [list .jpg $bytes]
2126    }
2127    return ""
2128}
2129
2130itcl::body Rappture::VtkStreamlinesViewer::BuildDownloadPopup { popup command } {
2131    Rappture::Balloon $popup \
2132        -title "[Rappture::filexfer::label downloadWord] as..."
2133    set inner [$popup component inner]
2134    label $inner.summary -text "" -anchor w
2135    radiobutton $inner.vtk_button -text "VTK data file" \
2136        -variable [itcl::scope _downloadPopup(format)] \
2137        -font "Helvetica 9 " \
2138        -value vtk 
2139    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
2140    radiobutton $inner.image_button -text "Image File" \
2141        -variable [itcl::scope _downloadPopup(format)] \
2142        -value image
2143    Rappture::Tooltip::for $inner.image_button \
2144        "Save as digital image."
2145
2146    button $inner.ok -text "Save" \
2147        -highlightthickness 0 -pady 2 -padx 3 \
2148        -command $command \
2149        -compound left \
2150        -image [Rappture::icon download]
2151
2152    button $inner.cancel -text "Cancel" \
2153        -highlightthickness 0 -pady 2 -padx 3 \
2154        -command [list $popup deactivate] \
2155        -compound left \
2156        -image [Rappture::icon cancel]
2157
2158    blt::table $inner \
2159        0,0 $inner.summary -cspan 2  \
2160        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2161        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2162        4,1 $inner.cancel -width .9i -fill y \
2163        4,0 $inner.ok -padx 2 -width .9i -fill y
2164    blt::table configure $inner r3 -height 4
2165    blt::table configure $inner r4 -pady 4
2166    raise $inner.image_button
2167    $inner.vtk_button invoke
2168    return $inner
2169}
2170
2171itcl::body Rappture::VtkStreamlinesViewer::SetObjectStyle { dataobj comp } {
2172    # Parse style string.
2173    set tag $dataobj-$comp
2174    set style [$dataobj style $comp]
2175    array set settings {
2176        -color \#808080
2177        -edges 0
2178        -edgecolor black
2179        -linewidth 1.0
2180        -opacity 0.4
2181        -wireframe 0
2182        -lighting 1
2183        -seeds 1
2184        -seedcolor white
2185        -visible 1
2186    }
2187    if { $dataobj != $_first } {
2188        set settings(-opacity) 1
2189    }
2190    array set settings $style
2191    SendCmd "streamlines add $tag"
2192    SendCmd "streamlines seed visible off $tag"
2193    set seeds [$dataobj hints seeds]
2194    if { $seeds != "" && ![info exists _seeds($dataobj)] } {
2195        set length [string length $seeds]
2196        SendCmd "streamlines seed fmesh 200 data follows $length $tag"
2197        SendCmd "$seeds"
2198        set _seeds($dataobj) 1
2199    }
2200    SendCmd "cutplane add $tag"
2201    SendCmd "polydata add $tag"
2202    set _settings(volumeEdges) $settings(-edges)
2203    set _settings(volumeLighting) $settings(-lighting)
2204    set _settings(volumeOpacity) $settings(-opacity)
2205    set _settings(volumeWireframe) $settings(-wireframe)
2206    set _settings(volumeOpacity) [expr $settings(-opacity) * 100.0]
2207    SetColormap $dataobj $comp
2208}
2209
2210itcl::body Rappture::VtkStreamlinesViewer::IsValidObject { dataobj } {
2211    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2212        return 0
2213    }
2214    return 1
2215}
2216
2217# ----------------------------------------------------------------------
2218# USAGE: ReceiveLegend <colormap> <title> <vmin> <vmax> <size>
2219#
2220# Invoked automatically whenever the "legend" command comes in from
2221# the rendering server.  Indicates that binary image data with the
2222# specified <size> will follow.
2223# ----------------------------------------------------------------------
2224itcl::body Rappture::VtkStreamlinesViewer::ReceiveLegend { colormap title vmin vmax size } {
2225    set _legendPending 0
2226    set _title $title
2227    regsub {\(mag\)} $title "" _title
2228    if { [IsConnected] } {
2229        set bytes [ReceiveBytes $size]
2230        if { ![info exists _image(legend)] } {
2231            set _image(legend) [image create photo]
2232        }
2233        $_image(legend) configure -data $bytes
2234        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2235        if { [catch {DrawLegend $_title} errs] != 0 } {
2236            puts stderr errs=$errs
2237        }
2238    }
2239}
2240
2241#
2242# DrawLegend --
2243#
2244#       Draws the legend in it's own canvas which resides to the right
2245#       of the contour plot area.
2246#
2247itcl::body Rappture::VtkStreamlinesViewer::DrawLegend { name } {
2248    set c $itk_component(view)
2249    set w [winfo width $c]
2250    set h [winfo height $c]
2251    set font "Arial 8"
2252    set lineht [font metrics $font -linespace]
2253   
2254    if { [info exists _fields($name)] } {
2255        foreach { title units } $_fields($name) break
2256        if { $units != "" } {
2257            set title [format "%s (%s)" $title $units]
2258        }
2259    } else {
2260        set title $name
2261    }
2262    if { $_settings(legendVisible) } {
2263        set x [expr $w - 2]
2264        if { [$c find withtag "legend"] == "" } {
2265            set y 2
2266            $c create text $x $y \
2267                -anchor ne \
2268                -fill $itk_option(-plotforeground) -tags "title legend" \
2269                -font $font
2270            incr y $lineht
2271            $c create text $x $y \
2272                -anchor ne \
2273                -fill $itk_option(-plotforeground) -tags "vmax legend" \
2274                -font $font
2275            incr y $lineht
2276            $c create image $x $y \
2277                -anchor ne \
2278                -image $_image(legend) -tags "colormap legend"
2279            $c create text $x [expr {$h-2}] \
2280                -anchor se \
2281                -fill $itk_option(-plotforeground) -tags "vmin legend" \
2282                -font $font
2283            #$c bind colormap <Enter> [itcl::code $this EnterLegend %x %y]
2284            $c bind colormap <Leave> [itcl::code $this LeaveLegend]
2285            $c bind colormap <Motion> [itcl::code $this MotionLegend %x %y]
2286        }
2287        $c bind title <ButtonPress> [itcl::code $this Combo post]
2288        $c bind title <Enter> [itcl::code $this Combo activate]
2289        $c bind title <Leave> [itcl::code $this Combo deactivate]
2290        # Reset the item coordinates according the current size of the plot.
2291        $c itemconfigure title -text $title
2292        if { [info exists _limits($_curFldName)] } {
2293            foreach {vmin vmax} $_limits($_curFldName) break
2294            $c itemconfigure vmin -text [format %g $vmin]
2295            $c itemconfigure vmax -text [format %g $vmax]
2296        }
2297        set y 2
2298        $c coords title $x $y
2299        incr y $lineht
2300        $c coords vmax $x $y
2301        incr y $lineht
2302        $c coords colormap $x $y
2303        $c coords vmin $x [expr {$h - 2}]
2304    }
2305}
2306
2307#
2308# EnterLegend --
2309#
2310itcl::body Rappture::VtkStreamlinesViewer::EnterLegend { x y } {
2311    SetLegendTip $x $y
2312}
2313
2314#
2315# MotionLegend --
2316#
2317itcl::body Rappture::VtkStreamlinesViewer::MotionLegend { x y } {
2318    Rappture::Tooltip::tooltip cancel
2319    set c $itk_component(view)
2320    SetLegendTip $x $y
2321}
2322
2323#
2324# LeaveLegend --
2325#
2326itcl::body Rappture::VtkStreamlinesViewer::LeaveLegend { } {
2327    Rappture::Tooltip::tooltip cancel
2328    .rappturetooltip configure -icon ""
2329}
2330
2331#
2332# SetLegendTip --
2333#
2334itcl::body Rappture::VtkStreamlinesViewer::SetLegendTip { x y } {
2335    set c $itk_component(view)
2336    set w [winfo width $c]
2337    set h [winfo height $c]
2338    set font "Arial 8"
2339    set lineht [font metrics $font -linespace]
2340   
2341    set imgHeight [image height $_image(legend)]
2342    set coords [$c coords colormap]
2343    set imgX [expr $w - [image width $_image(legend)] - 2]
2344    set imgY [expr $y - 2 * ($lineht + 2)]
2345
2346    if { [info exists _fields($_title)] } {
2347        foreach { title units } $_fields($_title) break
2348        if { $units != "" } {
2349            set title [format "%s (%s)" $title $units]
2350        }
2351    } else {
2352        set title $_title
2353    }
2354    # Make a swatch of the selected color
2355    if { [catch { $_image(legend) get 10 $imgY } pixel] != 0 } {
2356        #puts stderr "out of range: $imgY"
2357        return
2358    }
2359    if { ![info exists _image(swatch)] } {
2360        set _image(swatch) [image create photo -width 24 -height 24]
2361    }
2362    set color [eval format "\#%02x%02x%02x" $pixel]
2363    $_image(swatch) put black  -to 0 0 23 23
2364    $_image(swatch) put $color -to 1 1 22 22
2365    .rappturetooltip configure -icon $_image(swatch)
2366
2367    # Compute the value of the point
2368    if { [info exists _limits($_curFldName)] } {
2369        foreach {vmin vmax} $_limits($_curFldName) break
2370        set t [expr 1.0 - (double($imgY) / double($imgHeight-1))]
2371        set value [expr $t * ($vmax - $vmin) + $vmin]
2372    } else {
2373        set value 0.0
2374    }
2375    set tipx [expr $x + 15]
2376    set tipy [expr $y - 5]
2377    Rappture::Tooltip::text $c "$title $value"
2378    Rappture::Tooltip::tooltip show $c +$tipx,+$tipy   
2379}
2380
2381
2382# ----------------------------------------------------------------------
2383# USAGE: Slice move x|y|z <newval>
2384#
2385# Called automatically when the user drags the slider to move the
2386# cut plane that slices 3D data.  Gets the current value from the
2387# slider and moves the cut plane to the appropriate point in the
2388# data set.
2389# ----------------------------------------------------------------------
2390itcl::body Rappture::VtkStreamlinesViewer::Slice {option args} {
2391    switch -- $option {
2392        "move" {
2393            set axis [lindex $args 0]
2394            set oldval $_settings(axis-${axis}position)
2395            set newval [lindex $args 1]
2396            if {[llength $args] != 2} {
2397                error "wrong # args: should be \"Slice move x|y|z newval\""
2398            }
2399            set newpos [expr {0.01*$newval}]
2400            SendCmd "cutplane slice $axis $newpos"
2401        }
2402        "tooltip" {
2403            set axis [lindex $args 0]
2404            set val [$itk_component(${axis}CutScale) get]
2405            return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2406        }
2407        default {
2408            error "bad option \"$option\": should be axis, move, or tooltip"
2409        }
2410    }
2411}
2412
2413
2414# ----------------------------------------------------------------------
2415# USAGE: _dropdown post
2416# USAGE: _dropdown unpost
2417# USAGE: _dropdown select
2418#
2419# Used internally to handle the dropdown list for this combobox.  The
2420# post/unpost options are invoked when the list is posted or unposted
2421# to manage the relief of the controlling button.  The select option
2422# is invoked whenever there is a selection from the list, to assign
2423# the value back to the gauge.
2424# ----------------------------------------------------------------------
2425itcl::body Rappture::VtkStreamlinesViewer::Combo {option} {
2426    set c $itk_component(view)
2427    switch -- $option {
2428        post {
2429            foreach { x1 y1 x2 y2 } [$c bbox title] break
2430            set x1 [expr [winfo width $itk_component(view)] - [winfo reqwidth $itk_component(fieldmenu)]]
2431            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2432            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2433            tk_popup $itk_component(fieldmenu) $x $y
2434        }
2435        activate {
2436            $c itemconfigure title -fill red
2437        }
2438        deactivate {
2439            $c itemconfigure title -fill white
2440        }
2441        invoke {
2442            $itk_component(field) value $_curFldLabel
2443            AdjustSetting field
2444        }
2445        default {
2446            error "bad option \"$option\": should be post, unpost, select"
2447        }
2448    }
2449}
2450
2451#
2452# ResetAxes --
2453#
2454#       Set axis z bounds and range
2455#
2456itcl::body Rappture::VtkStreamlinesViewer::ResetAxes {} {
2457    if { ![info exists _limits($_curFldName)] } {
2458        SendCmd "dataset maprange all"
2459        SendCmd "axis autorange z on"
2460        SendCmd "axis autobounds z on"
2461        return
2462    }
2463    foreach { xmin xmax } $_limits(x) break
2464    foreach { ymin ymax } $_limits(y) break
2465    foreach { zmin zmax } $_limits(z) break
2466    foreach { vmin vmax } $_limits($_curFldName) break
2467    set dataRange   [expr $vmax - $vmin]
2468    set boundsRange [expr $xmax - $xmin]
2469    set r [expr $ymax - $ymin]
2470    if {$r > $boundsRange} {
2471        set boundsRange $r
2472    }
2473    if {$dataRange < 1.0e-16} {
2474        set dataScale 1.0
2475    } else {
2476        set dataScale [expr $boundsRange / $dataRange]
2477    }
2478    set heightScale 1.0
2479    set bMin [expr $heightScale * $dataScale * $vmin]
2480    set bMax [expr $heightScale * $dataScale * $vmax]
2481    SendCmd "dataset maprange explicit $_limits($_curFldName) $_curFldName"
2482    SendCmd "axis bounds z $bMin $bMax"
2483    SendCmd "axis range z $_limits($_curFldName)"
2484}
Note: See TracBrowser for help on using the repository browser.