source: trunk/gui/scripts/vtkisosurfaceviewer.tcl @ 4440

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

Minor fixes for isosurface viewer

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