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

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

Use type method of field in flowvisviewer to determine data format

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