source: trunk/gui/scripts/flowvisviewer.tcl @ 3947

Last change on this file since 3947 was 3947, checked in by ldelgass, 11 years ago

Remove unused method/event, send VTK data when blob isn't defined: we should
probably use the type method of the dataobj, but this method isn't currently
reliable or well-defined: is it the incoming type of data or the outgoing,
converted type of data? What is the enum of possible values?

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