source: branches/1.3/gui/scripts/vtkisosurfaceviewer.tcl @ 4766

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

merge r4765 from trunk

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