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

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

Fixes for dataobj delete in VTK viewers:

  • Don't hide datasets from delete method since it isn't buffered and causes

flashes

  • Don't keep deleted dataobjs in _dlist: the commands are no longer valid even

though server objects remain. FIXME: should delete server objects or reuse
dataobj names for results, as we leak server datasets when user clears
datasets. However, we don't want to delete hidden sequence elts.

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