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

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

Collapse redundant transp/opacity settings in flowvisviewer in place of single
opacity setting.

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