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

Last change on this file since 5273 was 5273, checked in by ldelgass, 5 years ago

Remove unused method/event, cleanups

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