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

Last change on this file since 3486 was 3486, checked in by ldelgass, 11 years ago

Set axis label format to %g in isosurface viewer

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