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

Last change on this file since 4797 was 4797, checked in by gah, 6 years ago

sync with 1.4-pre

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 parameters {title args} {
60        # do nothing
61    }
62    public method scale {args}
63
64    # The following methods are only used by this class.
65
66    private method AdjustSetting {what {value ""}}
67    private method BuildAxisTab {}
68    private method BuildCameraTab {}
69    private method BuildColormap { name }
70    private method BuildCutplaneTab {}
71    private method BuildDownloadPopup { widget command }
72    private method BuildIsosurfaceTab {}
73    private method Combo { option }
74    private method Connect {}
75    private method CurrentDatasets {args}
76    private method Disconnect {}
77    private method DoChangeContourLevels {}
78    private method DoResize {}
79    private method DoRotate {}
80    private method DrawLegend {}
81    private method EnterLegend { x y }
82    private method EventuallyChangeContourLevels {}
83    private method EventuallyRequestLegend {}
84    private method EventuallyResize { w h }
85    private method EventuallyRotate { q }
86    private method EventuallySetCutplane { axis args }
87    private method GenerateContourList {}
88    private method GetImage { args }
89    private method GetVtkData { args }
90    private method InitSettings { args  }
91    private method IsValidObject { dataobj }
92    private method LeaveLegend {}
93    private method MotionLegend { x y }
94    private method Pan {option x y}
95    private method PanCamera {}
96    private method Pick {x y}
97    private method Rebuild {}
98    private method ReceiveDataset { args }
99    private method ReceiveImage { args }
100    private method ReceiveLegend { colormap title vmin vmax size }
101    private method RequestLegend {}
102    private method Rotate {option x y}
103    private method SetCurrentColormap { color }
104    private method SetCurrentFieldName { dataobj }
105    private method SetLegendTip { x y }
106    private method SetObjectStyle { dataobj comp }
107    private method SetOrientation { side }
108    private method Slice {option args}
109    private method Zoom {option}
110    private method ViewToQuaternion {} {
111        return [list $_view(-qw) $_view(-qx) $_view(-qy) $_view(-qz)]
112    }
113
114    private variable _arcball ""
115
116    private variable _dlist ""     ;    # list of data objects
117    private variable _obj2datasets
118    private variable _obj2ovride   ;    # maps dataobj => style override
119    private variable _datasets     ;    # contains all the dataobj-component
120                                   ;    # datasets in the server
121    private variable _colormaps    ;    # contains all the colormaps
122                                   ;    # in the server.
123    # The name of the current colormap used.  The colormap is global to all
124    # heightmaps displayed.
125    private variable _currentColormap ""
126    private variable _currentNumContours -1
127
128    private variable _dataset2style    ;# maps dataobj-component to transfunc
129
130    private variable _click        ;    # info used for rotate operations
131    private variable _limits       ;    # autoscale min/max for all axes
132    private variable _view         ;    # view params for 3D view
133    private variable _settings
134    private variable _style;            # Array of current component styles.
135    private variable _changed
136    private variable _initialStyle;     # Array of initial component styles.
137    private variable _reset 1;          # indicates if camera needs to be reset
138                                        # to starting position.
139
140    private variable _first ""     ;    # This is the topmost dataset.
141    private variable _start 0
142    private variable _title ""
143    private variable _isolines
144    private variable _contourList
145    private variable _currentLimits ""
146    private variable _widget
147
148    common _downloadPopup;              # download options from popup
149    private common _hardcopy
150    private variable _width 0
151    private variable _height 0
152    private variable _resizePending 0
153    private variable _rotatePending 0
154    private variable _cutplanePending 0
155    private variable _legendPending 0
156    private variable _field      ""
157    private variable _colorMode "scalar";       #  Mode of colormap (vmag or scalar)
158    private variable _fieldNames {}
159    private variable _fields
160    private variable _curFldName ""
161    private variable _curFldLabel ""
162}
163
164itk::usual VtkIsosurfaceViewer {
165    keep -background -foreground -cursor -font
166    keep -plotbackground -plotforeground
167}
168
169# ----------------------------------------------------------------------
170# CONSTRUCTOR
171# ----------------------------------------------------------------------
172itcl::body Rappture::VtkIsosurfaceViewer::constructor {hostlist args} {
173    package require vtk
174    set _serverType "vtkvis"
175
176    # Rebuild event
177    $_dispatcher register !rebuild
178    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
179
180    # Resize event
181    $_dispatcher register !resize
182    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
183
184    # Rotate event
185    $_dispatcher register !rotate
186    $_dispatcher dispatch $this !rotate "[itcl::code $this DoRotate]; list"
187
188    # Legend event
189    $_dispatcher register !legend
190    $_dispatcher dispatch $this !legend "[itcl::code $this RequestLegend]; list"
191
192    # Contour levels event
193    $_dispatcher register !contours
194    $_dispatcher dispatch $this !contours \
195        "[itcl::code $this DoChangeContourLevels]; list"
196
197    # X-Cutplane event
198    $_dispatcher register !xcutplane
199    $_dispatcher dispatch $this !xcutplane \
200        "[itcl::code $this AdjustSetting -xcutplaneposition]; list"
201
202    # Y-Cutplane event
203    $_dispatcher register !ycutplane
204    $_dispatcher dispatch $this !ycutplane \
205        "[itcl::code $this AdjustSetting -ycutplaneposition]; list"
206
207    # Z-Cutplane event
208    $_dispatcher register !zcutplane
209    $_dispatcher dispatch $this !zcutplane \
210        "[itcl::code $this AdjustSetting -zcutplaneposition]; list"
211
212    #
213    # Populate parser with commands handle incoming requests
214    #
215    $_parser alias image [itcl::code $this ReceiveImage]
216    $_parser alias dataset [itcl::code $this ReceiveDataset]
217    $_parser alias legend [itcl::code $this ReceiveLegend]
218
219    # Initialize the view to some default parameters.
220    array set _view {
221        -ortho           0
222        -qw              0.853553
223        -qx              -0.353553
224        -qy              0.353553
225        -qz              0.146447
226        -xpan            0
227        -ypan            0
228        -zoom            1.0
229    }
230    set _arcball [blt::arcball create 100 100]
231    $_arcball quaternion [ViewToQuaternion]
232
233    array set _contourList {
234        numLevels       10
235        reqValues       ""
236        updatePending   0
237        values          ""
238    }
239    array set _settings {
240        -axesvisible                    1
241        -axislabels                     1
242        -axisminorticks                 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 -axislabels -axisminorticks -ortho
997        #SendCmd "axis lformat all %g"
998        StopBufferingCommands
999        SendCmd "imgflush"
1000        StartBufferingCommands
1001    }
1002    set _first ""
1003    SendCmd "dataset visible 0"
1004    eval scale $_dlist
1005    foreach dataobj [get -objects] {
1006        if { [info exists _obj2ovride($dataobj-raise)] &&  $_first == "" } {
1007            set _first $dataobj
1008            SetCurrentFieldName $dataobj
1009        }
1010        set _obj2datasets($dataobj) ""
1011        foreach comp [$dataobj components] {
1012            set tag $dataobj-$comp
1013            if { ![info exists _datasets($tag)] } {
1014                set bytes [$dataobj vtkdata $comp]
1015                if 0 {
1016                    set f [open "/tmp/isosurface.vtk" "w"]
1017                    puts $f $bytes
1018                    close $f
1019                }
1020                set length [string length $bytes]
1021                if { $_reportClientInfo }  {
1022                    set info {}
1023                    lappend info "tool_id"       [$dataobj hints toolId]
1024                    lappend info "tool_name"     [$dataobj hints toolName]
1025                    lappend info "tool_version"  [$dataobj hints toolRevision]
1026                    lappend info "tool_title"    [$dataobj hints toolTitle]
1027                    lappend info "dataset_label" [$dataobj hints label]
1028                    lappend info "dataset_size"  $length
1029                    lappend info "dataset_tag"   $tag
1030                    SendCmd "clientinfo [list $info]"
1031                }
1032                SendCmd "dataset add $tag data follows $length"
1033                append _outbuf $bytes
1034                set _datasets($tag) 1
1035                SetObjectStyle $dataobj $comp
1036            }
1037            lappend _obj2datasets($dataobj) $tag
1038            if { [info exists _obj2ovride($dataobj-raise)] } {
1039                SendCmd "contour3d visible 1 $tag"
1040            }
1041        }
1042    }
1043
1044    InitSettings -cutplanesvisible -isosurfacevisible -outline
1045    if { $_reset } {
1046        # These are settings that rely on a dataset being loaded.
1047        InitSettings \
1048            -isosurfacelighting \
1049            -field \
1050            -isosurfacevisible \
1051            -isosurfaceedges -isosurfacelighting -isosurfaceopacity \
1052            -isosurfacewireframe \
1053            -cutplanesvisible \
1054            -xcutplaneposition -ycutplaneposition -zcutplaneposition \
1055            -xcutplanevisible -ycutplanevisible -zcutplanevisible \
1056            -cutplanepreinterp -numcontours
1057
1058        Zoom reset
1059        foreach axis { x y z } {
1060            # Another problem fixed by a <view>. We looking into a data
1061            # object for the name of the axes. This should be global to
1062            # the viewer itself.
1063            set label [$_first hints ${axis}label]
1064            if { $label == "" } {
1065                set label [string toupper $axis]
1066            }
1067            SendCmd [list axis name $axis $label]
1068        }
1069        if { [array size _fields] < 2 } {
1070            catch {blt::table forget $itk_component(field) $itk_component(field_l)}
1071        }
1072        set _reset 0
1073    }
1074    # Redraw the legend even if we're using the same colormap. The position
1075    # of the isolines may have changed because the range of data changed.
1076    DrawLegend
1077
1078    # Actually write the commands to the server socket.  If it fails, we don't
1079    # care.  We're finished here.
1080    blt::busy hold $itk_component(hull)
1081    StopBufferingCommands;              # Turn off buffering and send commands.
1082    blt::busy release $itk_component(hull)
1083}
1084
1085# ----------------------------------------------------------------------
1086# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1087#
1088# Returns a list of server IDs for the current datasets being displayed.  This
1089# is normally a single ID, but it might be a list of IDs if the current data
1090# object has multiple components.
1091# ----------------------------------------------------------------------
1092itcl::body Rappture::VtkIsosurfaceViewer::CurrentDatasets {args} {
1093    set flag [lindex $args 0]
1094    switch -- $flag {
1095        "-all" {
1096            if { [llength $args] > 1 } {
1097                error "CurrentDatasets: can't specify dataobj after \"-all\""
1098            }
1099            set dlist [get -objects]
1100        }
1101        "-visible" {
1102            if { [llength $args] > 1 } {
1103                set dlist {}
1104                set args [lrange $args 1 end]
1105                foreach dataobj $args {
1106                    if { [info exists _obj2ovride($dataobj-raise)] } {
1107                        lappend dlist $dataobj
1108                    }
1109                }
1110            } else {
1111                set dlist [get -visible]
1112            }
1113        }           
1114        default {
1115            set dlist $args
1116        }
1117    }
1118    set rlist ""
1119    foreach dataobj $dlist {
1120        foreach comp [$dataobj components] {
1121            set tag $dataobj-$comp
1122            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1123                lappend rlist $tag
1124            }
1125        }
1126    }
1127    return $rlist
1128}
1129
1130# ----------------------------------------------------------------------
1131# USAGE: Zoom in
1132# USAGE: Zoom out
1133# USAGE: Zoom reset
1134#
1135# Called automatically when the user clicks on one of the zoom
1136# controls for this widget.  Changes the zoom for the current view.
1137# ----------------------------------------------------------------------
1138itcl::body Rappture::VtkIsosurfaceViewer::Zoom {option} {
1139    switch -- $option {
1140        "in" {
1141            set _view(-zoom) [expr {$_view(-zoom)*1.25}]
1142            SendCmd "camera zoom $_view(-zoom)"
1143        }
1144        "out" {
1145            set _view(-zoom) [expr {$_view(-zoom)*0.8}]
1146            SendCmd "camera zoom $_view(-zoom)"
1147        }
1148        "reset" {
1149            array set _view {
1150                -qw     0.853553
1151                -qx     -0.353553
1152                -qy     0.353553
1153                -qz     0.146447
1154                -xpan   0
1155                -ypan   0
1156                -zoom   1.0
1157            }
1158            if { $_first != "" } {
1159                set location [$_first hints camera]
1160                if { $location != "" } {
1161                    array set _view $location
1162                }
1163            }
1164            $_arcball quaternion [ViewToQuaternion]
1165            DoRotate
1166            SendCmd "camera reset"
1167        }
1168    }
1169}
1170
1171itcl::body Rappture::VtkIsosurfaceViewer::PanCamera {} {
1172    set x $_view(-xpan)
1173    set y $_view(-ypan)
1174    SendCmd "camera pan $x $y"
1175}
1176
1177
1178# ----------------------------------------------------------------------
1179# USAGE: Rotate click <x> <y>
1180# USAGE: Rotate drag <x> <y>
1181# USAGE: Rotate release <x> <y>
1182#
1183# Called automatically when the user clicks/drags/releases in the
1184# plot area.  Moves the plot according to the user's actions.
1185# ----------------------------------------------------------------------
1186itcl::body Rappture::VtkIsosurfaceViewer::Rotate {option x y} {
1187    switch -- $option {
1188        "click" {
1189            $itk_component(view) configure -cursor fleur
1190            set _click(x) $x
1191            set _click(y) $y
1192        }
1193        "drag" {
1194            if {[array size _click] == 0} {
1195                Rotate click $x $y
1196            } else {
1197                set w [winfo width $itk_component(view)]
1198                set h [winfo height $itk_component(view)]
1199                if {$w <= 0 || $h <= 0} {
1200                    return
1201                }
1202
1203                if {[catch {
1204                    # this fails sometimes for no apparent reason
1205                    set dx [expr {double($x-$_click(x))/$w}]
1206                    set dy [expr {double($y-$_click(y))/$h}]
1207                }]} {
1208                    return
1209                }
1210                if { $dx == 0 && $dy == 0 } {
1211                    return
1212                }
1213                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1214                EventuallyRotate $q
1215                set _click(x) $x
1216                set _click(y) $y
1217            }
1218        }
1219        "release" {
1220            Rotate drag $x $y
1221            $itk_component(view) configure -cursor ""
1222            catch {unset _click}
1223        }
1224        default {
1225            error "bad option \"$option\": should be click, drag, release"
1226        }
1227    }
1228}
1229
1230itcl::body Rappture::VtkIsosurfaceViewer::Pick {x y} {
1231    foreach tag [CurrentDatasets -visible] {
1232        SendCmdNoSplash "dataset getscalar pixel $x $y $tag"
1233    }
1234}
1235
1236# ----------------------------------------------------------------------
1237# USAGE: $this Pan click x y
1238#        $this Pan drag x y
1239#        $this Pan release x y
1240#
1241# Called automatically when the user clicks on one of the zoom
1242# controls for this widget.  Changes the zoom for the current view.
1243# ----------------------------------------------------------------------
1244itcl::body Rappture::VtkIsosurfaceViewer::Pan {option x y} {
1245    switch -- $option {
1246        "set" {
1247            set w [winfo width $itk_component(view)]
1248            set h [winfo height $itk_component(view)]
1249            set x [expr $x / double($w)]
1250            set y [expr $y / double($h)]
1251            set _view(-xpan) [expr $_view(-xpan) + $x]
1252            set _view(-ypan) [expr $_view(-ypan) + $y]
1253            PanCamera
1254            return
1255        }
1256        "click" {
1257            set _click(x) $x
1258            set _click(y) $y
1259            $itk_component(view) configure -cursor hand1
1260        }
1261        "drag" {
1262            if { ![info exists _click(x)] } {
1263                set _click(x) $x
1264            }
1265            if { ![info exists _click(y)] } {
1266                set _click(y) $y
1267            }
1268            set w [winfo width $itk_component(view)]
1269            set h [winfo height $itk_component(view)]
1270            set dx [expr ($_click(x) - $x)/double($w)]
1271            set dy [expr ($_click(y) - $y)/double($h)]
1272            set _click(x) $x
1273            set _click(y) $y
1274            set _view(-xpan) [expr $_view(-xpan) - $dx]
1275            set _view(-ypan) [expr $_view(-ypan) - $dy]
1276            PanCamera
1277        }
1278        "release" {
1279            Pan drag $x $y
1280            $itk_component(view) configure -cursor ""
1281        }
1282        default {
1283            error "unknown option \"$option\": should set, click, drag, or release"
1284        }
1285    }
1286}
1287
1288# ----------------------------------------------------------------------
1289# USAGE: InitSettings <what> ?<value>?
1290#
1291# Used internally to update rendering settings whenever parameters
1292# change in the popup settings panel.  Sends the new settings off
1293# to the back end.
1294# ----------------------------------------------------------------------
1295itcl::body Rappture::VtkIsosurfaceViewer::InitSettings { args } {
1296    foreach spec $args {
1297        if { [info exists _settings($_first-$spec)] } {
1298            # Reset global setting with dataobj specific setting
1299            set _settings($spec) $_settings($_first-$spec)
1300        }
1301        AdjustSetting $spec
1302    }
1303}
1304
1305#
1306# AdjustSetting --
1307#
1308#       Changes/updates a specific setting in the widget.  There are
1309#       usually user-setable option.  Commands are sent to the render
1310#       server.
1311#
1312itcl::body Rappture::VtkIsosurfaceViewer::AdjustSetting {what {value ""}} {
1313    if { ![isconnected] } {
1314        return
1315    }
1316    switch -- $what {
1317        "-axesvisible" {
1318            set bool $_settings($what)
1319            SendCmd "axis visible all $bool"
1320        }
1321        "-axislabels" {
1322            set bool $_settings($what)
1323            SendCmd "axis labels all $bool"
1324        }
1325        "-axisminorticks" {
1326            set bool $_settings($what)
1327            SendCmd "axis minticks 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::BuildIsosurfaceTab {} {
1601
1602    set fg [option get $itk_component(hull) font Font]
1603    #set bfg [option get $itk_component(hull) boldFont Font]
1604
1605    set inner [$itk_component(main) insert end \
1606        -title "Isosurface Settings" \
1607        -icon [Rappture::icon volume-on]]
1608    $inner configure -borderwidth 4
1609
1610    checkbutton $inner.contour \
1611        -text "Isosurfaces" \
1612        -variable [itcl::scope _settings(-isosurfacevisible)] \
1613        -command [itcl::code $this AdjustSetting -isosurfacevisible] \
1614        -font "Arial 9"
1615
1616    checkbutton $inner.wireframe \
1617        -text "Wireframe" \
1618        -variable [itcl::scope _settings(-isosurfacewireframe)] \
1619        -command [itcl::code $this AdjustSetting -isosurfacewireframe] \
1620        -font "Arial 9"
1621
1622    checkbutton $inner.lighting \
1623        -text "Enable Lighting" \
1624        -variable [itcl::scope _settings(-isosurfacelighting)] \
1625        -command [itcl::code $this AdjustSetting -isosurfacelighting] \
1626        -font "Arial 9"
1627
1628    checkbutton $inner.edges \
1629        -text "Edges" \
1630        -variable [itcl::scope _settings(-isosurfaceedges)] \
1631        -command [itcl::code $this AdjustSetting -isosurfaceedges] \
1632        -font "Arial 9"
1633
1634    checkbutton $inner.outline \
1635        -text "Outline" \
1636        -variable [itcl::scope _settings(-outline)] \
1637        -command [itcl::code $this AdjustSetting -outline] \
1638        -font "Arial 9"
1639
1640    checkbutton $inner.legend \
1641        -text "Legend" \
1642        -variable [itcl::scope _settings(-legendvisible)] \
1643        -command [itcl::code $this AdjustSetting -legendvisible] \
1644        -font "Arial 9"
1645
1646    label $inner.linecolor_l -text "Isolines" -font "Arial 9"
1647    itk_component add isolineColor {
1648        Rappture::Combobox $inner.linecolor -width 10 -editable 0
1649    }
1650    $inner.linecolor choices insert end \
1651        "black"              "black"            \
1652        "blue"               "blue"             \
1653        "cyan"               "cyan"             \
1654        "green"              "green"            \
1655        "grey"               "grey"             \
1656        "magenta"            "magenta"          \
1657        "orange"             "orange"           \
1658        "red"                "red"              \
1659        "white"              "white"            \
1660        "none"               "none"
1661
1662    $itk_component(isolineColor) value "white"
1663    bind $inner.linecolor <<Value>> \
1664        [itcl::code $this AdjustSetting -isolinecolor]
1665
1666    label $inner.background_l -text "Background" -font "Arial 9"
1667    itk_component add background {
1668        Rappture::Combobox $inner.background -width 10 -editable 0
1669    }
1670    $inner.background choices insert end \
1671        "black"              "black"            \
1672        "white"              "white"            \
1673        "grey"               "grey"             
1674
1675    $itk_component(background) value $_settings(-background)
1676    bind $inner.background <<Value>> \
1677        [itcl::code $this AdjustSetting -background]
1678
1679    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1680    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1681        -variable [itcl::scope _widget(-isosurfaceopacity)] \
1682        -width 10 \
1683        -showvalue off \
1684        -command [itcl::code $this AdjustSetting -isosurfaceopacity]
1685    $inner.opacity set [expr $_settings(-isosurfaceopacity) * 100.0]
1686
1687    itk_component add field_l {
1688        label $inner.field_l -text "Field" -font "Arial 9"
1689    } {
1690        ignore -font
1691    }
1692    itk_component add field {
1693        Rappture::Combobox $inner.field -width 10 -editable 0
1694    }
1695    bind $inner.field <<Value>> \
1696        [itcl::code $this AdjustSetting -field]
1697
1698    label $inner.colormap_l -text "Colormap" -font "Arial 9"
1699    itk_component add colormap {
1700        Rappture::Combobox $inner.colormap -width 10 -editable 0
1701    }
1702    $inner.colormap choices insert end [GetColormapList]
1703
1704    $itk_component(colormap) value "BCGYR"
1705    bind $inner.colormap <<Value>> \
1706        [itcl::code $this AdjustSetting -colormap]
1707
1708    label $inner.numcontours_l -text "Number of Isosurfaces" -font "Arial 9"
1709    itk_component add numcontours {
1710        Rappture::Spinint $inner.numcontours \
1711            -min 0 -max 50 -font "arial 9"
1712    }
1713    $itk_component(numcontours) value $_settings(-numcontours)
1714    bind $itk_component(numcontours) <<Value>> \
1715        [itcl::code $this AdjustSetting -numcontours]
1716
1717    blt::table $inner \
1718        0,0 $inner.field_l   -anchor w -pady 2  \
1719        0,1 $inner.field     -anchor w -pady 2  -fill x \
1720        1,0 $inner.colormap_l -anchor w -pady 2  \
1721        1,1 $inner.colormap   -anchor w -pady 2  -fill x \
1722        2,0 $inner.linecolor_l  -anchor w -pady 2  \
1723        2,1 $inner.linecolor    -anchor w -pady 2 -fill x  \
1724        3,0 $inner.background_l -anchor w -pady 2 \
1725        3,1 $inner.background -anchor w -pady 2  -fill x \
1726        4,0 $inner.numcontours_l -anchor w -pady 2 \
1727        4,1 $inner.numcontours -anchor w -pady 2 \
1728        5,0 $inner.wireframe -anchor w -pady 2 -cspan 2 \
1729        6,0 $inner.lighting  -anchor w -pady 2 -cspan 2 \
1730        7,0 $inner.edges     -anchor w -pady 2 -cspan 2 \
1731        8,0 $inner.outline   -anchor w -pady 2 -cspan 2 \
1732        9,0 $inner.legend    -anchor w -pady 2 \
1733        10,0 $inner.opacity_l -anchor w -pady 2 \
1734        10,1 $inner.opacity   -fill x   -pady 2 -fill x \
1735
1736    blt::table configure $inner r* c* -resize none
1737    blt::table configure $inner r11 c1 -resize expand
1738}
1739
1740itcl::body Rappture::VtkIsosurfaceViewer::BuildAxisTab {} {
1741
1742    set fg [option get $itk_component(hull) font Font]
1743    #set bfg [option get $itk_component(hull) boldFont Font]
1744
1745    set inner [$itk_component(main) insert end \
1746        -title "Axis Settings" \
1747        -icon [Rappture::icon axis2]]
1748    $inner configure -borderwidth 4
1749
1750    checkbutton $inner.visible \
1751        -text "Axes" \
1752        -variable [itcl::scope _settings(-axesvisible)] \
1753        -command [itcl::code $this AdjustSetting -axesvisible] \
1754        -font "Arial 9"
1755
1756    checkbutton $inner.labels \
1757        -text "Axis Labels" \
1758        -variable [itcl::scope _settings(-axislabels)] \
1759        -command [itcl::code $this AdjustSetting -axislabels] \
1760        -font "Arial 9"
1761    label $inner.grid_l -text "Grid" -font "Arial 9"
1762    checkbutton $inner.xgrid \
1763        -text "X" \
1764        -variable [itcl::scope _settings(-xgrid)] \
1765        -command [itcl::code $this AdjustSetting -xgrid] \
1766        -font "Arial 9"
1767    checkbutton $inner.ygrid \
1768        -text "Y" \
1769        -variable [itcl::scope _settings(-ygrid)] \
1770        -command [itcl::code $this AdjustSetting -ygrid] \
1771        -font "Arial 9"
1772    checkbutton $inner.zgrid \
1773        -text "Z" \
1774        -variable [itcl::scope _settings(-zgrid)] \
1775        -command [itcl::code $this AdjustSetting -zgrid] \
1776        -font "Arial 9"
1777    checkbutton $inner.minorticks \
1778        -text "Minor Ticks" \
1779        -variable [itcl::scope _settings(-axisminorticks)] \
1780        -command [itcl::code $this AdjustSetting -axisminorticks] \
1781        -font "Arial 9"
1782
1783    label $inner.mode_l -text "Mode" -font "Arial 9"
1784
1785    itk_component add axisMode {
1786        Rappture::Combobox $inner.mode -width 10 -editable 0
1787    }
1788    $inner.mode choices insert end \
1789        "static_triad"    "static" \
1790        "closest_triad"   "closest" \
1791        "furthest_triad"  "farthest" \
1792        "outer_edges"     "outer"         
1793    $itk_component(axisMode) value $_settings(-axismode)
1794    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting -axismode]
1795
1796    blt::table $inner \
1797        0,0 $inner.visible -anchor w -cspan 4 \
1798        1,0 $inner.labels  -anchor w -cspan 4 \
1799        2,0 $inner.minorticks  -anchor w -cspan 4 \
1800        4,0 $inner.grid_l  -anchor w \
1801        4,1 $inner.xgrid   -anchor w \
1802        4,2 $inner.ygrid   -anchor w \
1803        4,3 $inner.zgrid   -anchor w \
1804        5,0 $inner.mode_l  -anchor w -padx { 2 0 } \
1805        5,1 $inner.mode    -fill x   -cspan 3
1806
1807    blt::table configure $inner r* c* -resize none
1808    blt::table configure $inner r7 c6 -resize expand
1809    blt::table configure $inner r3 -height 0.125i
1810}
1811
1812
1813itcl::body Rappture::VtkIsosurfaceViewer::BuildCameraTab {} {
1814    set inner [$itk_component(main) insert end \
1815        -title "Camera Settings" \
1816        -icon [Rappture::icon camera]]
1817    $inner configure -borderwidth 4
1818
1819    label $inner.view_l -text "view" -font "Arial 9"
1820    set f [frame $inner.view]
1821    foreach side { front back left right top bottom } {
1822        button $f.$side  -image [Rappture::icon view$side] \
1823            -command [itcl::code $this SetOrientation $side]
1824        Rappture::Tooltip::for $f.$side "Change the view to $side"
1825        pack $f.$side -side left
1826    }
1827
1828    blt::table $inner \
1829        0,0 $inner.view_l -anchor e -pady 2 \
1830        0,1 $inner.view -anchor w -pady 2
1831
1832    set labels { qx qy qz qw xpan ypan zoom }
1833    set row 1
1834    foreach tag $labels {
1835        label $inner.${tag}label -text $tag -font "Arial 9"
1836        entry $inner.${tag} -font "Arial 9"  -bg white \
1837            -textvariable [itcl::scope _view(-$tag)]
1838        bind $inner.${tag} <KeyPress-Return> \
1839            [itcl::code $this camera set ${tag}]
1840        blt::table $inner \
1841            $row,0 $inner.${tag}label -anchor e -pady 2 \
1842            $row,1 $inner.${tag} -anchor w -pady 2
1843        blt::table configure $inner r$row -resize none
1844        incr row
1845    }
1846    checkbutton $inner.ortho \
1847        -text "Orthographic Projection" \
1848        -variable [itcl::scope _view(-ortho)] \
1849        -command [itcl::code $this AdjustSetting -ortho] \
1850        -font "Arial 9"
1851    blt::table $inner \
1852            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
1853    blt::table configure $inner r$row -resize none
1854    incr row
1855
1856    blt::table configure $inner c* r* -resize none
1857    blt::table configure $inner c2 -resize expand
1858    blt::table configure $inner r$row -resize expand
1859}
1860
1861itcl::body Rappture::VtkIsosurfaceViewer::BuildCutplaneTab {} {
1862
1863    set fg [option get $itk_component(hull) font Font]
1864   
1865    set inner [$itk_component(main) insert end \
1866        -title "Cutplane Settings" \
1867        -icon [Rappture::icon cutbutton]]
1868
1869    $inner configure -borderwidth 4
1870
1871    checkbutton $inner.visible \
1872        -text "Cutplanes" \
1873        -variable [itcl::scope _settings(-cutplanesvisible)] \
1874        -command [itcl::code $this AdjustSetting -cutplanesvisible] \
1875        -font "Arial 9"
1876
1877    checkbutton $inner.wireframe \
1878        -text "Wireframe" \
1879        -variable [itcl::scope _settings(-cutplanewireframe)] \
1880        -command [itcl::code $this AdjustSetting -cutplanewireframe] \
1881        -font "Arial 9"
1882
1883    checkbutton $inner.lighting \
1884        -text "Enable Lighting" \
1885        -variable [itcl::scope _settings(-cutplanelighting)] \
1886        -command [itcl::code $this AdjustSetting -cutplanelighting] \
1887        -font "Arial 9"
1888
1889    checkbutton $inner.edges \
1890        -text "Edges" \
1891        -variable [itcl::scope _settings(-cutplaneedges)] \
1892        -command [itcl::code $this AdjustSetting -cutplaneedges] \
1893        -font "Arial 9"
1894
1895    checkbutton $inner.preinterp \
1896        -text "Interpolate Scalars" \
1897        -variable [itcl::scope _settings(-cutplanepreinterp)] \
1898        -command [itcl::code $this AdjustSetting -cutplanepreinterp] \
1899        -font "Arial 9"
1900
1901    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1902    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1903        -variable [itcl::scope _widget(-cutplaneopacity)] \
1904        -width 10 \
1905        -showvalue off \
1906        -command [itcl::code $this AdjustSetting -cutplaneopacity]
1907    $inner.opacity set [expr $_settings(-cutplaneopacity) * 100.0]
1908
1909    # X-value slicer...
1910    itk_component add xbutton {
1911        Rappture::PushButton $inner.xbutton \
1912            -onimage [Rappture::icon x-cutplane-red] \
1913            -offimage [Rappture::icon x-cutplane-red] \
1914            -command [itcl::code $this AdjustSetting -xcutplanevisible] \
1915            -variable [itcl::scope _settings(-xcutplanevisible)] \
1916    }
1917    Rappture::Tooltip::for $itk_component(xbutton) \
1918        "Toggle the X-axis cutplane on/off"
1919    $itk_component(xbutton) select
1920    itk_component add xposition {
1921        ::scale $inner.xval -from 100 -to 0 \
1922            -width 10 -orient vertical -showvalue 1 \
1923            -borderwidth 1 -highlightthickness 0 \
1924            -command [itcl::code $this EventuallySetCutplane x] \
1925            -variable [itcl::scope _settings(-xcutplaneposition)] \
1926            -foreground red2 -font "Arial 9 bold"
1927    } {
1928        usual
1929        ignore -borderwidth -highlightthickness -foreground -font -background
1930    }
1931    # Set the default cutplane value before disabling the scale.
1932    $itk_component(xposition) set 50
1933    $itk_component(xposition) configure -state disabled
1934    Rappture::Tooltip::for $itk_component(xposition) \
1935        "@[itcl::code $this Slice tooltip x]"
1936
1937    # Y-value slicer...
1938    itk_component add ybutton {
1939        Rappture::PushButton $inner.ybutton \
1940            -onimage [Rappture::icon y-cutplane-green] \
1941            -offimage [Rappture::icon y-cutplane-green] \
1942            -command [itcl::code $this AdjustSetting -ycutplanevisible] \
1943            -variable [itcl::scope _settings(-ycutplanevisible)] \
1944    }
1945    Rappture::Tooltip::for $itk_component(ybutton) \
1946        "Toggle the Y-axis cutplane on/off"
1947    $itk_component(ybutton) select
1948
1949    itk_component add yposition {
1950        ::scale $inner.yval -from 100 -to 0 \
1951            -width 10 -orient vertical -showvalue 1 \
1952            -borderwidth 1 -highlightthickness 0 \
1953            -command [itcl::code $this EventuallySetCutplane y] \
1954            -variable [itcl::scope _settings(-ycutplaneposition)] \
1955            -foreground green3 -font "Arial 9 bold"
1956    } {
1957        usual
1958        ignore -borderwidth -highlightthickness -foreground -font
1959    }
1960    Rappture::Tooltip::for $itk_component(yposition) \
1961        "@[itcl::code $this Slice tooltip y]"
1962    # Set the default cutplane value before disabling the scale.
1963    $itk_component(yposition) set 50
1964    $itk_component(yposition) configure -state disabled
1965
1966    # Z-value slicer...
1967    itk_component add zbutton {
1968        Rappture::PushButton $inner.zbutton \
1969            -onimage [Rappture::icon z-cutplane-blue] \
1970            -offimage [Rappture::icon z-cutplane-blue] \
1971            -command [itcl::code $this AdjustSetting -zcutplanevisible] \
1972            -variable [itcl::scope _settings(-zcutplanevisible)] \
1973    } {
1974        usual
1975        ignore -foreground
1976    }
1977    Rappture::Tooltip::for $itk_component(zbutton) \
1978        "Toggle the Z-axis cutplane on/off"
1979    $itk_component(zbutton) select
1980
1981    itk_component add zposition {
1982        ::scale $inner.zval -from 100 -to 0 \
1983            -width 10 -orient vertical -showvalue 1 \
1984            -borderwidth 1 -highlightthickness 0 \
1985            -command [itcl::code $this EventuallySetCutplane z] \
1986            -variable [itcl::scope _settings(-zcutplaneposition)] \
1987            -foreground blue3 -font "Arial 9 bold"
1988    } {
1989        usual
1990        ignore -borderwidth -highlightthickness -foreground -font
1991    }
1992    $itk_component(zposition) set 50
1993    $itk_component(zposition) configure -state disabled
1994    Rappture::Tooltip::for $itk_component(zposition) \
1995        "@[itcl::code $this Slice tooltip z]"
1996
1997    blt::table $inner \
1998        0,0 $inner.visible              -anchor w -pady 2 -cspan 3 \
1999        1,0 $inner.lighting             -anchor w -pady 2 -cspan 3 \
2000        2,0 $inner.wireframe            -anchor w -pady 2 -cspan 3 \
2001        3,0 $inner.edges                -anchor w -pady 2 -cspan 3 \
2002        4,0 $inner.preinterp            -anchor w -pady 2 -cspan 3 \
2003        5,0 $inner.opacity_l            -anchor w -pady 2 -cspan 1 \
2004        5,1 $inner.opacity              -fill x   -pady 2 -cspan 3 \
2005        6,0 $inner.xbutton              -anchor w -padx 2 -pady 2 \
2006        7,0 $inner.ybutton              -anchor w -padx 2 -pady 2 \
2007        8,0 $inner.zbutton              -anchor w -padx 2 -pady 2 \
2008        6,1 $inner.xval                 -fill y -rspan 4 \
2009        6,2 $inner.yval                 -fill y -rspan 4 \
2010        6,3 $inner.zval                 -fill y -rspan 4 \
2011
2012
2013    blt::table configure $inner r* c* -resize none
2014    blt::table configure $inner r9 c4 -resize expand
2015}
2016
2017
2018
2019#
2020#  camera --
2021#
2022itcl::body Rappture::VtkIsosurfaceViewer::camera {option args} {
2023    switch -- $option {
2024        "show" {
2025            puts [array get _view]
2026        }
2027        "set" {
2028            set what [lindex $args 0]
2029            set x $_view($what)
2030            set code [catch { string is double $x } result]
2031            if { $code != 0 || !$result } {
2032                return
2033            }
2034            switch -- $what {
2035                "-ortho" {
2036                    if {$_view($what)} {
2037                        SendCmd "camera mode ortho"
2038                    } else {
2039                        SendCmd "camera mode persp"
2040                    }
2041                }
2042                "-xpan" - "-ypan" {
2043                    PanCamera
2044                }
2045                "-qx" - "-qy" - "-qz" - "-qw" {
2046                    set q [ViewToQuaternion]
2047                    $_arcball quaternion $q
2048                    EventuallyRotate $q
2049                }
2050                "-zoom" {
2051                    SendCmd "camera zoom $_view(-zoom)"
2052                }
2053             }
2054        }
2055    }
2056}
2057
2058itcl::body Rappture::VtkIsosurfaceViewer::GetVtkData { args } {
2059    set bytes ""
2060    foreach dataobj [get] {
2061        foreach cname [$dataobj components] {
2062            set tag $dataobj-$cname
2063            set contents [$dataobj vtkdata $cname]
2064            append bytes "$contents\n"
2065        }
2066    }
2067    return [list .vtk $bytes]
2068}
2069
2070itcl::body Rappture::VtkIsosurfaceViewer::GetImage { args } {
2071    if { [image width $_image(download)] > 0 &&
2072         [image height $_image(download)] > 0 } {
2073        set bytes [$_image(download) data -format "jpeg -quality 100"]
2074        set bytes [Rappture::encoding::decode -as b64 $bytes]
2075        return [list .jpg $bytes]
2076    }
2077    return ""
2078}
2079
2080itcl::body Rappture::VtkIsosurfaceViewer::BuildDownloadPopup { popup command } {
2081    Rappture::Balloon $popup \
2082        -title "[Rappture::filexfer::label downloadWord] as..."
2083    set inner [$popup component inner]
2084    label $inner.summary -text "" -anchor w
2085    radiobutton $inner.vtk_button -text "VTK data file" \
2086        -variable [itcl::scope _downloadPopup(format)] \
2087        -font "Arial 9 " \
2088        -value vtk 
2089    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
2090    radiobutton $inner.image_button -text "Image File" \
2091        -variable [itcl::scope _downloadPopup(format)] \
2092        -font "Arial 9 " \
2093        -value image
2094    Rappture::Tooltip::for $inner.image_button \
2095        "Save as digital image."
2096
2097    button $inner.ok -text "Save" \
2098        -highlightthickness 0 -pady 2 -padx 3 \
2099        -command $command \
2100        -compound left \
2101        -image [Rappture::icon download]
2102
2103    button $inner.cancel -text "Cancel" \
2104        -highlightthickness 0 -pady 2 -padx 3 \
2105        -command [list $popup deactivate] \
2106        -compound left \
2107        -image [Rappture::icon cancel]
2108
2109    blt::table $inner \
2110        0,0 $inner.summary -cspan 2  \
2111        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2112        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2113        4,1 $inner.cancel -width .9i -fill y \
2114        4,0 $inner.ok -padx 2 -width .9i -fill y
2115    blt::table configure $inner r3 -height 4
2116    blt::table configure $inner r4 -pady 4
2117    raise $inner.image_button
2118    $inner.vtk_button invoke
2119    return $inner
2120}
2121
2122itcl::body Rappture::VtkIsosurfaceViewer::SetObjectStyle { dataobj comp } {
2123    # Parse style string.
2124    set tag $dataobj-$comp
2125    array set style {
2126        -color                  BCGYR
2127        -cutplanesvisible       0
2128        -edgecolor              black
2129        -edges                  0
2130        -isosurfaceopacity      0.6
2131        -isosurfacevisible      1
2132        -levels                 10
2133        -lighting               1
2134        -linewidth              1.0
2135        -outline                0
2136        -wireframe              0
2137        -xcutplaneposition      50
2138        -xcutplanevisible       1
2139        -ycutplaneposition      50
2140        -ycutplanevisible       1
2141        -zcutplaneposition      50
2142        -zcutplanevisible       1
2143    }
2144    array set style [$dataobj style $comp]
2145    if { $dataobj != $_first || $style(-levels) == 1 } {
2146        set style(-isosurfaceopacity) 1.0
2147    }
2148
2149    # This is too complicated.  We want to set the colormap, number of
2150    # isolines and opacity for the dataset.  They can be the default values,
2151    # the style hints loaded with the dataset, or set by user controls.  As
2152    # datasets get loaded, they first use the defaults that are overidden
2153    # by the style hints.  If the user changes the global controls, then that
2154    # overrides everything else.  I don't know what it means when global
2155    # controls are specified as style hints by each dataset.  It complicates
2156    # the code to handle aberrant cases.
2157
2158    if { $_changed(-isosurfaceopacity) } {
2159        set style(-isosurfaceopacity) $_settings(-isosurfaceopacity)
2160    }
2161    if { $_changed(-numcontours) } {
2162        set style(-levels) $_settings(-numcontours)
2163    }
2164    if { $_changed(-colormap) } {
2165        set style(-color) $_settings(-colormap)
2166    }
2167    if { $_currentColormap == "" } {
2168        SetCurrentColormap $style(-color)
2169        $itk_component(colormap) value $style(-color)
2170    }
2171    if { $_contourList(numLevels) != $style(-levels) } {
2172        if { [llength $style(-levels)] > 1 } {
2173            set _contourList(reqValues) [lsort -real $style(-levels)]
2174        } else {
2175            set _settings(-numcontours) $style(-levels)
2176            $itk_component(numcontours) value $style(-levels)
2177            set _contourList(numLevels) $style(-levels)
2178        }
2179        EventuallyChangeContourLevels
2180    }
2181    set _settings(-isosurfacevisible) $style(-isosurfacevisible)
2182    set _settings(-cutplanesvisible)  $style(-cutplanesvisible)
2183    set _settings(-xcutplanevisible)  $style(-xcutplanevisible)
2184    set _settings(-ycutplanevisible)  $style(-ycutplanevisible)
2185    set _settings(-zcutplanevisible)  $style(-zcutplanevisible)
2186    set _settings(-xcutplaneposition) $style(-xcutplaneposition)
2187    set _settings(-ycutplaneposition) $style(-ycutplaneposition)
2188    set _settings(-zcutplaneposition) $style(-zcutplaneposition)
2189 
2190    SendCmd "cutplane add $tag"
2191    SendCmd "cutplane visible $style(-cutplanesvisible) $tag"
2192
2193    SendCmd "outline add $tag"
2194    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
2195    SendCmd "outline visible $style(-outline) $tag"
2196    set _settings(-outline) $style(-outline)
2197 
2198    GenerateContourList
2199    SendCmd [list contour3d add contourlist $_contourList(values) $tag]
2200    SendCmd "contour3d visible $style(-isosurfacevisible) $tag"
2201    SendCmd "contour3d edges $style(-edges) $tag"
2202    set _settings(-isosurfaceedges) $style(-edges)
2203    #SendCmd "contour3d color [Color2RGB $settings(-color)] $tag"
2204    SendCmd "contour3d lighting $style(-lighting) $tag"
2205    set _settings(-isosurfacelighting) $style(-lighting)
2206    SendCmd "contour3d linecolor [Color2RGB $style(-edgecolor)] $tag"
2207    SendCmd "contour3d linewidth $style(-linewidth) $tag"
2208    SendCmd "contour3d opacity $style(-isosurfaceopacity) $tag"
2209    set _settings(-isosurfaceopacity) $style(-isosurfaceopacity)
2210    SetCurrentColormap $style(-color)
2211    SendCmd "contour3d wireframe $style(-wireframe) $tag"
2212    set _settings(-isosurfacewireframe) $style(-wireframe)
2213}
2214
2215itcl::body Rappture::VtkIsosurfaceViewer::IsValidObject { dataobj } {
2216    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2217        return 0
2218    }
2219    return 1
2220}
2221
2222#
2223# EnterLegend --
2224#
2225itcl::body Rappture::VtkIsosurfaceViewer::EnterLegend { x y } {
2226    SetLegendTip $x $y
2227}
2228
2229#
2230# MotionLegend --
2231#
2232itcl::body Rappture::VtkIsosurfaceViewer::MotionLegend { x y } {
2233    Rappture::Tooltip::tooltip cancel
2234    set c $itk_component(view)
2235    set cw [winfo width $c]
2236    set ch [winfo height $c]
2237    if { $x >= 0 && $x < $cw && $y >= 0 && $y < $ch } {
2238        SetLegendTip $x $y
2239    }
2240}
2241
2242#
2243# LeaveLegend --
2244#
2245itcl::body Rappture::VtkIsosurfaceViewer::LeaveLegend { } {
2246    Rappture::Tooltip::tooltip cancel
2247    .rappturetooltip configure -icon ""
2248}
2249
2250#
2251# SetLegendTip --
2252#
2253itcl::body Rappture::VtkIsosurfaceViewer::SetLegendTip { x y } {
2254    set fname $_curFldName
2255    set c $itk_component(view)
2256    set w [winfo width $c]
2257    set h [winfo height $c]
2258
2259    set font "Arial 8"
2260    set lineht [font metrics $font -linespace]
2261   
2262    set ih [image height $_image(legend)]
2263    set iy [expr $y - ($lineht + 2)]
2264
2265    if { [string match "component*" $fname] } {
2266        set title ""
2267    } else {
2268        if { [info exists _fields($fname)] } {
2269            foreach { title units } $_fields($fname) break
2270            if { $units != "" } {
2271                set title [format "%s (%s)" $title $units]
2272            }
2273        } else {
2274            set title $fname
2275        }
2276    }
2277    # If there's a legend title, increase the offset by the line height.
2278    if { $title != "" } {
2279        incr iy -$lineht
2280    }
2281    # Make a swatch of the selected color
2282    if { [catch { $_image(legend) get 10 $iy } pixel] != 0 } {
2283        return
2284    }
2285    if { ![info exists _image(swatch)] } {
2286        set _image(swatch) [image create photo -width 24 -height 24]
2287    }
2288    set color [eval format "\#%02x%02x%02x" $pixel]
2289    $_image(swatch) put black  -to 0 0 23 23
2290    $_image(swatch) put $color -to 1 1 22 22
2291    .rappturetooltip configure -icon $_image(swatch)
2292
2293    # Compute the value of the point
2294    if { [info exists _limits($_curFldName)] } {
2295        foreach { vmin vmax } $_limits($_curFldName) break
2296        set t [expr 1.0 - (double($iy) / double($ih-1))]
2297        set value [expr $t * ($vmax - $vmin) + $vmin]
2298    } else {
2299        set value 0.0
2300    }
2301    set tx [expr $x + 15]
2302    set ty [expr $y - 5]
2303    if { [info exists _isolines($y)] } {
2304        Rappture::Tooltip::text $c [format "$title %g (isosurface)" $_isolines($y)]
2305    } else {
2306        Rappture::Tooltip::text $c [format "$title %g" $value]
2307    }
2308    Rappture::Tooltip::tooltip show $c +$tx,+$ty   
2309}
2310
2311
2312# ----------------------------------------------------------------------
2313# USAGE: Slice move x|y|z <newval>
2314#
2315# Called automatically when the user drags the slider to move the
2316# cut plane that slices 3D data.  Gets the current value from the
2317# slider and moves the cut plane to the appropriate point in the
2318# data set.
2319# ----------------------------------------------------------------------
2320itcl::body Rappture::VtkIsosurfaceViewer::Slice {option args} {
2321    switch -- $option {
2322        "move" {
2323            set axis [lindex $args 0]
2324            set newval [lindex $args 1]
2325            if {[llength $args] != 2} {
2326                error "wrong # args: should be \"Slice move x|y|z newval\""
2327            }
2328            set newpos [expr {0.01*$newval}]
2329            SendCmd "cutplane slice $axis $newpos"
2330        }
2331        "tooltip" {
2332            set axis [lindex $args 0]
2333            set val [$itk_component(${axis}position) get]
2334            return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2335        }
2336        default {
2337            error "bad option \"$option\": should be axis, move, or tooltip"
2338        }
2339    }
2340}
2341
2342#
2343# ReceiveLegend --
2344#
2345#       Invoked automatically whenever the "legend" command comes in from
2346#       the rendering server.  Indicates that binary image data with the
2347#       specified <size> will follow.
2348#
2349itcl::body Rappture::VtkIsosurfaceViewer::ReceiveLegend { colormap title min max size } {
2350    #puts stderr "ReceiveLegend colormap=$colormap title=$title range=$min,$max size=$size"
2351    set _title $title
2352    regsub {\(mag\)} $title "" _title
2353    if { [IsConnected] } {
2354        set bytes [ReceiveBytes $size]
2355        if { ![info exists _image(legend)] } {
2356            set _image(legend) [image create photo]
2357        }
2358        $_image(legend) configure -data $bytes
2359        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2360        if { [catch {DrawLegend} errs] != 0 } {
2361            global errorInfo
2362            puts stderr "errs=$errs errorInfo=$errorInfo"
2363        }
2364    }
2365}
2366
2367#
2368# DrawLegend --
2369#
2370#       Draws the legend in the own canvas on the right side of the plot area.
2371#
2372itcl::body Rappture::VtkIsosurfaceViewer::DrawLegend {} {
2373    set fname $_curFldName
2374    set c $itk_component(view)
2375    set w [winfo width $c]
2376    set h [winfo height $c]
2377    set font "Arial 8"
2378    set lineht [font metrics $font -linespace]
2379   
2380    if { [string match "component*" $fname] } {
2381        set title ""
2382    } else {
2383        if { [info exists _fields($fname)] } {
2384            foreach { title units } $_fields($fname) break
2385            if { $units != "" } {
2386                set title [format "%s (%s)" $title $units]
2387            }
2388        } else {
2389            set title $fname
2390        }
2391    }
2392    set x [expr $w - 2]
2393    if { !$_settings(-legendvisible) } {
2394        $c delete legend
2395        return
2396    }
2397    if { [$c find withtag "legend"] == "" } {
2398        set y 2
2399        # If there's a legend title, create a text item for the title.
2400        $c create text $x $y \
2401            -anchor ne \
2402            -fill $itk_option(-plotforeground) -tags "title legend" \
2403            -font $font
2404        if { $title != "" } {
2405            incr y $lineht
2406        }
2407        $c create text $x $y \
2408            -anchor ne \
2409            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2410            -font $font
2411        incr y $lineht
2412        $c create image $x $y \
2413            -anchor ne \
2414            -image $_image(legend) -tags "colormap legend"
2415        $c create rectangle $x $y 1 1 \
2416            -fill "" -outline "" -tags "sensor legend"
2417        $c create text $x [expr {$h-2}] \
2418            -anchor se \
2419            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2420            -font $font
2421        $c bind sensor <Enter> [itcl::code $this EnterLegend %x %y]
2422        $c bind sensor <Leave> [itcl::code $this LeaveLegend]
2423        $c bind sensor <Motion> [itcl::code $this MotionLegend %x %y]
2424    }
2425    $c delete isoline
2426    set x2 $x
2427    set iw [image width $_image(legend)]
2428    set ih [image height $_image(legend)]
2429    set x1 [expr $x2 - ($iw*12)/10]
2430    set color $_settings(-isolinecolor)
2431    # Draw the isolines on the legend.
2432    array unset _isolines
2433    if { $color != "none"  && [info exists _limits($_curFldName)] &&
2434         $_settings(-numcontours) > 0 } {
2435
2436        foreach { vmin vmax } $_limits($_curFldName) break
2437        set range [expr double($vmax - $vmin)]
2438        if { $range <= 0.0 } {
2439            set range 1.0;              # Min is greater or equal to max.
2440        }
2441        set tags "isoline legend"
2442        set offset [expr 2 + $lineht]
2443        if { $title != "" } {
2444            incr offset $lineht
2445        }
2446        foreach value $_contourList(values) {
2447            set norm [expr 1.0 - (($value - $vmin) / $range)]
2448            set y1 [expr int(round(($norm * $ih) + $offset))]
2449            for { set off 0 } { $off < 3 } { incr off } {
2450                set _isolines([expr $y1 + $off]) $value
2451                set _isolines([expr $y1 - $off]) $value
2452            }
2453            $c create line $x1 $y1 $x2 $y1 -fill $color -tags $tags
2454        }
2455    }
2456
2457    $c bind title <ButtonPress> [itcl::code $this Combo post]
2458    $c bind title <Enter> [itcl::code $this Combo activate]
2459    $c bind title <Leave> [itcl::code $this Combo deactivate]
2460    # Reset the item coordinates according the current size of the plot.
2461    $c itemconfigure title -text $title
2462    if { [info exists _limits($_curFldName)] } {
2463        foreach { vmin vmax } $_limits($_curFldName) break
2464        $c itemconfigure vmin -text [format %g $vmin]
2465        $c itemconfigure vmax -text [format %g $vmax]
2466    }
2467    set y 2
2468    # If there's a legend title, move the title to the correct position
2469    if { $title != "" } {
2470        $c itemconfigure title -text $title
2471        $c coords title $x $y
2472        incr y $lineht
2473        $c raise title
2474    }
2475    $c coords vmax $x $y
2476    incr y $lineht
2477    $c coords colormap $x $y
2478    $c coords sensor [expr $x - $iw] $y $x [expr $y + $ih]
2479    $c raise sensor
2480    $c coords vmin $x [expr {$h - 2}]
2481}
2482
2483# ----------------------------------------------------------------------
2484# USAGE: _dropdown post
2485# USAGE: _dropdown unpost
2486# USAGE: _dropdown select
2487#
2488# Used internally to handle the dropdown list for this combobox.  The
2489# post/unpost options are invoked when the list is posted or unposted
2490# to manage the relief of the controlling button.  The select option
2491# is invoked whenever there is a selection from the list, to assign
2492# the value back to the gauge.
2493# ----------------------------------------------------------------------
2494itcl::body Rappture::VtkIsosurfaceViewer::Combo {option} {
2495    set c $itk_component(view)
2496    switch -- $option {
2497        post {
2498            foreach { x1 y1 x2 y2 } [$c bbox title] break
2499            set cw [winfo width $itk_component(view)]
2500            set mw [winfo reqwidth $itk_component(fieldmenu)]
2501            set x1 [expr $cw - $mw]
2502            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2503            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2504            tk_popup $itk_component(fieldmenu) $x $y
2505        }
2506        activate {
2507            $c itemconfigure title -fill red
2508        }
2509        deactivate {
2510            $c itemconfigure title -fill $itk_option(-plotforeground)
2511        }
2512        invoke {
2513            $itk_component(field) value $_curFldLabel
2514            AdjustSetting -field
2515        }
2516        default {
2517            error "bad option \"$option\": should be post, unpost, select"
2518        }
2519    }
2520}
2521
2522#
2523# SetCurrentColormap --
2524#
2525itcl::body Rappture::VtkIsosurfaceViewer::SetCurrentColormap { name } {
2526    # Keep track of the colormaps that we build.
2527    if { ![info exists _colormaps($name)] } {
2528        BuildColormap $name
2529        set _colormaps($name) 1
2530    }
2531    set _currentColormap $name
2532    SendCmd "contour3d colormap $_currentColormap"
2533    SendCmd "cutplane colormap $_currentColormap"
2534}
2535
2536#
2537# BuildColormap --
2538#
2539#       Build the designated colormap on the server.
2540#
2541itcl::body Rappture::VtkIsosurfaceViewer::BuildColormap { name } {
2542    set cmap [ColorsToColormap $name]
2543    if { [llength $cmap] == 0 } {
2544        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
2545    }
2546    set wmap "0.0 1.0 1.0 1.0"
2547    SendCmd "colormap add $name { $cmap } { $wmap }"
2548}
2549
2550itcl::body Rappture::VtkIsosurfaceViewer::SetOrientation { side } {
2551    array set positions {
2552        front "1 0 0 0"
2553        back  "0 0 1 0"
2554        left  "0.707107 0 -0.707107 0"
2555        right "0.707107 0 0.707107 0"
2556        top   "0.707107 -0.707107 0 0"
2557        bottom "0.707107 0.707107 0 0"
2558    }
2559    foreach name { -qw -qx -qy -qz } value $positions($side) {
2560        set _view($name) $value
2561    }
2562    set q [ViewToQuaternion]
2563    $_arcball quaternion $q
2564    SendCmd "camera orient $q"
2565    SendCmd "camera reset"
2566    set _view(-xpan) 0
2567    set _view(-ypan) 0
2568    set _view(-zoom) 1.0
2569}
2570
2571itcl::body Rappture::VtkIsosurfaceViewer::GenerateContourList {} {
2572    if { ![info exists _limits($_curFldName)] } {
2573        puts stderr "no _curFldName"
2574        return ""
2575    }
2576    if { $_contourList(numLevels) < 1 } {
2577        # There are tools that set 0 levels to get cutplanes only
2578        #puts stderr "numLevels < 1"
2579        return ""
2580    }
2581    if { [llength $_contourList(reqValues)] > 1 } {
2582        set values $_contourList(reqValues)
2583    } else {
2584        foreach { vmin vmax } $_limits($_curFldName) break
2585        set v [blt::vector create \#auto]
2586        $v seq $vmin $vmax [expr $_contourList(numLevels)+2]
2587        $v delete end 0
2588        set values [$v range 0 end]
2589        blt::vector destroy $v
2590    }
2591    set _contourList(values) $values
2592}
2593
2594itcl::body Rappture::VtkIsosurfaceViewer::SetCurrentFieldName { dataobj } {
2595    set _first $dataobj
2596    $itk_component(field) choices delete 0 end
2597    $itk_component(fieldmenu) delete 0 end
2598    array unset _fields
2599    set _curFldName ""
2600    foreach cname [$_first components] {
2601        foreach fname [$_first fieldnames $cname] {
2602            if { [info exists _fields($fname)] } {
2603                continue
2604            }
2605            foreach { label units components } \
2606                [$_first fieldinfo $fname] break
2607            $itk_component(field) choices insert end "$fname" "$label"
2608            $itk_component(fieldmenu) add radiobutton -label "$label" \
2609                -value $label -variable [itcl::scope _curFldLabel] \
2610                -selectcolor red \
2611                -activebackground $itk_option(-plotbackground) \
2612                -activeforeground $itk_option(-plotforeground) \
2613                -font "Arial 8" \
2614                -command [itcl::code $this Combo invoke]
2615            set _fields($fname) [list $label $units $components]
2616            if { $_curFldName == "" } {
2617                set _curFldName $fname
2618                set _curFldLabel $label
2619            }
2620        }
2621    }
2622    $itk_component(field) value $_curFldLabel
2623    if { ![info exists _limits($_curFldName)] } {
2624        SendCmd "dataset maprange all"
2625    } else {
2626        set limits $_limits($_curFldName)
2627        SendCmd "dataset maprange explicit $limits $_curFldName"
2628        if { $limits != $_currentLimits } {
2629            set _currentLimits $limits
2630            EventuallyChangeContourLevels
2631        }
2632    }
2633}
Note: See TracBrowser for help on using the repository browser.