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

Last change on this file since 4759 was 4759, checked in by ldelgass, 10 years ago

merge r4756:4758 from trunk

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