source: trunk/gui/scripts/vtkisosurfaceviewer.tcl @ 4343

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

Fix background,isolinecolor settings

File size: 86.5 KB
Line 
1# -*- mode: tcl; indent-tabs-mode: nil -*-
2# ----------------------------------------------------------------------
3#  COMPONENT: vtkisosurfaceviewer - Vtk 3D contour object viewer
4#
5#  It connects to the Vtk server running on a rendering farm,
6#  transmits data, and displays the results.
7# ======================================================================
8#  AUTHOR:  Michael McLennan, Purdue University
9#  Copyright (c) 2004-2005  Purdue Research Foundation
10#
11#  See the file "license.terms" for information on usage and
12#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13# ======================================================================
14package require Itk
15package require BLT
16#package require Img
17
18option add *VtkIsosurfaceViewer.width 4i widgetDefault
19option add *VtkIsosurfaceViewer*cursor crosshair widgetDefault
20option add *VtkIsosurfaceViewer.height 4i widgetDefault
21option add *VtkIsosurfaceViewer.foreground black widgetDefault
22option add *VtkIsosurfaceViewer.controlBackground gray widgetDefault
23option add *VtkIsosurfaceViewer.controlDarkBackground #999999 widgetDefault
24option add *VtkIsosurfaceViewer.plotBackground black widgetDefault
25option add *VtkIsosurfaceViewer.plotForeground white widgetDefault
26option add *VtkIsosurfaceViewer.font \
27    -*-helvetica-medium-r-normal-*-12-* widgetDefault
28
29# must use this name -- plugs into Rappture::resources::load
30proc VtkIsosurfaceViewer_init_resources {} {
31    Rappture::resources::register \
32        vtkvis_server Rappture::VtkIsosurfaceViewer::SetServerList
33}
34
35itcl::class Rappture::VtkIsosurfaceViewer {
36    inherit Rappture::VisViewer
37
38    itk_option define -plotforeground plotForeground Foreground ""
39    itk_option define -plotbackground plotBackground Background ""
40
41    constructor { hostlist args } {
42        Rappture::VisViewer::constructor $hostlist
43    } {
44        # defined below
45    }
46    destructor {
47        # defined below
48    }
49    public proc SetServerList { namelist } {
50        Rappture::VisViewer::SetServerList "vtkvis" $namelist
51    }
52    public method add {dataobj {settings ""}}
53    public method camera {option args}
54    public method delete {args}
55    public method disconnect {}
56    public method download {option args}
57    public method get {args}
58    public method isconnected {}
59    public method limits { colormap }
60    public method parameters {title args} {
61        # do nothing
62    }
63    public method scale {args}
64
65    protected method Connect {}
66    protected method CurrentDatasets {args}
67    protected method Disconnect {}
68    protected method DoResize {}
69    protected method DoRotate {}
70    protected method AdjustSetting {what {value ""}}
71    protected method InitSettings { args  }
72    protected method Pan {option x y}
73    protected method Pick {x y}
74    protected method Rebuild {}
75    protected method ReceiveDataset { args }
76    protected method ReceiveImage { args }
77    protected method ReceiveLegend { colormap title vmin vmax size }
78    protected method Rotate {option x y}
79    protected method Zoom {option}
80
81    # The following methods are only used by this class.
82    private method BuildAxisTab {}
83    private method BuildCameraTab {}
84    private method BuildColormap { name }
85    private method BuildCutplaneTab {}
86    private method BuildDownloadPopup { widget command }
87    private method BuildIsosurfaceTab {}
88    private method Combo { option }
89    private method DrawLegend {}
90    private method EnterLegend { x y }
91    private method EventuallyResize { w h }
92    private method EventuallyRotate { q }
93    private method EventuallyRequestLegend {}
94    private method EventuallySetCutplane { axis args }
95    private method GetImage { args }
96    private method GetVtkData { args }
97    private method IsValidObject { dataobj }
98    private method LeaveLegend {}
99    private method MotionLegend { x y }
100    private method PanCamera {}
101    private method RequestLegend {}
102    private method SetLegendTip { x y }
103    private method SetObjectStyle { dataobj comp }
104    private method Slice {option args}
105    private method SetCurrentColormap { color }
106    private method SetOrientation { side }
107    private method UpdateContourList {}
108
109    private variable _arcball ""
110
111    private variable _dlist ""     ;    # list of data objects
112    private variable _obj2datasets
113    private variable _obj2ovride   ;    # maps dataobj => style override
114    private variable _datasets     ;    # contains all the dataobj-component
115                                   ;    # datasets in the server
116    private variable _colormaps    ;    # contains all the colormaps
117                                   ;    # in the server.
118    # The name of the current colormap used.  The colormap is global to all
119    # heightmaps displayed.
120    private variable _currentColormap ""
121    private variable _currentNumContours -1
122    private variable _currentOpacity ""
123
124    private variable _dataset2style    ;# maps dataobj-component to transfunc
125
126    private variable _click        ;    # info used for rotate operations
127    private variable _limits       ;    # autoscale min/max for all axes
128    private variable _view         ;    # view params for 3D view
129    private variable _settings
130    private variable _style;            # Array of current component styles.
131    private variable _changed
132    private variable _initialStyle;     # Array of initial component styles.
133    private variable _reset 1;          # indicates if camera needs to be reset
134                                        # to starting position.
135
136    private variable _first ""     ;    # This is the topmost dataset.
137    private variable _start 0
138    private variable _title ""
139    private variable _isolines
140    private variable _contourList ""
141
142    common _downloadPopup;              # download options from popup
143    private common _hardcopy
144    private variable _width 0
145    private variable _height 0
146    private variable _resizePending 0
147    private variable _rotatePending 0
148    private variable _cutplanePending 0
149    private variable _legendPending 0
150    private variable _field      ""
151    private variable _colorMode "scalar";       #  Mode of colormap (vmag or scalar)
152    private variable _fieldNames {}
153    private variable _fields
154    private variable _curFldName ""
155    private variable _curFldLabel ""
156}
157
158itk::usual VtkIsosurfaceViewer {
159    keep -background -foreground -cursor -font
160    keep -plotbackground -plotforeground
161}
162
163# ----------------------------------------------------------------------
164# CONSTRUCTOR
165# ----------------------------------------------------------------------
166itcl::body Rappture::VtkIsosurfaceViewer::constructor {hostlist args} {
167    package require vtk
168    set _serverType "vtkvis"
169
170    # Rebuild event
171    $_dispatcher register !rebuild
172    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
173
174    # Resize event
175    $_dispatcher register !resize
176    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
177
178    # Rotate event
179    $_dispatcher register !rotate
180    $_dispatcher dispatch $this !rotate "[itcl::code $this DoRotate]; list"
181
182    # Legend event
183    $_dispatcher register !legend
184    $_dispatcher dispatch $this !legend "[itcl::code $this RequestLegend]; list"
185
186    # X-Cutplane event
187    $_dispatcher register !xcutplane
188    $_dispatcher dispatch $this !xcutplane \
189        "[itcl::code $this AdjustSetting -xcutplaneposition]; list"
190
191    # Y-Cutplane event
192    $_dispatcher register !ycutplane
193    $_dispatcher dispatch $this !ycutplane \
194        "[itcl::code $this AdjustSetting -ycutplaneposition]; list"
195
196    # Z-Cutplane event
197    $_dispatcher register !zcutplane
198    $_dispatcher dispatch $this !zcutplane \
199        "[itcl::code $this AdjustSetting -zcutplaneposition]; list"
200
201    #
202    # Populate parser with commands handle incoming requests
203    #
204    $_parser alias image [itcl::code $this ReceiveImage]
205    $_parser alias dataset [itcl::code $this ReceiveDataset]
206    $_parser alias legend [itcl::code $this ReceiveLegend]
207
208    # Initialize the view to some default parameters.
209    array set _view {
210        qw              0.853553
211        qx              -0.353553
212        qy              0.353553
213        qz              0.146447
214        zoom            1.0
215        xpan            0
216        ypan            0
217        ortho           0
218    }
219    set _arcball [blt::arcball create 100 100]
220    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
221    $_arcball quaternion $q
222
223    array set _settings {
224        -background                     black
225        -colormap                       BCGYR
226        -colormapvisible                1
227        -field                          "Default"
228        -isolinecolor                   white
229        -axesvisible                    1
230        -axislabelsvisible              1
231        -cutplaneedges                  0
232        -cutplanelighting               1
233        -cutplaneopacity                100
234        -cutplanepreinterp              1
235        -cutplanesvisible               0
236        -cutplanewireframe              0
237        -isosurfaceedges                0
238        -isosurfacelighting             1
239        -isosurfaceopacity              60
240        -isosurfaceoutline              0
241        -isosurfacevisible              1
242        -isosurfacewireframe            0
243        -legendvisible                  1
244        -numcontours                    10
245        -xaxisgrid                      0
246        -xcutplaneposition              50
247        -xcutplanevisible               1
248        -yaxisgrid                      0
249        -ycutplaneposition              50
250        -ycutplanevisible               1
251        -zaxisgrid                      0
252        -zcutplaneposition              50
253        -zcutplanevisible               1
254    }
255    array set _changed {
256        -isosurfaceopacity       0
257        -colormap                0
258        -numcontours             0
259    }
260
261    itk_component add view {
262        canvas $itk_component(plotarea).view \
263            -highlightthickness 0 -borderwidth 0
264    } {
265        usual
266        ignore -highlightthickness -borderwidth  -background
267    }
268
269    itk_component add fieldmenu {
270        menu $itk_component(plotarea).menu -bg black -fg white -relief flat \
271            -tearoff 0
272    } {
273        usual
274        ignore -background -foreground -relief -tearoff
275    }
276    set c $itk_component(view)
277    bind $c <Configure> [itcl::code $this EventuallyResize %w %h]
278    bind $c <4> [itcl::code $this Zoom in 0.25]
279    bind $c <5> [itcl::code $this Zoom out 0.25]
280    bind $c <KeyPress-Left>  [list %W xview scroll 10 units]
281    bind $c <KeyPress-Right> [list %W xview scroll -10 units]
282    bind $c <KeyPress-Up>    [list %W yview scroll 10 units]
283    bind $c <KeyPress-Down>  [list %W yview scroll -10 units]
284    bind $c <Enter> "focus %W"
285    bind $c <Control-F1> [itcl::code $this ToggleConsole]
286
287    # Fix the scrollregion in case we go off screen
288    $c configure -scrollregion [$c bbox all]
289
290    set _map(id) [$c create image 0 0 -anchor nw -image $_image(plot)]
291    set _map(cwidth) -1
292    set _map(cheight) -1
293    set _map(zoom) 1.0
294    set _map(original) ""
295
296    set f [$itk_component(main) component controls]
297    itk_component add reset {
298        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
299            -highlightthickness 0 \
300            -image [Rappture::icon reset-view] \
301            -command [itcl::code $this Zoom reset]
302    } {
303        usual
304        ignore -highlightthickness
305    }
306    pack $itk_component(reset) -side top -padx 2 -pady 2
307    Rappture::Tooltip::for $itk_component(reset) \
308        "Reset the view to the default zoom level"
309
310    itk_component add zoomin {
311        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
312            -highlightthickness 0 \
313            -image [Rappture::icon zoom-in] \
314            -command [itcl::code $this Zoom in]
315    } {
316        usual
317        ignore -highlightthickness
318    }
319    pack $itk_component(zoomin) -side top -padx 2 -pady 2
320    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
321
322    itk_component add zoomout {
323        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
324            -highlightthickness 0 \
325            -image [Rappture::icon zoom-out] \
326            -command [itcl::code $this Zoom out]
327    } {
328        usual
329        ignore -highlightthickness
330    }
331    pack $itk_component(zoomout) -side top -padx 2 -pady 2
332    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
333
334    itk_component add contour {
335        Rappture::PushButton $f.contour \
336            -onimage [Rappture::icon volume-on] \
337            -offimage [Rappture::icon volume-off] \
338            -variable [itcl::scope _settings(-isosurfacevisible)] \
339            -command [itcl::code $this AdjustSetting -isosurfacevisible]
340    }
341    $itk_component(contour) select
342    Rappture::Tooltip::for $itk_component(contour) \
343        "Don't display the isosurface"
344    pack $itk_component(contour) -padx 2 -pady 2
345
346    itk_component add cutplane {
347        Rappture::PushButton $f.cutplane \
348            -onimage [Rappture::icon cutbutton] \
349            -offimage [Rappture::icon cutbutton] \
350            -variable [itcl::scope _settings(-cutplanesvisible)] \
351            -command [itcl::code $this AdjustSetting -cutplanesvisible]
352    }
353    Rappture::Tooltip::for $itk_component(cutplane) \
354        "Show/Hide cutplanes"
355    pack $itk_component(cutplane) -padx 2 -pady 2
356
357
358    if { [catch {
359        BuildIsosurfaceTab
360        BuildCutplaneTab
361        BuildAxisTab
362        BuildCameraTab
363    } errs] != 0 } {
364        puts stderr errs=$errs
365    }
366    # Legend
367
368    set _image(legend) [image create photo]
369    itk_component add legend {
370        canvas $itk_component(plotarea).legend -width 50 -highlightthickness 0
371    } {
372        usual
373        ignore -highlightthickness
374        rename -background -plotbackground plotBackground Background
375    }
376
377    # Hack around the Tk panewindow.  The problem is that the requested
378    # size of the 3d view isn't set until an image is retrieved from
379    # the server.  So the panewindow uses the tiny size.
380    set w 10000
381    pack forget $itk_component(view)
382    blt::table $itk_component(plotarea) \
383        0,0 $itk_component(view) -fill both -reqwidth $w
384    blt::table configure $itk_component(plotarea) c1 -resize none
385
386    # Bindings for rotation via mouse
387    bind $itk_component(view) <ButtonPress-1> \
388        [itcl::code $this Rotate click %x %y]
389    bind $itk_component(view) <B1-Motion> \
390        [itcl::code $this Rotate drag %x %y]
391    bind $itk_component(view) <ButtonRelease-1> \
392        [itcl::code $this Rotate release %x %y]
393
394    # Bindings for panning via mouse
395    bind $itk_component(view) <ButtonPress-2> \
396        [itcl::code $this Pan click %x %y]
397    bind $itk_component(view) <B2-Motion> \
398        [itcl::code $this Pan drag %x %y]
399    bind $itk_component(view) <ButtonRelease-2> \
400        [itcl::code $this Pan release %x %y]
401
402    #bind $itk_component(view) <ButtonRelease-3> \
403    #    [itcl::code $this Pick %x %y]
404
405    # Bindings for panning via keyboard
406    bind $itk_component(view) <KeyPress-Left> \
407        [itcl::code $this Pan set -10 0]
408    bind $itk_component(view) <KeyPress-Right> \
409        [itcl::code $this Pan set 10 0]
410    bind $itk_component(view) <KeyPress-Up> \
411        [itcl::code $this Pan set 0 -10]
412    bind $itk_component(view) <KeyPress-Down> \
413        [itcl::code $this Pan set 0 10]
414    bind $itk_component(view) <Shift-KeyPress-Left> \
415        [itcl::code $this Pan set -2 0]
416    bind $itk_component(view) <Shift-KeyPress-Right> \
417        [itcl::code $this Pan set 2 0]
418    bind $itk_component(view) <Shift-KeyPress-Up> \
419        [itcl::code $this Pan set 0 -2]
420    bind $itk_component(view) <Shift-KeyPress-Down> \
421        [itcl::code $this Pan set 0 2]
422
423    # Bindings for zoom via keyboard
424    bind $itk_component(view) <KeyPress-Prior> \
425        [itcl::code $this Zoom out]
426    bind $itk_component(view) <KeyPress-Next> \
427        [itcl::code $this Zoom in]
428
429    bind $itk_component(view) <Enter> "focus $itk_component(view)"
430
431    if {[string equal "x11" [tk windowingsystem]]} {
432        # Bindings for zoom via mouse
433        bind $itk_component(view) <4> [itcl::code $this Zoom out]
434        bind $itk_component(view) <5> [itcl::code $this Zoom in]
435    }
436
437    set _image(download) [image create photo]
438
439    eval itk_initialize $args
440
441    EnableWaitDialog 500
442    Connect
443    update
444}
445
446# ----------------------------------------------------------------------
447# DESTRUCTOR
448# ----------------------------------------------------------------------
449itcl::body Rappture::VtkIsosurfaceViewer::destructor {} {
450    Disconnect
451    image delete $_image(plot)
452    image delete $_image(download)
453    catch { blt::arcball destroy $_arcball }
454}
455
456itcl::body Rappture::VtkIsosurfaceViewer::DoResize {} {
457    if { $_width < 2 } {
458        set _width 500
459    }
460    if { $_height < 2 } {
461        set _height 500
462    }
463    set _start [clock clicks -milliseconds]
464    SendCmd "screen size $_width $_height"
465
466    EventuallyRequestLegend
467    set _resizePending 0
468}
469
470itcl::body Rappture::VtkIsosurfaceViewer::DoRotate {} {
471    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
472    SendCmd "camera orient $q"
473    set _rotatePending 0
474}
475
476itcl::body Rappture::VtkIsosurfaceViewer::EventuallyRequestLegend {} {
477    if { !$_legendPending } {
478        set _legendPending 1
479        $_dispatcher event -idle !legend
480    }
481}
482
483itcl::body Rappture::VtkIsosurfaceViewer::EventuallyResize { w h } {
484    set _width $w
485    set _height $h
486    $_arcball resize $w $h
487    if { !$_resizePending } {
488        set _resizePending 1
489        $_dispatcher event -after 400 !resize
490    }
491}
492
493set rotate_delay 100
494
495itcl::body Rappture::VtkIsosurfaceViewer::EventuallyRotate { q } {
496    foreach { _view(qw) _view(qx) _view(qy) _view(qz) } $q break
497    if { !$_rotatePending } {
498        set _rotatePending 1
499        global rotate_delay
500        $_dispatcher event -after $rotate_delay !rotate
501    }
502}
503
504itcl::body Rappture::VtkIsosurfaceViewer::EventuallySetCutplane { axis args } {
505    if { !$_cutplanePending } {
506        set _cutplanePending 1
507        $_dispatcher event -after 100 !${axis}cutplane
508    }
509}
510
511# ----------------------------------------------------------------------
512# USAGE: add <dataobj> ?<settings>?
513#
514# Clients use this to add a data object to the plot.  The optional
515# <settings> are used to configure the plot.  Allowed settings are
516# -color, -brightness, -width, -linestyle, and -raise.
517# ----------------------------------------------------------------------
518itcl::body Rappture::VtkIsosurfaceViewer::add {dataobj {settings ""}} {
519    if { ![$dataobj isvalid] } {
520        return;                         # Object doesn't contain valid data.
521    }
522    array set params {
523        -color auto
524        -width 1
525        -linestyle solid
526        -brightness 0
527        -raise 0
528        -description ""
529        -param ""
530        -type ""
531    }
532    array set params $settings
533    set params(-description) ""
534    set params(-param) ""
535    array set params $settings
536
537    if {$params(-color) == "auto" || $params(-color) == "autoreset"} {
538        # can't handle -autocolors yet
539        set params(-color) black
540    }
541    set pos [lsearch -exact $_dlist $dataobj]
542    if {$pos < 0} {
543        lappend _dlist $dataobj
544    }
545    set _obj2ovride($dataobj-color) $params(-color)
546    set _obj2ovride($dataobj-width) $params(-width)
547    set _obj2ovride($dataobj-raise) $params(-raise)
548    $_dispatcher event -idle !rebuild
549}
550
551
552# ----------------------------------------------------------------------
553# USAGE: delete ?<dataobj1> <dataobj2> ...?
554#
555#       Clients use this to delete a dataobj from the plot.  If no dataobjs
556#       are specified, then all dataobjs are deleted.  No data objects are
557#       deleted.  They are only removed from the display list.
558#
559# ----------------------------------------------------------------------
560itcl::body Rappture::VtkIsosurfaceViewer::delete {args} {
561    if { [llength $args] == 0} {
562        set args $_dlist
563    }
564    # Delete all specified dataobjs
565    set changed 0
566    foreach dataobj $args {
567        set pos [lsearch -exact $_dlist $dataobj]
568        if { $pos < 0 } {
569            continue;                   # Don't know anything about it.
570        }
571        # Remove it from the dataobj list.
572        set _dlist [lreplace $_dlist $pos $pos]
573        array unset _obj2ovride $dataobj-*
574        array unset _settings $dataobj-*
575        set changed 1
576    }
577    # If anything changed, then rebuild the plot
578    if { $changed } {
579        $_dispatcher event -idle !rebuild
580    }
581}
582
583# ----------------------------------------------------------------------
584# USAGE: get ?-objects?
585# USAGE: get ?-visible?
586# USAGE: get ?-image view?
587#
588# Clients use this to query the list of objects being plotted, in
589# order from bottom to top of this result.  The optional "-image"
590# flag can also request the internal images being shown.
591# ----------------------------------------------------------------------
592itcl::body Rappture::VtkIsosurfaceViewer::get {args} {
593    if {[llength $args] == 0} {
594        set args "-objects"
595    }
596
597    set op [lindex $args 0]
598    switch -- $op {
599        "-objects" {
600            # put the dataobj list in order according to -raise options
601            set dlist {}
602            foreach dataobj $_dlist {
603                if { ![IsValidObject $dataobj] } {
604                    continue
605                }
606                if {[info exists _obj2ovride($dataobj-raise)] &&
607                    $_obj2ovride($dataobj-raise)} {
608                    set dlist [linsert $dlist 0 $dataobj]
609                } else {
610                    lappend dlist $dataobj
611                }
612            }
613            return $dlist
614        }
615        "-visible" {
616            set dlist {}
617            foreach dataobj $_dlist {
618                if { ![IsValidObject $dataobj] } {
619                    continue
620                }
621                if { ![info exists _obj2ovride($dataobj-raise)] } {
622                    # No setting indicates that the object isn't visible.
623                    continue
624                }
625                # Otherwise use the -raise parameter to put the object to
626                # the front of the list.
627                if { $_obj2ovride($dataobj-raise) } {
628                    set dlist [linsert $dlist 0 $dataobj]
629                } else {
630                    lappend dlist $dataobj
631                }
632            }
633            return $dlist
634        }           
635        -image {
636            if {[llength $args] != 2} {
637                error "wrong # args: should be \"get -image view\""
638            }
639            switch -- [lindex $args end] {
640                view {
641                    return $_image(plot)
642                }
643                default {
644                    error "bad image name \"[lindex $args end]\": should be view"
645                }
646            }
647        }
648        default {
649            error "bad option \"$op\": should be -objects or -image"
650        }
651    }
652}
653
654# ----------------------------------------------------------------------
655# USAGE: scale ?<data1> <data2> ...?
656#
657# Sets the default limits for the overall plot according to the
658# limits of the data for all of the given <data> objects.  This
659# accounts for all objects--even those not showing on the screen.
660# Because of this, the limits are appropriate for all objects as
661# the user scans through data in the ResultSet viewer.
662# ----------------------------------------------------------------------
663itcl::body Rappture::VtkIsosurfaceViewer::scale { args } {
664    foreach dataobj $args {
665        if { ![$dataobj isvalid] } {
666            continue;                   # Object doesn't contain valid data.
667        }
668        foreach axis { x y z } {
669            set lim [$dataobj limits $axis]
670            if { ![info exists _limits($axis)] } {
671                set _limits($axis) $lim
672                continue
673            }
674            foreach {min max} $lim break
675            foreach {amin amax} $_limits($axis) break
676            if { $amin > $min } {
677                set amin $min
678            }
679            if { $amax < $max } {
680                set amax $max
681            }
682            set _limits($axis) [list $amin $amax]
683        }
684        foreach { fname lim } [$dataobj fieldlimits] {
685            if { ![info exists _limits($fname)] } {
686                set _limits($fname) $lim
687                continue
688            }
689            foreach {min max} $lim break
690            foreach {fmin fmax} $_limits($fname) break
691            if { $fmin > $min } {
692                set fmin $min
693            }
694            if { $fmax < $max } {
695                set fmax $max
696            }
697            set _limits($fname) [list $fmin $fmax]
698        }
699    }
700}
701
702# ----------------------------------------------------------------------
703# USAGE: download coming
704# USAGE: download controls <downloadCommand>
705# USAGE: download now
706#
707# Clients use this method to create a downloadable representation
708# of the plot.  Returns a list of the form {ext string}, where
709# "ext" is the file extension (indicating the type of data) and
710# "string" is the data itself.
711# ----------------------------------------------------------------------
712itcl::body Rappture::VtkIsosurfaceViewer::download {option args} {
713    switch $option {
714        coming {
715            if {[catch {
716                blt::winop snap $itk_component(plotarea) $_image(download)
717            }]} {
718                $_image(download) configure -width 1 -height 1
719                $_image(download) put #000000
720            }
721        }
722        controls {
723            set popup .vtkviewerdownload
724            if { ![winfo exists .vtkviewerdownload] } {
725                set inner [BuildDownloadPopup $popup [lindex $args 0]]
726            } else {
727                set inner [$popup component inner]
728            }
729            set _downloadPopup(image_controls) $inner.image_frame
730            set num [llength [get]]
731            set num [expr {($num == 1) ? "1 result" : "$num results"}]
732            set word [Rappture::filexfer::label downloadWord]
733            $inner.summary configure -text "$word $num in the following format:"
734            update idletasks            ;# Fix initial sizes
735            return $popup
736        }
737        now {
738            set popup .vtkviewerdownload
739            if {[winfo exists .vtkviewerdownload]} {
740                $popup deactivate
741            }
742            switch -- $_downloadPopup(format) {
743                "image" {
744                    return [$this GetImage [lindex $args 0]]
745                }
746                "vtk" {
747                    return [$this GetVtkData [lindex $args 0]]
748                }
749            }
750            return ""
751        }
752        default {
753            error "bad option \"$option\": should be coming, controls, now"
754        }
755    }
756}
757
758# ----------------------------------------------------------------------
759# USAGE: Connect ?<host:port>,<host:port>...?
760#
761# Clients use this method to establish a connection to a new
762# server, or to reestablish a connection to the previous server.
763# Any existing connection is automatically closed.
764# ----------------------------------------------------------------------
765itcl::body Rappture::VtkIsosurfaceViewer::Connect {} {
766    set _hosts [GetServerList "vtkvis"]
767    if { "" == $_hosts } {
768        return 0
769    }
770    set result [VisViewer::Connect $_hosts]
771    if { $result } {
772        if { $_reportClientInfo }  {
773            # Tell the server the viewer, hub, user and session.
774            # Do this immediately on connect before buffering any commands
775            global env
776
777            set info {}
778            set user "???"
779            if { [info exists env(USER)] } {
780                set user $env(USER)
781            }
782            set session "???"
783            if { [info exists env(SESSION)] } {
784                set session $env(SESSION)
785            }
786            lappend info "hub" [exec hostname]
787            lappend info "client" "vtkisosurfaceviewer"
788            lappend info "user" $user
789            lappend info "session" $session
790            SendCmd "clientinfo [list $info]"
791        }
792
793        set w [winfo width $itk_component(view)]
794        set h [winfo height $itk_component(view)]
795        EventuallyResize $w $h
796    }
797    return $result
798}
799
800#
801# isconnected --
802#
803#       Indicates if we are currently connected to the visualization server.
804#
805itcl::body Rappture::VtkIsosurfaceViewer::isconnected {} {
806    return [VisViewer::IsConnected]
807}
808
809#
810# disconnect --
811#
812itcl::body Rappture::VtkIsosurfaceViewer::disconnect {} {
813    Disconnect
814    set _reset 1
815}
816
817#
818# Disconnect --
819#
820#       Clients use this method to disconnect from the current rendering
821#       server.
822#
823itcl::body Rappture::VtkIsosurfaceViewer::Disconnect {} {
824    VisViewer::Disconnect
825
826    $_dispatcher cancel !rebuild
827    $_dispatcher cancel !resize
828    $_dispatcher cancel !rotate
829    $_dispatcher cancel !xcutplane
830    $_dispatcher cancel !ycutplane
831    $_dispatcher cancel !zcutplane
832    $_dispatcher cancel !legend
833    # disconnected -- no more data sitting on server
834    set _outbuf ""
835    array unset _datasets
836    array unset _data
837    array unset _colormaps
838    array unset _seeds
839    array unset _dataset2style
840    array unset _obj2datasets
841}
842
843# ----------------------------------------------------------------------
844# USAGE: ReceiveImage -bytes <size> -type <type> -token <token>
845#
846# Invoked automatically whenever the "image" command comes in from
847# the rendering server.  Indicates that binary image data with the
848# specified <size> will follow.
849# ----------------------------------------------------------------------
850itcl::body Rappture::VtkIsosurfaceViewer::ReceiveImage { args } {
851    array set info {
852        -token "???"
853        -bytes 0
854        -type image
855    }
856    array set info $args
857    set bytes [ReceiveBytes $info(-bytes)]
858    if { $info(-type) == "image" } {
859        if 0 {
860            set f [open "last.ppm" "w"]
861            puts $f $bytes
862            close $f
863        }
864        $_image(plot) configure -data $bytes
865        #set time [clock seconds]
866        #set date [clock format $time]
867        #set w [image width $_image(plot)]
868        #set h [image height $_image(plot)]
869        #puts stderr "$date: received image ${w}x${h} image"       
870        if { $_start > 0 } {
871            set finish [clock clicks -milliseconds]
872            #puts stderr "round trip time [expr $finish -$_start] milliseconds"
873            set _start 0
874        }
875    } elseif { $info(type) == "print" } {
876        set tag $this-print-$info(-token)
877        set _hardcopy($tag) $bytes
878    }
879}
880
881#
882# ReceiveDataset --
883#
884itcl::body Rappture::VtkIsosurfaceViewer::ReceiveDataset { args } {
885    if { ![isconnected] } {
886        return
887    }
888    set option [lindex $args 0]
889    switch -- $option {
890        "scalar" {
891            set option [lindex $args 1]
892            switch -- $option {
893                "world" {
894                    foreach { x y z value tag } [lrange $args 2 end] break
895                }
896                "pixel" {
897                    foreach { x y value tag } [lrange $args 2 end] break
898                }
899            }
900        }
901        "vector" {
902            set option [lindex $args 1]
903            switch -- $option {
904                "world" {
905                    foreach { x y z vx vy vz tag } [lrange $args 2 end] break
906                }
907                "pixel" {
908                    foreach { x y vx vy vz tag } [lrange $args 2 end] break
909                }
910            }
911        }
912        "names" {
913            foreach { name } [lindex $args 1] {
914                #puts stderr "Dataset: $name"
915            }
916        }
917        default {
918            error "unknown dataset option \"$option\" from server"
919        }
920    }
921}
922
923# ----------------------------------------------------------------------
924# USAGE: Rebuild
925#
926# Called automatically whenever something changes that affects the
927# data in the widget.  Clears any existing data and rebuilds the
928# widget to display new data.
929# ----------------------------------------------------------------------
930itcl::body Rappture::VtkIsosurfaceViewer::Rebuild {} {
931    set w [winfo width $itk_component(view)]
932    set h [winfo height $itk_component(view)]
933    if { $w < 2 || $h < 2 } {
934        $_dispatcher event -idle !rebuild
935        return
936    }
937
938    # Turn on buffering of commands to the server.  We don't want to
939    # be preempted by a server disconnect/reconnect (which automatically
940    # generates a new call to Rebuild).   
941    StartBufferingCommands
942
943    if { $_reset } {
944        set _width $w
945        set _height $h
946        $_arcball resize $w $h
947        DoResize
948        #
949        # Reset the camera and other view parameters
950        #
951        set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
952        $_arcball quaternion $q
953        if {$_view(ortho)} {
954            SendCmd "camera mode ortho"
955        } else {
956            SendCmd "camera mode persp"
957        }
958        DoRotate
959        PanCamera
960        set _first ""
961        InitSettings -xaxisgrid -yaxisgrid -zaxisgrid -axismode \
962            -axesvisible -axislabelsvisible
963        foreach axis { x y z } {
964            SendCmd "axis lformat $axis %g"
965        }
966        StopBufferingCommands
967        SendCmd "imgflush"
968        StartBufferingCommands
969    }
970    set _first ""
971    SendCmd "dataset visible 0"
972    foreach dataobj [get -objects] {
973        if { [info exists _obj2ovride($dataobj-raise)] &&  $_first == "" } {
974            set _first $dataobj
975        }
976        set _obj2datasets($dataobj) ""
977        foreach comp [$dataobj components] {
978            set tag $dataobj-$comp
979            if { ![info exists _datasets($tag)] } {
980                set bytes [$dataobj vtkdata $comp]
981                if 0 {
982                    set f [open "/tmp/isosurface.vtk" "w"]
983                    puts $f $bytes
984                    close $f
985                }
986                set length [string length $bytes]
987                if { $_reportClientInfo }  {
988                    set info {}
989                    lappend info "tool_id"       [$dataobj hints toolId]
990                    lappend info "tool_name"     [$dataobj hints toolName]
991                    lappend info "tool_version"  [$dataobj hints toolRevision]
992                    lappend info "tool_title"    [$dataobj hints toolTitle]
993                    lappend info "dataset_label" [$dataobj hints label]
994                    lappend info "dataset_size"  $length
995                    lappend info "dataset_tag"   $tag
996                    SendCmd "clientinfo [list $info]"
997                }
998                append _outbuf "dataset add $tag data follows $length\n"
999                append _outbuf $bytes
1000                set _datasets($tag) 1
1001                SetObjectStyle $dataobj $comp
1002            }
1003            lappend _obj2datasets($dataobj) $tag
1004            if { [info exists _obj2ovride($dataobj-raise)] } {
1005                # Setting dataset visible enables outline
1006                # and contour3d
1007                SendCmd "dataset visible 1 $tag"
1008            }
1009        }
1010    }
1011
1012    if { $_first != "" } {
1013        $itk_component(field) choices delete 0 end
1014        $itk_component(fieldmenu) delete 0 end
1015        array unset _fields
1016        set _curFldName ""
1017        foreach cname [$_first components] {
1018            foreach fname [$_first fieldnames $cname] {
1019                if { [info exists _fields($fname)] } {
1020                    continue
1021                }
1022                foreach { label units components } \
1023                    [$_first fieldinfo $fname] break
1024                $itk_component(field) choices insert end "$fname" "$label"
1025                $itk_component(fieldmenu) add radiobutton -label "$label" \
1026                    -value $label -variable [itcl::scope _curFldLabel] \
1027                    -selectcolor red \
1028                    -activebackground $itk_option(-plotbackground) \
1029                    -activeforeground $itk_option(-plotforeground) \
1030                    -font "Arial 8" \
1031                    -command [itcl::code $this Combo invoke]
1032                set _fields($fname) [list $label $units $components]
1033                if { $_curFldName == "" } {
1034                    set _curFldName $fname
1035                    set _curFldLabel $label
1036                }
1037            }
1038        }
1039        $itk_component(field) value $_curFldLabel
1040    }
1041    InitSettings -cutplanesvisible -isosurfacevisible -isosurfaceoutline
1042    if { $_reset } {
1043        # These are settings that rely on a dataset being loaded.
1044        InitSettings \
1045            -isosurfacelighting \
1046            -field \
1047            -isosurfacevisible \
1048            -isosurfaceedges -isosurfacelighting -isosurfaceopacity \
1049            -isosurfacewireframe \
1050            -cutplanesvisible \
1051            -xcutplaneposition -ycutplaneposition -zcutplaneposition \
1052            -xcutplanevisible -ycutplanevisible -zcutplanevisible \
1053            -cutplanepreinterp -numcontours
1054
1055        Zoom reset
1056        foreach axis { x y z } {
1057            # Another problem fixed by a <view>. We looking into a data
1058            # object for the name of the axes. This should be global to
1059            # the viewer itself.
1060            set label [$_first hints ${axis}label]
1061            if { $label == "" } {
1062                set label [string toupper $axis]
1063            }
1064            # May be a space in the axis label.
1065            SendCmd [list axis name $axis $label]
1066        }
1067        if { [array size _fields] < 2 } {
1068            blt::table forget $itk_component(field) $itk_component(field_l)
1069        }
1070        set _reset 0
1071    }
1072
1073    # Actually write the commands to the server socket.  If it fails, we don't
1074    # care.  We're finished here.
1075    blt::busy hold $itk_component(hull)
1076    StopBufferingCommands;              # Turn off buffering and send commands.
1077    blt::busy release $itk_component(hull)
1078}
1079
1080# ----------------------------------------------------------------------
1081# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1082#
1083# Returns a list of server IDs for the current datasets being displayed.  This
1084# is normally a single ID, but it might be a list of IDs if the current data
1085# object has multiple components.
1086# ----------------------------------------------------------------------
1087itcl::body Rappture::VtkIsosurfaceViewer::CurrentDatasets {args} {
1088    set flag [lindex $args 0]
1089    switch -- $flag {
1090        "-all" {
1091            if { [llength $args] > 1 } {
1092                error "CurrentDatasets: can't specify dataobj after \"-all\""
1093            }
1094            set dlist [get -objects]
1095        }
1096        "-visible" {
1097            if { [llength $args] > 1 } {
1098                set dlist {}
1099                set args [lrange $args 1 end]
1100                foreach dataobj $args {
1101                    if { [info exists _obj2ovride($dataobj-raise)] } {
1102                        lappend dlist $dataobj
1103                    }
1104                }
1105            } else {
1106                set dlist [get -visible]
1107            }
1108        }           
1109        default {
1110            set dlist $args
1111        }
1112    }
1113    set rlist ""
1114    foreach dataobj $dlist {
1115        foreach comp [$dataobj components] {
1116            set tag $dataobj-$comp
1117            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1118                lappend rlist $tag
1119            }
1120        }
1121    }
1122    return $rlist
1123}
1124
1125# ----------------------------------------------------------------------
1126# USAGE: Zoom in
1127# USAGE: Zoom out
1128# USAGE: Zoom reset
1129#
1130# Called automatically when the user clicks on one of the zoom
1131# controls for this widget.  Changes the zoom for the current view.
1132# ----------------------------------------------------------------------
1133itcl::body Rappture::VtkIsosurfaceViewer::Zoom {option} {
1134    switch -- $option {
1135        "in" {
1136            set _view(zoom) [expr {$_view(zoom)*1.25}]
1137            SendCmd "camera zoom $_view(zoom)"
1138        }
1139        "out" {
1140            set _view(zoom) [expr {$_view(zoom)*0.8}]
1141            SendCmd "camera zoom $_view(zoom)"
1142        }
1143        "reset" {
1144            array set _view {
1145                qw     0.853553
1146                qx     -0.353553
1147                qy     0.353553
1148                qz     0.146447
1149                zoom   1.0
1150                xpan   0
1151                ypan   0
1152            }
1153            if { $_first != "" } {
1154                set location [$_first hints camera]
1155                if { $location != "" } {
1156                    array set _view $location
1157                }
1158            }
1159            set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1160            $_arcball quaternion $q
1161            DoRotate
1162            SendCmd "camera reset"
1163        }
1164    }
1165}
1166
1167itcl::body Rappture::VtkIsosurfaceViewer::PanCamera {} {
1168    set x $_view(xpan)
1169    set y $_view(ypan)
1170    SendCmd "camera pan $x $y"
1171}
1172
1173
1174# ----------------------------------------------------------------------
1175# USAGE: Rotate click <x> <y>
1176# USAGE: Rotate drag <x> <y>
1177# USAGE: Rotate release <x> <y>
1178#
1179# Called automatically when the user clicks/drags/releases in the
1180# plot area.  Moves the plot according to the user's actions.
1181# ----------------------------------------------------------------------
1182itcl::body Rappture::VtkIsosurfaceViewer::Rotate {option x y} {
1183    switch -- $option {
1184        "click" {
1185            $itk_component(view) configure -cursor fleur
1186            set _click(x) $x
1187            set _click(y) $y
1188        }
1189        "drag" {
1190            if {[array size _click] == 0} {
1191                Rotate click $x $y
1192            } else {
1193                set w [winfo width $itk_component(view)]
1194                set h [winfo height $itk_component(view)]
1195                if {$w <= 0 || $h <= 0} {
1196                    return
1197                }
1198
1199                if {[catch {
1200                    # this fails sometimes for no apparent reason
1201                    set dx [expr {double($x-$_click(x))/$w}]
1202                    set dy [expr {double($y-$_click(y))/$h}]
1203                }]} {
1204                    return
1205                }
1206                if { $dx == 0 && $dy == 0 } {
1207                    return
1208                }
1209                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1210                EventuallyRotate $q
1211                set _click(x) $x
1212                set _click(y) $y
1213            }
1214        }
1215        "release" {
1216            Rotate drag $x $y
1217            $itk_component(view) configure -cursor ""
1218            catch {unset _click}
1219        }
1220        default {
1221            error "bad option \"$option\": should be click, drag, release"
1222        }
1223    }
1224}
1225
1226itcl::body Rappture::VtkIsosurfaceViewer::Pick {x y} {
1227    foreach tag [CurrentDatasets -visible] {
1228        SendCmdNoSplash "dataset getscalar pixel $x $y $tag"
1229    }
1230}
1231
1232# ----------------------------------------------------------------------
1233# USAGE: $this Pan click x y
1234#        $this Pan drag x y
1235#        $this Pan release x y
1236#
1237# Called automatically when the user clicks on one of the zoom
1238# controls for this widget.  Changes the zoom for the current view.
1239# ----------------------------------------------------------------------
1240itcl::body Rappture::VtkIsosurfaceViewer::Pan {option x y} {
1241    switch -- $option {
1242        "set" {
1243            set w [winfo width $itk_component(view)]
1244            set h [winfo height $itk_component(view)]
1245            set x [expr $x / double($w)]
1246            set y [expr $y / double($h)]
1247            set _view(xpan) [expr $_view(xpan) + $x]
1248            set _view(ypan) [expr $_view(ypan) + $y]
1249            PanCamera
1250            return
1251        }
1252        "click" {
1253            set _click(x) $x
1254            set _click(y) $y
1255            $itk_component(view) configure -cursor hand1
1256        }
1257        "drag" {
1258            if { ![info exists _click(x)] } {
1259                set _click(x) $x
1260            }
1261            if { ![info exists _click(y)] } {
1262                set _click(y) $y
1263            }
1264            set w [winfo width $itk_component(view)]
1265            set h [winfo height $itk_component(view)]
1266            set dx [expr ($_click(x) - $x)/double($w)]
1267            set dy [expr ($_click(y) - $y)/double($h)]
1268            set _click(x) $x
1269            set _click(y) $y
1270            set _view(xpan) [expr $_view(xpan) - $dx]
1271            set _view(ypan) [expr $_view(ypan) - $dy]
1272            PanCamera
1273        }
1274        "release" {
1275            Pan drag $x $y
1276            $itk_component(view) configure -cursor ""
1277        }
1278        default {
1279            error "unknown option \"$option\": should set, click, drag, or release"
1280        }
1281    }
1282}
1283
1284# ----------------------------------------------------------------------
1285# USAGE: InitSettings <what> ?<value>?
1286#
1287# Used internally to update rendering settings whenever parameters
1288# change in the popup settings panel.  Sends the new settings off
1289# to the back end.
1290# ----------------------------------------------------------------------
1291itcl::body Rappture::VtkIsosurfaceViewer::InitSettings { args } {
1292    foreach spec $args {
1293        if { [info exists _settings($_first-$spec)] } {
1294            # Reset global setting with dataobj specific setting
1295            set _settings($spec) $_settings($_first-$spec)
1296        }
1297        AdjustSetting $spec
1298    }
1299}
1300
1301#
1302# AdjustSetting --
1303#
1304#       Changes/updates a specific setting in the widget.  There are
1305#       usually user-setable option.  Commands are sent to the render
1306#       server.
1307#
1308itcl::body Rappture::VtkIsosurfaceViewer::AdjustSetting {what {value ""}} {
1309    if { ![isconnected] } {
1310        return
1311    }
1312    switch -- $what {
1313        "-background" {
1314            set bgcolor [$itk_component(background) value]
1315            array set fgcolors {
1316                "black" "white"
1317                "white" "black"
1318                "grey"  "black"
1319            }
1320            configure -plotbackground $bgcolor \
1321                -plotforeground $fgcolors($bgcolor)
1322            $itk_component(view) delete "legend"
1323            DrawLegend
1324        }
1325        "-axesvisible" {
1326            set bool $_settings(-axesvisible)
1327            SendCmd "axis visible all $bool"
1328        }
1329        "-axislabelsvisible" {
1330            set bool $_settings(-axislabelsvisible)
1331            SendCmd "axis labels all $bool"
1332        }
1333        "-xaxisgrid" - "-yaxisgrid" - "-zaxisgrid" {
1334            set axis [string tolower [string range $what 1 1]]
1335            set bool $_settings($what)
1336            SendCmd "axis grid $axis $bool"
1337        }
1338        "-axismode" {
1339            set mode [$itk_component(axisMode) value]
1340            set mode [$itk_component(axisMode) translate $mode]
1341            set _settings($what) $mode
1342            SendCmd "axis flymode $mode"
1343        }
1344        "-cutplaneedges" {
1345            set bool $_settings($what)
1346            SendCmd "cutplane edges $bool"
1347        }
1348        "-cutplanesvisible" {
1349            set bool $_settings($what)
1350            SendCmd "cutplane visible $bool"
1351        }
1352        "-cutplanewireframe" {
1353            set bool $_settings($what)
1354            SendCmd "cutplane wireframe $bool"
1355        }
1356        "-cutplanelighting" {
1357            set bool $_settings($what)
1358            SendCmd "cutplane lighting $bool"
1359        }
1360        "-cutplaneopacity" {
1361            set val $_settings($what)
1362            set sval [expr { 0.01 * double($val) }]
1363            SendCmd "cutplane opacity $sval"
1364        }
1365        "-cutplanepreinterp" {
1366            set bool $_settings($what)
1367            SendCmd "cutplane preinterp $bool"
1368        }
1369        "-xcutplanevisible" - "-ycutplanevisible" - "-zcutplanevisible" {
1370            set axis [string tolower [string range $what 1 1]]
1371            set bool $_settings($what)
1372            if { $bool } {
1373                $itk_component(${axis}position) configure -state normal \
1374                    -troughcolor white
1375            } else {
1376                $itk_component(${axis}position) configure -state disabled \
1377                    -troughcolor grey82
1378            }
1379            SendCmd "cutplane axis $axis $bool"
1380        }
1381        "-xcutplaneposition" - "-ycutplaneposition" - "-zcutplaneposition" {
1382            set axis [string tolower [string range $what 1 1]]
1383            set pos [expr $_settings($what) * 0.01]
1384            SendCmd "cutplane slice ${axis} ${pos}"
1385            set _cutplanePending 0
1386        }
1387        "-colormap" {
1388            set _changed(-colormap) 1
1389            StartBufferingCommands
1390            set color [$itk_component(colormap) value]
1391            set _settings(-colormap) $color
1392            if { $color == "none" } {
1393                if { $_settings(-colormapvisible) } {
1394                    SendCmd "contour3d colormode constant {}"
1395                    set _settings(-colormapvisible) 0
1396                }
1397            } else {
1398                if { !$_settings(-colormapvisible) } {
1399                    SendCmd "contour3d colormode $_colorMode $_curFldName"
1400                    set _settings(-colormapvisible) 1
1401                }
1402                SetCurrentColormap $color
1403            }
1404            StopBufferingCommands
1405            EventuallyRequestLegend
1406        }
1407        "-numcontours" {
1408            set _settings($what) [$itk_component(numcontours) value]
1409            set _currentNumContours $_settings($what)
1410            UpdateContourList
1411            set _changed($what) 1
1412            SendCmd "contour3d contourlist [list $_contourList]"
1413            DrawLegend
1414        }
1415        "-isosurfacewireframe" {
1416            set bool $_settings($what)
1417            SendCmd "contour3d wireframe $bool"
1418        }
1419        "-isosurfacevisible" {
1420            set bool $_settings($what)
1421            SendCmd "contour3d visible $bool"
1422            if { $bool } {
1423                Rappture::Tooltip::for $itk_component(contour) \
1424                    "Hide the isosurface"
1425            } else {
1426                Rappture::Tooltip::for $itk_component(contour) \
1427                    "Show the isosurface"
1428            }
1429            DrawLegend
1430        }
1431        "-isosurfacelighting" {
1432            set bool $_settings($what)
1433            SendCmd "contour3d lighting $bool"
1434        }
1435        "-isosurfaceedges" {
1436            set bool $_settings($what)
1437            SendCmd "contour3d edges $bool"
1438        }
1439        "-isosurfaceoutline" {
1440            set bool $_settings($what)
1441            SendCmd "outline visible $bool"
1442        }
1443        "-isolinecolor" {
1444            set color [$itk_component(isolineColor) value]
1445            set _settings($what) $color
1446            DrawLegend
1447        }
1448        "-isosurfaceopacity" {
1449            set val $_settings($what)
1450            set sval [expr { 0.01 * double($val) }]
1451            SendCmd "contour3d opacity $sval"
1452        }
1453        "-field" {
1454            set label [$itk_component(field) value]
1455            set fname [$itk_component(field) translate $label]
1456            set _settings($what) $fname
1457            if { [info exists _fields($fname)] } {
1458                foreach { label units components } $_fields($fname) break
1459                if { $components > 1 } {
1460                    set _colorMode vmag
1461                } else {
1462                    set _colorMode scalar
1463                }
1464                set _curFldName $fname
1465                set _curFldLabel $label
1466            } else {
1467                puts stderr "unknown field \"$fname\""
1468                return
1469            }
1470            SendCmd "dataset scalar $_curFldName"
1471            if { ![info exists _limits($_curFldName)] } {
1472                SendCmd "dataset maprange all"
1473            } else {
1474                SendCmd "dataset maprange explicit $_limits($_curFldName) $_curFldName"
1475            }
1476            SendCmd "cutplane colormode $_colorMode $_curFldName"
1477            SendCmd "contour3d colormode $_colorMode $_curFldName"
1478            SendCmd "camera reset"
1479            UpdateContourList
1480            DrawLegend
1481        }
1482        "-legendvisible" {
1483            if { !$_settings($what) } {
1484                $itk_component(view) delete legend
1485            }
1486            DrawLegend
1487        }
1488        default {
1489            error "don't know how to fix $what"
1490        }
1491    }
1492}
1493
1494
1495#
1496# RequestLegend --
1497#
1498#       Request a new legend from the server.  The size of the legend
1499#       is determined from the height of the canvas. 
1500#
1501# This should be called when
1502#       1.  A new current colormap is set.
1503#       2.  Window is resized.
1504#       3.  The limits of the data have changed.  (Just need a redraw).
1505#       4.  Number of isolines have changed. (Just need a redraw).
1506#       5.  Legend becomes visible (Just need a redraw).
1507#
1508itcl::body Rappture::VtkIsosurfaceViewer::RequestLegend {} {
1509    set _legendPending 0
1510    if { ![info exists _fields($_curFldName)] } {
1511        return
1512    }
1513    set fname $_curFldName
1514    set font "Arial 8"
1515    set lineht [font metrics $font -linespace]
1516    set w 12
1517    set h [expr {$_height - 2 * ($lineht + 2)}]
1518    if { $h < 1 } {
1519        return
1520    }
1521    if { [string match "component*" $fname] } {
1522        set title ""
1523    } else {
1524        if { [info exists _fields($fname)] } {
1525            foreach { title units } $_fields($fname) break
1526            if { $units != "" } {
1527                set title [format "%s (%s)" $title $units]
1528            }
1529        } else {
1530            set title $fname
1531        }
1532    }
1533    # If there's a title too, subtract one more line
1534    if { $title != "" } {
1535        incr h -$lineht
1536    }
1537    # Set the legend on the first heightmap dataset.
1538    if { $_currentColormap != ""  } {
1539        set cmap $_currentColormap
1540        SendCmdNoWait "legend $cmap scalar $_curFldName {} $w $h 0"
1541    }
1542}
1543
1544# ----------------------------------------------------------------------
1545# CONFIGURATION OPTION: -plotbackground
1546# ----------------------------------------------------------------------
1547itcl::configbody Rappture::VtkIsosurfaceViewer::plotbackground {
1548    if { [isconnected] } {
1549        set rgb [Color2RGB $itk_option(-plotbackground)]
1550        SendCmd "screen bgcolor $rgb"
1551    }
1552}
1553
1554# ----------------------------------------------------------------------
1555# CONFIGURATION OPTION: -plotforeground
1556# ----------------------------------------------------------------------
1557itcl::configbody Rappture::VtkIsosurfaceViewer::plotforeground {
1558    if { [isconnected] } {
1559        set rgb [Color2RGB $itk_option(-plotforeground)]
1560        SendCmd "axis color all $rgb"
1561        SendCmd "outline color $rgb"
1562        SendCmd "cutplane color $rgb"
1563    }
1564}
1565
1566itcl::body Rappture::VtkIsosurfaceViewer::limits { dataobj } {
1567    foreach { limits(xmin) limits(xmax) } [$dataobj limits x] break
1568    foreach { limits(ymin) limits(ymax) } [$dataobj limits y] break
1569    foreach { limits(zmin) limits(zmax) } [$dataobj limits z] break
1570    foreach { limits(vmin) limits(vmax) } [$dataobj limits v] break
1571    return [array get limits]
1572}
1573
1574itcl::body Rappture::VtkIsosurfaceViewer::BuildIsosurfaceTab {} {
1575
1576    set fg [option get $itk_component(hull) font Font]
1577    #set bfg [option get $itk_component(hull) boldFont Font]
1578
1579    set inner [$itk_component(main) insert end \
1580        -title "Isosurface Settings" \
1581        -icon [Rappture::icon volume-on]]
1582    $inner configure -borderwidth 4
1583
1584    checkbutton $inner.contour \
1585        -text "Isosurfaces" \
1586        -variable [itcl::scope _settings(-isosurfacevisible)] \
1587        -command [itcl::code $this AdjustSetting -isosurfacevisible] \
1588        -font "Arial 9"
1589
1590    checkbutton $inner.wireframe \
1591        -text "Wireframe" \
1592        -variable [itcl::scope _settings(-isosurfacewireframe)] \
1593        -command [itcl::code $this AdjustSetting -isosurfacewireframe] \
1594        -font "Arial 9"
1595
1596    checkbutton $inner.lighting \
1597        -text "Enable Lighting" \
1598        -variable [itcl::scope _settings(-isosurfacelighting)] \
1599        -command [itcl::code $this AdjustSetting -isosurfacelighting] \
1600        -font "Arial 9"
1601
1602    checkbutton $inner.edges \
1603        -text "Edges" \
1604        -variable [itcl::scope _settings(-isosurfaceedges)] \
1605        -command [itcl::code $this AdjustSetting -isosurfaceedges] \
1606        -font "Arial 9"
1607
1608    checkbutton $inner.outline \
1609        -text "Outline" \
1610        -variable [itcl::scope _settings(-isosurfaceoutline)] \
1611        -command [itcl::code $this AdjustSetting -isosurfaceoutline] \
1612        -font "Arial 9"
1613
1614    checkbutton $inner.legend \
1615        -text "Legend" \
1616        -variable [itcl::scope _settings(-legendvisible)] \
1617        -command [itcl::code $this AdjustSetting -legendvisible] \
1618        -font "Arial 9"
1619
1620    label $inner.linecolor_l -text "Isolines" -font "Arial 9"
1621    itk_component add isolineColor {
1622        Rappture::Combobox $inner.linecolor -width 10 -editable 0
1623    }
1624    $inner.linecolor choices insert end \
1625        "black"              "black"            \
1626        "blue"               "blue"             \
1627        "cyan"               "cyan"             \
1628        "green"              "green"            \
1629        "grey"               "grey"             \
1630        "magenta"            "magenta"          \
1631        "orange"             "orange"           \
1632        "red"                "red"              \
1633        "white"              "white"            \
1634        "none"               "none"
1635
1636    $itk_component(isolineColor) value "white"
1637    bind $inner.linecolor <<Value>> \
1638        [itcl::code $this AdjustSetting -isolinecolor]
1639
1640    label $inner.background_l -text "Background" -font "Arial 9"
1641    itk_component add background {
1642        Rappture::Combobox $inner.background -width 10 -editable 0
1643    }
1644    $inner.background choices insert end \
1645        "black"              "black"            \
1646        "white"              "white"            \
1647        "grey"               "grey"             
1648
1649    $itk_component(background) value $_settings(-background)
1650    bind $inner.background <<Value>> \
1651        [itcl::code $this AdjustSetting -background]
1652
1653    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1654    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1655        -variable [itcl::scope _settings(-isosurfaceopacity)] \
1656        -width 10 \
1657        -showvalue off \
1658        -command [itcl::code $this AdjustSetting -isosurfaceopacity]
1659
1660    itk_component add field_l {
1661        label $inner.field_l -text "Field" -font "Arial 9"
1662    } {
1663        ignore -font
1664    }
1665    itk_component add field {
1666        Rappture::Combobox $inner.field -width 10 -editable 0
1667    }
1668    bind $inner.field <<Value>> \
1669        [itcl::code $this AdjustSetting -field]
1670
1671    label $inner.colormap_l -text "Colormap" -font "Arial 9"
1672    itk_component add colormap {
1673        Rappture::Combobox $inner.colormap -width 10 -editable 0
1674    }
1675    $inner.colormap choices insert end [GetColormapList]
1676
1677    $itk_component(colormap) value "BCGYR"
1678    bind $inner.colormap <<Value>> \
1679        [itcl::code $this AdjustSetting -colormap]
1680
1681    label $inner.numcontours_l -text "Number of Isosurfaces" -font "Arial 9"
1682    itk_component add numcontours {
1683        Rappture::Spinint $inner.numcontours \
1684            -min 0 -max 50 -font "arial 9"
1685    }
1686    $itk_component(numcontours) value $_settings(-numcontours)
1687    bind $itk_component(numcontours) <<Value>> \
1688        [itcl::code $this AdjustSetting -numcontours]
1689
1690    blt::table $inner \
1691        0,0 $inner.field_l   -anchor w -pady 2  \
1692        0,1 $inner.field     -anchor w -pady 2  -fill x \
1693        1,0 $inner.colormap_l -anchor w -pady 2  \
1694        1,1 $inner.colormap   -anchor w -pady 2  -fill x \
1695        2,0 $inner.linecolor_l  -anchor w -pady 2  \
1696        2,1 $inner.linecolor    -anchor w -pady 2 -fill x  \
1697        3,0 $inner.background_l -anchor w -pady 2 \
1698        3,1 $inner.background -anchor w -pady 2  -fill x \
1699        4,0 $inner.numcontours_l -anchor w -pady 2 \
1700        4,1 $inner.numcontours -anchor w -pady 2 \
1701        5,0 $inner.wireframe -anchor w -pady 2 -cspan 2 \
1702        6,0 $inner.lighting  -anchor w -pady 2 -cspan 2 \
1703        7,0 $inner.edges     -anchor w -pady 2 -cspan 2 \
1704        8,0 $inner.outline   -anchor w -pady 2 -cspan 2 \
1705        9,0 $inner.legend    -anchor w -pady 2 \
1706        10,0 $inner.opacity_l -anchor w -pady 2 \
1707        10,1 $inner.opacity   -fill x   -pady 2 -fill x \
1708
1709    blt::table configure $inner r* c* -resize none
1710    blt::table configure $inner r11 c1 -resize expand
1711}
1712
1713itcl::body Rappture::VtkIsosurfaceViewer::BuildAxisTab {} {
1714
1715    set fg [option get $itk_component(hull) font Font]
1716    #set bfg [option get $itk_component(hull) boldFont Font]
1717
1718    set inner [$itk_component(main) insert end \
1719        -title "Axis Settings" \
1720        -icon [Rappture::icon axis2]]
1721    $inner configure -borderwidth 4
1722
1723    checkbutton $inner.visible \
1724        -text "Show Axes" \
1725        -variable [itcl::scope _settings(-axesvisible)] \
1726        -command [itcl::code $this AdjustSetting -axesvisible] \
1727        -font "Arial 9"
1728
1729    checkbutton $inner.labels \
1730        -text "Show Axis Labels" \
1731        -variable [itcl::scope _settings(-axislabelsvisible)] \
1732        -command [itcl::code $this AdjustSetting -axislabelsvisible] \
1733        -font "Arial 9"
1734
1735    checkbutton $inner.gridx \
1736        -text "Show X Grid" \
1737        -variable [itcl::scope _settings(-xaxisgrid)] \
1738        -command [itcl::code $this AdjustSetting -xaxisgrid] \
1739        -font "Arial 9"
1740    checkbutton $inner.gridy \
1741        -text "Show Y Grid" \
1742        -variable [itcl::scope _settings(-yaxisgrid)] \
1743        -command [itcl::code $this AdjustSetting -yaxisgrid] \
1744        -font "Arial 9"
1745    checkbutton $inner.gridz \
1746        -text "Show Z Grid" \
1747        -variable [itcl::scope _settings(-zaxisgrid)] \
1748        -command [itcl::code $this AdjustSetting -zaxisgrid] \
1749        -font "Arial 9"
1750
1751    label $inner.mode_l -text "Mode" -font "Arial 9"
1752
1753    itk_component add axisMode {
1754        Rappture::Combobox $inner.mode -width 10 -editable 0
1755    }
1756    $inner.mode choices insert end \
1757        "static_triad"    "static" \
1758        "closest_triad"   "closest" \
1759        "furthest_triad"  "farthest" \
1760        "outer_edges"     "outer"         
1761    $itk_component(axisMode) value "static"
1762    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting -axismode]
1763
1764    blt::table $inner \
1765        0,0 $inner.visible -anchor w -cspan 2 \
1766        1,0 $inner.labels  -anchor w -cspan 2 \
1767        2,0 $inner.gridx   -anchor w -cspan 2 \
1768        3,0 $inner.gridy   -anchor w -cspan 2 \
1769        4,0 $inner.gridz   -anchor w -cspan 2 \
1770        5,0 $inner.mode_l  -anchor w -cspan 2 -padx { 2 0 } \
1771        6,0 $inner.mode    -fill x   -cspan 2
1772
1773    blt::table configure $inner r* c* -resize none
1774    blt::table configure $inner r7 c1 -resize expand
1775}
1776
1777
1778itcl::body Rappture::VtkIsosurfaceViewer::BuildCameraTab {} {
1779    set inner [$itk_component(main) insert end \
1780        -title "Camera Settings" \
1781        -icon [Rappture::icon camera]]
1782    $inner configure -borderwidth 4
1783
1784    label $inner.view_l -text "view" -font "Arial 9"
1785    set f [frame $inner.view]
1786    foreach side { front back left right top bottom } {
1787        button $f.$side  -image [Rappture::icon view$side] \
1788            -command [itcl::code $this SetOrientation $side]
1789        Rappture::Tooltip::for $f.$side "Change the view to $side"
1790        pack $f.$side -side left
1791    }
1792
1793    blt::table $inner \
1794        0,0 $inner.view_l -anchor e -pady 2 \
1795        0,1 $inner.view -anchor w -pady 2
1796
1797    set labels { qx qy qz qw xpan ypan zoom }
1798    set row 1
1799    foreach tag $labels {
1800        label $inner.${tag}label -text $tag -font "Arial 9"
1801        entry $inner.${tag} -font "Arial 9"  -bg white \
1802            -textvariable [itcl::scope _view($tag)]
1803        bind $inner.${tag} <KeyPress-Return> \
1804            [itcl::code $this camera set ${tag}]
1805        blt::table $inner \
1806            $row,0 $inner.${tag}label -anchor e -pady 2 \
1807            $row,1 $inner.${tag} -anchor w -pady 2
1808        blt::table configure $inner r$row -resize none
1809        incr row
1810    }
1811    checkbutton $inner.ortho \
1812        -text "Orthographic Projection" \
1813        -variable [itcl::scope _view(ortho)] \
1814        -command [itcl::code $this camera set ortho] \
1815        -font "Arial 9"
1816    blt::table $inner \
1817            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
1818    blt::table configure $inner r$row -resize none
1819    incr row
1820
1821    blt::table configure $inner c* r* -resize none
1822    blt::table configure $inner c2 -resize expand
1823    blt::table configure $inner r$row -resize expand
1824}
1825
1826itcl::body Rappture::VtkIsosurfaceViewer::BuildCutplaneTab {} {
1827
1828    set fg [option get $itk_component(hull) font Font]
1829   
1830    set inner [$itk_component(main) insert end \
1831        -title "Cutplane Settings" \
1832        -icon [Rappture::icon cutbutton]]
1833
1834    $inner configure -borderwidth 4
1835
1836    checkbutton $inner.visible \
1837        -text "Cutplanes" \
1838        -variable [itcl::scope _settings(-cutplanesvisible)] \
1839        -command [itcl::code $this AdjustSetting -cutplanesvisible] \
1840        -font "Arial 9"
1841
1842    checkbutton $inner.wireframe \
1843        -text "Wireframe" \
1844        -variable [itcl::scope _settings(-cutplanewireframe)] \
1845        -command [itcl::code $this AdjustSetting -cutplanewireframe] \
1846        -font "Arial 9"
1847
1848    checkbutton $inner.lighting \
1849        -text "Enable Lighting" \
1850        -variable [itcl::scope _settings(-cutplanelighting)] \
1851        -command [itcl::code $this AdjustSetting -cutplanelighting] \
1852        -font "Arial 9"
1853
1854    checkbutton $inner.edges \
1855        -text "Edges" \
1856        -variable [itcl::scope _settings(-cutplaneedges)] \
1857        -command [itcl::code $this AdjustSetting -cutplaneedges] \
1858        -font "Arial 9"
1859
1860    checkbutton $inner.preinterp \
1861        -text "Interpolate Scalars" \
1862        -variable [itcl::scope _settings(-cutplanepreinterp)] \
1863        -command [itcl::code $this AdjustSetting -cutplanepreinterp] \
1864        -font "Arial 9"
1865
1866    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1867    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1868        -variable [itcl::scope _settings(-cutplaneopacity)] \
1869        -width 10 \
1870        -showvalue off \
1871        -command [itcl::code $this AdjustSetting -cutplaneopacity]
1872    $inner.opacity set $_settings(-cutplaneopacity)
1873
1874    # X-value slicer...
1875    itk_component add xbutton {
1876        Rappture::PushButton $inner.xbutton \
1877            -onimage [Rappture::icon x-cutplane-red] \
1878            -offimage [Rappture::icon x-cutplane-red] \
1879            -command [itcl::code $this AdjustSetting -xcutplanevisible] \
1880            -variable [itcl::scope _settings(-xcutplanevisible)] \
1881    }
1882    Rappture::Tooltip::for $itk_component(xbutton) \
1883        "Toggle the X-axis cutplane on/off"
1884    $itk_component(xbutton) select
1885    itk_component add xposition {
1886        ::scale $inner.xval -from 100 -to 0 \
1887            -width 10 -orient vertical -showvalue 1 \
1888            -borderwidth 1 -highlightthickness 0 \
1889            -command [itcl::code $this EventuallySetCutplane x] \
1890            -variable [itcl::scope _settings(-xcutplaneposition)] \
1891            -foreground red2 -font "Arial 9 bold"
1892    } {
1893        usual
1894        ignore -borderwidth -highlightthickness -foreground -font -background
1895    }
1896    # Set the default cutplane value before disabling the scale.
1897    $itk_component(xposition) set 50
1898    $itk_component(xposition) configure -state disabled
1899    Rappture::Tooltip::for $itk_component(xposition) \
1900        "@[itcl::code $this Slice tooltip x]"
1901
1902    # Y-value slicer...
1903    itk_component add ybutton {
1904        Rappture::PushButton $inner.ybutton \
1905            -onimage [Rappture::icon y-cutplane-green] \
1906            -offimage [Rappture::icon y-cutplane-green] \
1907            -command [itcl::code $this AdjustSetting -ycutplanevisible] \
1908            -variable [itcl::scope _settings(-ycutplanevisible)] \
1909    }
1910    Rappture::Tooltip::for $itk_component(ybutton) \
1911        "Toggle the Y-axis cutplane on/off"
1912    $itk_component(ybutton) select
1913
1914    itk_component add yposition {
1915        ::scale $inner.yval -from 100 -to 0 \
1916            -width 10 -orient vertical -showvalue 1 \
1917            -borderwidth 1 -highlightthickness 0 \
1918            -command [itcl::code $this EventuallySetCutplane y] \
1919            -variable [itcl::scope _settings(-ycutplaneposition)] \
1920            -foreground green3 -font "Arial 9 bold"
1921    } {
1922        usual
1923        ignore -borderwidth -highlightthickness -foreground -font
1924    }
1925    Rappture::Tooltip::for $itk_component(yposition) \
1926        "@[itcl::code $this Slice tooltip y]"
1927    # Set the default cutplane value before disabling the scale.
1928    $itk_component(yposition) set 50
1929    $itk_component(yposition) configure -state disabled
1930
1931    # Z-value slicer...
1932    itk_component add zbutton {
1933        Rappture::PushButton $inner.zbutton \
1934            -onimage [Rappture::icon z-cutplane-blue] \
1935            -offimage [Rappture::icon z-cutplane-blue] \
1936            -command [itcl::code $this AdjustSetting -zcutplanevisible] \
1937            -variable [itcl::scope _settings(-zcutplanevisible)] \
1938    } {
1939        usual
1940        ignore -foreground
1941    }
1942    Rappture::Tooltip::for $itk_component(zbutton) \
1943        "Toggle the Z-axis cutplane on/off"
1944    $itk_component(zbutton) select
1945
1946    itk_component add zposition {
1947        ::scale $inner.zval -from 100 -to 0 \
1948            -width 10 -orient vertical -showvalue 1 \
1949            -borderwidth 1 -highlightthickness 0 \
1950            -command [itcl::code $this EventuallySetCutplane z] \
1951            -variable [itcl::scope _settings(-zcutplaneposition)] \
1952            -foreground blue3 -font "Arial 9 bold"
1953    } {
1954        usual
1955        ignore -borderwidth -highlightthickness -foreground -font
1956    }
1957    $itk_component(zposition) set 50
1958    $itk_component(zposition) configure -state disabled
1959    Rappture::Tooltip::for $itk_component(zposition) \
1960        "@[itcl::code $this Slice tooltip z]"
1961
1962    blt::table $inner \
1963        0,0 $inner.visible              -anchor w -pady 2 -cspan 3 \
1964        1,0 $inner.lighting             -anchor w -pady 2 -cspan 3 \
1965        2,0 $inner.wireframe            -anchor w -pady 2 -cspan 3 \
1966        3,0 $inner.edges                -anchor w -pady 2 -cspan 3 \
1967        4,0 $inner.preinterp            -anchor w -pady 2 -cspan 3 \
1968        5,0 $inner.opacity_l            -anchor w -pady 2 -cspan 1 \
1969        5,1 $inner.opacity              -fill x   -pady 2 -cspan 3 \
1970        6,0 $inner.xbutton              -anchor w -padx 2 -pady 2 \
1971        7,0 $inner.ybutton              -anchor w -padx 2 -pady 2 \
1972        8,0 $inner.zbutton              -anchor w -padx 2 -pady 2 \
1973        6,1 $inner.xval                 -fill y -rspan 4 \
1974        6,2 $inner.yval                 -fill y -rspan 4 \
1975        6,3 $inner.zval                 -fill y -rspan 4 \
1976
1977
1978    blt::table configure $inner r* c* -resize none
1979    blt::table configure $inner r9 c4 -resize expand
1980}
1981
1982
1983
1984#
1985#  camera --
1986#
1987itcl::body Rappture::VtkIsosurfaceViewer::camera {option args} {
1988    switch -- $option {
1989        "show" {
1990            puts [array get _view]
1991        }
1992        "set" {
1993            set who [lindex $args 0]
1994            set x $_view($who)
1995            set code [catch { string is double $x } result]
1996            if { $code != 0 || !$result } {
1997                return
1998            }
1999            switch -- $who {
2000                "ortho" {
2001                    if {$_view(ortho)} {
2002                        SendCmd "camera mode ortho"
2003                    } else {
2004                        SendCmd "camera mode persp"
2005                    }
2006                }
2007                "xpan" - "ypan" {
2008                    PanCamera
2009                }
2010                "qx" - "qy" - "qz" - "qw" {
2011                    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2012                    $_arcball quaternion $q
2013                    EventuallyRotate $q
2014                }
2015                "zoom" {
2016                    SendCmd "camera zoom $_view(zoom)"
2017                }
2018             }
2019        }
2020    }
2021}
2022
2023itcl::body Rappture::VtkIsosurfaceViewer::GetVtkData { args } {
2024    set bytes ""
2025    foreach dataobj [get] {
2026        foreach cname [$dataobj components] {
2027            set tag $dataobj-$cname
2028            set contents [$dataobj vtkdata $cname]
2029            append bytes "$contents\n"
2030        }
2031    }
2032    return [list .vtk $bytes]
2033}
2034
2035itcl::body Rappture::VtkIsosurfaceViewer::GetImage { args } {
2036    if { [image width $_image(download)] > 0 &&
2037         [image height $_image(download)] > 0 } {
2038        set bytes [$_image(download) data -format "jpeg -quality 100"]
2039        set bytes [Rappture::encoding::decode -as b64 $bytes]
2040        return [list .jpg $bytes]
2041    }
2042    return ""
2043}
2044
2045itcl::body Rappture::VtkIsosurfaceViewer::BuildDownloadPopup { popup command } {
2046    Rappture::Balloon $popup \
2047        -title "[Rappture::filexfer::label downloadWord] as..."
2048    set inner [$popup component inner]
2049    label $inner.summary -text "" -anchor w
2050    radiobutton $inner.vtk_button -text "VTK data file" \
2051        -variable [itcl::scope _downloadPopup(format)] \
2052        -font "Arial 9 " \
2053        -value vtk 
2054    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
2055    radiobutton $inner.image_button -text "Image File" \
2056        -variable [itcl::scope _downloadPopup(format)] \
2057        -font "Arial 9 " \
2058        -value image
2059    Rappture::Tooltip::for $inner.image_button \
2060        "Save as digital image."
2061
2062    button $inner.ok -text "Save" \
2063        -highlightthickness 0 -pady 2 -padx 3 \
2064        -command $command \
2065        -compound left \
2066        -image [Rappture::icon download]
2067
2068    button $inner.cancel -text "Cancel" \
2069        -highlightthickness 0 -pady 2 -padx 3 \
2070        -command [list $popup deactivate] \
2071        -compound left \
2072        -image [Rappture::icon cancel]
2073
2074    blt::table $inner \
2075        0,0 $inner.summary -cspan 2  \
2076        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2077        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2078        4,1 $inner.cancel -width .9i -fill y \
2079        4,0 $inner.ok -padx 2 -width .9i -fill y
2080    blt::table configure $inner r3 -height 4
2081    blt::table configure $inner r4 -pady 4
2082    raise $inner.image_button
2083    $inner.vtk_button invoke
2084    return $inner
2085}
2086
2087itcl::body Rappture::VtkIsosurfaceViewer::SetObjectStyle { dataobj comp } {
2088    # Parse style string.
2089    set tag $dataobj-$comp
2090    array set style {
2091        -color BCGYR
2092        -cutplanesvisible 0
2093        -edgecolor black
2094        -edges 0
2095        -isosurfacevisible 1
2096        -levels 10
2097        -lighting 1
2098        -linewidth 1.0
2099        -opacity 0.6
2100        -outline 0
2101        -xcutplanevisible 1
2102        -xcutplaneposition 50
2103        -ycutplanevisible 1
2104        -ycutplaneposition 50
2105        -zcutplanevisible 1
2106        -zcutplaneposition 50
2107        -wireframe 0
2108    }
2109    array set style [$dataobj style $comp]
2110    if { $dataobj != $_first || $style(-levels) == 1 } {
2111        set style(-opacity) 1
2112    }
2113    SendCmd "cutplane add $tag"
2114    SendCmd "cutplane visible 0 $tag"
2115
2116    # This is too complicated.  We want to set the colormap, number of
2117    # isolines and opacity for the dataset.  They can be the default values,
2118    # the style hints loaded with the dataset, or set by user controls.  As
2119    # datasets get loaded, they first use the defaults that are overidden
2120    # by the style hints.  If the user changes the global controls, then that
2121    # overrides everything else.  I don't know what it means when global
2122    # controls are specified as style hints by each dataset.  It complicates
2123    # the code to handle aberrant cases.
2124
2125    if { $_changed(-isosurfaceopacity) } {
2126        set style(-opacity) $_settings(-isosurfaceopacity)
2127    }
2128    if { $_changed(-numcontours) } {
2129        set style(-levels) $_settings(-numcontours)
2130    }
2131    if { $_changed(-colormap) } {
2132        set style(-color) $_settings(-colormap)
2133    }
2134    if { $_currentColormap == "" } {
2135        SetCurrentColormap $style(-color)
2136        $itk_component(colormap) value $style(-color)
2137    }
2138    set _currentOpacity $style(-opacity)
2139    if { $_currentNumContours != $style(-levels) } {
2140        set _currentNumContours $style(-levels)
2141        set _settings(-numcontours) $_currentNumContours
2142        $itk_component(numcontours) value $_currentNumContours
2143        UpdateContourList
2144        DrawLegend
2145    }
2146    set _settings(-isosurfacevisible) $style(-isosurfacevisible)
2147    set _settings(-cutplanesvisible)  $style(-cutplanesvisible)
2148    set _settings(-xcutplanevisible)  $style(-xcutplanevisible)
2149    set _settings(-ycutplanevisible)  $style(-ycutplanevisible)
2150    set _settings(-zcutplanevisible)  $style(-zcutplanevisible)
2151    set _settings(-xcutplaneposition) $style(-xcutplaneposition)
2152    set _settings(-ycutplaneposition) $style(-ycutplaneposition)
2153    set _settings(-zcutplaneposition) $style(-zcutplaneposition)
2154 
2155    SendCmd [list contour3d add contourlist $_contourList $tag]
2156    SendCmd "contour3d edges $style(-edges) $tag"
2157    SendCmd "outline add $tag"
2158    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
2159    SendCmd "outline visible $style(-outline) $tag"
2160    set _settings(-isosurfaceoutline) $style(-outline)
2161    set _settings(-isosurfaceedges) $style(-edges)
2162    #SendCmd "contour3d color [Color2RGB $settings(-color)] $tag"
2163    SendCmd "contour3d lighting $style(-lighting) $tag"
2164    set _settings(-isosurfacelighting) $style(-lighting)
2165    SendCmd "contour3d linecolor [Color2RGB $style(-edgecolor)] $tag"
2166    SendCmd "contour3d linewidth $style(-linewidth) $tag"
2167    SendCmd "contour3d opacity $_currentOpacity $tag"
2168    set _settings(-isosurfaceopacity) $style(-opacity)
2169    SetCurrentColormap $style(-color)
2170    SendCmd "contour3d wireframe $style(-wireframe) $tag"
2171    set _settings(-isosurfacewireframe) $style(-wireframe)
2172    set _settings(-isosurfaceopacity) [expr $style(-opacity) * 100.0]
2173}
2174
2175itcl::body Rappture::VtkIsosurfaceViewer::IsValidObject { dataobj } {
2176    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2177        return 0
2178    }
2179    return 1
2180}
2181
2182#
2183# EnterLegend --
2184#
2185itcl::body Rappture::VtkIsosurfaceViewer::EnterLegend { x y } {
2186    SetLegendTip $x $y
2187}
2188
2189#
2190# MotionLegend --
2191#
2192itcl::body Rappture::VtkIsosurfaceViewer::MotionLegend { x y } {
2193    Rappture::Tooltip::tooltip cancel
2194    set c $itk_component(view)
2195    set cw [winfo width $c]
2196    set ch [winfo height $c]
2197    if { $x >= 0 && $x < $cw && $y >= 0 && $y < $ch } {
2198        SetLegendTip $x $y
2199    }
2200}
2201
2202#
2203# LeaveLegend --
2204#
2205itcl::body Rappture::VtkIsosurfaceViewer::LeaveLegend { } {
2206    Rappture::Tooltip::tooltip cancel
2207    .rappturetooltip configure -icon ""
2208}
2209
2210#
2211# SetLegendTip --
2212#
2213itcl::body Rappture::VtkIsosurfaceViewer::SetLegendTip { x y } {
2214    set fname $_curFldName
2215    set c $itk_component(view)
2216    set w [winfo width $c]
2217    set h [winfo height $c]
2218
2219    set font "Arial 8"
2220    set lineht [font metrics $font -linespace]
2221   
2222    set ih [image height $_image(legend)]
2223    set iy [expr $y - ($lineht + 2)]
2224
2225    if { [string match "component*" $fname] } {
2226        set title ""
2227    } else {
2228        if { [info exists _fields($fname)] } {
2229            foreach { title units } $_fields($fname) break
2230            if { $units != "" } {
2231                set title [format "%s (%s)" $title $units]
2232            }
2233        } else {
2234            set title $fname
2235        }
2236    }
2237    # If there's a legend title, increase the offset by the line height.
2238    if { $title != "" } {
2239        incr iy -$lineht
2240    }
2241    # Make a swatch of the selected color
2242    if { [catch { $_image(legend) get 10 $iy } pixel] != 0 } {
2243        return
2244    }
2245    if { ![info exists _image(swatch)] } {
2246        set _image(swatch) [image create photo -width 24 -height 24]
2247    }
2248    set color [eval format "\#%02x%02x%02x" $pixel]
2249    $_image(swatch) put black  -to 0 0 23 23
2250    $_image(swatch) put $color -to 1 1 22 22
2251    .rappturetooltip configure -icon $_image(swatch)
2252
2253    # Compute the value of the point
2254    if { [info exists _limits($_curFldName)] } {
2255        foreach { vmin vmax } $_limits($_curFldName) break
2256        set t [expr 1.0 - (double($iy) / double($ih-1))]
2257        set value [expr $t * ($vmax - $vmin) + $vmin]
2258    } else {
2259        set value 0.0
2260    }
2261    set tx [expr $x + 15]
2262    set ty [expr $y - 5]
2263    if { [info exists _isolines($y)] } {
2264        Rappture::Tooltip::text $c [format "$title %g (isosurface)" $_isolines($y)]
2265    } else {
2266        Rappture::Tooltip::text $c [format "$title %g" $value]
2267    }
2268    Rappture::Tooltip::tooltip show $c +$tx,+$ty   
2269}
2270
2271
2272# ----------------------------------------------------------------------
2273# USAGE: Slice move x|y|z <newval>
2274#
2275# Called automatically when the user drags the slider to move the
2276# cut plane that slices 3D data.  Gets the current value from the
2277# slider and moves the cut plane to the appropriate point in the
2278# data set.
2279# ----------------------------------------------------------------------
2280itcl::body Rappture::VtkIsosurfaceViewer::Slice {option args} {
2281    switch -- $option {
2282        "move" {
2283            set axis [lindex $args 0]
2284            set newval [lindex $args 1]
2285            if {[llength $args] != 2} {
2286                error "wrong # args: should be \"Slice move x|y|z newval\""
2287            }
2288            set newpos [expr {0.01*$newval}]
2289            SendCmd "cutplane slice $axis $newpos"
2290        }
2291        "tooltip" {
2292            set axis [lindex $args 0]
2293            set val [$itk_component(${axis}position) get]
2294            return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2295        }
2296        default {
2297            error "bad option \"$option\": should be axis, move, or tooltip"
2298        }
2299    }
2300}
2301
2302#
2303# ReceiveLegend --
2304#
2305#       Invoked automatically whenever the "legend" command comes in from
2306#       the rendering server.  Indicates that binary image data with the
2307#       specified <size> will follow.
2308#
2309itcl::body Rappture::VtkIsosurfaceViewer::ReceiveLegend { colormap title min max size } {
2310    #puts stderr "ReceiveLegend colormap=$colormap title=$title range=$min,$max size=$size"
2311    set _title $title
2312    regsub {\(mag\)} $title "" _title
2313    if { [IsConnected] } {
2314        set bytes [ReceiveBytes $size]
2315        if { ![info exists _image(legend)] } {
2316            set _image(legend) [image create photo]
2317        }
2318        $_image(legend) configure -data $bytes
2319        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2320        if { [catch {DrawLegend} errs] != 0 } {
2321            global errorInfo
2322            puts stderr "errs=$errs errorInfo=$errorInfo"
2323        }
2324    }
2325}
2326
2327#
2328# DrawLegend --
2329#
2330#       Draws the legend in the own canvas on the right side of the plot area.
2331#
2332itcl::body Rappture::VtkIsosurfaceViewer::DrawLegend {} {
2333    set fname $_curFldName
2334    set c $itk_component(view)
2335    set w [winfo width $c]
2336    set h [winfo height $c]
2337    set font "Arial 8"
2338    set lineht [font metrics $font -linespace]
2339   
2340    if { [string match "component*" $fname] } {
2341        set title ""
2342    } else {
2343        if { [info exists _fields($fname)] } {
2344            foreach { title units } $_fields($fname) break
2345            if { $units != "" } {
2346                set title [format "%s (%s)" $title $units]
2347            }
2348        } else {
2349            set title $fname
2350        }
2351    }
2352    set x [expr $w - 2]
2353    if { !$_settings(-legendvisible) } {
2354        $c delete legend
2355        return
2356    }
2357    if { [$c find withtag "legend"] == "" } {
2358        set y 2
2359        # If there's a legend title, create a text item for the title.
2360        $c create text $x $y \
2361            -anchor ne \
2362            -fill $itk_option(-plotforeground) -tags "title legend" \
2363            -font $font
2364        if { $title != "" } {
2365            incr y $lineht
2366        }
2367        $c create text $x $y \
2368            -anchor ne \
2369            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2370            -font $font
2371        incr y $lineht
2372        $c create image $x $y \
2373            -anchor ne \
2374            -image $_image(legend) -tags "colormap legend"
2375        $c create rectangle $x $y 1 1 \
2376            -fill "" -outline "" -tags "sensor legend"
2377        $c create text $x [expr {$h-2}] \
2378            -anchor se \
2379            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2380            -font $font
2381        $c bind sensor <Enter> [itcl::code $this EnterLegend %x %y]
2382        $c bind sensor <Leave> [itcl::code $this LeaveLegend]
2383        $c bind sensor <Motion> [itcl::code $this MotionLegend %x %y]
2384    }
2385    $c delete isoline
2386    set x2 $x
2387    set iw [image width $_image(legend)]
2388    set ih [image height $_image(legend)]
2389    set x1 [expr $x2 - ($iw*12)/10]
2390    set color $_settings(-isolinecolor)
2391    # Draw the isolines on the legend.
2392    array unset _isolines
2393    if { $color != "none"  && [info exists _limits($_curFldName)] &&
2394         $_settings(-numcontours) > 0 } {
2395
2396        foreach { vmin vmax } $_limits($_curFldName) break
2397        set range [expr double($vmax - $vmin)]
2398        if { $range <= 0.0 } {
2399            set range 1.0;              # Min is greater or equal to max.
2400        }
2401        set tags "isoline legend"
2402        set offset [expr 2 + $lineht]
2403        if { $title != "" } {
2404            incr offset $lineht
2405        }
2406        foreach value $_contourList {
2407            set norm [expr 1.0 - (($value - $vmin) / $range)]
2408            set y1 [expr int(round(($norm * $ih) + $offset))]
2409            for { set off 0 } { $off < 3 } { incr off } {
2410                set _isolines([expr $y1 + $off]) $value
2411                set _isolines([expr $y1 - $off]) $value
2412            }
2413            $c create line $x1 $y1 $x2 $y1 -fill $color -tags $tags
2414        }
2415    }
2416
2417    $c bind title <ButtonPress> [itcl::code $this Combo post]
2418    $c bind title <Enter> [itcl::code $this Combo activate]
2419    $c bind title <Leave> [itcl::code $this Combo deactivate]
2420    # Reset the item coordinates according the current size of the plot.
2421    $c itemconfigure title -text $title
2422    if { [info exists _limits($_curFldName)] } {
2423        foreach { vmin vmax } $_limits($_curFldName) break
2424        $c itemconfigure vmin -text [format %g $vmin]
2425        $c itemconfigure vmax -text [format %g $vmax]
2426    }
2427    set y 2
2428    # If there's a legend title, move the title to the correct position
2429    if { $title != "" } {
2430        $c itemconfigure title -text $title
2431        $c coords title $x $y
2432        incr y $lineht
2433        $c raise title
2434    }
2435    $c coords vmax $x $y
2436    incr y $lineht
2437    $c coords colormap $x $y
2438    $c coords sensor [expr $x - $iw] $y $x [expr $y + $ih]
2439    $c raise sensor
2440    $c coords vmin $x [expr {$h - 2}]
2441}
2442
2443# ----------------------------------------------------------------------
2444# USAGE: _dropdown post
2445# USAGE: _dropdown unpost
2446# USAGE: _dropdown select
2447#
2448# Used internally to handle the dropdown list for this combobox.  The
2449# post/unpost options are invoked when the list is posted or unposted
2450# to manage the relief of the controlling button.  The select option
2451# is invoked whenever there is a selection from the list, to assign
2452# the value back to the gauge.
2453# ----------------------------------------------------------------------
2454itcl::body Rappture::VtkIsosurfaceViewer::Combo {option} {
2455    set c $itk_component(view)
2456    switch -- $option {
2457        post {
2458            foreach { x1 y1 x2 y2 } [$c bbox title] break
2459            set cw [winfo width $itk_component(view)]
2460            set mw [winfo reqwidth $itk_component(fieldmenu)]
2461            set x1 [expr $cw - $mw]
2462            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2463            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2464            tk_popup $itk_component(fieldmenu) $x $y
2465        }
2466        activate {
2467            $c itemconfigure title -fill red
2468        }
2469        deactivate {
2470            $c itemconfigure title -fill $itk_option(-plotforeground)
2471        }
2472        invoke {
2473            $itk_component(field) value $_curFldLabel
2474            AdjustSetting -field
2475        }
2476        default {
2477            error "bad option \"$option\": should be post, unpost, select"
2478        }
2479    }
2480}
2481
2482#
2483# SetCurrentColormap --
2484#
2485itcl::body Rappture::VtkIsosurfaceViewer::SetCurrentColormap { name } {
2486    # Keep track of the colormaps that we build.
2487    if { ![info exists _colormaps($name)] } {
2488        BuildColormap $name
2489        set _colormaps($name) 1
2490    }
2491    set _currentColormap $name
2492    SendCmd "contour3d colormap $_currentColormap"
2493    SendCmd "cutplane colormap $_currentColormap"
2494}
2495
2496#
2497# BuildColormap --
2498#
2499#       Build the designated colormap on the server.
2500#
2501itcl::body Rappture::VtkIsosurfaceViewer::BuildColormap { name } {
2502    set cmap [ColorsToColormap $name]
2503    if { [llength $cmap] == 0 } {
2504        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
2505    }
2506    set wmap "0.0 1.0 1.0 1.0"
2507    SendCmd "colormap add $name { $cmap } { $wmap }"
2508}
2509
2510itcl::body Rappture::VtkIsosurfaceViewer::SetOrientation { side } {
2511    array set positions {
2512        front "1 0 0 0"
2513        back  "0 0 1 0"
2514        left  "0.707107 0 -0.707107 0"
2515        right "0.707107 0 0.707107 0"
2516        top   "0.707107 -0.707107 0 0"
2517        bottom "0.707107 0.707107 0 0"
2518    }
2519    foreach name { qw qx qy qz } value $positions($side) {
2520        set _view($name) $value
2521    }
2522    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2523    $_arcball quaternion $q
2524    SendCmd "camera orient $q"
2525    SendCmd "camera reset"
2526    set _view(xpan) 0
2527    set _view(ypan) 0
2528    set _view(zoom) 1.0
2529}
2530
2531itcl::body Rappture::VtkIsosurfaceViewer::UpdateContourList {} {
2532    if { ![info exists _limits($_curFldName)] } {
2533        return
2534    }
2535    if { $_currentNumContours < 1 } {
2536        set _contourList ""
2537        return
2538    }
2539    foreach { vmin vmax } $_limits($_curFldName) break
2540    set v [blt::vector create \#auto]
2541    $v seq $vmin $vmax [expr $_currentNumContours+2]
2542    $v delete end 0
2543    set _contourList [$v range 0 end]
2544    blt::vector destroy $v
2545}
2546
Note: See TracBrowser for help on using the repository browser.