source: branches/1.3/gui/scripts/flowvisviewer.tcl @ 4848

Last change on this file since 4848 was 4848, checked in by ldelgass, 6 years ago

revert viewers to 1.3.5 tag versions

File size: 104.3 KB
Line 
1# -*- mode: tcl; indent-tabs-mode: nil -*-
2# ----------------------------------------------------------------------
3#  COMPONENT: flowvisviewer - 3D flow rendering
4#
5#
6# This widget performs volume and flow rendering on 3D scalar/vector datasets.
7# It connects to the Flowvis server running on a rendering farm, transmits
8# data, and displays the results.
9#
10# ======================================================================
11#  AUTHOR:  Michael McLennan, Purdue University
12#  Copyright (c) 2004-2012  HUBzero Foundation, LLC
13#
14# See the file "license.terms" for information on usage and redistribution of
15# this file, and for a DISCLAIMER OF ALL WARRANTIES.
16# ======================================================================
17package require Itk
18package require BLT
19package require Img
20
21option add *FlowvisViewer.width 5i widgetDefault
22option add *FlowvisViewer*cursor crosshair widgetDefault
23option add *FlowvisViewer.height 4i widgetDefault
24option add *FlowvisViewer.foreground black widgetDefault
25option add *FlowvisViewer.controlBackground gray widgetDefault
26option add *FlowvisViewer.controlDarkBackground #999999 widgetDefault
27option add *FlowvisViewer.plotBackground black widgetDefault
28option add *FlowvisViewer.plotForeground white widgetDefault
29option add *FlowvisViewer.plotOutline gray widgetDefault
30option add *FlowvisViewer.font \
31    -*-helvetica-medium-r-normal-*-12-* widgetDefault
32
33# must use this name -- plugs into Rappture::resources::load
34proc FlowvisViewer_init_resources {} {
35    Rappture::resources::register \
36        nanovis_server Rappture::FlowvisViewer::SetServerList
37}
38
39itcl::class Rappture::FlowvisViewer {
40    inherit Rappture::VisViewer
41
42    itk_option define -plotforeground plotForeground Foreground ""
43    itk_option define -plotbackground plotBackground Background ""
44    itk_option define -plotoutline plotOutline PlotOutline ""
45
46    constructor { hostlist args } {
47        Rappture::VisViewer::constructor $hostlist
48    } {
49        # defined below
50    }
51    destructor {
52        # defined below
53    }
54    public proc SetServerList { namelist } {
55        Rappture::VisViewer::SetServerList "nanovis" $namelist
56    }
57    public method add {dataobj {settings ""}}
58    public method camera {option args}
59    public method delete {args}
60    public method disconnect {}
61    public method download {option args}
62    public method flow {option}
63    public method get {args}
64    public method isconnected {}
65    public method limits { tf }
66    public method overmarker { m x }
67    public method parameters {title args} {
68        # do nothing
69    }
70    public method rmdupmarker { m x }
71    public method scale {args}
72    public method updatetransferfuncs {}
73
74    protected method Connect {}
75    protected method CurrentVolumeIds {{what -all}}
76    protected method Disconnect {}
77    protected method Resize {}
78    protected method ResizeLegend {}
79    protected method AdjustSetting {what {value ""}}
80    protected method InitSettings { args }
81    protected method Pan {option x y}
82    protected method Rebuild {}
83    protected method ReceiveData { args }
84    protected method ReceiveImage { args }
85    protected method ReceiveLegend { tf vmin vmax size }
86    protected method Rotate {option x y}
87    protected method SendDataObjs {}
88    protected method SendTransferFuncs {}
89    protected method Slice {option args}
90    protected method SlicerTip {axis}
91    protected method Zoom {option}
92
93    # soon to be removed.
94    protected method Flow {option args}
95    protected method Play {}
96    protected method Pause {}
97
98
99    # The following methods are only used by this class.
100
101    private method AddIsoMarker { x y }
102    private method BuildCameraTab {}
103    private method BuildCutplanesTab {}
104    private method BuildViewTab {}
105    private method BuildVolumeTab {}
106    private method ComputeTransferFunc { tf }
107    private method EventuallyResize { w h }
108    private method EventuallyGoto { nSteps }
109    private method EventuallyResizeLegend { }
110    private method FlowCmd { dataobj comp nbytes extents }
111    private method GetMovie { widget width height }
112    private method GetPngImage { widget width height }
113    private method NameTransferFunc { dataobj comp }
114    private method PanCamera {}
115    private method ParseLevelsOption { tf levels }
116    private method ParseMarkersOption { tf markers }
117    private method WaitIcon { option widget }
118    private method str2millisecs { value }
119    private method millisecs2str { value }
120    private method GetFlowInfo { widget }
121    private method particles { tag name }
122    private method box { tag name }
123    private method streams { tag name }
124    private method arrows { tag name }
125    private method SetOrientation { side }
126
127    private variable _arcball ""
128    private variable _dlist ""     ;# list of data objects
129    private variable _allDataObjs
130    private variable _obj2ovride   ;# maps dataobj => style override
131    private variable _serverObjs   ;# maps dataobj-component to volume ID
132                                    # in the server
133    private variable _sendobjs ""  ;# list of data objs to send to server
134    private variable _recvObjs  ;# list of data objs to send to server
135    private variable _obj2style    ;# maps dataobj-component to transfunc
136    private variable _style2objs   ;# maps tf back to list of
137                                    # dataobj-components using the tf.
138    private variable _obj2flow;         # Maps dataobj-component to a flow.
139
140    private variable _reset 1;          # Connection to server has been reset
141    private variable _click        ;# info used for rotate operations
142    private variable _limits       ;# autoscale min/max for all axes
143    private variable _view         ;# view params for 3D view
144    private variable _isomarkers    ;# array of isosurface level values 0..1
145    private common   _settings
146    private variable _activeTf ""  ;# The currently active transfer function.
147    private variable _first ""     ;# This is the topmost volume.
148    private variable _nextToken 0
149    private variable _icon 0
150    private variable _flow
151    # This
152    # indicates which isomarkers and transfer
153    # function to use when changing markers,
154    # opacity, or thickness.
155    private common _downloadPopup          ;# download options from popup
156
157    private common _hardcopy
158    private variable _width 0
159    private variable _height 0
160    private variable _resizePending 0
161    private variable _resizeLegendPending 0
162    private variable _gotoPending 0
163}
164
165itk::usual FlowvisViewer {
166    keep -background -foreground -cursor -font
167    keep -plotbackground -plotforeground
168}
169
170# ----------------------------------------------------------------------
171# CONSTRUCTOR
172# ----------------------------------------------------------------------
173itcl::body Rappture::FlowvisViewer::constructor { hostlist args } {
174    set _serverType "nanovis"
175
176    # Draw legend event
177    $_dispatcher register !legend
178    $_dispatcher dispatch $this !legend "[itcl::code $this ResizeLegend]; list"
179
180    # Send dataobjs event
181    $_dispatcher register !send_dataobjs
182    $_dispatcher dispatch $this !send_dataobjs \
183        "[itcl::code $this SendDataObjs]; list"
184
185    # Send transferfunctions event
186    $_dispatcher register !send_transfunc
187    $_dispatcher dispatch $this !send_transfunc \
188        "[itcl::code $this SendTransferFuncs]; list"
189
190    # Rebuild event.
191    $_dispatcher register !rebuild
192    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
193
194    # Resize event.
195    $_dispatcher register !resize
196    $_dispatcher dispatch $this !resize "[itcl::code $this Resize]; list"
197
198    $_dispatcher register !play
199    $_dispatcher dispatch $this !play "[itcl::code $this flow next]; list"
200   
201    # Draw legend event
202    $_dispatcher register !goto
203    $_dispatcher dispatch $this !goto "[itcl::code $this flow goto2]; list"
204
205    $_dispatcher register !movietimeout
206    $_dispatcher register !waiticon
207
208    set _flow(state) 0
209
210    array set _downloadPopup {
211        format draft
212    }
213    #
214    # Populate parser with commands handle incoming requests
215    #
216    $_parser alias image [itcl::code $this ReceiveImage]
217    $_parser alias legend [itcl::code $this ReceiveLegend]
218    $_parser alias data [itcl::code $this ReceiveData]
219
220    # Initialize the view to some default parameters.
221    array set _view {
222        qw      0.853553
223        qx      -0.353553
224        qy      0.353553
225        qz      0.146447
226        zoom    1.0
227        xpan    0
228        ypan    0
229    }
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    set _limits(vmin) 0.0
235    set _limits(vmax) 1.0
236    set _reset 1
237
238    array set _settings [subst {
239        $this-qw                $_view(qw)
240        $this-qx                $_view(qx)
241        $this-qy                $_view(qy)
242        $this-qz                $_view(qz)
243        $this-zoom              $_view(zoom)   
244        $this-xpan              $_view(xpan)
245        $this-ypan              $_view(ypan)
246        $this-arrows            0
247        $this-currenttime       0
248        $this-duration          1:00
249        $this-loop              0
250        $this-play              0
251        $this-speed             500
252        $this-step              0
253        $this-streams           0
254        $this-volume            1
255        $this-xcutplane         0
256        $this-xcutposition      0
257        $this-ycutplane         0
258        $this-ycutposition      0
259        $this-zcutplane         0
260        $this-zcutposition      0
261    }]
262
263    itk_component add 3dview {
264        label $itk_component(plotarea).view -image $_image(plot) \
265            -highlightthickness 0 -borderwidth 0
266    } {
267        usual
268        ignore -highlightthickness -borderwidth  -background
269    }
270    bind $itk_component(3dview) <Control-F1> [itcl::code $this ToggleConsole]
271
272    set f [$itk_component(main) component controls]
273    itk_component add reset {
274        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
275            -highlightthickness 0 \
276            -image [Rappture::icon reset-view] \
277            -command [itcl::code $this Zoom reset]
278    } {
279        usual
280        ignore -highlightthickness
281    }
282    pack $itk_component(reset) -side top -padx 2 -pady 2
283    Rappture::Tooltip::for $itk_component(reset) "Reset the view to the default zoom level"
284
285    itk_component add zoomin {
286        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
287            -highlightthickness 0 \
288            -image [Rappture::icon zoom-in] \
289            -command [itcl::code $this Zoom in]
290    } {
291        usual
292        ignore -highlightthickness
293    }
294    pack $itk_component(zoomin) -side top -padx 2 -pady 2
295    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
296
297    itk_component add zoomout {
298        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
299            -highlightthickness 0 \
300            -image [Rappture::icon zoom-out] \
301            -command [itcl::code $this Zoom out]
302    } {
303        usual
304        ignore -highlightthickness
305    }
306    pack $itk_component(zoomout) -side top -padx 2 -pady 2
307    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
308
309    itk_component add volume {
310        Rappture::PushButton $f.volume \
311            -onimage [Rappture::icon volume-on] \
312            -offimage [Rappture::icon volume-off] \
313            -command [itcl::code $this AdjustSetting volume] \
314            -variable [itcl::scope _settings($this-volume)]
315    }
316    $itk_component(volume) select
317    Rappture::Tooltip::for $itk_component(volume) \
318        "Toggle the volume cloud on/off"
319    pack $itk_component(volume) -padx 2 -pady 2
320
321    if { [catch {
322        BuildViewTab
323        BuildVolumeTab
324        BuildCutplanesTab
325        BuildCameraTab
326    } errs] != 0 } {
327        global errorInfo
328        puts stderr "errs=$errs errorInfo=$errorInfo"
329    }
330
331    bind $itk_component(3dview) <Configure> \
332        [itcl::code $this EventuallyResize %w %h]
333
334    # Legend
335    set _image(legend) [image create photo]
336    itk_component add legend {
337        canvas $itk_component(plotarea).legend \
338            -height 50 -highlightthickness 0 -background black
339    } {
340        usual
341        ignore -highlightthickness
342        rename -background -plotbackground plotBackground Background
343    }
344    bind $itk_component(legend) <Configure> \
345        [itcl::code $this EventuallyResizeLegend]
346
347    # Hack around the Tk panewindow.  The problem is that the requested
348    # size of the 3d view isn't set until an image is retrieved from
349    # the server.  So the panewindow uses the tiny size.
350    set w 10000
351    pack forget $itk_component(3dview)
352    blt::table $itk_component(plotarea) \
353        0,0 $itk_component(3dview) -fill both -reqwidth $w \
354        1,0 $itk_component(legend) -fill x
355    blt::table configure $itk_component(plotarea) r1 -resize none   
356    # Create flow controls...
357
358    itk_component add flowcontrols {
359        frame $itk_interior.flowcontrols
360    } {
361        usual
362        rename -background -controlbackground controlBackground Background
363    }
364    pack forget $itk_component(main)
365    blt::table $itk_interior \
366        0,0 $itk_component(main) -fill both  \
367        1,0 $itk_component(flowcontrols) -fill x
368    blt::table configure $itk_interior r1 -resize none
369
370    # Rewind
371    itk_component add rewind {
372        button $itk_component(flowcontrols).reset \
373            -borderwidth 1 -padx 1 -pady 1 \
374            -image [Rappture::icon flow-rewind] \
375            -command [itcl::code $this flow reset]
376    } {
377        usual
378        ignore -borderwidth
379        rename -highlightbackground -controlbackground controlBackground \
380            Background
381    }
382    Rappture::Tooltip::for $itk_component(rewind) \
383        "Rewind flow"
384
385    # Stop
386    itk_component add stop {
387        button $itk_component(flowcontrols).stop \
388            -borderwidth 1 -padx 1 -pady 1 \
389            -image [Rappture::icon flow-stop] \
390            -command [itcl::code $this flow stop]
391    } {
392        usual
393        ignore -borderwidth
394        rename -highlightbackground -controlbackground controlBackground \
395            Background
396    }
397    Rappture::Tooltip::for $itk_component(stop) \
398        "Stop flow"
399
400    # Play
401    itk_component add play {
402        Rappture::PushButton $itk_component(flowcontrols).play \
403            -onimage [Rappture::icon flow-pause] \
404            -offimage [Rappture::icon flow-play] \
405            -variable [itcl::scope _settings($this-play)] \
406            -command [itcl::code $this flow toggle]
407    }
408    set fg [option get $itk_component(hull) font Font]
409    Rappture::Tooltip::for $itk_component(play) \
410        "Play/Pause flow"
411
412    # Loop
413    itk_component add loop {
414        Rappture::PushButton $itk_component(flowcontrols).loop \
415            -onimage [Rappture::icon flow-loop] \
416            -offimage [Rappture::icon flow-loop] \
417            -variable [itcl::scope _settings($this-loop)]
418    }
419    Rappture::Tooltip::for $itk_component(loop) \
420        "Play continuously"
421
422    itk_component add dial {
423        Rappture::Flowdial $itk_component(flowcontrols).dial \
424            -length 10 -valuewidth 0 -valuepadding 0 -padding 6 \
425            -linecolor "" -activelinecolor "" \
426            -min 0.0 -max 1.0 \
427            -variable [itcl::scope _settings($this-currenttime)] \
428            -knobimage [Rappture::icon knob2] -knobposition center@middle
429    } {
430        usual
431        ignore -dialprogresscolor
432        rename -background -controlbackground controlBackground Background
433    }
434    $itk_component(dial) current 0.0
435    bind $itk_component(dial) <<Value>> [itcl::code $this flow goto]
436    # Duration
437    itk_component add duration {
438        entry $itk_component(flowcontrols).duration \
439            -textvariable [itcl::scope _settings($this-duration)] \
440            -bg white -width 6 -font "arial 9"
441    } {
442        usual
443        ignore -highlightthickness -background
444    }
445    bind $itk_component(duration) <Return> [itcl::code $this flow duration]
446    bind $itk_component(duration) <KP_Enter> [itcl::code $this flow duration]
447    bind $itk_component(duration) <Tab> [itcl::code $this flow duration]
448    Rappture::Tooltip::for $itk_component(duration) \
449        "Set duration of flow (format is min:sec)"
450
451
452    itk_component add durationlabel {
453        label $itk_component(flowcontrols).durationl \
454            -text "Duration:" -font $fg \
455            -highlightthickness 0
456    } {
457        usual
458        ignore -highlightthickness
459        rename -background -controlbackground controlBackground Background
460    }
461
462    itk_component add speedlabel {
463        label $itk_component(flowcontrols).speedl -text "Speed:" -font $fg \
464            -highlightthickness 0
465    } {
466        usual
467        ignore -highlightthickness
468        rename -background -controlbackground controlBackground Background
469    }
470
471    # Speed
472    itk_component add speed {
473        Rappture::Flowspeed $itk_component(flowcontrols).speed \
474            -min 1 -max 10 -width 3 -font "arial 9"
475    } {
476        usual
477        ignore -highlightthickness
478        rename -background -controlbackground controlBackground Background
479    }
480    Rappture::Tooltip::for $itk_component(speed) \
481        "Change speed of flow"
482
483    $itk_component(speed) value 1
484    bind $itk_component(speed) <<Value>> [itcl::code $this flow speed]
485
486
487    blt::table $itk_component(flowcontrols) \
488        0,0 $itk_component(rewind) -padx {3 0} \
489        0,1 $itk_component(stop) -padx {2 0} \
490        0,2 $itk_component(play) -padx {2 0} \
491        0,3 $itk_component(loop) -padx {2 0} \
492        0,4 $itk_component(dial) -fill x -padx {2 0 } \
493        0,5 $itk_component(duration) -padx { 0 0} \
494        0,7 $itk_component(speed) -padx {2 3}
495
496#        0,6 $itk_component(speedlabel) -padx {2 0}
497    blt::table configure $itk_component(flowcontrols) c* -resize none
498    blt::table configure $itk_component(flowcontrols) c4 -resize both
499    blt::table configure $itk_component(flowcontrols) r0 -pady 1
500    # Bindings for rotation via mouse
501    bind $itk_component(3dview) <ButtonPress-1> \
502        [itcl::code $this Rotate click %x %y]
503    bind $itk_component(3dview) <B1-Motion> \
504        [itcl::code $this Rotate drag %x %y]
505    bind $itk_component(3dview) <ButtonRelease-1> \
506        [itcl::code $this Rotate release %x %y]
507
508    bind $itk_component(3dview) <Configure> \
509        [itcl::code $this EventuallyResize %w %h]
510
511    # Bindings for panning via mouse
512    bind $itk_component(3dview) <ButtonPress-2> \
513        [itcl::code $this Pan click %x %y]
514    bind $itk_component(3dview) <B2-Motion> \
515        [itcl::code $this Pan drag %x %y]
516    bind $itk_component(3dview) <ButtonRelease-2> \
517        [itcl::code $this Pan release %x %y]
518
519    # Bindings for panning via keyboard
520    bind $itk_component(3dview) <KeyPress-Left> \
521        [itcl::code $this Pan set -10 0]
522    bind $itk_component(3dview) <KeyPress-Right> \
523        [itcl::code $this Pan set 10 0]
524    bind $itk_component(3dview) <KeyPress-Up> \
525        [itcl::code $this Pan set 0 -10]
526    bind $itk_component(3dview) <KeyPress-Down> \
527        [itcl::code $this Pan set 0 10]
528    bind $itk_component(3dview) <Shift-KeyPress-Left> \
529        [itcl::code $this Pan set -2 0]
530    bind $itk_component(3dview) <Shift-KeyPress-Right> \
531        [itcl::code $this Pan set 2 0]
532    bind $itk_component(3dview) <Shift-KeyPress-Up> \
533        [itcl::code $this Pan set 0 -2]
534    bind $itk_component(3dview) <Shift-KeyPress-Down> \
535        [itcl::code $this Pan set 0 2]
536
537    # Bindings for zoom via keyboard
538    bind $itk_component(3dview) <KeyPress-Prior> \
539        [itcl::code $this Zoom out]
540    bind $itk_component(3dview) <KeyPress-Next> \
541        [itcl::code $this Zoom in]
542
543    bind $itk_component(3dview) <Enter> "focus $itk_component(3dview)"
544
545    if {[string equal "x11" [tk windowingsystem]]} {
546        # Bindings for zoom via mouse
547        bind $itk_component(3dview) <4> [itcl::code $this Zoom out]
548        bind $itk_component(3dview) <5> [itcl::code $this Zoom in]
549    }
550
551    set _image(download) [image create photo]
552
553    eval itk_initialize $args
554
555    Connect
556}
557
558# ----------------------------------------------------------------------
559# DESTRUCTOR
560# ----------------------------------------------------------------------
561itcl::body Rappture::FlowvisViewer::destructor {} {
562    set _sendobjs ""  ;# stop any send in progress
563    $_dispatcher cancel !rebuild
564    $_dispatcher cancel !send_dataobjs
565    $_dispatcher cancel !send_transfunc
566    image delete $_image(plot)
567    image delete $_image(legend)
568    image delete $_image(download)
569    catch { blt::arcball destroy $_arcball }
570    array unset _settings $this-*
571}
572
573# ----------------------------------------------------------------------
574# USAGE: add <dataobj> ?<settings>?
575#
576# Clients use this to add a data object to the plot.  The optional
577# <settings> are used to configure the plot.  Allowed settings are
578# -color, -brightness, -width, -linestyle, and -raise.
579# ----------------------------------------------------------------------
580itcl::body Rappture::FlowvisViewer::add {dataobj {settings ""}} {
581    array set params {
582        -color auto
583        -width 1
584        -linestyle solid
585        -brightness 0
586        -raise 0
587        -description ""
588        -param ""
589    }
590    array set params $settings
591    if {$params(-color) == "auto" || $params(-color) == "autoreset"} {
592        # can't handle -autocolors yet
593        set params(-color) black
594    }
595    foreach comp [$dataobj components] {
596        set flowobj [$dataobj flowhints $comp]
597        if { $flowobj == "" } {
598            puts stderr "no flowhints $dataobj-$comp"
599            continue
600        }
601        set _obj2flow($dataobj-$comp) $flowobj
602    }
603    set pos [lsearch -exact $_dlist $dataobj]
604    if {$pos < 0} {
605        lappend _dlist $dataobj
606        set _allDataObjs($dataobj) 1
607        set _obj2ovride($dataobj-color) $params(-color)
608        set _obj2ovride($dataobj-width) $params(-width)
609        set _obj2ovride($dataobj-raise) $params(-raise)
610        $_dispatcher event -idle !rebuild
611    }
612}
613
614# ----------------------------------------------------------------------
615# USAGE: get ?-objects?
616# USAGE: get ?-image 3dview|legend?
617#
618# Clients use this to query the list of objects being plotted, in
619# order from bottom to top of this result.  The optional "-image"
620# flag can also request the internal images being shown.
621# ----------------------------------------------------------------------
622itcl::body Rappture::FlowvisViewer::get {args} {
623    if {[llength $args] == 0} {
624        set args "-objects"
625    }
626
627    set op [lindex $args 0]
628    switch -- $op {
629      -objects {
630        # put the dataobj list in order according to -raise options
631        set dlist $_dlist
632        foreach obj $dlist {
633            if {[info exists _obj2ovride($obj-raise)] && $_obj2ovride($obj-raise)} {
634                set i [lsearch -exact $dlist $obj]
635                if {$i >= 0} {
636                    set dlist [lreplace $dlist $i $i]
637                    lappend dlist $obj
638                }
639            }
640        }
641        return $dlist
642      }
643      -image {
644        if {[llength $args] != 2} {
645            error "wrong # args: should be \"get -image 3dview|legend\""
646        }
647        switch -- [lindex $args end] {
648            3dview {
649                return $_image(plot)
650            }
651            legend {
652                return $_image(legend)
653            }
654            default {
655                error "bad image name \"[lindex $args end]\": should be 3dview or legend"
656            }
657        }
658      }
659      default {
660        error "bad option \"$op\": should be -objects or -image"
661      }
662    }
663}
664
665# ----------------------------------------------------------------------
666# USAGE: delete ?<dataobj1> <dataobj2> ...?
667#
668#       Clients use this to delete a dataobj from the plot.  If no dataobjs
669#       are specified, then all dataobjs are deleted.  No data objects are
670#       deleted.  They are only removed from the display list.
671#
672# ----------------------------------------------------------------------
673itcl::body Rappture::FlowvisViewer::delete {args} {
674     flow stop
675    if {[llength $args] == 0} {
676        set args $_dlist
677    }
678
679    # Delete all specified dataobjs
680    set changed 0
681    foreach dataobj $args {
682        set pos [lsearch -exact $_dlist $dataobj]
683        if { $pos >= 0 } {
684            foreach comp [$dataobj components] {
685                array unset _limits $dataobj-$comp-*
686            }
687            set _dlist [lreplace $_dlist $pos $pos]
688            array unset _obj2ovride $dataobj-*
689            array unset _obj2flow $dataobj-*
690            array unset _serverObjs $dataobj-*
691            array unset _obj2style $dataobj-*
692            set changed 1
693        }
694    }
695    # If anything changed, then rebuild the plot
696    if {$changed} {
697        # Repair the reverse lookup
698        foreach tf [array names _style2objs] {
699            set list {}
700            foreach {dataobj comp} $_style2objs($tf) break
701            if { [info exists _serverObjs($dataobj-$comp)] } {
702                lappend list $dataobj $comp
703            }
704            if { $list == "" } {
705                array unset _style2objs $tf
706            } else {
707                set _style2objs($tf) $list
708            }
709        }
710        $_dispatcher event -idle !rebuild
711    }
712}
713
714# ----------------------------------------------------------------------
715# USAGE: scale ?<data1> <data2> ...?
716#
717# Sets the default limits for the overall plot according to the
718# limits of the data for all of the given <data> objects.  This
719# accounts for all objects--even those not showing on the screen.
720# Because of this, the limits are appropriate for all objects as
721# the user scans through data in the ResultSet viewer.
722# ----------------------------------------------------------------------
723itcl::body Rappture::FlowvisViewer::scale {args} {
724    foreach val {xmin xmax ymin ymax vmin vmax} {
725        set _limits($val) ""
726    }
727    foreach obj $args {
728        foreach axis {x y v} {
729
730            foreach { min max } [$obj limits $axis] break
731
732            if {"" != $min && "" != $max} {
733                if {"" == $_limits(${axis}min)} {
734                    set _limits(${axis}min) $min
735                    set _limits(${axis}max) $max
736                } else {
737                    if {$min < $_limits(${axis}min)} {
738                        set _limits(${axis}min) $min
739                    }
740                    if {$max > $_limits(${axis}max)} {
741                        set _limits(${axis}max) $max
742                    }
743                }
744            }
745        }
746    }
747}
748
749# ----------------------------------------------------------------------
750# USAGE: download coming
751# USAGE: download controls <downloadCommand>
752# USAGE: download now
753#
754# Clients use this method to create a downloadable representation
755# of the plot.  Returns a list of the form {ext string}, where
756# "ext" is the file extension (indicating the type of data) and
757# "string" is the data itself.
758# ----------------------------------------------------------------------
759itcl::body Rappture::FlowvisViewer::download {option args} {
760    set popup .flowvisviewerdownload
761    switch $option {
762        coming {
763            if {[catch {
764                blt::winop snap $itk_component(plotarea) $_image(download)
765            }]} {
766                $_image(download) configure -width 1 -height 1
767                $_image(download) put #000000
768            }
769        }
770        controls {
771            if {![winfo exists $popup]} {
772                # if we haven't created the popup yet, do it now
773                Rappture::Balloon $popup \
774                    -title "[Rappture::filexfer::label downloadWord] as..."
775                set inner [$popup component inner]
776                label $inner.summary -text "" -anchor w
777                pack $inner.summary -side top
778                set img $_image(plot)
779                set res "[image width $img]x[image height $img]"
780                radiobutton $inner.draft -text "Image (draft $res)" \
781                    -variable Rappture::FlowvisViewer::_downloadPopup(format) \
782                    -value draft
783                pack $inner.draft -anchor w
784
785                set res "640x480"
786                radiobutton $inner.medium -text "Movie (standard $res)" \
787                    -variable Rappture::FlowvisViewer::_downloadPopup(format) \
788                    -value $res
789                pack $inner.medium -anchor w
790
791                set res "1024x768"
792                radiobutton $inner.high -text "Movie (high quality $res)" \
793                    -variable Rappture::FlowvisViewer::_downloadPopup(format) \
794                    -value $res
795                pack $inner.high -anchor w
796                button $inner.go -text [Rappture::filexfer::label download] \
797                    -command [lindex $args 0]
798                pack $inner.go -pady 4
799                $inner.draft select
800            } else {
801                set inner [$popup component inner]
802            }
803            set num [llength [get]]
804            set num [expr {($num == 1) ? "1 result" : "$num results"}]
805            set word [Rappture::filexfer::label downloadWord]
806            $inner.summary configure -text "$word $num in the following format:"
807            update idletasks ;# fix initial sizes
808            update
809            return $popup
810        }
811        now {
812            if { [winfo exists $popup] } {
813                $popup deactivate
814            }
815            switch -- $_downloadPopup(format) {
816                draft {
817                    # Get the image data (as base64) and decode it back to
818                    # binary.  This is better than writing to temporary
819                    # files.  When we switch to the BLT picture image it
820                    # won't be necessary to decode the image data.
821                    set bytes [$_image(plot) data -format "jpeg -quality 100"]
822                    set bytes [Rappture::encoding::decode -as b64 $bytes]
823                    return [list .jpg $bytes]
824                }
825                "640x480" {
826                    return [$this GetMovie [lindex $args 0] 640 480]
827                }
828                "1024x768" {
829                    return [$this GetMovie [lindex $args 0] 1024 768]
830                }
831                default {
832                    error "bad download format $_downloadPopup(format)"
833                }
834            }
835        }
836        default {
837            error "bad option \"$option\": should be coming, controls, now"
838        }
839    }
840}
841
842# ----------------------------------------------------------------------
843# USAGE: Connect ?<host:port>,<host:port>...?
844#
845# Clients use this method to establish a connection to a new
846# server, or to reestablish a connection to the previous server.
847# Any existing connection is automatically closed.
848# ----------------------------------------------------------------------
849itcl::body Rappture::FlowvisViewer::Connect {} {
850    set _hosts [GetServerList "nanovis"]
851    if { "" == $_hosts } {
852        return 0
853    }
854    set _reset 1
855    set result [VisViewer::Connect $_hosts]
856    if { $result } {
857        if { $_reportClientInfo }  {
858            # Tell the server the viewer, hub, user and session.
859            # Do this immediately on connect before buffing any commands
860            global env
861
862            set info {}
863            set user "???"
864            if { [info exists env(USER)] } {
865                set user $env(USER)
866            }
867            set session "???"
868            if { [info exists env(SESSION)] } {
869                set session $env(SESSION)
870            }
871            lappend info "version" "$Rappture::version"
872            lappend info "build" "$Rappture::build"
873            lappend info "svnurl" "$Rappture::svnurl"
874            lappend info "installdir" "$Rappture::installdir"
875            lappend info "hub" [exec hostname]
876            lappend info "client" "flowvisviewer"
877            lappend info "user" $user
878            lappend info "session" $session
879            SendCmd "clientinfo [list $info]"
880        }
881
882        set w [winfo width $itk_component(3dview)]
883        set h [winfo height $itk_component(3dview)]
884        EventuallyResize $w $h
885    }
886    return $result
887}
888
889#
890# isconnected --
891#
892#       Indicates if we are currently connected to the visualization server.
893#
894itcl::body Rappture::FlowvisViewer::isconnected {} {
895    return [VisViewer::IsConnected]
896}
897
898#
899# disconnect --
900#
901itcl::body Rappture::FlowvisViewer::disconnect {} {
902    Disconnect
903}
904
905#
906# Disconnect --
907#
908#       Clients use this method to disconnect from the current rendering
909#       server.
910#
911itcl::body Rappture::FlowvisViewer::Disconnect {} {
912    VisViewer::Disconnect
913
914    # disconnected -- no more data sitting on server
915    array unset _serverObjs
916    set _sendobjs ""
917}
918
919# ----------------------------------------------------------------------
920# USAGE: SendDataObjs
921#
922# Used internally to send a series of volume objects off to the
923# server.  Sends each object, a little at a time, with updates in
924# between so the interface doesn't lock up.
925# ----------------------------------------------------------------------
926itcl::body Rappture::FlowvisViewer::SendDataObjs {} {
927    blt::busy hold $itk_component(hull)
928    foreach dataobj $_sendobjs {
929        foreach comp [$dataobj components] {
930            # Send the data as one huge base64-encoded mess -- yuck!
931            set data [$dataobj blob $comp]
932            set nbytes [string length $data]
933            set extents [$dataobj extents $comp]
934
935            # I have a field. Is a vector field or a volume field?
936            if { $extents == 1 } {
937                set cmd "volume data follows $nbytes $dataobj-$comp\n"
938            } else {
939                set cmd [FlowCmd $dataobj $comp $nbytes $extents]
940                if { $cmd == "" } {
941                    puts stderr "no command"
942                    continue
943                }
944            }
945            f { ![SendBytes $cmd] } {
946                puts stderr "can't send"
947                return
948            }
949            if { ![SendBytes $data] } {
950                puts stderr "can't send"
951                return
952            }
953            NameTransferFunc $dataobj $comp
954            set _recvObjs($dataobj-$comp) 1
955        }
956    }
957    set _sendobjs ""
958    blt::busy release $itk_component(hull)
959
960    # Turn on buffering of commands to the server.  We don't want to
961    # be preempted by a server disconnect/reconnect (which automatically
962    # generates a new call to Rebuild).   
963    StartBufferingCommands
964
965    # activate the proper volume
966    set _first [lindex [get] 0]
967    if { "" != $_first } {
968        set axis [$_first hints updir]
969        if {"" != $axis} {
970            SendCmd "up $axis"
971        }
972
973        if 0 {
974        set location [$_first hints camera]
975        if { $location != "" } {
976            array set _view $location
977        }
978        set _settings($this-qw)    $_view(qw)
979        set _settings($this-qx)    $_view(qx)
980        set _settings($this-qy)    $_view(qy)
981        set _settings($this-qz)    $_view(qz)
982        set _settings($this-xpan)  $_view(xpan)
983        set _settings($this-ypan)  $_view(ypan)
984        set _settings($this-zoom)  $_view(zoom)
985        set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
986        $_arcball quaternion $q
987        SendCmd "camera orient $q"
988        SendCmd "camera reset"
989        PanCamera
990        SendCmd "camera zoom $_view(zoom)"
991        }
992        # The active transfer function is by default the first component of
993        # the first data object.  This assumes that the data is always
994        # successfully transferred.
995        set comp [lindex [$_first components] 0]
996        set _activeTf [lindex $_obj2style($_first-$comp) 0]
997    }
998
999    SendCmd "flow reset"
1000    StopBufferingCommands
1001}
1002
1003# ----------------------------------------------------------------------
1004# USAGE: SendTransferFuncs
1005# ----------------------------------------------------------------------
1006itcl::body Rappture::FlowvisViewer::SendTransferFuncs {} {
1007    if { $_activeTf == "" } {
1008        puts stderr "no active tf"
1009        return
1010    }
1011    set tf $_activeTf
1012    if { $_first == "" } {
1013        puts stderr "no first"
1014        return
1015    }
1016
1017    # Ensure that the global opacity and thickness settings (in the slider
1018    # settings widgets) are used for the active transfer-function.  Update the
1019    # values in the _settings varible.
1020    set value $_settings($this-opacity)
1021    set opacity [expr { double($value) * 0.01 }]
1022    set _settings($this-$tf-opacity) $opacity
1023    set value $_settings($this-thickness)
1024    # Scale values between 0.00001 and 0.01000
1025    set thickness [expr {double($value) * 0.0001}]
1026    set _settings($this-$tf-thickness) $thickness
1027
1028    foreach key [array names _obj2style $_first-*] {
1029        if { [info exists _obj2style($key)] } {
1030            foreach tf $_obj2style($key) {
1031                ComputeTransferFunc $tf
1032            }
1033        }
1034    }
1035    EventuallyResizeLegend
1036}
1037
1038# ----------------------------------------------------------------------
1039# USAGE: ReceiveImage -bytes $size -type $type -token $token
1040#
1041# Invoked automatically whenever the "image" command comes in from
1042# the rendering server.  Indicates that binary image data with the
1043# specified <size> will follow.
1044# ----------------------------------------------------------------------
1045itcl::body Rappture::FlowvisViewer::ReceiveImage { args } {
1046    array set info {
1047        -token "???"
1048        -bytes 0
1049        -type image
1050    }
1051    array set info $args
1052    set bytes [ReceiveBytes $info(-bytes)]
1053    ReceiveEcho <<line "<read $info(-bytes) bytes"
1054    switch -- $info(-type)  {
1055        "image" {
1056            $_image(plot) configure -data $bytes
1057            #puts stderr "image received [image width $_image(plot)] by [image height $_image(plot)]"
1058        }
1059        "print" {
1060            set tag $this-$info(-token)
1061            set _hardcopy($tag) $bytes
1062        }
1063        "movie" {
1064            set tag $this-$info(-token)
1065            set _hardcopy($tag) $bytes
1066        }
1067        default {
1068            puts stderr "unknown download type $info(-type)"
1069        }
1070    }
1071}
1072
1073#
1074# ReceiveLegend --
1075#
1076#       The procedure is the response from the render server to each "legend"
1077#       command.  The server sends back a "legend" command invoked our
1078#       the slave interpreter.  The purpose is to collect data of the image
1079#       representing the legend in the canvas.  In addition, the isomarkers
1080#       of the active transfer function are displayed.
1081#
1082#       I don't know is this is the right place to display the isomarkers.
1083#       I don't know all the different paths used to draw the plot. There's
1084#       "Rebuild", "add", etc.
1085#
1086itcl::body Rappture::FlowvisViewer::ReceiveLegend { tag vmin vmax size } {
1087    if { ![isconnected] } {
1088        return
1089    }
1090    #puts stderr "receive legend $tag $vmin $vmax $size"
1091    set bytes [ReceiveBytes $size]
1092    $_image(legend) configure -data $bytes
1093    ReceiveEcho <<line "<read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
1094
1095    set c $itk_component(legend)
1096    set w [winfo width $c]
1097    set h [winfo height $c]
1098    set lx 10
1099    # FIXME:  I don't know what I have to do this for the 2D flow
1100    #         example.  Otherwise the canvas background is white.
1101    #         I'll get to this when we add background changes into
1102    #         nanvis.
1103    $c configure -background black
1104    set ly [expr {$h - 1}]
1105    if {"" == [$c find withtag transfunc]} {
1106        $c create image 10 10 -anchor nw \
1107            -image $_image(legend) -tags transfunc
1108        $c create text $lx $ly -anchor sw \
1109            -fill $itk_option(-plotforeground) -tags "limits vmin"
1110        $c create text [expr {$w-$lx}] $ly -anchor se \
1111            -fill $itk_option(-plotforeground) -tags "limits vmax"
1112        $c lower transfunc
1113        $c bind transfunc <ButtonRelease-1> \
1114            [itcl::code $this AddIsoMarker %x %y]
1115    }
1116    # Display the markers used by the active transfer function.
1117    set tf $_obj2style($tag)
1118    array set limits [limits $tf]
1119    $c itemconfigure vmin -text [format %.2g $limits(vmin)]
1120    $c coords vmin $lx $ly
1121
1122    $c itemconfigure vmax -text [format %.2g $limits(vmax)]
1123    $c coords vmax [expr {$w-$lx}] $ly
1124
1125    if { [info exists _isomarkers($tf)] } {
1126        foreach m $_isomarkers($tf) {
1127            $m visible yes
1128        }
1129    }
1130}
1131
1132#
1133# ReceiveData --
1134#
1135#       The procedure is the response from the render server to each "data
1136#       follows" command.  The server sends back a "data" command invoked our
1137#       the slave interpreter.  The purpose is to collect the min/max of the
1138#       volume sent to the render server.  Since the client (flowvisviewer)
1139#       doesn't parse 3D data formats, we rely on the server (flowvis) to
1140#       tell us what the limits are.  Once we've received the limits to all
1141#       the data we've sent (tracked by _recvObjs) we can then determine
1142#       what the transfer functions are for these # volumes.
1143#
1144#       Note: There is a considerable tradeoff in having the server report
1145#             back what the data limits are.  It means that much of the code
1146#             having to do with transfer-functions has to wait for the data
1147#             to come back, since the isomarkers are calculated based upon
1148#             the data limits.  The client code is much messier because of
1149#             this.  The alternative is to parse any of the 3D formats on the
1150#             client side.
1151#
1152itcl::body Rappture::FlowvisViewer::ReceiveData { args } {
1153    if { ![isconnected] } {
1154        return
1155    }
1156    # Arguments from server are name value pairs. Stuff them in an array.
1157    array set values $args
1158    set tag $values(tag)
1159    set parts [split $tag -]
1160    set dataobj [lindex $parts 0]
1161    set _serverObjs($tag) 0
1162    set _limits($tag-min)  $values(min);  # Minimum value of the volume.
1163    set _limits($tag-max)  $values(max);  # Maximum value of the volume.
1164    unset _recvObjs($tag)
1165    if { [array size _recvObjs] == 0 } {
1166        updatetransferfuncs
1167    }
1168}
1169
1170#
1171# Rebuild --
1172#
1173# Called automatically whenever something changes that affects the data
1174# in the widget.  Clears any existing data and rebuilds the widget to
1175# display new data. 
1176#
1177itcl::body Rappture::FlowvisViewer::Rebuild {} {
1178    set w [winfo width $itk_component(3dview)]
1179    set h [winfo height $itk_component(3dview)]
1180    if { $w < 2 || $h < 2 } {
1181        $_dispatcher event -idle !rebuild
1182        return
1183    }
1184
1185    # Turn on buffering of commands to the server.  We don't want to
1186    # be preempted by a server disconnect/reconnect (which automatically
1187    # generates a new call to Rebuild).   
1188    StartBufferingCommands
1189
1190    # Hide all the isomarkers. Can't remove them. Have to remember the
1191    # settings since the user may have created/deleted/moved markers.
1192
1193    foreach tf [array names _isomarkers] {
1194        foreach m $_isomarkers($tf) {
1195            $m visible no
1196        }
1197    }
1198
1199    if { $_width != $w || $_height != $h || $_reset } {
1200        set _width $w
1201        set _height $h
1202        $_arcball resize $w $h
1203        Resize
1204    }
1205
1206    set _first ""
1207    foreach dataobj [get] {
1208        foreach comp [$dataobj components] {
1209            set tag $dataobj-$comp
1210            # Send the data as one huge base64-encoded mess -- yuck!
1211            set data [$dataobj blob $comp]
1212            set nbytes [string length $data]
1213            if { $_reportClientInfo }  {
1214                set info {}
1215                lappend info "tool_id"       [$dataobj hints toolid]
1216                lappend info "tool_name"     [$dataobj hints toolname]
1217                lappend info "tool_title"    [$dataobj hints tooltitle]
1218                lappend info "tool_command"  [$dataobj hints toolcommand]
1219                lappend info "tool_revision" [$dataobj hints toolrevision]
1220                lappend info "dataset_label" [$dataobj hints label]
1221                lappend info "dataset_size"  $nbytes
1222                lappend info "dataset_tag"   $tag
1223                SendCmd "clientinfo [list $info]"
1224            }
1225            set extents [$dataobj extents $comp]
1226            # I have a field. Is a vector field or a volume field?
1227            if { $extents == 1 } {
1228                set cmd "volume data follows $nbytes $tag\n"
1229            } else {
1230                set cmd [FlowCmd $dataobj $comp $nbytes $extents]
1231                if { $cmd == "" } {
1232                    puts stderr "no command"
1233                    continue
1234                }
1235            }
1236            append _outbuf $cmd
1237            append _outbuf $data
1238            NameTransferFunc $dataobj $comp
1239            set _recvObjs($tag) 1
1240        }
1241    }
1242
1243    set _first [lindex [get] 0]
1244
1245    # Reset the camera and other view parameters
1246    InitSettings light2side light transp isosurface grid axes volume outline
1247   
1248    # nothing to send -- activate the proper volume
1249    if {"" != $_first} {
1250        AdjustSetting light
1251        AdjustSetting transp
1252        set axis [$_first hints updir]
1253        if {"" != $axis} {
1254            SendCmd "up $axis"
1255        }
1256        set location [$_first hints camera]
1257        if { $location != "" } {
1258            array set _view $location
1259        }
1260
1261    }
1262    set _settings($this-qw)    $_view(qw)
1263    set _settings($this-qx)    $_view(qx)
1264    set _settings($this-qy)    $_view(qy)
1265    set _settings($this-qz)    $_view(qz)
1266    set _settings($this-xpan)  $_view(xpan)
1267    set _settings($this-ypan)  $_view(ypan)
1268    set _settings($this-zoom)  $_view(zoom)
1269
1270    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1271    $_arcball quaternion $q
1272    SendCmd "camera orient $q"
1273    SendCmd "camera reset"
1274    PanCamera
1275    SendCmd "camera zoom $_view(zoom)"
1276
1277    foreach dataobj [get] {
1278        foreach comp [$dataobj components] {
1279            NameTransferFunc $dataobj $comp
1280        }
1281    }
1282
1283    # nothing to send -- activate the proper ivol
1284    set _first [lindex [get] 0]
1285    if {"" != $_first} {
1286        set axis [$_first hints updir]
1287        if {"" != $axis} {
1288            SendCmd "up $axis"
1289        }
1290        set location [$_first hints camera]
1291        if { $location != "" } {
1292            array set _view $location
1293        }
1294        set comp [lindex [$_first components] 0]
1295        set _activeTf [lindex $_obj2style($_first-$comp) 0]
1296    }
1297
1298
1299    # sync the state of slicers
1300    set vols [CurrentVolumeIds -cutplanes]
1301    foreach axis {x y z} {
1302        SendCmd "cutplane state $_settings($this-${axis}cutplane) $axis $vols"
1303        set pos [expr {0.01*$_settings($this-${axis}cutposition)}]
1304        SendCmd "cutplane position $pos $axis $vols"
1305    }
1306    SendCmd "volume data state $_settings($this-volume)"
1307    EventuallyResizeLegend
1308
1309    # Actually write the commands to the server socket.  If it fails, we don't
1310    # care.  We're finished here.
1311    blt::busy hold $itk_component(hull)
1312    StopBufferingCommands
1313    blt::busy release $itk_component(hull)
1314    set _reset 0
1315}
1316
1317# ----------------------------------------------------------------------
1318# USAGE: CurrentVolumeIds ?-cutplanes?
1319#
1320# Returns a list of volume server IDs for the current volume being
1321# displayed.  This is normally a single ID, but it might be a list
1322# of IDs if the current data object has multiple components.
1323# ----------------------------------------------------------------------
1324itcl::body Rappture::FlowvisViewer::CurrentVolumeIds {{what -all}} {
1325    return ""
1326    if { $_first == "" } {
1327        return
1328    }
1329    foreach key [array names _serverObjs *-*] {
1330        if {[string match $_first-* $key]} {
1331            array set style {
1332                -cutplanes 1
1333            }
1334            foreach {dataobj comp} [split $key -] break
1335            array set style [lindex [$dataobj components -style $comp] 0]
1336            if {$what != "-cutplanes" || $style(-cutplanes)} {
1337                lappend rlist $_serverObjs($key)
1338            }
1339        }
1340    }
1341    return $rlist
1342}
1343
1344# ----------------------------------------------------------------------
1345# USAGE: Zoom in
1346# USAGE: Zoom out
1347# USAGE: Zoom reset
1348#
1349# Called automatically when the user clicks on one of the zoom
1350# controls for this widget.  Changes the zoom for the current view.
1351# ----------------------------------------------------------------------
1352itcl::body Rappture::FlowvisViewer::Zoom {option} {
1353    switch -- $option {
1354        "in" {
1355            set _view(zoom) [expr {$_view(zoom)*1.25}]
1356            set _settings($this-zoom) $_view(zoom)
1357            SendCmd "camera zoom $_view(zoom)"
1358        }
1359        "out" {
1360            set _view(zoom) [expr {$_view(zoom)*0.8}]
1361            set _settings($this-zoom) $_view(zoom)
1362            SendCmd "camera zoom $_view(zoom)"
1363        }
1364        "reset" {
1365            array set _view {
1366                qw      0.853553
1367                qx      -0.353553
1368                qy      0.353553
1369                qz      0.146447
1370                zoom    1.0
1371                xpan   0
1372                ypan   0
1373            }
1374            if { $_first != "" } {
1375                set location [$_first hints camera]
1376                if { $location != "" } {
1377                    array set _view $location
1378                }
1379            }
1380            set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1381            $_arcball quaternion $q
1382            SendCmd "camera orient $q"
1383            SendCmd "camera reset"
1384            set _settings($this-qw)    $_view(qw)
1385            set _settings($this-qx)    $_view(qx)
1386            set _settings($this-qy)    $_view(qy)
1387            set _settings($this-qz)    $_view(qz)
1388            set _settings($this-xpan)  $_view(xpan)
1389            set _settings($this-ypan)  $_view(ypan)
1390            set _settings($this-zoom)  $_view(zoom)
1391        }
1392    }
1393}
1394
1395itcl::body Rappture::FlowvisViewer::PanCamera {} {
1396    #set x [expr ($_view(xpan)) / $_limits(xrange)]
1397    #set y [expr ($_view(ypan)) / $_limits(yrange)]
1398    set x $_view(xpan)
1399    set y $_view(ypan)
1400    SendCmd "camera pan $x $y"
1401}
1402
1403# ----------------------------------------------------------------------
1404# USAGE: Rotate click <x> <y>
1405# USAGE: Rotate drag <x> <y>
1406# USAGE: Rotate release <x> <y>
1407#
1408# Called automatically when the user clicks/drags/releases in the
1409# plot area.  Moves the plot according to the user's actions.
1410# ----------------------------------------------------------------------
1411itcl::body Rappture::FlowvisViewer::Rotate {option x y} {
1412    switch -- $option {
1413        click {
1414            $itk_component(3dview) configure -cursor fleur
1415            set _click(x) $x
1416            set _click(y) $y
1417        }
1418        drag {
1419            if {[array size _click] == 0} {
1420                Rotate click $x $y
1421            } else {
1422                set w [winfo width $itk_component(3dview)]
1423                set h [winfo height $itk_component(3dview)]
1424                if {$w <= 0 || $h <= 0} {
1425                    return
1426                }
1427
1428                if {[catch {
1429                    # this fails sometimes for no apparent reason
1430                    set dx [expr {double($x-$_click(x))/$w}]
1431                    set dy [expr {double($y-$_click(y))/$h}]
1432                }]} {
1433                    return
1434                }
1435
1436                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1437                foreach { _view(qw) _view(qx) _view(qy) _view(qz) } $q break
1438                set _settings($this-qw) $_view(qw)
1439                set _settings($this-qx) $_view(qx)
1440                set _settings($this-qy) $_view(qy)
1441                set _settings($this-qz) $_view(qz)
1442                SendCmd "camera orient $q"
1443
1444                set _click(x) $x
1445                set _click(y) $y
1446            }
1447        }
1448        release {
1449            Rotate drag $x $y
1450            $itk_component(3dview) configure -cursor ""
1451            catch {unset _click}
1452        }
1453        default {
1454            error "bad option \"$option\": should be click, drag, release"
1455        }
1456    }
1457}
1458
1459# ----------------------------------------------------------------------
1460# USAGE: $this Pan click x y
1461#        $this Pan drag x y
1462#        $this Pan release x y
1463#
1464# Called automatically when the user clicks on one of the zoom
1465# controls for this widget.  Changes the zoom for the current view.
1466# ----------------------------------------------------------------------
1467itcl::body Rappture::FlowvisViewer::Pan {option x y} {
1468    # Experimental stuff
1469    set w [winfo width $itk_component(3dview)]
1470    set h [winfo height $itk_component(3dview)]
1471    if { $option == "set" } {
1472        set x [expr $x / double($w)]
1473        set y [expr $y / double($h)]
1474        set _view(xpan) [expr $_view(xpan) + $x]
1475        set _view(ypan) [expr $_view(ypan) + $y]
1476        PanCamera
1477        set _settings($this-xpan) $_view(xpan)
1478        set _settings($this-ypan) $_view(ypan)
1479        return
1480    }
1481    if { $option == "click" } {
1482        set _click(x) $x
1483        set _click(y) $y
1484        $itk_component(3dview) configure -cursor hand1
1485    }
1486    if { $option == "drag" || $option == "release" } {
1487        set dx [expr ($_click(x) - $x)/double($w)]
1488        set dy [expr ($_click(y) - $y)/double($h)]
1489        set _click(x) $x
1490        set _click(y) $y
1491        set _view(xpan) [expr $_view(xpan) - $dx]
1492        set _view(ypan) [expr $_view(ypan) - $dy]
1493        PanCamera
1494        set _settings($this-xpan) $_view(xpan)
1495        set _settings($this-ypan) $_view(ypan)
1496    }
1497    if { $option == "release" } {
1498        $itk_component(3dview) configure -cursor ""
1499    }
1500}
1501
1502
1503# ----------------------------------------------------------------------
1504# USAGE: Flow movie record|stop|play ?on|off|toggle?
1505#
1506# Called when the user clicks on the record, stop or play buttons
1507# for flow visualization.
1508# ----------------------------------------------------------------------
1509itcl::body Rappture::FlowvisViewer::Flow {option args} {
1510    switch -- $option {
1511        movie {
1512            if {[llength $args] < 1 || [llength $args] > 2} {
1513                error "wrong # args: should be \"Flow movie record|stop|play ?on|off|toggle?\""
1514            }
1515            set action [lindex $args 0]
1516            set op [lindex $args 1]
1517            if {$op == ""} { set op "on" }
1518
1519            set current [State $action]
1520            if {$op == "toggle"} {
1521                if {$current == "on"} {
1522                    set op "off"
1523                } else {
1524                    set op "on"
1525                }
1526            }
1527            set cmds ""
1528            switch -- $action {
1529                record {
1530                    if { [$itk_component(rewind) cget -relief] != "sunken" } {
1531                        $itk_component(rewind) configure -relief sunken
1532                        $itk_component(stop) configure -relief raised
1533                        $itk_component(play) configure -relief raised
1534                        set inner $itk_component(settingsFrame)
1535                        set frames [$inner.framecnt value]
1536                        set _settings(nsteps) $frames
1537                        set cmds "flow capture $frames"
1538                        SendCmd $cmds
1539                    }
1540                }
1541                stop {
1542                    if { [$itk_component(stop) cget -relief] != "sunken" } {
1543                        $itk_component(rewind) configure -relief raised
1544                        $itk_component(stop) configure -relief sunken
1545                        $itk_component(play) configure -relief raised
1546                        _pause
1547                        set cmds "flow reset"
1548                        SendCmd $cmds
1549                    }
1550                }
1551                play {
1552                    if { [$itk_component(play) cget -relief] != "sunken" } {
1553                        $itk_component(rewind) configure -relief raised
1554                        $itk_component(stop) configure -relief raised
1555                        $itk_component(play) configure \
1556                            -image [Rappture::icon flow-pause] \
1557                            -relief sunken
1558                        bind $itk_component(play) <ButtonPress> \
1559                            [itcl::code $this _pause]
1560                        flow next
1561                    }
1562                }
1563                default {
1564                    error "bad option \"$option\": should be one of record|stop|play"
1565                }
1566
1567            }
1568        }
1569        default {
1570            error "bad option \"$option\": should be movie"
1571        }
1572    }
1573}
1574
1575# ----------------------------------------------------------------------
1576# USAGE: Play
1577#
1578# ----------------------------------------------------------------------
1579itcl::body Rappture::FlowvisViewer::Play {} {
1580    SendCmd "flow next"
1581    set delay [expr {int(ceil(pow($_settings(speed)/10.0+2,2.0)*15))}]
1582    $_dispatcher event -after $delay !play
1583}
1584
1585# ----------------------------------------------------------------------
1586# USAGE: Pause
1587#
1588# Invoked when the user hits the "pause" button to stop playing the
1589# current sequence of frames as a movie.
1590# ----------------------------------------------------------------------
1591itcl::body Rappture::FlowvisViewer::Pause {} {
1592    $_dispatcher cancel !play
1593
1594    # Toggle the button to "play" mode
1595    $itk_component(play) configure \
1596        -image [Rappture::icon flow-start] \
1597        -relief raised
1598    bind $itk_component(play) <ButtonPress> \
1599        [itcl::code $this Flow movie play toggle]
1600}
1601
1602# ----------------------------------------------------------------------
1603# USAGE: InitSettings <what> ?<value>?
1604#
1605# Used internally to update rendering settings whenever parameters
1606# change in the popup settings panel.  Sends the new settings off
1607# to the back end.
1608# ----------------------------------------------------------------------
1609itcl::body Rappture::FlowvisViewer::InitSettings { args } {
1610    foreach arg $args {
1611        AdjustSetting $arg
1612    }
1613}
1614
1615# ----------------------------------------------------------------------
1616# USAGE: AdjustSetting <what> ?<value>?
1617#
1618# Used internally to update rendering settings whenever parameters
1619# change in the popup settings panel.  Sends the new settings off
1620# to the back end.
1621# ----------------------------------------------------------------------
1622itcl::body Rappture::FlowvisViewer::AdjustSetting {what {value ""}} {
1623    switch -- $what {
1624        colormap {
1625            set color [$itk_component(colormap) value]
1626            set _settings(colormap) $color
1627            #ResetColormap $color
1628        }
1629        light {
1630            if { $_first != "" } {
1631                set comp [lindex [$_first components] 0]
1632                set tag $_first-$comp
1633                set diffuse [expr {0.01*$_settings($this-light)}]
1634                set ambient [expr {1.0 - $diffuse}]
1635                set specularLevel 0.3
1636                set specularExp 90.0
1637                SendCmd "$tag configure -ambient $ambient -diffuse $diffuse -specularLevel $specularLevel -specularExp $specularExp"
1638            }
1639        }
1640        light2side {
1641            if { $_first != "" } {
1642                set comp [lindex [$_first components] 0]
1643                set tag $_first-$comp
1644                set val $_settings($this-light2side)
1645                SendCmd "$tag configure -light2side $val"
1646            }
1647        }
1648        transp {
1649            if { $_first != "" } {
1650                set comp [lindex [$_first components] 0]
1651                set tag $_first-$comp
1652                set opacity [expr { 0.01 * double($_settings($this-transp)) }]
1653                SendCmd "$tag configure -opacity $opacity"
1654            }
1655        }
1656        opacity {
1657            if { $_first != "" && $_activeTf != "" } {
1658                set opacity [expr { 0.01 * double($_settings($this-opacity)) }]
1659                set tf $_activeTf
1660                set _settings($this-$tf-opacity) $opacity
1661                updatetransferfuncs
1662            }
1663        }
1664
1665        thickness {
1666            if { $_first != "" && $_activeTf != "" } {
1667                set val $_settings($this-thickness)
1668                # Scale values between 0.00001 and 0.01000
1669                set sval [expr {0.0001*double($val)}]
1670                set tf $_activeTf
1671                set _settings($this-$tf-thickness) $sval
1672                updatetransferfuncs
1673            }
1674        }
1675        "outline" {
1676            if { $_first != "" } {
1677                set comp [lindex [$_first components] 0]
1678                set tag $_first-$comp
1679                SendCmd "$tag configure -outline $_settings($this-outline)"
1680            }
1681        }
1682        "isosurface" {
1683            if { [isconnected] } {
1684                SendCmd "volume shading isosurface $_settings($this-isosurface)"
1685            }
1686        }
1687        "grid" {
1688            if { [isconnected] } {
1689                SendCmd "grid visible $_settings($this-grid)"
1690            }
1691        }
1692        "axes" {
1693            if { [isconnected] } {
1694                SendCmd "axis visible $_settings($this-axes)"
1695            }
1696        }
1697        "legend" {
1698            if { $_settings($this-legend) } {
1699                blt::table $itk_component(plotarea) \
1700                    0,0 $itk_component(3dview) -fill both \
1701                    1,0 $itk_component(legend) -fill x
1702                blt::table configure $itk_component(plotarea) r1 -resize none
1703            } else {
1704                blt::table forget $itk_component(legend)
1705            }
1706        }
1707        "volume" {
1708            if { $_first != "" } {
1709                set comp [lindex [$_first components] 0]
1710                set tag $_first-$comp
1711                SendCmd "$tag configure -volume $_settings($this-volume)"
1712            }
1713        }
1714        "xcutplane" - "ycutplane" - "zcutplane" {
1715            set axis [string range $what 0 0]
1716            set bool $_settings($this-$what)
1717            if { [isconnected] } {
1718                set vols [CurrentVolumeIds -cutplanes]
1719                SendCmd "cutplane state $bool $axis $vols"
1720            }
1721            if { $bool } {
1722                $itk_component(${axis}CutScale) configure -state normal \
1723                    -troughcolor white
1724            } else {
1725                $itk_component(${axis}CutScale) configure -state disabled \
1726                    -troughcolor grey82
1727            }
1728        }
1729        default {
1730            error "don't know how to fix $what"
1731        }
1732    }
1733}
1734
1735# ----------------------------------------------------------------------
1736# USAGE: ResizeLegend
1737#
1738# Used internally to update the legend area whenever it changes size
1739# or when the field changes.  Asks the server to send a new legend
1740# for the current field.
1741# ----------------------------------------------------------------------
1742itcl::body Rappture::FlowvisViewer::ResizeLegend {} {
1743    set _resizeLegendPending 0
1744    set lineht [font metrics $itk_option(-font) -linespace]
1745    set w [expr {$_width-20}]
1746    set h [expr {[winfo height $itk_component(legend)]-20-$lineht}]
1747
1748    if { $_first == "" } {
1749        return
1750    }
1751    set comp [lindex [$_first components] 0]
1752    set tag $_first-$comp
1753    #set _activeTf [lindex $_obj2style($tag) 0]
1754    if {$w > 0 && $h > 0 && "" != $_activeTf} {
1755        #SendCmd "legend $_activeTf $w $h"
1756        SendCmd "$tag legend $w $h"
1757    } else {
1758    # Can't do this as this will remove the items associated with the
1759    # isomarkers.
1760
1761    #$itk_component(legend) delete all
1762    }
1763}
1764
1765#
1766# NameTransferFunc --
1767#
1768#       Creates a transfer function name based on the <style> settings in the
1769#       library run.xml file. This placeholder will be used later to create
1770#       and send the actual transfer function once the data info has been sent
1771#       to us by the render server. [We won't know the volume limits until the
1772#       server parses the 3D data and sends back the limits via ReceiveData.]
1773#
1774#       FIXME: The current way we generate transfer-function names completely
1775#              ignores the -markers option.  The problem is that we are forced
1776#              to compute the name from an increasing complex set of values:
1777#              color, levels, marker, opacity.  I think we're stuck doing it
1778#              now.
1779#
1780itcl::body Rappture::FlowvisViewer::NameTransferFunc { dataobj comp } {
1781    array set style {
1782        -color BCGYR
1783        -levels 6
1784        -opacity 1.0
1785        -light 40
1786        -transp 50
1787    }
1788    array set style [lindex [$dataobj components -style $comp] 0]
1789    set _settings($this-light) $style(-light)
1790    set _settings($this-transp) $style(-transp)
1791    set _settings($this-opacity) [expr $style(-opacity) * 100]
1792    set tf "$style(-color):$style(-levels):$style(-opacity)"
1793    set _obj2style($dataobj-$comp) $tf
1794    lappend _style2objs($tf) $dataobj $comp
1795    return $tf
1796}
1797
1798#
1799# ComputeTransferFunc --
1800#
1801#   Computes and sends the transfer function to the render server.  It's
1802#   assumed that the volume data limits are known and that the global
1803#   transfer-functions slider values have be setup.  Both parts are
1804#   needed to compute the relative value (location) of the marker, and
1805#   the alpha map of the transfer function.
1806#
1807itcl::body Rappture::FlowvisViewer::ComputeTransferFunc { tf } {
1808    array set style {
1809        -color BCGYR
1810        -levels 6
1811        -opacity 1.0
1812        -light 40
1813        -transp 50
1814    }
1815    set dataobj ""; set comp ""
1816    foreach {dataobj comp} $_style2objs($tf) break
1817    if { $dataobj == "" } {
1818        return 0
1819    }
1820    array set style [lindex [$dataobj components -style $comp] 0]
1821
1822
1823    # We have to parse the style attributes for a volume using this
1824    # transfer-function *once*.  This sets up the initial isomarkers for the
1825    # transfer function.  The user may add/delete markers, so we have to
1826    # maintain a list of markers for each transfer-function.  We use the one
1827    # of the volumes (the first in the list) using the transfer-function as a
1828    # reference.
1829    #
1830    # FIXME: The current way we generate transfer-function names completely
1831    #        ignores the -markers option.  The problem is that we are forced
1832    #        to compute the name from an increasing complex set of values:
1833    #        color, levels, marker, opacity.  I think the cow's out of the
1834    #        barn on this one.
1835
1836    if { ![info exists _isomarkers($tf)] } {
1837        # Have to defer creation of isomarkers until we have data limits
1838        if { [info exists style(-markers)] &&
1839             [llength $style(-markers)] > 0  } {
1840            ParseMarkersOption $tf $style(-markers)
1841        } else {
1842            ParseLevelsOption $tf $style(-levels)
1843        }
1844    }
1845    if { [info exists style(-nonuniformcolors)] } {
1846        foreach { value color } $style(-nonuniformcolors) {
1847            append cmap "$value [Color2RGB $color] "
1848        }
1849    } else {
1850        set cmap [ColorsToColormap $style(-color)]
1851    }
1852    set tag $this-$tf
1853    if { ![info exists _settings($tag-opacity)] } {
1854        set _settings($tag-opacity) $style(-opacity)
1855    }
1856    set max 1.0 ;#$_settings($tag-opacity)
1857   
1858    set isovalues {}
1859    foreach m $_isomarkers($tf) {
1860        lappend isovalues [$m relval]
1861    }
1862    # Sort the isovalues
1863    set isovalues [lsort -real $isovalues]
1864
1865    if { ![info exists _settings($tag-thickness)]} {
1866        set _settings($tag-thickness) 0.005
1867    }
1868    set delta $_settings($tag-thickness)
1869
1870    set first [lindex $isovalues 0]
1871    set last [lindex $isovalues end]
1872    set wmap ""
1873    if { $first == "" || $first != 0.0 } {
1874        lappend wmap 0.0 0.0
1875    }
1876    foreach x $isovalues {
1877        set x1 [expr {$x-$delta-0.00001}]
1878        set x2 [expr {$x-$delta}]
1879        set x3 [expr {$x+$delta}]
1880        set x4 [expr {$x+$delta+0.00001}]
1881        if { $x1 < 0.0 } {
1882            set x1 0.0
1883        } elseif { $x1 > 1.0 } {
1884            set x1 1.0
1885        }
1886        if { $x2 < 0.0 } {
1887            set x2 0.0
1888        } elseif { $x2 > 1.0 } {
1889            set x2 1.0
1890        }
1891        if { $x3 < 0.0 } {
1892            set x3 0.0
1893        } elseif { $x3 > 1.0 } {
1894            set x3 1.0
1895        }
1896        if { $x4 < 0.0 } {
1897            set x4 0.0
1898        } elseif { $x4 > 1.0 } {
1899            set x4 1.0
1900        }
1901        # add spikes in the middle
1902        lappend wmap $x1 0.0
1903        lappend wmap $x2 $max
1904        lappend wmap $x3 $max
1905        lappend wmap $x4 0.0
1906    }
1907    if { $last == "" || $last != 1.0 } {
1908        lappend wmap 1.0 0.0
1909    }
1910    SendCmd "transfunc define $tf { $cmap } { $wmap }"
1911    return [SendCmd "$dataobj-$comp configure -transferfunction $tf"]
1912}
1913
1914# ----------------------------------------------------------------------
1915# CONFIGURATION OPTION: -plotbackground
1916# ----------------------------------------------------------------------
1917itcl::configbody Rappture::FlowvisViewer::plotbackground {
1918    if { [isconnected] } {
1919        foreach {r g b} [Color2RGB $itk_option(-plotbackground)] break
1920        #fix this!
1921        #SendCmd "color background $r $g $b"
1922    }
1923}
1924
1925# ----------------------------------------------------------------------
1926# CONFIGURATION OPTION: -plotforeground
1927# ----------------------------------------------------------------------
1928itcl::configbody Rappture::FlowvisViewer::plotforeground {
1929    if { [isconnected] } {
1930        foreach {r g b} [Color2RGB $itk_option(-plotforeground)] break
1931        #fix this!
1932        #SendCmd "color background $r $g $b"
1933    }
1934}
1935
1936# ----------------------------------------------------------------------
1937# CONFIGURATION OPTION: -plotoutline
1938# ----------------------------------------------------------------------
1939itcl::configbody Rappture::FlowvisViewer::plotoutline {
1940    # Must check if we are connected because this routine is called from the
1941    # class body when the -plotoutline itk_option is defined.  At that point
1942    # the FlowvisViewer class constructor hasn't been called, so we can't
1943    # start sending commands to visualization server.
1944    if { [isconnected] } {
1945        if {"" == $itk_option(-plotoutline)} {
1946            SendCmd "volume outline state off"
1947        } else {
1948            SendCmd "volume outline state on"
1949            SendCmd "volume outline color [Color2RGB $itk_option(-plotoutline)]"
1950        }
1951    }
1952}
1953
1954#
1955# The -levels option takes a single value that represents the number
1956# of evenly distributed markers based on the current data range. Each
1957# marker is a relative value from 0.0 to 1.0.
1958#
1959itcl::body Rappture::FlowvisViewer::ParseLevelsOption { tf levels } {
1960    set c $itk_component(legend)
1961    regsub -all "," $levels " " levels
1962    if {[string is int $levels]} {
1963        for {set i 1} { $i <= $levels } {incr i} {
1964            set x [expr {double($i)/($levels+1)}]
1965            set m [Rappture::IsoMarker \#auto $c $this $tf]
1966            $m relval $x
1967            lappend _isomarkers($tf) $m
1968        }
1969    } else {
1970        foreach x $levels {
1971            set m [Rappture::IsoMarker \#auto $c $this $tf]
1972            $m relval $x
1973            lappend _isomarkers($tf) $m
1974        }
1975    }
1976}
1977
1978#
1979# The -markers option takes a list of zero or more values (the values
1980# may be separated either by spaces or commas) that have the following
1981# format:
1982#
1983#   N%  Percent of current total data range.  Converted to
1984#       to a relative value between 0.0 and 1.0.
1985#   N   Absolute value of marker.  If the marker is outside of
1986#       the current range, it will be displayed on the outer
1987#       edge of the legends, but it range it represents will
1988#       not be seen.
1989#
1990itcl::body Rappture::FlowvisViewer::ParseMarkersOption { tf markers } {
1991    set c $itk_component(legend)
1992    regsub -all "," $markers " " markers
1993    foreach marker $markers {
1994        set n [scan $marker "%g%s" value suffix]
1995        if { $n == 2 && $suffix == "%" } {
1996            # ${n}% : Set relative value.
1997            set value [expr {$value * 0.01}]
1998            set m [Rappture::IsoMarker \#auto $c $this $tf]
1999            $m relval $value
2000            lappend _isomarkers($tf) $m
2001        } else {
2002            # ${n} : Set absolute value.
2003            set m [Rappture::IsoMarker \#auto $c $this $tf]
2004            $m absval $value
2005            lappend _isomarkers($tf) $m
2006        }
2007    }
2008}
2009
2010# ----------------------------------------------------------------------
2011# USAGE: UndateTransferFuncs
2012# ----------------------------------------------------------------------
2013itcl::body Rappture::FlowvisViewer::updatetransferfuncs {} {
2014    $_dispatcher event -after 100 !send_transfunc
2015}
2016
2017itcl::body Rappture::FlowvisViewer::AddIsoMarker { x y } {
2018    if { $_activeTf == "" } {
2019        error "active transfer function isn't set"
2020    }
2021    set tf $_activeTf
2022    set c $itk_component(legend)
2023    set m [Rappture::IsoMarker \#auto $c $this $tf]
2024    set w [winfo width $c]
2025    $m relval [expr {double($x-10)/($w-20)}]
2026    lappend _isomarkers($tf) $m
2027    updatetransferfuncs
2028    return 1
2029}
2030
2031itcl::body Rappture::FlowvisViewer::rmdupmarker { marker x } {
2032    set tf [$marker transferfunc]
2033    set bool 0
2034    if { [info exists _isomarkers($tf)] } {
2035        set list {}
2036        set marker [namespace tail $marker]
2037        foreach m $_isomarkers($tf) {
2038            set sx [$m screenpos]
2039            if { $m != $marker } {
2040                if { $x >= ($sx-3) && $x <= ($sx+3) } {
2041                    $marker relval [$m relval]
2042                    itcl::delete object $m
2043                    bell
2044                    set bool 1
2045                    continue
2046                }
2047            }
2048            lappend list $m
2049        }
2050        set _isomarkers($tf) $list
2051        updatetransferfuncs
2052    }
2053    return $bool
2054}
2055
2056itcl::body Rappture::FlowvisViewer::overmarker { marker x } {
2057    set tf [$marker transferfunc]
2058    if { [info exists _isomarkers($tf)] } {
2059        set marker [namespace tail $marker]
2060        foreach m $_isomarkers($tf) {
2061            set sx [$m screenpos]
2062            if { $m != $marker } {
2063                set bool [expr { $x >= ($sx-3) && $x <= ($sx+3) }]
2064                $m activate $bool
2065            }
2066        }
2067    }
2068    return ""
2069}
2070
2071itcl::body Rappture::FlowvisViewer::limits { tf } {
2072    set _limits(vmin) 0.0
2073    set _limits(vmax) 1.0
2074    if { ![info exists _style2objs($tf)] } {
2075        puts stderr "no style2objs for $tf tf=($tf)"
2076        return [array get _limits]
2077    }
2078    set min ""; set max ""
2079    foreach {dataobj comp} $_style2objs($tf) {
2080        set tag $dataobj-$comp
2081        if { ![info exists _serverObjs($tag)] } {
2082            puts stderr "$tag not in serverObjs?"
2083            continue
2084        }
2085        if { ![info exists _limits($tag-min)] } {
2086            puts stderr "$tag no min?"
2087            continue
2088        }
2089        if { $min == "" || $min > $_limits($tag-min) } {
2090            set min $_limits($tag-min)
2091        }
2092        if { $max == "" || $max < $_limits($tag-max) } {
2093            set max $_limits($tag-max)
2094        }
2095    }
2096    if { $min != "" } {
2097        set _limits(vmin) $min
2098    }
2099    if { $max != "" } {
2100        set _limits(vmax) $max
2101    }
2102    return [array get _limits]
2103}
2104
2105itcl::body Rappture::FlowvisViewer::BuildViewTab {} {
2106    foreach { key value } {
2107        grid            0
2108        axes            0
2109        outline         1
2110        volume          1
2111        legend          1
2112        particles       1
2113        lic             1
2114    } {
2115        set _settings($this-$key) $value
2116    }
2117
2118    set fg [option get $itk_component(hull) font Font]
2119    #set bfg [option get $itk_component(hull) boldFont Font]
2120
2121    set inner [$itk_component(main) insert end \
2122        -title "View Settings" \
2123        -icon [Rappture::icon wrench]]
2124    $inner configure -borderwidth 4
2125
2126    set ::Rappture::FlowvisViewer::_settings($this-isosurface) 0
2127    checkbutton $inner.isosurface \
2128        -text "Isosurface shading" \
2129        -variable [itcl::scope _settings($this-isosurface)] \
2130        -command [itcl::code $this AdjustSetting isosurface] \
2131        -font "Arial 9"
2132
2133    checkbutton $inner.axes \
2134        -text "Axes" \
2135        -variable [itcl::scope _settings($this-axes)] \
2136        -command [itcl::code $this AdjustSetting axes] \
2137        -font "Arial 9"
2138
2139    checkbutton $inner.grid \
2140        -text "Grid" \
2141        -variable [itcl::scope _settings($this-grid)] \
2142        -command [itcl::code $this AdjustSetting grid] \
2143        -font "Arial 9"
2144
2145    checkbutton $inner.outline \
2146        -text "Outline" \
2147        -variable [itcl::scope _settings($this-outline)] \
2148        -command [itcl::code $this AdjustSetting outline] \
2149        -font "Arial 9"
2150
2151    checkbutton $inner.legend \
2152        -text "Legend" \
2153        -variable [itcl::scope _settings($this-legend)] \
2154        -command [itcl::code $this AdjustSetting legend] \
2155        -font "Arial 9"
2156
2157    checkbutton $inner.volume \
2158        -text "Volume" \
2159        -variable [itcl::scope _settings($this-volume)] \
2160        -command [itcl::code $this AdjustSetting volume] \
2161        -font "Arial 9"
2162
2163    checkbutton $inner.particles \
2164        -text "Particles" \
2165        -variable [itcl::scope _settings($this-particles)] \
2166        -command [itcl::code $this AdjustSetting particles] \
2167        -font "Arial 9"
2168
2169    checkbutton $inner.lic \
2170        -text "Lic" \
2171        -variable [itcl::scope _settings($this-lic)] \
2172        -command [itcl::code $this AdjustSetting lic] \
2173        -font "Arial 9"
2174
2175    frame $inner.frame
2176
2177    blt::table $inner \
2178        0,0 $inner.axes  -cspan 2 -anchor w \
2179        1,0 $inner.grid  -cspan 2 -anchor w \
2180        2,0 $inner.outline  -cspan 2 -anchor w \
2181        3,0 $inner.volume  -cspan 2 -anchor w \
2182        4,0 $inner.legend  -cspan 2 -anchor w
2183
2184    bind $inner <Map> [itcl::code $this GetFlowInfo $inner]
2185
2186    blt::table configure $inner r* -resize none
2187    blt::table configure $inner r5 -resize expand
2188}
2189
2190itcl::body Rappture::FlowvisViewer::BuildVolumeTab {} {
2191    foreach { key value } {
2192        light2side      1
2193        light           40
2194        transp          50
2195        opacity         100
2196        thickness       350
2197    } {
2198        set _settings($this-$key) $value
2199    }
2200
2201    set inner [$itk_component(main) insert end \
2202        -title "Volume Settings" \
2203        -icon [Rappture::icon volume-on]]
2204    $inner configure -borderwidth 4
2205
2206    set fg [option get $itk_component(hull) font Font]
2207    #set bfg [option get $itk_component(hull) boldFont Font]
2208
2209    checkbutton $inner.vol -text "Show volume" -font $fg \
2210        -text "Volume" \
2211        -variable [itcl::scope _settings($this-volume)] \
2212        -command [itcl::code $this AdjustSetting volume] \
2213        -font "Arial 9"
2214
2215    label $inner.shading -text "Shading:" -font $fg
2216
2217    checkbutton $inner.light2side -text "Two-sided lighting" -font $fg \
2218        -variable [itcl::scope _settings($this-light2side)] \
2219        -command [itcl::code $this AdjustSetting light2side]
2220
2221    label $inner.dim -text "Glow" -font $fg
2222    ::scale $inner.light -from 0 -to 100 -orient horizontal \
2223        -variable [itcl::scope _settings($this-light)] \
2224        -width 10 \
2225        -showvalue off -command [itcl::code $this AdjustSetting light]
2226    label $inner.bright -text "Surface" -font $fg
2227
2228    label $inner.fog -text "Clear" -font $fg
2229    ::scale $inner.transp -from 0 -to 100 -orient horizontal \
2230        -variable [itcl::scope _settings($this-transp)] \
2231        -width 10 \
2232        -showvalue off -command [itcl::code $this AdjustSetting transp]
2233    label $inner.plastic -text "Opaque" -font $fg
2234
2235    label $inner.clear -text "Clear" -font $fg
2236    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
2237        -variable [itcl::scope _settings($this-opacity)] \
2238        -width 10 \
2239        -showvalue off -command [itcl::code $this AdjustSetting opacity]
2240    label $inner.opaque -text "Opaque" -font $fg
2241
2242    label $inner.thin -text "Thin" -font $fg
2243    ::scale $inner.thickness -from 0 -to 1000 -orient horizontal \
2244        -variable [itcl::scope _settings($this-thickness)] \
2245        -width 10 \
2246        -showvalue off -command [itcl::code $this AdjustSetting thickness]
2247    label $inner.thick -text "Thick" -font $fg
2248
2249    label $inner.colormap_l -text "Colormap" -font "Arial 9"
2250    itk_component add colormap {
2251        Rappture::Combobox $inner.colormap -width 10 -editable no
2252    }
2253
2254    $inner.colormap choices insert end \
2255        "BCGYR"              "BCGYR"            \
2256        "BGYOR"              "BGYOR"            \
2257        "blue"               "blue"             \
2258        "blue-to-brown"      "blue-to-brown"    \
2259        "blue-to-orange"     "blue-to-orange"   \
2260        "blue-to-grey"       "blue-to-grey"     \
2261        "green-to-magenta"   "green-to-magenta" \
2262        "greyscale"          "greyscale"        \
2263        "nanohub"            "nanohub"          \
2264        "rainbow"            "rainbow"          \
2265        "spectral"           "spectral"         \
2266        "ROYGB"              "ROYGB"            \
2267        "RYGCB"              "RYGCB"            \
2268        "brown-to-blue"      "brown-to-blue"    \
2269        "grey-to-blue"       "grey-to-blue"     \
2270        "orange-to-blue"     "orange-to-blue"   \
2271        "none"               "none"
2272
2273    $itk_component(colormap) value "BCGYR"
2274    bind $inner.colormap <<Value>> \
2275        [itcl::code $this AdjustSetting colormap]
2276
2277    blt::table $inner \
2278        0,0 $inner.vol -cspan 4 -anchor w -pady 2 \
2279        1,0 $inner.shading -cspan 4 -anchor w -pady {10 2} \
2280        2,0 $inner.light2side -cspan 4 -anchor w -pady 2 \
2281        3,0 $inner.dim -anchor e -pady 2 \
2282        3,1 $inner.light -cspan 2 -pady 2 -fill x \
2283        3,3 $inner.bright -anchor w -pady 2 \
2284        4,0 $inner.fog -anchor e -pady 2 \
2285        4,1 $inner.transp -cspan 2 -pady 2 -fill x \
2286        4,3 $inner.plastic -anchor w -pady 2 \
2287        5,0 $inner.thin -anchor e -pady 2 \
2288        5,1 $inner.thickness -cspan 2 -pady 2 -fill x\
2289        5,3 $inner.thick -anchor w -pady 2
2290
2291    blt::table configure $inner c0 c1 c3 r* -resize none
2292    blt::table configure $inner r6 -resize expand
2293}
2294
2295itcl::body Rappture::FlowvisViewer::BuildCutplanesTab {} {
2296    set inner [$itk_component(main) insert end \
2297        -title "Cutplane Settings" \
2298        -icon [Rappture::icon cutbutton]]
2299    $inner configure -borderwidth 4
2300
2301    # X-value slicer...
2302    itk_component add xCutButton {
2303        Rappture::PushButton $inner.xbutton \
2304            -onimage [Rappture::icon x-cutplane] \
2305            -offimage [Rappture::icon x-cutplane] \
2306            -command [itcl::code $this AdjustSetting xcutplane] \
2307            -variable [itcl::scope _settings($this-xcutplane)]
2308    }
2309    Rappture::Tooltip::for $itk_component(xCutButton) \
2310        "Toggle the X cut plane on/off"
2311
2312    itk_component add xCutScale {
2313        ::scale $inner.xval -from 100 -to 0 \
2314            -width 10 -orient vertical -showvalue off \
2315            -borderwidth 1 -highlightthickness 0 \
2316            -command [itcl::code $this Slice move x] \
2317            -variable [itcl::scope _settings($this-xcutposition)]
2318    } {
2319        usual
2320        ignore -borderwidth -highlightthickness
2321    }
2322    # Set the default cutplane value before disabling the scale.
2323    $itk_component(xCutScale) set 50
2324    $itk_component(xCutScale) configure -state disabled
2325    Rappture::Tooltip::for $itk_component(xCutScale) \
2326        "@[itcl::code $this SlicerTip x]"
2327
2328    # Y-value slicer...
2329    itk_component add yCutButton {
2330        Rappture::PushButton $inner.ybutton \
2331            -onimage [Rappture::icon y-cutplane] \
2332            -offimage [Rappture::icon y-cutplane] \
2333            -command [itcl::code $this AdjustSetting ycutplane] \
2334            -variable [itcl::scope _settings($this-ycutplane)]
2335    }
2336    Rappture::Tooltip::for $itk_component(yCutButton) \
2337        "Toggle the Y cut plane on/off"
2338
2339    itk_component add yCutScale {
2340        ::scale $inner.yval -from 100 -to 0 \
2341            -width 10 -orient vertical -showvalue off \
2342            -borderwidth 1 -highlightthickness 0 \
2343            -command [itcl::code $this Slice move y] \
2344            -variable [itcl::scope _settings($this-ycutposition)]
2345    } {
2346        usual
2347        ignore -borderwidth -highlightthickness
2348    }
2349    Rappture::Tooltip::for $itk_component(yCutScale) \
2350        "@[itcl::code $this SlicerTip y]"
2351    # Set the default cutplane value before disabling the scale.
2352    $itk_component(yCutScale) set 50
2353    $itk_component(yCutScale) configure -state disabled
2354
2355    # Z-value slicer...
2356    itk_component add zCutButton {
2357        Rappture::PushButton $inner.zbutton \
2358            -onimage [Rappture::icon z-cutplane] \
2359            -offimage [Rappture::icon z-cutplane] \
2360            -command [itcl::code $this AdjustSetting zcutplane] \
2361            -variable [itcl::scope _settings($this-zcutplane)]
2362    }
2363    Rappture::Tooltip::for $itk_component(zCutButton) \
2364        "Toggle the Z cut plane on/off"
2365
2366    itk_component add zCutScale {
2367        ::scale $inner.zval -from 100 -to 0 \
2368            -width 10 -orient vertical -showvalue off \
2369            -borderwidth 1 -highlightthickness 0 \
2370            -command [itcl::code $this Slice move z] \
2371            -variable [itcl::scope _settings($this-zcutposition)]
2372    } {
2373        usual
2374        ignore -borderwidth -highlightthickness
2375    }
2376    $itk_component(zCutScale) set 50
2377    $itk_component(zCutScale) configure -state disabled
2378    #$itk_component(zCutScale) configure -state disabled
2379    Rappture::Tooltip::for $itk_component(zCutScale) \
2380        "@[itcl::code $this SlicerTip z]"
2381
2382    blt::table $inner \
2383        1,1 $itk_component(xCutButton) \
2384        1,2 $itk_component(yCutButton) \
2385        1,3 $itk_component(zCutButton) \
2386        0,1 $itk_component(xCutScale) \
2387        0,2 $itk_component(yCutScale) \
2388        0,3 $itk_component(zCutScale) \
2389
2390    blt::table configure $inner r0 r1 c* -resize none
2391    blt::table configure $inner r2 c4 -resize expand
2392    blt::table configure $inner c0 -width 2
2393    blt::table configure $inner c1 c2 c3 -padx 2
2394}
2395
2396itcl::body Rappture::FlowvisViewer::BuildCameraTab {} {
2397    set inner [$itk_component(main) insert end \
2398        -title "Camera Settings" \
2399        -icon [Rappture::icon camera]]
2400    $inner configure -borderwidth 4
2401
2402    label $inner.view_l -text "view" -font "Arial 9"
2403    set f [frame $inner.view]
2404    foreach side { front back left right top bottom } {
2405        button $f.$side  -image [Rappture::icon view$side] \
2406            -command [itcl::code $this SetOrientation $side]
2407        Rappture::Tooltip::for $f.$side "Change the view to $side"
2408        pack $f.$side -side left
2409    }
2410
2411    blt::table $inner \
2412        0,0 $inner.view_l -anchor e -pady 2 \
2413        0,1 $inner.view -anchor w -pady 2
2414
2415    set row 1
2416    set labels { qw qx qy qz xpan ypan zoom }
2417    foreach tag $labels {
2418        label $inner.${tag}label -text $tag -font "Arial 9"
2419        entry $inner.${tag} -font "Arial 9"  -bg white \
2420            -textvariable [itcl::scope _settings($this-$tag)]
2421        bind $inner.${tag} <KeyPress-Return> \
2422            [itcl::code $this camera set ${tag}]
2423        blt::table $inner \
2424            $row,0 $inner.${tag}label -anchor e -pady 2 \
2425            $row,1 $inner.${tag} -anchor w -pady 2
2426        blt::table configure $inner r$row -resize none
2427        incr row
2428    }
2429
2430    blt::table configure $inner c* r* -resize none
2431    blt::table configure $inner c2 -resize expand
2432    blt::table configure $inner r$row -resize expand
2433}
2434
2435itcl::body Rappture::FlowvisViewer::GetFlowInfo { w } {
2436    set flowobj ""
2437    foreach key [array names _obj2flow] {
2438        set flowobj $_obj2flow($key)
2439        break
2440    }
2441    if { $flowobj == "" } {
2442        return
2443    }
2444    if { [winfo exists $w.frame] } {
2445        destroy $w.frame
2446    }
2447    set inner [frame $w.frame]
2448    blt::table $w \
2449        5,0 $inner -fill both -cspan 2 -anchor nw
2450    array set hints [$flowobj hints]
2451    checkbutton $inner.showstreams -text "Streams Plane" \
2452        -variable [itcl::scope _settings($this-streams)] \
2453        -command  [itcl::code $this streams $key $hints(name)]  \
2454        -font "Arial 9"
2455    Rappture::Tooltip::for $inner.showstreams $hints(description)
2456
2457    checkbutton $inner.showarrows -text "Arrows" \
2458        -variable [itcl::scope _settings($this-arrows)] \
2459        -command  [itcl::code $this arrows $key $hints(name)]  \
2460        -font "Arial 9"
2461
2462    label $inner.particles -text "Particles"         -font "Arial 9 bold"
2463    label $inner.boxes -text "Boxes"         -font "Arial 9 bold"
2464
2465    blt::table $inner \
2466        1,0 $inner.showstreams  -anchor w \
2467        2,0 $inner.showarrows  -anchor w
2468    blt::table configure $inner c0 c1 -resize none
2469    blt::table configure $inner c2 -resize expand
2470
2471    set row 3
2472    set particles [$flowobj particles]
2473    if { [llength $particles] > 0 } {
2474        blt::table $inner $row,0 $inner.particles  -anchor w
2475        incr row
2476    }
2477    foreach part $particles {
2478        array unset info
2479        array set info $part
2480        set name $info(name)
2481        if { ![info exists _settings($this-particles-$name)] } {
2482            set _settings($this-particles-$name) $info(hide)
2483        }
2484        checkbutton $inner.part$row -text $info(label) \
2485            -variable [itcl::scope _settings($this-particles-$name)] \
2486            -onvalue 0 -offvalue 1 \
2487            -command [itcl::code $this particles $key $name] \
2488            -font "Arial 9"
2489        Rappture::Tooltip::for $inner.part$row $info(description)
2490        blt::table $inner $row,0 $inner.part$row -anchor w
2491        if { !$_settings($this-particles-$name) } {
2492            $inner.part$row select
2493        }
2494        incr row
2495    }
2496    set boxes [$flowobj boxes]
2497    if { [llength $boxes] > 0 } {
2498        blt::table $inner $row,0 $inner.boxes  -anchor w
2499        incr row
2500    }
2501    foreach box $boxes {
2502        array unset info
2503        array set info $box
2504        set name $info(name)
2505        if { ![info exists _settings($this-box-$name)] } {
2506            set _settings($this-box-$name) $info(hide)
2507        }
2508        checkbutton $inner.box$row -text $info(label) \
2509            -variable [itcl::scope _settings($this-box-$name)] \
2510            -onvalue 0 -offvalue 1 \
2511            -command [itcl::code $this box $key $name] \
2512            -font "Arial 9"
2513        Rappture::Tooltip::for $inner.box$row $info(description)
2514        blt::table $inner $row,0 $inner.box$row -anchor w
2515        if { !$_settings($this-box-$name) } {
2516            $inner.box$row select
2517        }
2518        incr row
2519    }
2520    blt::table configure $inner r* -resize none
2521    blt::table configure $inner r$row -resize expand
2522    blt::table configure $inner c3 -resize expand
2523    event generate [winfo parent [winfo parent $w]] <Configure>
2524}
2525
2526itcl::body Rappture::FlowvisViewer::particles { tag name } {
2527    set bool $_settings($this-particles-$name)
2528    SendCmd "$tag particles configure {$name} -hide $bool"
2529}
2530
2531itcl::body Rappture::FlowvisViewer::box { tag name } {
2532    set bool $_settings($this-box-$name)
2533    SendCmd "$tag box configure {$name} -hide $bool"
2534}
2535
2536itcl::body Rappture::FlowvisViewer::streams { tag name } {
2537    set bool $_settings($this-streams)
2538    SendCmd "$tag configure -slice $bool"
2539}
2540
2541itcl::body Rappture::FlowvisViewer::arrows { tag name } {
2542    set bool $_settings($this-arrows)
2543    SendCmd "$tag configure -arrows $bool"
2544}
2545
2546# ----------------------------------------------------------------------
2547# USAGE: Slice move x|y|z <newval>
2548#
2549# Called automatically when the user drags the slider to move the
2550# cut plane that slices 3D data.  Gets the current value from the
2551# slider and moves the cut plane to the appropriate point in the
2552# data set.
2553# ----------------------------------------------------------------------
2554itcl::body Rappture::FlowvisViewer::Slice {option args} {
2555    switch -- $option {
2556        move {
2557            if {[llength $args] != 2} {
2558                error "wrong # args: should be \"Slice move x|y|z newval\""
2559            }
2560            set axis [lindex $args 0]
2561            set newval [lindex $args 1]
2562            set newpos [expr {0.01*$newval}]
2563
2564            # show the current value in the readout
2565
2566            set ids [CurrentVolumeIds -cutplanes]
2567            SendCmd "cutplane position $newpos $axis $ids"
2568        }
2569        default {
2570            error "bad option \"$option\": should be axis, move, or volume"
2571        }
2572    }
2573}
2574
2575# ----------------------------------------------------------------------
2576# USAGE: SlicerTip <axis>
2577#
2578# Used internally to generate a tooltip for the x/y/z slicer controls.
2579# Returns a message that includes the current slicer value.
2580# ----------------------------------------------------------------------
2581itcl::body Rappture::FlowvisViewer::SlicerTip {axis} {
2582    set val [$itk_component(${axis}CutScale) get]
2583#    set val [expr {0.01*($val-50)
2584#        *($_limits(${axis}max)-$_limits(${axis}min))
2585#          + 0.5*($_limits(${axis}max)+$_limits(${axis}min))}]
2586    return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2587}
2588
2589itcl::body Rappture::FlowvisViewer::Resize {} {
2590    $_arcball resize $_width $_height
2591    SendCmd "screen size $_width $_height"
2592    set _resizePending 0
2593}
2594
2595itcl::body Rappture::FlowvisViewer::EventuallyResize { w h } {
2596    set _width $w
2597    set _height $h
2598    $_arcball resize $w $h
2599    if { !$_resizePending } {
2600        $_dispatcher event -after 200 !resize
2601        set _resizePending 1
2602    }
2603}
2604
2605itcl::body Rappture::FlowvisViewer::EventuallyResizeLegend {} {
2606    if { !$_resizeLegendPending } {
2607        $_dispatcher event -after 100 !legend
2608        set _resizeLegendPending 1
2609    }
2610}
2611
2612itcl::body Rappture::FlowvisViewer::EventuallyGoto { nSteps } {
2613    set _flow(goto) $nSteps
2614    if { !$_gotoPending } {
2615        $_dispatcher event -after 1000 !goto
2616        set _gotoPending 1
2617    }
2618}
2619
2620#  camera --
2621itcl::body Rappture::FlowvisViewer::camera {option args} {
2622    switch -- $option {
2623        "show" {
2624            puts [array get _view]
2625        }
2626        "set" {
2627            set who [lindex $args 0]
2628            set x $_settings($this-$who)
2629            set code [catch { string is double $x } result]
2630            if { $code != 0 || !$result } {
2631                set _settings($this-$who) $_view($who)
2632                return
2633            }
2634            switch -- $who {
2635                "xpan" - "ypan" {
2636                    set _view($who) $_settings($this-$who)
2637                    PanCamera
2638                }
2639                "qx" - "qy" - "qz" - "qw" {
2640                    set _view($who) $_settings($this-$who)
2641                    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2642                    $_arcball quaternion $q
2643                    SendCmd "camera orient $q"
2644                }
2645                "zoom" {
2646                    set _view($who) $_settings($this-$who)
2647                    SendCmd "camera zoom $_view(zoom)"
2648                }
2649            }
2650        }
2651    }
2652}
2653
2654itcl::body Rappture::FlowvisViewer::FlowCmd { dataobj comp nbytes extents } {
2655    set tag "$dataobj-$comp"
2656    if { ![info exists _obj2flow($tag)] } {
2657        append cmd "flow add $tag\n"
2658        append cmd "$tag data follows $nbytes $extents\n"
2659        return $cmd
2660    }
2661    set flowobj $_obj2flow($tag)
2662    if { $flowobj == "" } {
2663        puts stderr "no flowobj"
2664        return ""
2665    }
2666    set cmd {}
2667    append cmd "if {\[flow exists $tag\]} {flow delete $tag}\n"
2668    array set info  [$flowobj hints]
2669    set _settings($this-volume) $info(volume)
2670    set _settings($this-outline) $info(outline)
2671    set _settings($this-arrows) $info(arrows)
2672    set _settings($this-duration) $info(duration)
2673    $itk_component(speed) value $info(speed)
2674    append cmd "flow add $tag"
2675    append cmd " -position $info(position)"
2676    append cmd " -axis $info(axis)"
2677    append cmd " -volume $info(volume)"
2678    append cmd " -outline $info(outline)"
2679    append cmd " -slice $info(streams)"
2680    append cmd " -arrows $info(arrows)\n"
2681    foreach part [$flowobj particles] {
2682        array unset info
2683        array set info $part
2684        set color [Color2RGB $info(color)]
2685        append cmd "$tag particles add $info(name)"
2686        append cmd " -position $info(position)"
2687        append cmd " -hide $info(hide)"
2688        append cmd " -axis $info(axis)"
2689        append cmd " -color {$color}"
2690        append cmd " -size $info(size)\n"
2691    }
2692    foreach box [$flowobj boxes] {
2693        array unset info
2694        set info(corner1) ""
2695        set info(corner2) ""
2696        array set info $box
2697        if { $info(corner1) == "" || $info(corner2) == "" } {
2698            continue
2699        }
2700        set color [Color2RGB $info(color)]
2701        append cmd "$tag box add $info(name)"
2702        append cmd " -color {$color}"
2703        append cmd " -hide $info(hide)"
2704        append cmd " -linewidth $info(linewidth) "
2705        append cmd " -corner1 {$info(corner1)} "
2706        append cmd " -corner2 {$info(corner2)}\n"
2707    }   
2708    append cmd "$tag data follows $nbytes $extents\n"
2709    return $cmd
2710}
2711
2712
2713#
2714# flow --
2715#
2716# Called when the user clicks on the stop or play buttons
2717# for flow visualization.
2718#
2719#        $this flow play
2720#        $this flow stop
2721#        $this flow toggle
2722#        $this flow reset
2723#        $this flow pause
2724#        $this flow next
2725#
2726itcl::body Rappture::FlowvisViewer::flow { args } {
2727    set option [lindex $args 0]
2728    switch -- $option {
2729        "goto2" {
2730            puts stderr "actually sending \"flow goto $_flow(goto)\""
2731            SendCmd "flow goto $_flow(goto)"
2732            set _gotoPending 0
2733        }
2734        "goto" {
2735            puts stderr "flow goto to $_settings($this-currenttime)"
2736            # Figure out how many steps to the current time based upon
2737            # the speed and duration.
2738            set current $_settings($this-currenttime)
2739            set speed [$itk_component(speed) value]
2740            set time [str2millisecs $_settings($this-duration)]
2741            $itk_component(dial) configure -max $time
2742            set delay [expr int(round(500.0/$speed))]
2743            set timePerStep [expr {double($time) / $delay}]
2744            set nSteps [expr {int(ceil($current/$timePerStep))}]
2745            EventuallyGoto $nSteps
2746        }
2747        "speed" {
2748            set speed [$itk_component(speed) value]
2749            set _flow(delay) [expr int(round(500.0/$speed))]
2750        }
2751        "duration" {
2752            set max [str2millisecs $_settings($this-duration)]
2753            if { $max < 0 } {
2754                bell
2755                return
2756            }
2757            set _flow(duration) $max
2758            set _settings($this-duration) [millisecs2str $max]
2759            $itk_component(dial) configure -max $max
2760        }
2761        "off" {
2762            set _flow(state) 0
2763            $_dispatcher cancel !play
2764            $itk_component(play) deselect
2765        }
2766        "on" {
2767            flow speed
2768            flow duration
2769            set _flow(state) 1
2770            set _settings($this-currenttime) 0
2771            $itk_component(play) select
2772        }
2773        "stop" {
2774            if { $_flow(state) } {
2775                flow off
2776                flow reset
2777            }
2778        }
2779        "pause" {
2780            if { $_flow(state) } {
2781                flow off
2782            }
2783        }
2784        "play" {
2785            # If the flow is currently off, then restart it.
2786            if { !$_flow(state) } {
2787                flow on
2788                # If we're at the end of the flow, reset the flow.
2789                set _settings($this-currenttime) \
2790                    [expr {$_settings($this-currenttime) + $_flow(delay)}]
2791                if { $_settings($this-currenttime) >= $_flow(duration) } {
2792                    set _settings($this-step) 1
2793                    SendCmd "flow reset"
2794                }
2795                flow next
2796            }
2797        }
2798        "toggle" {
2799            if { $_settings($this-play) } {
2800                flow play
2801            } else {
2802                flow pause
2803            }
2804        }
2805        "reset" {
2806            set _settings($this-currenttime) 0
2807            SendCmd "flow reset"
2808        }
2809        "next" {
2810            if { ![winfo viewable $itk_component(3dview)] } {
2811                flow stop
2812                return
2813            }
2814            set _settings($this-currenttime) \
2815                [expr {$_settings($this-currenttime) + $_flow(delay)}]
2816            if { $_settings($this-currenttime) >= $_flow(duration) } {
2817                if { !$_settings($this-loop) } {
2818                    flow off
2819                    return
2820                }
2821                flow reset
2822            } else {
2823                SendCmd "flow next"
2824            }
2825            $_dispatcher event -after $_flow(delay) !play
2826        }
2827        default {
2828            error "bad option \"$option\": should be play, stop, toggle, or reset."
2829        }
2830    }
2831}
2832
2833itcl::body Rappture::FlowvisViewer::WaitIcon  { option widget } {
2834    switch -- $option {
2835        "start" {
2836            $_dispatcher dispatch $this !waiticon \
2837                "[itcl::code $this WaitIcon "next" $widget] ; list"
2838            set _icon 0
2839            $widget configure -image [Rappture::icon bigroller${_icon}]
2840            $_dispatcher event -after 100 !waiticon
2841        }
2842        "next" {
2843            incr _icon
2844            if { $_icon >= 8 } {
2845                set _icon 0
2846            }
2847            $widget configure -image [Rappture::icon bigroller${_icon}]
2848            $_dispatcher event -after 100 !waiticon
2849        }
2850        "stop" {
2851            $_dispatcher cancel !waiticon
2852        }
2853    }
2854}
2855
2856itcl::body Rappture::FlowvisViewer::GetPngImage  { widget width height } {
2857    set token "print[incr _nextToken]"
2858    set var ::Rappture::FlowvisViewer::_hardcopy($this-$token)
2859    set $var ""
2860
2861    # Setup an automatic timeout procedure.
2862    $_dispatcher dispatch $this !pngtimeout "set $var {} ; list"
2863
2864    set popup .flowvisviewerprint
2865    if {![winfo exists $popup]} {
2866        Rappture::Balloon $popup -title "Generating file..."
2867        set inner [$popup component inner]
2868        label $inner.title -text "Generating hardcopy." -font "Arial 10 bold"
2869        label $inner.please -text "This may take a minute." -font "Arial 10"
2870        label $inner.icon -image [Rappture::icon bigroller0]
2871        button $inner.cancel -text "Cancel" -font "Arial 10 bold" \
2872            -command [list set $var ""]
2873        blt::table $inner \
2874            0,0 $inner.title -cspan 2 \
2875            1,0 $inner.please -anchor w \
2876            1,1 $inner.icon -anchor e  \
2877            2,0 $inner.cancel -cspan 2
2878        blt::table configure $inner r0 -pady 4
2879        blt::table configure $inner r2 -pady 4
2880        bind $inner.cancel <KeyPress-Return> [list $inner.cancel invoke]
2881    } else {
2882        set inner [$popup component inner]
2883    }
2884
2885    $_dispatcher event -after 60000 !pngtimeout
2886    WaitIcon start $inner.icon
2887    grab set $inner
2888    focus $inner.cancel
2889
2890    SendCmd "print $token $width $height"
2891
2892    $popup activate $widget below
2893    update idletasks
2894    update
2895    # We wait here for either
2896    #  1) the png to be delivered or
2897    #  2) timeout or 
2898    #  3) user cancels the operation.
2899    tkwait variable $var
2900
2901    # Clean up.
2902    $_dispatcher cancel !pngtimeout
2903    WaitIcon stop $inner.icon
2904    grab release $inner
2905    $popup deactivate
2906    update
2907
2908    if { $_hardcopy($this-$token) != "" } {
2909        return [list .png $_hardcopy($this-$token)]
2910    }
2911    return ""
2912}
2913
2914itcl::body Rappture::FlowvisViewer::GetMovie { widget w h } {
2915    set token "movie[incr _nextToken]"
2916    set var ::Rappture::FlowvisViewer::_hardcopy($this-$token)
2917    set $var ""
2918
2919    # Setup an automatic timeout procedure.
2920    $_dispatcher dispatch $this !movietimeout "set $var {} ; list"
2921    set popup .flowvisviewermovie
2922    if {![winfo exists $popup]} {
2923        Rappture::Balloon $popup -title "Generating movie..."
2924        set inner [$popup component inner]
2925        label $inner.title -text "Generating movie for download" \
2926                -font "Arial 10 bold"
2927        label $inner.please -text "This may take a few minutes." \
2928                -font "Arial 10"
2929        label $inner.icon -image [Rappture::icon bigroller0]
2930        button $inner.cancel -text "Cancel" -font "Arial 10 bold" \
2931            -command [list set $var ""]
2932        blt::table $inner \
2933            0,0 $inner.title -cspan 2 \
2934            1,0 $inner.please -anchor w \
2935            1,1 $inner.icon -anchor e  \
2936            2,0 $inner.cancel -cspan 2
2937        blt::table configure $inner r0 -pady 4
2938        blt::table configure $inner r2 -pady 4
2939        bind $inner.cancel <KeyPress-Return> [list $inner.cancel invoke]
2940    } else {
2941        set inner [$popup component inner]
2942    }
2943    update
2944    # Timeout is set to 10 minutes.
2945    $_dispatcher event -after 600000 !movietimeout
2946    WaitIcon start $inner.icon
2947    grab set $inner
2948    focus $inner.cancel
2949   
2950    flow duration
2951    flow speed
2952    set nframes [expr round($_flow(duration) / $_flow(delay))]
2953    set framerate [expr 1000.0 / $_flow(delay)]
2954
2955    # These are specific to MPEG1 video generation
2956    set framerate 25.0
2957    set bitrate 6.0e+6
2958
2959    set start [clock seconds]
2960    SendCmd "flow video $token -width $w -height $h -numframes $nframes "
2961   
2962    $popup activate $widget below
2963    update idletasks
2964    update
2965    # We wait here until
2966    #  1. the movie is delivered or
2967    #  2. we've timed out or 
2968    #  3. the user has canceled the operation.b
2969    tkwait variable $var
2970
2971    puts stderr "Video generated in [expr [clock seconds] - $start] seconds."
2972
2973    # Clean up.
2974    $_dispatcher cancel !movietimeout
2975    WaitIcon stop $inner.icon
2976    grab release $inner
2977    $popup deactivate
2978    destroy $popup
2979    update
2980
2981    # This will both cancel the movie generation (if it hasn't already
2982    # completed) and reset the flow.
2983    SendCmd "flow reset"
2984    if { $_hardcopy($this-$token) != "" } {
2985        return [list .mpg $_hardcopy($this-$token)]
2986    }
2987    return ""
2988}
2989
2990itcl::body Rappture::FlowvisViewer::str2millisecs { value } {
2991    set parts [split $value :]
2992    set secs 0
2993    set mins 0
2994    if { [llength $parts] == 1 } {
2995        scan [lindex $parts 0] "%d" secs
2996    } else {
2997        scan [lindex $parts 1] "%d" secs
2998        scan [lindex $parts 0] "%d" mins
2999    }
3000    set ms [expr {(($mins * 60) + $secs) * 1000.0}]
3001    if { $ms > 600000.0 } {
3002        set ms 600000.0
3003    }
3004    if { $ms == 0.0 } {
3005        set ms 60000.0
3006    }
3007    return $ms
3008}
3009
3010itcl::body Rappture::FlowvisViewer::millisecs2str { value } {
3011    set min [expr floor($value / 60000.0)]
3012    set sec [expr ($value - ($min*60000.0)) / 1000.0]
3013    return [format %02d:%02d [expr round($min)] [expr round($sec)]]
3014}
3015
3016itcl::body Rappture::FlowvisViewer::SetOrientation { side } {
3017    array set positions {
3018        front "1 0 0 0"
3019        back  "0 0 1 0"
3020        left  "0.707107 0 -0.707107 0"
3021        right "0.707107 0 0.707107 0"
3022        top   "0.707107 -0.707107 0 0"
3023        bottom "0.707107 0.707107 0 0"
3024    }
3025    foreach name { qw qx qy qz } value $positions($side) {
3026        set _view($name) $value
3027    }
3028    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
3029    $_arcball quaternion $q
3030    SendCmd "camera orient $q"
3031    SendCmd "camera reset"
3032    set _view(xpan) 0.0
3033    set _view(ypan) 0.0
3034    set _view(zoom) 1.0
3035    set _settings($this-xpan) $_view(xpan)
3036    set _settings($this-ypan) $_view(ypan)
3037    set _settings($this-zoom) $_view(zoom)
3038}
Note: See TracBrowser for help on using the repository browser.