source: trunk/gui/scripts/flowvisviewer.tcl

Last change on this file was 6675, checked in by ldelgass, 8 years ago

Revert volume viewer changes to release branch versions

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