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

Last change on this file since 3543 was 3543, checked in by gah, 12 years ago

fix order of values in legend; tweak placement of isosurfaces

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