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

Last change on this file since 4555 was 4555, checked in by ldelgass, 7 years ago

merge r4166 from trunk

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