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

Last change on this file since 5347 was 5347, checked in by ldelgass, 5 years ago

set _downloadPopup to private access

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