source: trunk/gui/scripts/vtksurfaceviewer.tcl @ 5157

Last change on this file since 5157 was 5157, checked in by ldelgass, 9 years ago

Surface viewer fixes (based on changes from isosurface viewer)

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