source: branches/uq/gui/scripts/vtkisosurfaceviewer.tcl @ 4798

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

sync with former 1.3 branch

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