source: branches/1.3/gui/scripts/vtkisosurfaceviewer.tcl @ 4759

Last change on this file since 4759 was 4759, checked in by ldelgass, 6 years ago

merge r4756:4758 from trunk

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