source: trunk/gui/scripts/vtkviewer.tcl @ 3515

Last change on this file since 3515 was 3454, checked in by gah, 11 years ago

add KP_Enter to Return bindings. Implement OK handler in visviewer base class. Fix setting # of isolines while running a sequence of heightmaps/contours

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