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

Last change on this file since 3392 was 3392, checked in by gah, 12 years ago

fixes for new stats file

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