source: branches/r9/gui/scripts/flowvisviewer.tcl @ 5106

Last change on this file since 5106 was 4919, checked in by gah, 9 years ago
File size: 102.3 KB
Line 
1# -*- mode: tcl; indent-tabs-mode: nil -*-
2# ----------------------------------------------------------------------
3#  COMPONENT: flowvisviewer - 3D flow rendering
4#
5#
6# This widget performs volume and flow rendering on 3D scalar/vector datasets.
7# It connects to the Flowvis server running on a rendering farm, transmits
8# data, and displays the results.
9#
10# ======================================================================
11#  AUTHOR:  Michael McLennan, Purdue University
12#  Copyright (c) 2004-2012  HUBzero Foundation, LLC
13#
14# See the file "license.terms" for information on usage and redistribution of
15# this file, and for a DISCLAIMER OF ALL WARRANTIES.
16# ======================================================================
17package require Itk
18package require BLT
19package require Img
20
21option add *FlowvisViewer.width 5i widgetDefault
22option add *FlowvisViewer*cursor crosshair widgetDefault
23option add *FlowvisViewer.height 4i widgetDefault
24option add *FlowvisViewer.foreground black widgetDefault
25option add *FlowvisViewer.controlBackground gray widgetDefault
26option add *FlowvisViewer.controlDarkBackground #999999 widgetDefault
27option add *FlowvisViewer.plotBackground black widgetDefault
28option add *FlowvisViewer.plotForeground white widgetDefault
29option add *FlowvisViewer.plotOutline gray widgetDefault
30option add *FlowvisViewer.font \
31    -*-helvetica-medium-r-normal-*-12-* widgetDefault
32
33# must use this name -- plugs into Rappture::resources::load
34proc FlowvisViewer_init_resources {} {
35    Rappture::resources::register \
36        nanovis_server Rappture::FlowvisViewer::SetServerList
37}
38
39itcl::class Rappture::FlowvisViewer {
40    inherit Rappture::VisViewer
41
42    itk_option define -plotforeground plotForeground Foreground ""
43    itk_option define -plotbackground plotBackground Background ""
44    itk_option define -plotoutline plotOutline PlotOutline ""
45
46    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 styles {
719        -color BCGYR
720        -levels 6
721        -markers ""
722        -opacity 1.0
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 styles [lindex [$dataobj components -style $cname] 0]
734                set cmap [ColorsToColormap $styles(-color)]
735                set _cname2defaultcolormap($cname) $cmap
736                set _settings($cname-colormap) $styles(-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 "version" "$Rappture::version"
887            lappend info "build" "$Rappture::build"
888            lappend info "svnurl" "$Rappture::svnurl"
889            lappend info "installdir" "$Rappture::installdir"
890            lappend info "hub" [exec hostname]
891            lappend info "client" "flowvisviewer"
892            lappend info "user" $user
893            lappend info "session" $session
894            SendCmd "clientinfo [list $info]"
895        }
896
897        set w [winfo width $itk_component(3dview)]
898        set h [winfo height $itk_component(3dview)]
899        EventuallyResize $w $h
900    }
901    return $result
902}
903
904#
905# isconnected --
906#
907#       Indicates if we are currently connected to the visualization server.
908#
909itcl::body Rappture::FlowvisViewer::isconnected {} {
910    return [VisViewer::IsConnected]
911}
912
913#
914# disconnect --
915#
916itcl::body Rappture::FlowvisViewer::disconnect {} {
917    Disconnect
918}
919
920#
921# Disconnect --
922#
923#       Clients use this method to disconnect from the current rendering
924#       server.
925#
926itcl::body Rappture::FlowvisViewer::Disconnect {} {
927    VisViewer::Disconnect
928
929    # disconnected -- no more data sitting on server
930    array unset _serverObjs
931}
932
933# ----------------------------------------------------------------------
934# USAGE: SendTransferFuncs
935# ----------------------------------------------------------------------
936itcl::body Rappture::FlowvisViewer::SendTransferFuncs {} {
937    if { $_activeTf == "" } {
938        puts stderr "no active tf"
939        return
940    }
941    set tf $_activeTf
942    if { $_first == "" } {
943        puts stderr "no first"
944        return
945    }
946
947    # Ensure that the global opacity and thickness settings (in the slider
948    # settings widgets) are used for the active transfer-function.  Update the
949    # values in the _settings varible.
950    set value $_settings($this-opacity)
951    set opacity [expr { double($value) * 0.01 }]
952    set _settings($this-$tf-opacity) $opacity
953    set value $_settings($this-thickness)
954    # Scale values between 0.00001 and 0.01000
955    set thickness [expr {double($value) * 0.0001}]
956    set _settings($this-$tf-thickness) $thickness
957
958    foreach key [array names _obj2style $_first-*] {
959        if { [info exists _obj2style($key)] } {
960            foreach tf $_obj2style($key) {
961                ComputeTransferFunc $tf
962            }
963        }
964    }
965    EventuallyResizeLegend
966}
967
968# ----------------------------------------------------------------------
969# USAGE: ReceiveImage -bytes $size -type $type -token $token
970#
971# Invoked automatically whenever the "image" command comes in from
972# the rendering server.  Indicates that binary image data with the
973# specified <size> will follow.
974# ----------------------------------------------------------------------
975itcl::body Rappture::FlowvisViewer::ReceiveImage { args } {
976    array set info {
977        -token "???"
978        -bytes 0
979        -type image
980    }
981    array set info $args
982    set bytes [ReceiveBytes $info(-bytes)]
983    ReceiveEcho <<line "<read $info(-bytes) bytes"
984    switch -- $info(-type)  {
985        "image" {
986            $_image(plot) configure -data $bytes
987            #puts stderr "image received [image width $_image(plot)] by [image height $_image(plot)]"
988        }
989        "print" {
990            set tag $this-$info(-token)
991            set _hardcopy($tag) $bytes
992        }
993        "movie" {
994            set tag $this-$info(-token)
995            set _hardcopy($tag) $bytes
996        }
997        default {
998            puts stderr "unknown download type $info(-type)"
999        }
1000    }
1001}
1002
1003#
1004# ReceiveLegend --
1005#
1006#       The procedure is the response from the render server to each "legend"
1007#       command.  The server sends back a "legend" command invoked our
1008#       the slave interpreter.  The purpose is to collect data of the image
1009#       representing the legend in the canvas.  In addition, the isomarkers
1010#       of the active transfer function are displayed.
1011#
1012#       I don't know is this is the right place to display the isomarkers.
1013#       I don't know all the different paths used to draw the plot. There's
1014#       "Rebuild", "add", etc.
1015#
1016itcl::body Rappture::FlowvisViewer::ReceiveLegend { tag vmin vmax size } {
1017    if { ![isconnected] } {
1018        return
1019    }
1020    #puts stderr "receive legend $tag $vmin $vmax $size"
1021    set bytes [ReceiveBytes $size]
1022    $_image(legend) configure -data $bytes
1023    ReceiveEcho <<line "<read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
1024
1025    set c $itk_component(legend)
1026    set w [winfo width $c]
1027    set h [winfo height $c]
1028    set lx 10
1029    set ly [expr {$h - 1}]
1030    if {"" == [$c find withtag colorbar]} {
1031        $c create image 10 10 -anchor nw \
1032            -image $_image(legend) -tags colorbar
1033        $c create text $lx $ly -anchor sw \
1034            -fill $itk_option(-plotforeground) -tags "limits vmin"
1035        $c create text [expr {$w-$lx}] $ly -anchor se \
1036            -fill $itk_option(-plotforeground) -tags "limits vmax"
1037        $c lower colorbar
1038        $c bind colorbar <ButtonRelease-1> [itcl::code $this AddIsoMarker %x %y]
1039    }
1040    # Display the markers used by the active transfer function.
1041    set tf $_obj2style($tag)
1042    foreach {vmin vmax} [limits $tf] break
1043    $c itemconfigure vmin -text [format %g $vmin]
1044    $c coords vmin $lx $ly
1045
1046    $c itemconfigure vmax -text [format %g $vmax]
1047    $c coords vmax [expr {$w-$lx}] $ly
1048
1049    if { [info exists _isomarkers($tf)] } {
1050        foreach m $_isomarkers($tf) {
1051            $m visible yes
1052        }
1053    }
1054}
1055
1056#
1057# ReceiveData --
1058#
1059#       The procedure is the response from the render server to each "data
1060#       follows" command.  The server sends back a "data" command invoked our
1061#       the slave interpreter.  The purpose is to collect the min/max of the
1062#       volume sent to the render server.  Since the client (flowvisviewer)
1063#       doesn't parse 3D data formats, we rely on the server (flowvis) to
1064#       tell us what the limits are.  Once we've received the limits to all
1065#       the data we've sent (tracked by _recvObjs) we can then determine
1066#       what the transfer functions are for these # volumes.
1067#
1068#       Note: There is a considerable tradeoff in having the server report
1069#             back what the data limits are.  It means that much of the code
1070#             having to do with transfer-functions has to wait for the data
1071#             to come back, since the isomarkers are calculated based upon
1072#             the data limits.  The client code is much messier because of
1073#             this.  The alternative is to parse any of the 3D formats on the
1074#             client side.
1075#
1076itcl::body Rappture::FlowvisViewer::ReceiveData { args } {
1077    if { ![isconnected] } {
1078        return
1079    }
1080    # Arguments from server are name value pairs. Stuff them in an array.
1081    array set values $args
1082    set tag $values(tag)
1083    set parts [split $tag -]
1084    set dataobj [lindex $parts 0]
1085    set _serverObjs($tag) 0
1086    set _limits($tag) [list $values(min) $values(max)]
1087    unset _recvObjs($tag)
1088    if { [array size _recvObjs] == 0 } {
1089        updateTransferFunctions
1090    }
1091}
1092
1093#
1094# Rebuild --
1095#
1096# Called automatically whenever something changes that affects the data
1097# in the widget.  Clears any existing data and rebuilds the widget to
1098# display new data. 
1099#
1100itcl::body Rappture::FlowvisViewer::Rebuild {} {
1101    set w [winfo width $itk_component(3dview)]
1102    set h [winfo height $itk_component(3dview)]
1103    if { $w < 2 || $h < 2 } {
1104        $_dispatcher event -idle !rebuild
1105        return
1106    }
1107
1108    # Turn on buffering of commands to the server.  We don't want to
1109    # be preempted by a server disconnect/reconnect (which automatically
1110    # generates a new call to Rebuild).   
1111    StartBufferingCommands
1112
1113    # Hide all the isomarkers. Can't remove them. Have to remember the
1114    # settings since the user may have created/deleted/moved markers.
1115
1116    foreach tf [array names _isomarkers] {
1117        foreach m $_isomarkers($tf) {
1118            $m visible no
1119        }
1120    }
1121
1122    if { $_width != $w || $_height != $h || $_reset } {
1123        set _width $w
1124        set _height $h
1125        $_arcball resize $w $h
1126        Resize
1127    }
1128
1129    set _first ""
1130    foreach dataobj [get] {
1131        foreach comp [$dataobj components] {
1132            set tag $dataobj-$comp
1133            set isvtk 0
1134            # FIXME: Would like to use the type method of the dataobj
1135            # but the returned value isn't well defined now
1136            if {[catch {
1137                # Send the data as one huge base64-encoded mess -- yuck!
1138                set data [$dataobj blob $comp]
1139            }]} {
1140                set data [$dataobj vtkdata $comp]
1141                set isvtk 1
1142            }
1143            set nbytes [string length $data]
1144            if { $_reportClientInfo }  {
1145                set info {}
1146                lappend info "tool_id"       [$dataobj hints toolId]
1147                lappend info "tool_name"     [$dataobj hints toolName]
1148                lappend info "tool_version"  [$dataobj hints toolRevision]
1149                lappend info "tool_title"    [$dataobj hints toolTitle]
1150                lappend info "dataset_label" [$dataobj hints label]
1151                lappend info "dataset_size"  $nbytes
1152                lappend info "dataset_tag"   $tag
1153                SendCmd "clientinfo [list $info]"
1154            }
1155            set extents [$dataobj extents $comp]
1156            # I have a field. Is a vector field or a volume field?
1157            if { !$isvtk && $extents == 1 } {
1158                set cmd "volume data follows $nbytes $tag\n"
1159            } else {
1160                set cmd [FlowCmd $dataobj $comp $nbytes $extents]
1161                if { $cmd == "" } {
1162                    puts stderr "no command"
1163                    continue
1164                }
1165            }
1166            append _outbuf $cmd
1167            append _outbuf $data
1168            NameTransferFunc $dataobj $comp
1169            set _recvObjs($tag) 1
1170        }
1171    }
1172
1173    set _first [lindex [get] 0]
1174
1175    # Reset the camera and other view parameters
1176    InitSettings light2side light transp isosurface grid axes volume outline
1177   
1178    # nothing to send -- activate the proper volume
1179    if {"" != $_first} {
1180        AdjustSetting light
1181        AdjustSetting transp
1182        set axis [$_first hints updir]
1183        if {"" != $axis} {
1184            SendCmd "up $axis"
1185        }
1186        set location [$_first hints camera]
1187        if { $location != "" } {
1188            array set _view $location
1189        }
1190
1191    }
1192    set _settings($this-qw)    $_view(qw)
1193    set _settings($this-qx)    $_view(qx)
1194    set _settings($this-qy)    $_view(qy)
1195    set _settings($this-qz)    $_view(qz)
1196    set _settings($this-xpan)  $_view(xpan)
1197    set _settings($this-ypan)  $_view(ypan)
1198    set _settings($this-zoom)  $_view(zoom)
1199
1200    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1201    $_arcball quaternion $q
1202    SendCmd "camera orient $q"
1203    SendCmd "camera reset"
1204    PanCamera
1205    SendCmd "camera zoom $_view(zoom)"
1206
1207    foreach dataobj [get] {
1208        foreach comp [$dataobj components] {
1209            NameTransferFunc $dataobj $comp
1210        }
1211    }
1212
1213    # nothing to send -- activate the proper ivol
1214    set _first [lindex [get] 0]
1215    if {"" != $_first} {
1216        set axis [$_first hints updir]
1217        if {"" != $axis} {
1218            SendCmd "up $axis"
1219        }
1220        set location [$_first hints camera]
1221        if { $location != "" } {
1222            array set _view $location
1223        }
1224        set comp [lindex [$_first components] 0]
1225        set _activeTf [lindex $_obj2style($_first-$comp) 0]
1226    }
1227
1228
1229    # sync the state of slicers
1230    set vols [CurrentVolumeIds -cutplanes]
1231    foreach axis {x y z} {
1232        SendCmd "cutplane state $_settings($this-${axis}cutplane) $axis $vols"
1233        set pos [expr {0.01*$_settings($this-${axis}cutposition)}]
1234        SendCmd "cutplane position $pos $axis $vols"
1235    }
1236    SendCmd "volume data state $_settings($this-volume)"
1237    EventuallyResizeLegend
1238
1239    # Actually write the commands to the server socket.  If it fails, we don't
1240    # care.  We're finished here.
1241    blt::busy hold $itk_component(hull)
1242    StopBufferingCommands
1243    blt::busy release $itk_component(hull)
1244    set _reset 0
1245}
1246
1247# ----------------------------------------------------------------------
1248# USAGE: CurrentVolumeIds ?-cutplanes?
1249#
1250# Returns a list of volume server IDs for the current volume being
1251# displayed.  This is normally a single ID, but it might be a list
1252# of IDs if the current data object has multiple components.
1253# ----------------------------------------------------------------------
1254itcl::body Rappture::FlowvisViewer::CurrentVolumeIds {{what -all}} {
1255    return ""
1256    if { $_first == "" } {
1257        return
1258    }
1259    foreach key [array names _serverObjs *-*] {
1260        if {[string match $_first-* $key]} {
1261            array set styles {
1262                -cutplanes 1
1263            }
1264            foreach {dataobj comp} [split $key -] break
1265            array set styles [lindex [$dataobj components -style $comp] 0]
1266            if {$what != "-cutplanes" || $styles(-cutplanes)} {
1267                lappend rlist $_serverObjs($key)
1268            }
1269        }
1270    }
1271    return $rlist
1272}
1273
1274# ----------------------------------------------------------------------
1275# USAGE: Zoom in
1276# USAGE: Zoom out
1277# USAGE: Zoom reset
1278#
1279# Called automatically when the user clicks on one of the zoom
1280# controls for this widget.  Changes the zoom for the current view.
1281# ----------------------------------------------------------------------
1282itcl::body Rappture::FlowvisViewer::Zoom {option} {
1283    switch -- $option {
1284        "in" {
1285            set _view(zoom) [expr {$_view(zoom)*1.25}]
1286            set _settings($this-zoom) $_view(zoom)
1287            SendCmd "camera zoom $_view(zoom)"
1288        }
1289        "out" {
1290            set _view(zoom) [expr {$_view(zoom)*0.8}]
1291            set _settings($this-zoom) $_view(zoom)
1292            SendCmd "camera zoom $_view(zoom)"
1293        }
1294        "reset" {
1295            array set _view {
1296                qw      0.853553
1297                qx      -0.353553
1298                qy      0.353553
1299                qz      0.146447
1300                zoom    1.0
1301                xpan   0
1302                ypan   0
1303            }
1304            if { $_first != "" } {
1305                set location [$_first hints camera]
1306                if { $location != "" } {
1307                    array set _view $location
1308                }
1309            }
1310            set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1311            $_arcball quaternion $q
1312            SendCmd "camera orient $q"
1313            SendCmd "camera reset"
1314            set _settings($this-qw)    $_view(qw)
1315            set _settings($this-qx)    $_view(qx)
1316            set _settings($this-qy)    $_view(qy)
1317            set _settings($this-qz)    $_view(qz)
1318            set _settings($this-xpan)  $_view(xpan)
1319            set _settings($this-ypan)  $_view(ypan)
1320            set _settings($this-zoom)  $_view(zoom)
1321        }
1322    }
1323}
1324
1325itcl::body Rappture::FlowvisViewer::PanCamera {} {
1326    set x $_view(xpan)
1327    set y $_view(ypan)
1328    SendCmd "camera pan $x $y"
1329}
1330
1331# ----------------------------------------------------------------------
1332# USAGE: Rotate click <x> <y>
1333# USAGE: Rotate drag <x> <y>
1334# USAGE: Rotate release <x> <y>
1335#
1336# Called automatically when the user clicks/drags/releases in the
1337# plot area.  Moves the plot according to the user's actions.
1338# ----------------------------------------------------------------------
1339itcl::body Rappture::FlowvisViewer::Rotate {option x y} {
1340    switch -- $option {
1341        click {
1342            $itk_component(3dview) configure -cursor fleur
1343            set _click(x) $x
1344            set _click(y) $y
1345        }
1346        drag {
1347            if {[array size _click] == 0} {
1348                Rotate click $x $y
1349            } else {
1350                set w [winfo width $itk_component(3dview)]
1351                set h [winfo height $itk_component(3dview)]
1352                if {$w <= 0 || $h <= 0} {
1353                    return
1354                }
1355
1356                if {[catch {
1357                    # this fails sometimes for no apparent reason
1358                    set dx [expr {double($x-$_click(x))/$w}]
1359                    set dy [expr {double($y-$_click(y))/$h}]
1360                }]} {
1361                    return
1362                }
1363
1364                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1365                foreach { _view(qw) _view(qx) _view(qy) _view(qz) } $q break
1366                set _settings($this-qw) $_view(qw)
1367                set _settings($this-qx) $_view(qx)
1368                set _settings($this-qy) $_view(qy)
1369                set _settings($this-qz) $_view(qz)
1370                SendCmd "camera orient $q"
1371
1372                set _click(x) $x
1373                set _click(y) $y
1374            }
1375        }
1376        release {
1377            Rotate drag $x $y
1378            $itk_component(3dview) configure -cursor ""
1379            catch {unset _click}
1380        }
1381        default {
1382            error "bad option \"$option\": should be click, drag, release"
1383        }
1384    }
1385}
1386
1387# ----------------------------------------------------------------------
1388# USAGE: $this Pan click x y
1389#        $this Pan drag x y
1390#        $this Pan release x y
1391#
1392# Called automatically when the user clicks on one of the zoom
1393# controls for this widget.  Changes the zoom for the current view.
1394# ----------------------------------------------------------------------
1395itcl::body Rappture::FlowvisViewer::Pan {option x y} {
1396    # Experimental stuff
1397    set w [winfo width $itk_component(3dview)]
1398    set h [winfo height $itk_component(3dview)]
1399    if { $option == "set" } {
1400        set x [expr $x / double($w)]
1401        set y [expr $y / double($h)]
1402        set _view(xpan) [expr $_view(xpan) + $x]
1403        set _view(ypan) [expr $_view(ypan) + $y]
1404        PanCamera
1405        set _settings($this-xpan) $_view(xpan)
1406        set _settings($this-ypan) $_view(ypan)
1407        return
1408    }
1409    if { $option == "click" } {
1410        set _click(x) $x
1411        set _click(y) $y
1412        $itk_component(3dview) configure -cursor hand1
1413    }
1414    if { $option == "drag" || $option == "release" } {
1415        set dx [expr ($_click(x) - $x)/double($w)]
1416        set dy [expr ($_click(y) - $y)/double($h)]
1417        set _click(x) $x
1418        set _click(y) $y
1419        set _view(xpan) [expr $_view(xpan) - $dx]
1420        set _view(ypan) [expr $_view(ypan) - $dy]
1421        PanCamera
1422        set _settings($this-xpan) $_view(xpan)
1423        set _settings($this-ypan) $_view(ypan)
1424    }
1425    if { $option == "release" } {
1426        $itk_component(3dview) configure -cursor ""
1427    }
1428}
1429
1430
1431# ----------------------------------------------------------------------
1432# USAGE: Flow movie record|stop|play ?on|off|toggle?
1433#
1434# Called when the user clicks on the record, stop or play buttons
1435# for flow visualization.
1436# ----------------------------------------------------------------------
1437itcl::body Rappture::FlowvisViewer::Flow {option args} {
1438    switch -- $option {
1439        movie {
1440            if {[llength $args] < 1 || [llength $args] > 2} {
1441                error "wrong # args: should be \"Flow movie record|stop|play ?on|off|toggle?\""
1442            }
1443            set action [lindex $args 0]
1444            set op [lindex $args 1]
1445            if {$op == ""} { set op "on" }
1446
1447            set current [State $action]
1448            if {$op == "toggle"} {
1449                if {$current == "on"} {
1450                    set op "off"
1451                } else {
1452                    set op "on"
1453                }
1454            }
1455            set cmds ""
1456            switch -- $action {
1457                record {
1458                    if { [$itk_component(rewind) cget -relief] != "sunken" } {
1459                        $itk_component(rewind) configure -relief sunken
1460                        $itk_component(stop) configure -relief raised
1461                        $itk_component(play) configure -relief raised
1462                        set inner $itk_component(settingsFrame)
1463                        set frames [$inner.framecnt value]
1464                        set _settings(nsteps) $frames
1465                        set cmds "flow capture $frames"
1466                        SendCmd $cmds
1467                    }
1468                }
1469                stop {
1470                    if { [$itk_component(stop) cget -relief] != "sunken" } {
1471                        $itk_component(rewind) configure -relief raised
1472                        $itk_component(stop) configure -relief sunken
1473                        $itk_component(play) configure -relief raised
1474                        _pause
1475                        set cmds "flow reset"
1476                        SendCmd $cmds
1477                    }
1478                }
1479                play {
1480                    if { [$itk_component(play) cget -relief] != "sunken" } {
1481                        $itk_component(rewind) configure -relief raised
1482                        $itk_component(stop) configure -relief raised
1483                        $itk_component(play) configure \
1484                            -image [Rappture::icon flow-pause] \
1485                            -relief sunken
1486                        bind $itk_component(play) <ButtonPress> \
1487                            [itcl::code $this _pause]
1488                        flow next
1489                    }
1490                }
1491                default {
1492                    error "bad option \"$option\": should be one of record|stop|play"
1493                }
1494
1495            }
1496        }
1497        default {
1498            error "bad option \"$option\": should be movie"
1499        }
1500    }
1501}
1502
1503# ----------------------------------------------------------------------
1504# USAGE: Play
1505#
1506# ----------------------------------------------------------------------
1507itcl::body Rappture::FlowvisViewer::Play {} {
1508    SendCmd "flow next"
1509    set delay [expr {int(ceil(pow($_settings(speed)/10.0+2,2.0)*15))}]
1510    $_dispatcher event -after $delay !play
1511}
1512
1513# ----------------------------------------------------------------------
1514# USAGE: Pause
1515#
1516# Invoked when the user hits the "pause" button to stop playing the
1517# current sequence of frames as a movie.
1518# ----------------------------------------------------------------------
1519itcl::body Rappture::FlowvisViewer::Pause {} {
1520    $_dispatcher cancel !play
1521
1522    # Toggle the button to "play" mode
1523    $itk_component(play) configure \
1524        -image [Rappture::icon flow-start] \
1525        -relief raised
1526    bind $itk_component(play) <ButtonPress> \
1527        [itcl::code $this Flow movie play toggle]
1528}
1529
1530# ----------------------------------------------------------------------
1531# USAGE: InitSettings <what> ?<value>?
1532#
1533# Used internally to update rendering settings whenever parameters
1534# change in the popup settings panel.  Sends the new settings off
1535# to the back end.
1536# ----------------------------------------------------------------------
1537itcl::body Rappture::FlowvisViewer::InitSettings { args } {
1538    foreach arg $args {
1539        AdjustSetting $arg
1540    }
1541}
1542
1543# ----------------------------------------------------------------------
1544# USAGE: AdjustSetting <what> ?<value>?
1545#
1546# Used internally to update rendering settings whenever parameters
1547# change in the popup settings panel.  Sends the new settings off
1548# to the back end.
1549# ----------------------------------------------------------------------
1550itcl::body Rappture::FlowvisViewer::AdjustSetting {what {value ""}} {
1551    switch -- $what {
1552        colormap {
1553            set color [$itk_component(colormap) value]
1554            set _settings(colormap) $color
1555            #ResetColormap $color
1556        }
1557        light {
1558            if { $_first != "" } {
1559                set comp [lindex [$_first components] 0]
1560                set tag $_first-$comp
1561                set diffuse [expr {0.01*$_settings($this-light)}]
1562                set ambient [expr {1.0 - $diffuse}]
1563                set specularLevel 0.3
1564                set specularExp 90.0
1565                SendCmd "$tag configure -ambient $ambient -diffuse $diffuse -specularLevel $specularLevel -specularExp $specularExp"
1566            }
1567        }
1568        light2side {
1569            if { $_first != "" } {
1570                set comp [lindex [$_first components] 0]
1571                set tag $_first-$comp
1572                set val $_settings($this-light2side)
1573                SendCmd "$tag configure -light2side $val"
1574            }
1575        }
1576        transp {
1577            if { $_first != "" } {
1578                set comp [lindex [$_first components] 0]
1579                set tag $_first-$comp
1580                set opacity [expr { 0.01 * double($_settings($this-transp)) }]
1581                SendCmd "$tag configure -opacity $opacity"
1582            }
1583        }
1584        opacity {
1585            if { $_first != "" && $_activeTf != "" } {
1586                set opacity [expr { 0.01 * double($_settings($this-opacity)) }]
1587                set tf $_activeTf
1588                set _settings($this-$tf-opacity) $opacity
1589                updateTransferFunctions
1590            }
1591        }
1592
1593        thickness {
1594            if { $_first != "" && $_activeTf != "" } {
1595                set val $_settings($this-thickness)
1596                # Scale values between 0.00001 and 0.01000
1597                set sval [expr {0.0001*double($val)}]
1598                set tf $_activeTf
1599                set _settings($this-$tf-thickness) $sval
1600                updateTransferFunctions
1601            }
1602        }
1603        "outline" {
1604            if { $_first != "" } {
1605                set comp [lindex [$_first components] 0]
1606                set tag $_first-$comp
1607                SendCmd "$tag configure -outline $_settings($this-outline)"
1608            }
1609        }
1610        "isosurface" {
1611            if { [isconnected] } {
1612                SendCmd "volume shading isosurface $_settings($this-isosurface)"
1613            }
1614        }
1615        "grid" {
1616            if { [isconnected] } {
1617                SendCmd "grid visible $_settings($this-grid)"
1618            }
1619        }
1620        "axes" {
1621            if { [isconnected] } {
1622                SendCmd "axis visible $_settings($this-axes)"
1623            }
1624        }
1625        "legend" {
1626            if { $_settings($this-legend) } {
1627                blt::table $itk_component(plotarea) \
1628                    0,0 $itk_component(3dview) -fill both \
1629                    1,0 $itk_component(legend) -fill x
1630                blt::table configure $itk_component(plotarea) r1 -resize none
1631            } else {
1632                blt::table forget $itk_component(legend)
1633            }
1634        }
1635        "volume" {
1636            if { $_first != "" } {
1637                set comp [lindex [$_first components] 0]
1638                set tag $_first-$comp
1639                SendCmd "$tag configure -volume $_settings($this-volume)"
1640            }
1641        }
1642        "xcutplane" - "ycutplane" - "zcutplane" {
1643            set axis [string range $what 0 0]
1644            set bool $_settings($this-$what)
1645            if { [isconnected] } {
1646                set vols [CurrentVolumeIds -cutplanes]
1647                SendCmd "cutplane state $bool $axis $vols"
1648            }
1649            if { $bool } {
1650                $itk_component(${axis}CutScale) configure -state normal \
1651                    -troughcolor white
1652            } else {
1653                $itk_component(${axis}CutScale) configure -state disabled \
1654                    -troughcolor grey82
1655            }
1656        }
1657        default {
1658            error "don't know how to fix $what"
1659        }
1660    }
1661}
1662
1663# ----------------------------------------------------------------------
1664# USAGE: ResizeLegend
1665#
1666# Used internally to update the legend area whenever it changes size
1667# or when the field changes.  Asks the server to send a new legend
1668# for the current field.
1669# ----------------------------------------------------------------------
1670itcl::body Rappture::FlowvisViewer::ResizeLegend {} {
1671    set _resizeLegendPending 0
1672    set lineht [font metrics $itk_option(-font) -linespace]
1673    set w [expr {$_width-20}]
1674    set h [expr {[winfo height $itk_component(legend)]-20-$lineht}]
1675
1676    if { $_first == "" } {
1677        return
1678    }
1679    set comp [lindex [$_first components] 0]
1680    set tag $_first-$comp
1681    #set _activeTf [lindex $_obj2style($tag) 0]
1682    if {$w > 0 && $h > 0 && "" != $_activeTf} {
1683        #SendCmd "legend $_activeTf $w $h"
1684        SendCmd "$tag legend $w $h"
1685    } else {
1686    # Can't do this as this will remove the items associated with the
1687    # isomarkers.
1688
1689    #$itk_component(legend) delete all
1690    }
1691}
1692
1693#
1694# NameTransferFunc --
1695#
1696#       Creates a transfer function name based on the <style> settings in the
1697#       library run.xml file. This placeholder will be used later to create
1698#       and send the actual transfer function once the data info has been sent
1699#       to us by the render server. [We won't know the volume limits until the
1700#       server parses the 3D data and sends back the limits via ReceiveData.]
1701#
1702#       FIXME: The current way we generate transfer-function names completely
1703#              ignores the -markers option.  The problem is that we are forced
1704#              to compute the name from an increasing complex set of values:
1705#              color, levels, marker, opacity.  I think we're stuck doing it
1706#              now.
1707#
1708itcl::body Rappture::FlowvisViewer::NameTransferFunc { dataobj cname } {
1709    array set styles {
1710        -color BCGYR
1711        -levels 6
1712        -light 40
1713        -opacity 1.0
1714        -transp 50
1715    }
1716    array set styles [lindex [$dataobj components -style $cname] 0]
1717    set _settings($this-light) $styles(-light)
1718    set _settings($this-transp) $styles(-transp)
1719    set _settings($this-opacity) [expr $styles(-opacity) * 100]
1720    set _obj2style($dataobj-$cname) $cname
1721    lappend _style2objs($cname) $dataobj $cname
1722    return $cname
1723}
1724
1725#
1726# ComputeTransferFunc --
1727#
1728#   Computes and sends the transfer function to the render server.  It's
1729#   assumed that the volume data limits are known and that the global
1730#   transfer-functions slider values have be setup.  Both parts are
1731#   needed to compute the relative value (location) of the marker, and
1732#   the alpha map of the transfer function.
1733#
1734itcl::body Rappture::FlowvisViewer::ComputeTransferFunc { tf } {
1735    array set styles {
1736        -color BCGYR
1737        -levels 6
1738        -opacity 1.0
1739        -light 40
1740        -transp 50
1741    }
1742    set dataobj ""; set comp ""
1743    foreach {dataobj comp} $_style2objs($tf) break
1744    if { $dataobj == "" } {
1745        return 0
1746    }
1747    array set styles [lindex [$dataobj components -style $comp] 0]
1748
1749
1750    # We have to parse the style attributes for a volume using this
1751    # transfer-function *once*.  This sets up the initial isomarkers for the
1752    # transfer function.  The user may add/delete markers, so we have to
1753    # maintain a list of markers for each transfer-function.  We use the one
1754    # of the volumes (the first in the list) using the transfer-function as a
1755    # reference.
1756    #
1757    # FIXME: The current way we generate transfer-function names completely
1758    #        ignores the -markers option.  The problem is that we are forced
1759    #        to compute the name from an increasing complex set of values:
1760    #        color, levels, marker, opacity.  I think the cow's out of the
1761    #        barn on this one.
1762
1763    if { ![info exists _isomarkers($tf)] } {
1764        # Have to defer creation of isomarkers until we have data limits
1765        if { [info exists styles(-markers)] &&
1766             [llength $styles(-markers)] > 0  } {
1767            ParseMarkersOption $tf $styles(-markers)
1768        } else {
1769            ParseLevelsOption $tf $styles(-levels)
1770        }
1771    }
1772    if { [info exists styles(-nonuniformcolors)] } {
1773        foreach { value color } $styles(-nonuniformcolors) {
1774            append cmap "$value [Color2RGB $color] "
1775        }
1776    } else {
1777        set cmap [ColorsToColormap $styles(-color)]
1778    }
1779    set tag $this-$tf
1780    if { ![info exists _settings($tag-opacity)] } {
1781        set _settings($tag-opacity) $styles(-opacity)
1782    }
1783    set max 1.0 ;#$_settings($tag-opacity)
1784   
1785    set isovalues {}
1786    foreach m $_isomarkers($tf) {
1787        lappend isovalues [$m relval]
1788    }
1789    # Sort the isovalues
1790    set isovalues [lsort -real $isovalues]
1791
1792    if { ![info exists _settings($tag-thickness)]} {
1793        set _settings($tag-thickness) 0.005
1794    }
1795    set delta $_settings($tag-thickness)
1796
1797    set first [lindex $isovalues 0]
1798    set last [lindex $isovalues end]
1799    set wmap ""
1800    if { $first == "" || $first != 0.0 } {
1801        lappend wmap 0.0 0.0
1802    }
1803    foreach x $isovalues {
1804        set x1 [expr {$x-$delta-0.00001}]
1805        set x2 [expr {$x-$delta}]
1806        set x3 [expr {$x+$delta}]
1807        set x4 [expr {$x+$delta+0.00001}]
1808        if { $x1 < 0.0 } {
1809            set x1 0.0
1810        } elseif { $x1 > 1.0 } {
1811            set x1 1.0
1812        }
1813        if { $x2 < 0.0 } {
1814            set x2 0.0
1815        } elseif { $x2 > 1.0 } {
1816            set x2 1.0
1817        }
1818        if { $x3 < 0.0 } {
1819            set x3 0.0
1820        } elseif { $x3 > 1.0 } {
1821            set x3 1.0
1822        }
1823        if { $x4 < 0.0 } {
1824            set x4 0.0
1825        } elseif { $x4 > 1.0 } {
1826            set x4 1.0
1827        }
1828        # add spikes in the middle
1829        lappend wmap $x1 0.0
1830        lappend wmap $x2 $max
1831        lappend wmap $x3 $max
1832        lappend wmap $x4 0.0
1833    }
1834    if { $last == "" || $last != 1.0 } {
1835        lappend wmap 1.0 0.0
1836    }
1837    SendCmd "transfunc define $tf { $cmap } { $wmap }"
1838    return [SendCmd "$dataobj-$comp configure -transferfunction $tf"]
1839}
1840
1841# ----------------------------------------------------------------------
1842# CONFIGURATION OPTION: -plotbackground
1843# ----------------------------------------------------------------------
1844itcl::configbody Rappture::FlowvisViewer::plotbackground {
1845    if { [isconnected] } {
1846        set color $itk_option(-plotbackground)
1847        set rgb [Color2RGB $color]
1848        SendCmd "screen bgcolor $rgb"
1849        $itk_component(legend) configure -background $color
1850    }
1851}
1852
1853# ----------------------------------------------------------------------
1854# CONFIGURATION OPTION: -plotforeground
1855# ----------------------------------------------------------------------
1856itcl::configbody Rappture::FlowvisViewer::plotforeground {
1857    if { [isconnected] } {
1858        set color $itk_option(-plotforeground)
1859        set rgb [Color2RGB $color]
1860        SendCmd "volume outline color $rgb"
1861        SendCmd "grid axiscolor $rgb"
1862        SendCmd "grid linecolor $rgb"
1863        $itk_component(legend) itemconfigure labels -fill $color
1864        $itk_component(legend) itemconfigure limits -fill $color
1865    }
1866}
1867
1868# ----------------------------------------------------------------------
1869# CONFIGURATION OPTION: -plotoutline
1870# ----------------------------------------------------------------------
1871itcl::configbody Rappture::FlowvisViewer::plotoutline {
1872    # Must check if we are connected because this routine is called from the
1873    # class body when the -plotoutline itk_option is defined.  At that point
1874    # the FlowvisViewer class constructor hasn't been called, so we can't
1875    # start sending commands to visualization server.
1876    if { [isconnected] } {
1877        if {"" == $itk_option(-plotoutline)} {
1878            SendCmd "volume outline state off"
1879        } else {
1880            SendCmd "volume outline state on"
1881            SendCmd "volume outline color [Color2RGB $itk_option(-plotoutline)]"
1882        }
1883    }
1884}
1885
1886#
1887# The -levels option takes a single value that represents the number
1888# of evenly distributed markers based on the current data range. Each
1889# marker is a relative value from 0.0 to 1.0.
1890#
1891itcl::body Rappture::FlowvisViewer::ParseLevelsOption { tf levels } {
1892    set c $itk_component(legend)
1893    regsub -all "," $levels " " levels
1894    if {[string is int $levels]} {
1895        for {set i 1} { $i <= $levels } {incr i} {
1896            set x [expr {double($i)/($levels+1)}]
1897            set m [Rappture::IsoMarker \#auto $c $this $tf]
1898            $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1899            $m relval $x
1900            lappend _isomarkers($tf) $m
1901        }
1902    } else {
1903        foreach x $levels {
1904            set m [Rappture::IsoMarker \#auto $c $this $tf]
1905            $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1906            $m relval $x
1907            lappend _isomarkers($tf) $m
1908        }
1909    }
1910}
1911
1912#
1913# The -markers option takes a list of zero or more values (the values
1914# may be separated either by spaces or commas) that have the following
1915# format:
1916#
1917#   N%  Percent of current total data range.  Converted to
1918#       to a relative value between 0.0 and 1.0.
1919#   N   Absolute value of marker.  If the marker is outside of
1920#       the current range, it will be displayed on the outer
1921#       edge of the legends, but it range it represents will
1922#       not be seen.
1923#
1924itcl::body Rappture::FlowvisViewer::ParseMarkersOption { tf markers } {
1925    set c $itk_component(legend)
1926    regsub -all "," $markers " " markers
1927    foreach marker $markers {
1928        set n [scan $marker "%g%s" value suffix]
1929        if { $n == 2 && $suffix == "%" } {
1930            # ${n}% : Set relative value.
1931            set value [expr {$value * 0.01}]
1932            set m [Rappture::IsoMarker \#auto $c $this $tf]
1933            $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1934            $m relval $value
1935            lappend _isomarkers($tf) $m
1936        } else {
1937            # ${n} : Set absolute value.
1938            set m [Rappture::IsoMarker \#auto $c $this $tf]
1939            $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1940            $m absval $value
1941            lappend _isomarkers($tf) $m
1942        }
1943    }
1944}
1945
1946# ----------------------------------------------------------------------
1947# USAGE: UndateTransferFuncs
1948# ----------------------------------------------------------------------
1949itcl::body Rappture::FlowvisViewer::updateTransferFunctions {} {
1950    $_dispatcher event -after 100 !send_transfunc
1951}
1952
1953itcl::body Rappture::FlowvisViewer::AddIsoMarker { x y } {
1954    if { $_activeTf == "" } {
1955        error "active transfer function isn't set"
1956    }
1957    set tf $_activeTf
1958    set c $itk_component(legend)
1959    set m [Rappture::IsoMarker \#auto $c $this $tf]
1960    $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1961    set w [winfo width $c]
1962    $m relval [expr {double($x-10)/($w-20)}]
1963    lappend _isomarkers($tf) $m
1964    updateTransferFunctions
1965    return 1
1966}
1967
1968itcl::body Rappture::FlowvisViewer::removeDuplicateMarker { marker x } {
1969    set tf [$marker transferfunc]
1970    set bool 0
1971    if { [info exists _isomarkers($tf)] } {
1972        set list {}
1973        set marker [namespace tail $marker]
1974        foreach m $_isomarkers($tf) {
1975            set sx [$m screenpos]
1976            if { $m != $marker } {
1977                if { $x >= ($sx-3) && $x <= ($sx+3) } {
1978                    $marker relval [$m relval]
1979                    itcl::delete object $m
1980                    bell
1981                    set bool 1
1982                    continue
1983                }
1984            }
1985            lappend list $m
1986        }
1987        set _isomarkers($tf) $list
1988        updateTransferFunctions
1989    }
1990    return $bool
1991}
1992
1993itcl::body Rappture::FlowvisViewer::overMarker { marker x } {
1994    set tf [$marker transferfunc]
1995    if { [info exists _isomarkers($tf)] } {
1996        set marker [namespace tail $marker]
1997        foreach m $_isomarkers($tf) {
1998            set sx [$m screenpos]
1999            if { $m != $marker } {
2000                set bool [expr { $x >= ($sx-3) && $x <= ($sx+3) }]
2001                $m activate $bool
2002            }
2003        }
2004    }
2005    return ""
2006}
2007
2008itcl::body Rappture::FlowvisViewer::limits { cname } {
2009    set _limits(v) [list 0.0 1.0]
2010    if { ![info exists _style2objs($cname)] } {
2011        puts stderr "no style2objs for $cname cname=($cname)"
2012        return [array get _limits]
2013    }
2014    set min ""; set max ""
2015    foreach tag [GetDatasetsWithComponent $cname] {
2016        if { ![info exists _serverObjs($tag)] } {
2017            puts stderr "$tag not in serverObjs?"
2018            continue
2019        }
2020        if { ![info exists _limits($tag)] } {
2021            puts stderr "$tag no min?"
2022            continue
2023        }
2024        foreach {vmin vmax} $_limits($tag) break
2025        if { $min == "" || $min > $vmin } {
2026            set min $vmin
2027        }
2028        if { $max == "" || $max < $vmax } {
2029            set max $vmax
2030        }
2031    }
2032    if { $min != "" && $max != "" } {
2033        set _limits(v) [list $min $max]
2034        set _limits($cname) [list $min $max]
2035    }
2036    return $_limits($cname)
2037}
2038
2039itcl::body Rappture::FlowvisViewer::BuildViewTab {} {
2040    foreach { key value } {
2041        grid            0
2042        axes            0
2043        outline         1
2044        volume          1
2045        legend          1
2046        particles       1
2047        lic             1
2048    } {
2049        set _settings($this-$key) $value
2050    }
2051
2052    set fg [option get $itk_component(hull) font Font]
2053    #set bfg [option get $itk_component(hull) boldFont Font]
2054
2055    set inner [$itk_component(main) insert end \
2056        -title "View Settings" \
2057        -icon [Rappture::icon wrench]]
2058    $inner configure -borderwidth 4
2059
2060    set ::Rappture::FlowvisViewer::_settings($this-isosurface) 0
2061    checkbutton $inner.isosurface \
2062        -text "Isosurface shading" \
2063        -variable [itcl::scope _settings($this-isosurface)] \
2064        -command [itcl::code $this AdjustSetting isosurface] \
2065        -font "Arial 9"
2066
2067    checkbutton $inner.axes \
2068        -text "Axes" \
2069        -variable [itcl::scope _settings($this-axes)] \
2070        -command [itcl::code $this AdjustSetting axes] \
2071        -font "Arial 9"
2072
2073    checkbutton $inner.grid \
2074        -text "Grid" \
2075        -variable [itcl::scope _settings($this-grid)] \
2076        -command [itcl::code $this AdjustSetting grid] \
2077        -font "Arial 9"
2078
2079    checkbutton $inner.outline \
2080        -text "Outline" \
2081        -variable [itcl::scope _settings($this-outline)] \
2082        -command [itcl::code $this AdjustSetting outline] \
2083        -font "Arial 9"
2084
2085    checkbutton $inner.legend \
2086        -text "Legend" \
2087        -variable [itcl::scope _settings($this-legend)] \
2088        -command [itcl::code $this AdjustSetting legend] \
2089        -font "Arial 9"
2090
2091    checkbutton $inner.volume \
2092        -text "Volume" \
2093        -variable [itcl::scope _settings($this-volume)] \
2094        -command [itcl::code $this AdjustSetting volume] \
2095        -font "Arial 9"
2096
2097    checkbutton $inner.particles \
2098        -text "Particles" \
2099        -variable [itcl::scope _settings($this-particles)] \
2100        -command [itcl::code $this AdjustSetting particles] \
2101        -font "Arial 9"
2102
2103    checkbutton $inner.lic \
2104        -text "Lic" \
2105        -variable [itcl::scope _settings($this-lic)] \
2106        -command [itcl::code $this AdjustSetting lic] \
2107        -font "Arial 9"
2108
2109    frame $inner.frame
2110
2111    blt::table $inner \
2112        0,0 $inner.axes  -cspan 2 -anchor w \
2113        1,0 $inner.grid  -cspan 2 -anchor w \
2114        2,0 $inner.outline  -cspan 2 -anchor w \
2115        3,0 $inner.volume  -cspan 2 -anchor w \
2116        4,0 $inner.legend  -cspan 2 -anchor w
2117
2118    bind $inner <Map> [itcl::code $this GetFlowInfo $inner]
2119
2120    blt::table configure $inner r* -resize none
2121    blt::table configure $inner r5 -resize expand
2122}
2123
2124itcl::body Rappture::FlowvisViewer::BuildVolumeTab {} {
2125    foreach { key value } {
2126        light2side      1
2127        light           40
2128        transp          50
2129        opacity         100
2130        thickness       350
2131    } {
2132        set _settings($this-$key) $value
2133    }
2134
2135    set inner [$itk_component(main) insert end \
2136        -title "Volume Settings" \
2137        -icon [Rappture::icon volume-on]]
2138    $inner configure -borderwidth 4
2139
2140    set fg [option get $itk_component(hull) font Font]
2141    #set bfg [option get $itk_component(hull) boldFont Font]
2142
2143    checkbutton $inner.vol -text "Show volume" -font $fg \
2144        -text "Volume" \
2145        -variable [itcl::scope _settings($this-volume)] \
2146        -command [itcl::code $this AdjustSetting volume] \
2147        -font "Arial 9"
2148
2149    label $inner.shading -text "Shading:" -font $fg
2150
2151    checkbutton $inner.light2side -text "Two-sided lighting" -font $fg \
2152        -variable [itcl::scope _settings($this-light2side)] \
2153        -command [itcl::code $this AdjustSetting light2side]
2154
2155    label $inner.dim -text "Glow" -font $fg
2156    ::scale $inner.light -from 0 -to 100 -orient horizontal \
2157        -variable [itcl::scope _settings($this-light)] \
2158        -width 10 \
2159        -showvalue off -command [itcl::code $this AdjustSetting light]
2160    label $inner.bright -text "Surface" -font $fg
2161
2162    label $inner.fog -text "Clear" -font $fg
2163    ::scale $inner.transp -from 0 -to 100 -orient horizontal \
2164        -variable [itcl::scope _settings($this-transp)] \
2165        -width 10 \
2166        -showvalue off -command [itcl::code $this AdjustSetting transp]
2167    label $inner.plastic -text "Opaque" -font $fg
2168
2169    label $inner.clear -text "Clear" -font $fg
2170    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
2171        -variable [itcl::scope _settings($this-opacity)] \
2172        -width 10 \
2173        -showvalue off -command [itcl::code $this AdjustSetting opacity]
2174    label $inner.opaque -text "Opaque" -font $fg
2175
2176    label $inner.thin -text "Thin" -font $fg
2177    ::scale $inner.thickness -from 0 -to 1000 -orient horizontal \
2178        -variable [itcl::scope _settings($this-thickness)] \
2179        -width 10 \
2180        -showvalue off -command [itcl::code $this AdjustSetting thickness]
2181    label $inner.thick -text "Thick" -font $fg
2182
2183    label $inner.colormap_l -text "Colormap" -font "Arial 9"
2184    itk_component add colormap {
2185        Rappture::Combobox $inner.colormap -width 10 -editable no
2186    }
2187
2188    $inner.colormap choices insert end [GetColormapList -includeNone]
2189    $itk_component(colormap) value "BCGYR"
2190    bind $inner.colormap <<Value>> \
2191        [itcl::code $this AdjustSetting colormap]
2192
2193    blt::table $inner \
2194        0,0 $inner.vol -cspan 4 -anchor w -pady 2 \
2195        1,0 $inner.shading -cspan 4 -anchor w -pady {10 2} \
2196        2,0 $inner.light2side -cspan 4 -anchor w -pady 2 \
2197        3,0 $inner.dim -anchor e -pady 2 \
2198        3,1 $inner.light -cspan 2 -pady 2 -fill x \
2199        3,3 $inner.bright -anchor w -pady 2 \
2200        4,0 $inner.fog -anchor e -pady 2 \
2201        4,1 $inner.transp -cspan 2 -pady 2 -fill x \
2202        4,3 $inner.plastic -anchor w -pady 2 \
2203        5,0 $inner.thin -anchor e -pady 2 \
2204        5,1 $inner.thickness -cspan 2 -pady 2 -fill x\
2205        5,3 $inner.thick -anchor w -pady 2
2206
2207    blt::table configure $inner c0 c1 c3 r* -resize none
2208    blt::table configure $inner r6 -resize expand
2209}
2210
2211itcl::body Rappture::FlowvisViewer::BuildCutplanesTab {} {
2212    set inner [$itk_component(main) insert end \
2213        -title "Cutplane Settings" \
2214        -icon [Rappture::icon cutbutton]]
2215    $inner configure -borderwidth 4
2216
2217    # X-value slicer...
2218    itk_component add xCutButton {
2219        Rappture::PushButton $inner.xbutton \
2220            -onimage [Rappture::icon x-cutplane] \
2221            -offimage [Rappture::icon x-cutplane] \
2222            -command [itcl::code $this AdjustSetting xcutplane] \
2223            -variable [itcl::scope _settings($this-xcutplane)]
2224    }
2225    Rappture::Tooltip::for $itk_component(xCutButton) \
2226        "Toggle the X cut plane on/off"
2227
2228    itk_component add xCutScale {
2229        ::scale $inner.xval -from 100 -to 0 \
2230            -width 10 -orient vertical -showvalue off \
2231            -borderwidth 1 -highlightthickness 0 \
2232            -command [itcl::code $this Slice move x] \
2233            -variable [itcl::scope _settings($this-xcutposition)]
2234    } {
2235        usual
2236        ignore -borderwidth -highlightthickness
2237    }
2238    # Set the default cutplane value before disabling the scale.
2239    $itk_component(xCutScale) set 50
2240    $itk_component(xCutScale) configure -state disabled
2241    Rappture::Tooltip::for $itk_component(xCutScale) \
2242        "@[itcl::code $this SlicerTip x]"
2243
2244    # Y-value slicer...
2245    itk_component add yCutButton {
2246        Rappture::PushButton $inner.ybutton \
2247            -onimage [Rappture::icon y-cutplane] \
2248            -offimage [Rappture::icon y-cutplane] \
2249            -command [itcl::code $this AdjustSetting ycutplane] \
2250            -variable [itcl::scope _settings($this-ycutplane)]
2251    }
2252    Rappture::Tooltip::for $itk_component(yCutButton) \
2253        "Toggle the Y cut plane on/off"
2254
2255    itk_component add yCutScale {
2256        ::scale $inner.yval -from 100 -to 0 \
2257            -width 10 -orient vertical -showvalue off \
2258            -borderwidth 1 -highlightthickness 0 \
2259            -command [itcl::code $this Slice move y] \
2260            -variable [itcl::scope _settings($this-ycutposition)]
2261    } {
2262        usual
2263        ignore -borderwidth -highlightthickness
2264    }
2265    Rappture::Tooltip::for $itk_component(yCutScale) \
2266        "@[itcl::code $this SlicerTip y]"
2267    # Set the default cutplane value before disabling the scale.
2268    $itk_component(yCutScale) set 50
2269    $itk_component(yCutScale) configure -state disabled
2270
2271    # Z-value slicer...
2272    itk_component add zCutButton {
2273        Rappture::PushButton $inner.zbutton \
2274            -onimage [Rappture::icon z-cutplane] \
2275            -offimage [Rappture::icon z-cutplane] \
2276            -command [itcl::code $this AdjustSetting zcutplane] \
2277            -variable [itcl::scope _settings($this-zcutplane)]
2278    }
2279    Rappture::Tooltip::for $itk_component(zCutButton) \
2280        "Toggle the Z cut plane on/off"
2281
2282    itk_component add zCutScale {
2283        ::scale $inner.zval -from 100 -to 0 \
2284            -width 10 -orient vertical -showvalue off \
2285            -borderwidth 1 -highlightthickness 0 \
2286            -command [itcl::code $this Slice move z] \
2287            -variable [itcl::scope _settings($this-zcutposition)]
2288    } {
2289        usual
2290        ignore -borderwidth -highlightthickness
2291    }
2292    $itk_component(zCutScale) set 50
2293    $itk_component(zCutScale) configure -state disabled
2294    #$itk_component(zCutScale) configure -state disabled
2295    Rappture::Tooltip::for $itk_component(zCutScale) \
2296        "@[itcl::code $this SlicerTip z]"
2297
2298    blt::table $inner \
2299        1,1 $itk_component(xCutButton) \
2300        1,2 $itk_component(yCutButton) \
2301        1,3 $itk_component(zCutButton) \
2302        0,1 $itk_component(xCutScale) \
2303        0,2 $itk_component(yCutScale) \
2304        0,3 $itk_component(zCutScale) \
2305
2306    blt::table configure $inner r0 r1 c* -resize none
2307    blt::table configure $inner r2 c4 -resize expand
2308    blt::table configure $inner c0 -width 2
2309    blt::table configure $inner c1 c2 c3 -padx 2
2310}
2311
2312itcl::body Rappture::FlowvisViewer::BuildCameraTab {} {
2313    set inner [$itk_component(main) insert end \
2314        -title "Camera Settings" \
2315        -icon [Rappture::icon camera]]
2316    $inner configure -borderwidth 4
2317
2318    label $inner.view_l -text "view" -font "Arial 9"
2319    set f [frame $inner.view]
2320    foreach side { front back left right top bottom } {
2321        button $f.$side  -image [Rappture::icon view$side] \
2322            -command [itcl::code $this SetOrientation $side]
2323        Rappture::Tooltip::for $f.$side "Change the view to $side"
2324        pack $f.$side -side left
2325    }
2326
2327    blt::table $inner \
2328        0,0 $inner.view_l -anchor e -pady 2 \
2329        0,1 $inner.view -anchor w -pady 2
2330
2331    set row 1
2332    set labels { qw qx qy qz xpan ypan zoom }
2333    foreach tag $labels {
2334        label $inner.${tag}label -text $tag -font "Arial 9"
2335        entry $inner.${tag} -font "Arial 9"  -bg white \
2336            -textvariable [itcl::scope _settings($this-$tag)]
2337        bind $inner.${tag} <KeyPress-Return> \
2338            [itcl::code $this camera set ${tag}]
2339        blt::table $inner \
2340            $row,0 $inner.${tag}label -anchor e -pady 2 \
2341            $row,1 $inner.${tag} -anchor w -pady 2
2342        blt::table configure $inner r$row -resize none
2343        incr row
2344    }
2345
2346    blt::table configure $inner c* r* -resize none
2347    blt::table configure $inner c2 -resize expand
2348    blt::table configure $inner r$row -resize expand
2349}
2350
2351itcl::body Rappture::FlowvisViewer::GetFlowInfo { w } {
2352    set flowobj ""
2353    foreach key [array names _obj2flow] {
2354        set flowobj $_obj2flow($key)
2355        break
2356    }
2357    if { $flowobj == "" } {
2358        return
2359    }
2360    if { [winfo exists $w.frame] } {
2361        destroy $w.frame
2362    }
2363    set inner [frame $w.frame]
2364    blt::table $w \
2365        5,0 $inner -fill both -cspan 2 -anchor nw
2366    array set hints [$flowobj hints]
2367    checkbutton $inner.showstreams -text "Streams Plane" \
2368        -variable [itcl::scope _settings($this-streams)] \
2369        -command  [itcl::code $this streams $key $hints(name)]  \
2370        -font "Arial 9"
2371    Rappture::Tooltip::for $inner.showstreams $hints(description)
2372
2373    checkbutton $inner.showarrows -text "Arrows" \
2374        -variable [itcl::scope _settings($this-arrows)] \
2375        -command  [itcl::code $this arrows $key $hints(name)]  \
2376        -font "Arial 9"
2377
2378    label $inner.particles -text "Particles"         -font "Arial 9 bold"
2379    label $inner.boxes -text "Boxes"         -font "Arial 9 bold"
2380
2381    blt::table $inner \
2382        1,0 $inner.showstreams  -anchor w \
2383        2,0 $inner.showarrows  -anchor w
2384    blt::table configure $inner c0 c1 -resize none
2385    blt::table configure $inner c2 -resize expand
2386
2387    set row 3
2388    set particles [$flowobj particles]
2389    if { [llength $particles] > 0 } {
2390        blt::table $inner $row,0 $inner.particles  -anchor w
2391        incr row
2392    }
2393    foreach part $particles {
2394        array unset info
2395        array set info $part
2396        set name $info(name)
2397        if { ![info exists _settings($this-particles-$name)] } {
2398            set _settings($this-particles-$name) $info(hide)
2399        }
2400        checkbutton $inner.part$row -text $info(label) \
2401            -variable [itcl::scope _settings($this-particles-$name)] \
2402            -onvalue 0 -offvalue 1 \
2403            -command [itcl::code $this particles $key $name] \
2404            -font "Arial 9"
2405        Rappture::Tooltip::for $inner.part$row $info(description)
2406        blt::table $inner $row,0 $inner.part$row -anchor w
2407        if { !$_settings($this-particles-$name) } {
2408            $inner.part$row select
2409        }
2410        incr row
2411    }
2412    set boxes [$flowobj boxes]
2413    if { [llength $boxes] > 0 } {
2414        blt::table $inner $row,0 $inner.boxes  -anchor w
2415        incr row
2416    }
2417    foreach box $boxes {
2418        array unset info
2419        array set info $box
2420        set name $info(name)
2421        if { ![info exists _settings($this-box-$name)] } {
2422            set _settings($this-box-$name) $info(hide)
2423        }
2424        checkbutton $inner.box$row -text $info(label) \
2425            -variable [itcl::scope _settings($this-box-$name)] \
2426            -onvalue 0 -offvalue 1 \
2427            -command [itcl::code $this box $key $name] \
2428            -font "Arial 9"
2429        Rappture::Tooltip::for $inner.box$row $info(description)
2430        blt::table $inner $row,0 $inner.box$row -anchor w
2431        if { !$_settings($this-box-$name) } {
2432            $inner.box$row select
2433        }
2434        incr row
2435    }
2436    blt::table configure $inner r* -resize none
2437    blt::table configure $inner r$row -resize expand
2438    blt::table configure $inner c3 -resize expand
2439    event generate [winfo parent [winfo parent $w]] <Configure>
2440}
2441
2442itcl::body Rappture::FlowvisViewer::particles { tag name } {
2443    set bool $_settings($this-particles-$name)
2444    SendCmd "$tag particles configure {$name} -hide $bool"
2445}
2446
2447itcl::body Rappture::FlowvisViewer::box { tag name } {
2448    set bool $_settings($this-box-$name)
2449    SendCmd "$tag box configure {$name} -hide $bool"
2450}
2451
2452itcl::body Rappture::FlowvisViewer::streams { tag name } {
2453    set bool $_settings($this-streams)
2454    SendCmd "$tag configure -slice $bool"
2455}
2456
2457itcl::body Rappture::FlowvisViewer::arrows { tag name } {
2458    set bool $_settings($this-arrows)
2459    SendCmd "$tag configure -arrows $bool"
2460}
2461
2462# ----------------------------------------------------------------------
2463# USAGE: Slice move x|y|z <newval>
2464#
2465# Called automatically when the user drags the slider to move the
2466# cut plane that slices 3D data.  Gets the current value from the
2467# slider and moves the cut plane to the appropriate point in the
2468# data set.
2469# ----------------------------------------------------------------------
2470itcl::body Rappture::FlowvisViewer::Slice {option args} {
2471    switch -- $option {
2472        move {
2473            if {[llength $args] != 2} {
2474                error "wrong # args: should be \"Slice move x|y|z newval\""
2475            }
2476            set axis [lindex $args 0]
2477            set newval [lindex $args 1]
2478            set newpos [expr {0.01*$newval}]
2479
2480            # show the current value in the readout
2481
2482            set ids [CurrentVolumeIds -cutplanes]
2483            SendCmd "cutplane position $newpos $axis $ids"
2484        }
2485        default {
2486            error "bad option \"$option\": should be axis, move, or volume"
2487        }
2488    }
2489}
2490
2491# ----------------------------------------------------------------------
2492# USAGE: SlicerTip <axis>
2493#
2494# Used internally to generate a tooltip for the x/y/z slicer controls.
2495# Returns a message that includes the current slicer value.
2496# ----------------------------------------------------------------------
2497itcl::body Rappture::FlowvisViewer::SlicerTip {axis} {
2498    set val [$itk_component(${axis}CutScale) get]
2499    return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2500}
2501
2502itcl::body Rappture::FlowvisViewer::Resize {} {
2503    $_arcball resize $_width $_height
2504    SendCmd "screen size $_width $_height"
2505    set _resizePending 0
2506}
2507
2508itcl::body Rappture::FlowvisViewer::EventuallyResize { w h } {
2509    set _width $w
2510    set _height $h
2511    $_arcball resize $w $h
2512    if { !$_resizePending } {
2513        $_dispatcher event -after 200 !resize
2514        set _resizePending 1
2515    }
2516}
2517
2518itcl::body Rappture::FlowvisViewer::EventuallyResizeLegend {} {
2519    if { !$_resizeLegendPending } {
2520        $_dispatcher event -after 100 !legend
2521        set _resizeLegendPending 1
2522    }
2523}
2524
2525itcl::body Rappture::FlowvisViewer::EventuallyGoto { nSteps } {
2526    set _flow(goto) $nSteps
2527    if { !$_gotoPending } {
2528        $_dispatcher event -after 1000 !goto
2529        set _gotoPending 1
2530    }
2531}
2532
2533#  camera --
2534itcl::body Rappture::FlowvisViewer::camera {option args} {
2535    switch -- $option {
2536        "show" {
2537            puts [array get _view]
2538        }
2539        "set" {
2540            set who [lindex $args 0]
2541            set x $_settings($this-$who)
2542            set code [catch { string is double $x } result]
2543            if { $code != 0 || !$result } {
2544                set _settings($this-$who) $_view($who)
2545                return
2546            }
2547            switch -- $who {
2548                "xpan" - "ypan" {
2549                    set _view($who) $_settings($this-$who)
2550                    PanCamera
2551                }
2552                "qx" - "qy" - "qz" - "qw" {
2553                    set _view($who) $_settings($this-$who)
2554                    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2555                    $_arcball quaternion $q
2556                    SendCmd "camera orient $q"
2557                }
2558                "zoom" {
2559                    set _view($who) $_settings($this-$who)
2560                    SendCmd "camera zoom $_view(zoom)"
2561                }
2562            }
2563        }
2564    }
2565}
2566
2567itcl::body Rappture::FlowvisViewer::FlowCmd { dataobj comp nbytes extents } {
2568    set tag "$dataobj-$comp"
2569    if { ![info exists _obj2flow($tag)] } {
2570        append cmd "flow add $tag\n"
2571        append cmd "$tag data follows $nbytes $extents\n"
2572        return $cmd
2573    }
2574    set flowobj $_obj2flow($tag)
2575    if { $flowobj == "" } {
2576        puts stderr "no flowobj"
2577        return ""
2578    }
2579    set cmd {}
2580    append cmd "if {\[flow exists $tag\]} {flow delete $tag}\n"
2581    array set info  [$flowobj hints]
2582    set _settings($this-volume) $info(volume)
2583    set _settings($this-outline) $info(outline)
2584    set _settings($this-arrows) $info(arrows)
2585    set _settings($this-duration) $info(duration)
2586    $itk_component(speed) value $info(speed)
2587    append cmd "flow add $tag"
2588    append cmd " -position $info(position)"
2589    append cmd " -axis $info(axis)"
2590    append cmd " -volume $info(volume)"
2591    append cmd " -outline $info(outline)"
2592    append cmd " -slice $info(streams)"
2593    append cmd " -arrows $info(arrows)\n"
2594    foreach part [$flowobj particles] {
2595        array unset info
2596        array set info $part
2597        set color [Color2RGB $info(color)]
2598        append cmd "$tag particles add $info(name)"
2599        append cmd " -position $info(position)"
2600        append cmd " -hide $info(hide)"
2601        append cmd " -axis $info(axis)"
2602        append cmd " -color {$color}"
2603        append cmd " -size $info(size)\n"
2604    }
2605    foreach box [$flowobj boxes] {
2606        array unset info
2607        set info(corner1) ""
2608        set info(corner2) ""
2609        array set info $box
2610        if { $info(corner1) == "" || $info(corner2) == "" } {
2611            continue
2612        }
2613        set color [Color2RGB $info(color)]
2614        append cmd "$tag box add $info(name)"
2615        append cmd " -color {$color}"
2616        append cmd " -hide $info(hide)"
2617        append cmd " -linewidth $info(linewidth) "
2618        append cmd " -corner1 {$info(corner1)} "
2619        append cmd " -corner2 {$info(corner2)}\n"
2620    }   
2621    append cmd "$tag data follows $nbytes $extents\n"
2622    return $cmd
2623}
2624
2625
2626#
2627# flow --
2628#
2629# Called when the user clicks on the stop or play buttons
2630# for flow visualization.
2631#
2632#        $this flow play
2633#        $this flow stop
2634#        $this flow toggle
2635#        $this flow reset
2636#        $this flow pause
2637#        $this flow next
2638#
2639itcl::body Rappture::FlowvisViewer::flow { args } {
2640    set option [lindex $args 0]
2641    switch -- $option {
2642        "goto2" {
2643            puts stderr "actually sending \"flow goto $_flow(goto)\""
2644            SendCmd "flow goto $_flow(goto)"
2645            set _gotoPending 0
2646        }
2647        "goto" {
2648            puts stderr "flow goto to $_settings($this-currenttime)"
2649            # Figure out how many steps to the current time based upon
2650            # the speed and duration.
2651            set current $_settings($this-currenttime)
2652            set speed [$itk_component(speed) value]
2653            set time [str2millisecs $_settings($this-duration)]
2654            $itk_component(dial) configure -max $time
2655            set delay [expr int(round(500.0/$speed))]
2656            set timePerStep [expr {double($time) / $delay}]
2657            set nSteps [expr {int(ceil($current/$timePerStep))}]
2658            EventuallyGoto $nSteps
2659        }
2660        "speed" {
2661            set speed [$itk_component(speed) value]
2662            set _flow(delay) [expr int(round(500.0/$speed))]
2663        }
2664        "duration" {
2665            set max [str2millisecs $_settings($this-duration)]
2666            if { $max < 0 } {
2667                bell
2668                return
2669            }
2670            set _flow(duration) $max
2671            set _settings($this-duration) [millisecs2str $max]
2672            $itk_component(dial) configure -max $max
2673        }
2674        "off" {
2675            set _flow(state) 0
2676            $_dispatcher cancel !play
2677            $itk_component(play) deselect
2678        }
2679        "on" {
2680            flow speed
2681            flow duration
2682            set _flow(state) 1
2683            set _settings($this-currenttime) 0
2684            $itk_component(play) select
2685        }
2686        "stop" {
2687            if { $_flow(state) } {
2688                flow off
2689                flow reset
2690            }
2691        }
2692        "pause" {
2693            if { $_flow(state) } {
2694                flow off
2695            }
2696        }
2697        "play" {
2698            # If the flow is currently off, then restart it.
2699            if { !$_flow(state) } {
2700                flow on
2701                # If we're at the end of the flow, reset the flow.
2702                set _settings($this-currenttime) \
2703                    [expr {$_settings($this-currenttime) + $_flow(delay)}]
2704                if { $_settings($this-currenttime) >= $_flow(duration) } {
2705                    set _settings($this-step) 1
2706                    SendCmd "flow reset"
2707                }
2708                flow next
2709            }
2710        }
2711        "toggle" {
2712            if { $_settings($this-play) } {
2713                flow play
2714            } else {
2715                flow pause
2716            }
2717        }
2718        "reset" {
2719            set _settings($this-currenttime) 0
2720            SendCmd "flow reset"
2721        }
2722        "next" {
2723            if { ![winfo viewable $itk_component(3dview)] } {
2724                flow stop
2725                return
2726            }
2727            set _settings($this-currenttime) \
2728                [expr {$_settings($this-currenttime) + $_flow(delay)}]
2729            if { $_settings($this-currenttime) >= $_flow(duration) } {
2730                if { !$_settings($this-loop) } {
2731                    flow off
2732                    return
2733                }
2734                flow reset
2735            } else {
2736                SendCmd "flow next"
2737            }
2738            $_dispatcher event -after $_flow(delay) !play
2739        }
2740        default {
2741            error "bad option \"$option\": should be play, stop, toggle, or reset."
2742        }
2743    }
2744}
2745
2746itcl::body Rappture::FlowvisViewer::WaitIcon  { option widget } {
2747    switch -- $option {
2748        "start" {
2749            $_dispatcher dispatch $this !waiticon \
2750                "[itcl::code $this WaitIcon "next" $widget] ; list"
2751            set _icon 0
2752            $widget configure -image [Rappture::icon bigroller${_icon}]
2753            $_dispatcher event -after 100 !waiticon
2754        }
2755        "next" {
2756            incr _icon
2757            if { $_icon >= 8 } {
2758                set _icon 0
2759            }
2760            $widget configure -image [Rappture::icon bigroller${_icon}]
2761            $_dispatcher event -after 100 !waiticon
2762        }
2763        "stop" {
2764            $_dispatcher cancel !waiticon
2765        }
2766    }
2767}
2768
2769itcl::body Rappture::FlowvisViewer::GetPngImage  { widget width height } {
2770    set token "print[incr _nextToken]"
2771    set var ::Rappture::FlowvisViewer::_hardcopy($this-$token)
2772    set $var ""
2773
2774    # Setup an automatic timeout procedure.
2775    $_dispatcher dispatch $this !pngtimeout "set $var {} ; list"
2776
2777    set popup .flowvisviewerprint
2778    if {![winfo exists $popup]} {
2779        Rappture::Balloon $popup -title "Generating file..."
2780        set inner [$popup component inner]
2781        label $inner.title -text "Generating hardcopy." -font "Arial 10 bold"
2782        label $inner.please -text "This may take a minute." -font "Arial 10"
2783        label $inner.icon -image [Rappture::icon bigroller0]
2784        button $inner.cancel -text "Cancel" -font "Arial 10 bold" \
2785            -command [list set $var ""]
2786        blt::table $inner \
2787            0,0 $inner.title -cspan 2 \
2788            1,0 $inner.please -anchor w \
2789            1,1 $inner.icon -anchor e  \
2790            2,0 $inner.cancel -cspan 2
2791        blt::table configure $inner r0 -pady 4
2792        blt::table configure $inner r2 -pady 4
2793        bind $inner.cancel <KeyPress-Return> [list $inner.cancel invoke]
2794    } else {
2795        set inner [$popup component inner]
2796    }
2797
2798    $_dispatcher event -after 60000 !pngtimeout
2799    WaitIcon start $inner.icon
2800    grab set $inner
2801    focus $inner.cancel
2802
2803    SendCmd "print $token $width $height"
2804
2805    $popup activate $widget below
2806    update idletasks
2807    update
2808    # We wait here for either
2809    #  1) the png to be delivered or
2810    #  2) timeout or 
2811    #  3) user cancels the operation.
2812    tkwait variable $var
2813
2814    # Clean up.
2815    $_dispatcher cancel !pngtimeout
2816    WaitIcon stop $inner.icon
2817    grab release $inner
2818    $popup deactivate
2819    update
2820
2821    if { $_hardcopy($this-$token) != "" } {
2822        return [list .png $_hardcopy($this-$token)]
2823    }
2824    return ""
2825}
2826
2827itcl::body Rappture::FlowvisViewer::GetMovie { widget w h } {
2828    set token "movie[incr _nextToken]"
2829    set var ::Rappture::FlowvisViewer::_hardcopy($this-$token)
2830    set $var ""
2831
2832    # Setup an automatic timeout procedure.
2833    $_dispatcher dispatch $this !movietimeout "set $var {} ; list"
2834    set popup .flowvisviewermovie
2835    if {![winfo exists $popup]} {
2836        Rappture::Balloon $popup -title "Generating movie..."
2837        set inner [$popup component inner]
2838        label $inner.title -text "Generating movie for download" \
2839                -font "Arial 10 bold"
2840        label $inner.please -text "This may take a few minutes." \
2841                -font "Arial 10"
2842        label $inner.icon -image [Rappture::icon bigroller0]
2843        button $inner.cancel -text "Cancel" -font "Arial 10 bold" \
2844            -command [list set $var ""]
2845        blt::table $inner \
2846            0,0 $inner.title -cspan 2 \
2847            1,0 $inner.please -anchor w \
2848            1,1 $inner.icon -anchor e  \
2849            2,0 $inner.cancel -cspan 2
2850        blt::table configure $inner r0 -pady 4
2851        blt::table configure $inner r2 -pady 4
2852        bind $inner.cancel <KeyPress-Return> [list $inner.cancel invoke]
2853    } else {
2854        set inner [$popup component inner]
2855    }
2856    update
2857    # Timeout is set to 10 minutes.
2858    $_dispatcher event -after 600000 !movietimeout
2859    WaitIcon start $inner.icon
2860    grab set $inner
2861    focus $inner.cancel
2862   
2863    flow duration
2864    flow speed
2865    set nframes [expr round($_flow(duration) / $_flow(delay))]
2866    set framerate [expr 1000.0 / $_flow(delay)]
2867
2868    # These are specific to MPEG1 video generation
2869    set framerate 25.0
2870    set bitrate 6.0e+6
2871
2872    set start [clock seconds]
2873    SendCmd "flow video $token -width $w -height $h -numframes $nframes "
2874   
2875    $popup activate $widget below
2876    update idletasks
2877    update
2878    # We wait here until
2879    #  1. the movie is delivered or
2880    #  2. we've timed out or 
2881    #  3. the user has canceled the operation.b
2882    tkwait variable $var
2883
2884    puts stderr "Video generated in [expr [clock seconds] - $start] seconds."
2885
2886    # Clean up.
2887    $_dispatcher cancel !movietimeout
2888    WaitIcon stop $inner.icon
2889    grab release $inner
2890    $popup deactivate
2891    destroy $popup
2892    update
2893
2894    # This will both cancel the movie generation (if it hasn't already
2895    # completed) and reset the flow.
2896    SendCmd "flow reset"
2897    if { $_hardcopy($this-$token) != "" } {
2898        return [list .mpg $_hardcopy($this-$token)]
2899    }
2900    return ""
2901}
2902
2903itcl::body Rappture::FlowvisViewer::str2millisecs { value } {
2904    set parts [split $value :]
2905    set secs 0
2906    set mins 0
2907    if { [llength $parts] == 1 } {
2908        scan [lindex $parts 0] "%d" secs
2909    } else {
2910        scan [lindex $parts 1] "%d" secs
2911        scan [lindex $parts 0] "%d" mins
2912    }
2913    set ms [expr {(($mins * 60) + $secs) * 1000.0}]
2914    if { $ms > 600000.0 } {
2915        set ms 600000.0
2916    }
2917    if { $ms == 0.0 } {
2918        set ms 60000.0
2919    }
2920    return $ms
2921}
2922
2923itcl::body Rappture::FlowvisViewer::millisecs2str { value } {
2924    set min [expr floor($value / 60000.0)]
2925    set sec [expr ($value - ($min*60000.0)) / 1000.0]
2926    return [format %02d:%02d [expr round($min)] [expr round($sec)]]
2927}
2928
2929itcl::body Rappture::FlowvisViewer::SetOrientation { side } {
2930    array set positions {
2931        front "1 0 0 0"
2932        back  "0 0 1 0"
2933        left  "0.707107 0 -0.707107 0"
2934        right "0.707107 0 0.707107 0"
2935        top   "0.707107 -0.707107 0 0"
2936        bottom "0.707107 0.707107 0 0"
2937    }
2938    foreach name { qw qx qy qz } value $positions($side) {
2939        set _view($name) $value
2940    }
2941    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2942    $_arcball quaternion $q
2943    SendCmd "camera orient $q"
2944    SendCmd "camera reset"
2945    set _view(xpan) 0.0
2946    set _view(ypan) 0.0
2947    set _view(zoom) 1.0
2948    set _settings($this-xpan) $_view(xpan)
2949    set _settings($this-ypan) $_view(ypan)
2950    set _settings($this-zoom) $_view(zoom)
2951}
2952
2953# Reset global settings from dataset's settings.
2954itcl::body Rappture::FlowvisViewer::BuildVolumeComponents {} {
2955    $itk_component(volcomponents) choices delete 0 end
2956    foreach name $_componentsList {
2957        $itk_component(volcomponents) choices insert end $name $name
2958    }
2959    set _current [lindex $_componentsList 0]
2960    $itk_component(volcomponents) value $_current
2961}
2962
2963# Reset global settings from dataset's settings.
2964itcl::body Rappture::FlowvisViewer::GetDatasetsWithComponent { cname } {
2965    if { ![info exists _volcomponents($cname)] } {
2966        return ""
2967    }
2968    set list ""
2969    foreach tag $_volcomponents($cname) {
2970        if { ![info exists _serverObjs($tag)] } {
2971            continue
2972        }
2973        lappend list $tag
2974    }
2975    return $list
2976}
Note: See TracBrowser for help on using the repository browser.