source: branches/1.7/gui/scripts/flowvisviewer.tcl @ 6306

Last change on this file since 6306 was 6306, checked in by ldelgass, 6 years ago

merge fixes from trunk

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