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

Last change on this file since 5110 was 5110, checked in by ldelgass, 9 years ago

merge r5092:r5097 from trunk (includes fix for viewer initial canvas size)

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