source: branches/uiuc_vtk_viewers/gui/scripts/vtkisosurfaceviewer.tcl @ 4953

Last change on this file since 4953 was 4953, checked in by dkearney, 9 years ago

cleaning up spaces and tabs

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