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

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

whitespace

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