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

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

Refactor _settings array in flowvisviewer: make it an obj. member variable,
remove $this from settings names

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