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

Last change on this file since 3899 was 3899, checked in by ldelgass, 8 years ago

Add cutplane visibility button to nanovis viewers.

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