source: branches/1.3/gui/scripts/flowvisviewer.tcl @ 4766

Last change on this file since 4766 was 4766, checked in by ldelgass, 10 years ago

merge r4765 from trunk

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