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

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

Merge opacity fixes for flowvisviewer from trunk

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