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

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

remove unused variables

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