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

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

Enable the wait animation in all nanovis and vtkvis viewers

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