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

Last change on this file since 3409 was 3409, checked in by gah, 11 years ago

nanovis missing _ in of _width, isosurface broke with wrong component name, streamlines default axis names changed to X, Y, and Z

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