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

Last change on this file since 4563 was 4533, checked in by gah, 10 years ago

update regression tester

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