source: trunk/gui/scripts/moleculeViewer.tcl @ 1128

Last change on this file since 1128 was 767, checked in by mmc, 17 years ago

Oops! Forgot to add the new -param option emitted by the ResultSet?,
so that the various viewers don't choke.

File size: 23.1 KB
Line 
1# ----------------------------------------------------------------------
2#  COMPONENT: MoleculeViewer - view a molecule in 3D
3#
4#  This widget brings up a 3D representation of a molecule, which you
5#  can rotate.  It extracts atoms and bonds from the Rappture XML
6#  representation for a <molecule>.
7# ======================================================================
8#  AUTHOR:  Michael McLennan, Purdue University
9#  Copyright (c) 2004-2005  Purdue Research Foundation
10#
11#  See the file "license.terms" for information on usage and
12#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13# ======================================================================
14package require Itk
15package require vtk
16package require vtkinteraction
17package require BLT
18package require Img
19
20option add *MoleculeViewer.width 3i widgetDefault
21option add *MoleculeViewer.height 3i widgetDefault
22option add *MoleculeViewer.backdrop black widgetDefault
23
24itcl::class Rappture::MoleculeViewer {
25    inherit itk::Widget
26
27    itk_option define -backdrop backdrop Backdrop "black"
28    itk_option define -device device Device ""
29
30    constructor {tool args} { # defined below }
31    destructor { # defined below }
32
33    public method add {dataobj {settings ""}}
34    public method get {}
35    public method delete {args}
36    public method parameters {title args} { # do nothing }
37
38    public method emblems {option}
39    public method download {option args}
40
41    protected method _clear {}
42    protected method _redraw {}
43    protected method _zoom {option}
44    protected method _move {option x y}
45    protected method _3dView {theta phi psi}
46    protected method _color2rgb {color}
47
48    private variable _dispatcher "" ;# dispatcher for !events
49
50    private variable _tool ""    ;# tool containing this viewer
51    private variable _dlist ""   ;# list of dataobj objects
52    private variable _dobj2raise ;# maps dataobj => raise flag
53    private variable _actors ""  ;# list of actors in renderer
54    private variable _label2atom ;# maps 2D text actor => underlying atom
55    private variable _view       ;# view params for 3D view
56    private variable _limits     ;# limits of x/y/z axes
57    private variable _click      ;# info used for _move operations
58    private variable _download "";# snapshot for download
59}
60                                                                               
61itk::usual MoleculeViewer {
62}
63
64# ----------------------------------------------------------------------
65# CONSTRUCTOR
66# ----------------------------------------------------------------------
67itcl::body Rappture::MoleculeViewer::constructor {tool args} {
68    set _tool $tool
69
70    Rappture::dispatcher _dispatcher
71    $_dispatcher register !redraw
72    $_dispatcher dispatch $this !redraw "[itcl::code $this _redraw]; list"
73    $_dispatcher register !render
74    $_dispatcher dispatch $this !render "$this-renWin Render; list"
75    $_dispatcher register !fixsize
76    $_dispatcher dispatch $this !fixsize \
77        "[itcl::code $this emblems fixPosition]; list"
78
79    itk_option add hull.width hull.height
80    pack propagate $itk_component(hull) no
81
82    vtkRenderWindow $this-renWin
83    vtkRenderer $this-ren
84    $this-renWin AddRenderer $this-ren
85
86    vtkRenderWindowInteractor $this-int
87    $this-int SetRenderWindow $this-renWin
88
89    vtkSphereSource $this-sphere
90    $this-sphere SetRadius 1.0
91    $this-sphere SetThetaResolution 18
92    $this-sphere SetPhiResolution 18
93
94    vtkPolyDataMapper $this-map
95    $this-map SetInput [$this-sphere GetOutput]
96
97    vtkCoordinate $this-xyzconv
98    $this-xyzconv SetCoordinateSystemToWorld
99
100    set _view(theta) 0
101    set _view(phi) 0
102    set _view(psi) 0
103
104    itk_component add controls {
105        frame $itk_interior.cntls
106    } {
107        usual
108        rename -background -controlbackground controlBackground Background
109    }
110    pack $itk_component(controls) -side right -fill y
111
112    itk_component add reset {
113        button $itk_component(controls).reset \
114            -borderwidth 1 -padx 1 -pady 1 \
115            -bitmap [Rappture::icon reset] \
116            -command [itcl::code $this _zoom reset]
117    } {
118        usual
119        ignore -borderwidth
120        rename -highlightbackground -controlbackground controlBackground Background
121    }
122    pack $itk_component(reset) -padx 4 -pady 4
123    Rappture::Tooltip::for $itk_component(reset) "Reset the view to the default zoom level"
124
125    itk_component add zoomin {
126        button $itk_component(controls).zin \
127            -borderwidth 1 -padx 1 -pady 1 \
128            -bitmap [Rappture::icon zoomin] \
129            -command [itcl::code $this _zoom in]
130    } {
131        usual
132        ignore -borderwidth
133        rename -highlightbackground -controlbackground controlBackground Background
134    }
135    pack $itk_component(zoomin) -padx 4 -pady 4
136    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
137
138    itk_component add zoomout {
139        button $itk_component(controls).zout \
140            -borderwidth 1 -padx 1 -pady 1 \
141            -bitmap [Rappture::icon zoomout] \
142            -command [itcl::code $this _zoom out]
143    } {
144        usual
145        ignore -borderwidth
146        rename -highlightbackground -controlbackground controlBackground Background
147    }
148    pack $itk_component(zoomout) -padx 4 -pady 4
149    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
150
151    itk_component add labels {
152        label $itk_component(controls).labels \
153            -borderwidth 1 -padx 1 -pady 1 \
154            -bitmap [Rappture::icon atoms]
155    } {
156        usual
157        ignore -borderwidth
158        rename -highlightbackground -controlbackground controlBackground Background
159    }
160    pack $itk_component(labels) -padx 4 -pady 8 -ipadx 1 -ipady 1
161    Rappture::Tooltip::for $itk_component(labels) "Show/hide the labels on atoms"
162    bind $itk_component(labels) <ButtonPress> \
163        [itcl::code $this emblems toggle]
164
165    #
166    # RENDERING AREA
167    #
168    itk_component add area {
169        frame $itk_interior.area
170    }
171    pack $itk_component(area) -expand yes -fill both
172    bind $itk_component(area) <Configure> \
173        [list $_dispatcher event -idle !fixsize]
174
175    itk_component add renderer {
176        vtkTkRenderWidget $itk_component(area).ren -rw $this-renWin
177    } {
178    }
179    pack $itk_component(renderer) -expand yes -fill both
180
181    eval itk_initialize $args
182
183    # prevent interactions -- use our own
184    blt::busy hold $itk_component(area) -cursor left_ptr
185    bind $itk_component(area)_Busy <ButtonPress> \
186        [itcl::code $this _move click %x %y]
187    bind $itk_component(area)_Busy <B1-Motion> \
188        [itcl::code $this _move drag %x %y]
189    bind $itk_component(area)_Busy <ButtonRelease> \
190        [itcl::code $this _move release %x %y]
191
192    emblems on
193
194    # create a photo for download snapshots
195    set _download [image create photo]
196}
197
198# ----------------------------------------------------------------------
199# DESTRUCTOR
200# ----------------------------------------------------------------------
201itcl::body Rappture::MoleculeViewer::destructor {} {
202    rename $this-renWin ""
203    rename $this-ren ""
204    rename $this-int ""
205    rename $this-sphere ""
206    rename $this-map ""
207    rename $this-xyzconv ""
208
209    image delete $_download
210}
211
212# ----------------------------------------------------------------------
213# USAGE: add <dataobj> ?<settings>?
214#
215# Clients use this to add a data object to the plot.  The optional
216# <settings> are used to configure the plot.  Allowed settings are
217# -color, -brightness, -width, -linestyle, and -raise. Only
218# -brightness and -raise do anything.
219# ----------------------------------------------------------------------
220itcl::body Rappture::MoleculeViewer::add {dataobj {settings ""}} {
221    array set params {
222        -color auto
223        -brightness 0
224        -width 1
225        -raise 0
226        -linestyle solid
227        -description ""
228        -param ""
229    }
230    foreach {opt val} $settings {
231        if {![info exists params($opt)]} {
232            error "bad settings \"$opt\": should be [join [lsort [array names params]] {, }]"
233        }
234        set params($opt) $val
235    }
236 
237    set pos [lsearch -exact $dataobj $_dlist]
238
239    if {$pos < 0} {
240        if {![Rappture::library isvalid $dataobj]} {
241            error "bad value \"$dataobj\": should be Rappture::library object"
242        }
243   
244        set emblem [$dataobj get components.molecule.about.emblems]
245        if {$emblem == "" || ![string is boolean $emblem] || !$emblem} {
246            emblems off
247        } else {
248            emblems on
249        }
250
251        lappend _dlist $dataobj
252        set _dobj2raise($dataobj) $params(-raise)
253
254        $_dispatcher event -idle !redraw
255    }
256}
257
258# ----------------------------------------------------------------------
259# USAGE: get
260#
261# Clients use this to query the list of objects being plotted, in
262# order from bottom to top of this result.
263# ----------------------------------------------------------------------
264itcl::body Rappture::MoleculeViewer::get {} {
265    # put the dataobj list in order according to -raise options
266    set dlist $_dlist
267    foreach obj $dlist {
268        if {[info exists _dobj2raise($obj)] && $_dobj2raise($obj)} {
269            set i [lsearch -exact $dlist $obj]
270            if {$i >= 0} {
271                set dlist [lreplace $dlist $i $i]
272                lappend dlist $obj
273            }
274        }
275    }
276    return $dlist
277}
278
279# ----------------------------------------------------------------------
280# USAGE: delete ?<dataobj> <dataobj> ...?
281#
282# Clients use this to delete a dataobj from the plot. If no dataobjs
283# are specified, then all dataobjs are deleted.
284# ----------------------------------------------------------------------
285itcl::body Rappture::MoleculeViewer::delete {args} {
286    if {[llength $args] == 0} {
287        set args $_dlist
288    }
289
290    # delete all specified dataobjs
291    set changed 0
292    foreach dataobj $args {
293        set pos [lsearch -exact $_dlist $dataobj]
294        if {$pos >= 0} {
295            set _dlist [lreplace $_dlist $pos $pos]
296            catch {unset _dobj2raise($dataobj)}
297            set changed 1
298        }
299    }
300
301    # if anything changed, then rebuild the plot
302    if {$changed} {
303        $_dispatcher event -idle !redraw
304    }
305}
306
307# ----------------------------------------------------------------------
308# USAGE: download coming
309# USAGE: download controls <downloadCommand>
310# USAGE: download now
311#
312# Clients use this method to create a downloadable representation
313# of the plot.  Returns a list of the form {ext string}, where
314# "ext" is the file extension (indicating the type of data) and
315# "string" is the data itself.
316# ----------------------------------------------------------------------
317itcl::body Rappture::MoleculeViewer::download {option args} {
318    switch $option {
319        coming {
320            if {[catch {blt::winop snap $itk_component(area) $_download}]} {
321                $_download configure -width 1 -height 1
322                $_download put #000000
323            }
324        }
325        controls {
326            # no controls for this download yet
327            return ""
328        }
329        now {
330            #
331            # Hack alert!  Need data in binary format,
332            # so we'll save to a file and read it back.
333            #
334            set tmpfile /tmp/image[pid].jpg
335            $_download write $tmpfile -format jpeg
336            set fid [open $tmpfile r]
337            fconfigure $fid -encoding binary -translation binary
338            set bytes [read $fid]
339            close $fid
340            file delete -force $tmpfile
341
342            return [list .jpg $bytes]
343        }
344        default {
345            error "bad option \"$option\": should be coming, controls, now"
346        }
347    }
348}
349
350# ----------------------------------------------------------------------
351# USAGE: _clear
352#
353# Used internally to clear the scene whenever it is about to change.
354# ----------------------------------------------------------------------
355itcl::body Rappture::MoleculeViewer::_clear {} {
356    foreach a $_actors {
357        $this-ren RemoveActor $a
358        rename $a ""
359    }
360    set _actors ""
361    catch {unset _label2atom}
362
363    foreach lim {xmin xmax ymin ymax zmin zmax} {
364        set _limits($lim) ""
365    }
366
367    $this-ren ResetCamera
368    $_dispatcher event -now !render
369}
370
371# ----------------------------------------------------------------------
372# USAGE: _redraw
373#
374# Used internally to rebuild the scene whenever options within this
375# widget change.  Destroys all actors and rebuilds them from scratch.
376# ----------------------------------------------------------------------
377itcl::body Rappture::MoleculeViewer::_redraw {} {
378    blt::busy hold $itk_component(hull); update
379
380    _clear
381
382    set dev [lindex [get] end]
383    if {"" != $dev} {
384        set lib [Rappture::library standard]
385
386        set counter 0
387        foreach atom [$dev children -type atom components.molecule] {
388            set symbol [$dev get components.molecule.$atom.symbol]
389            set xyz [$dev get components.molecule.$atom.xyz]
390            regsub {,} $xyz {} xyz
391
392            # update overall limits for molecules along all axes
393            foreach axis {x y z} val $xyz {
394                if {"" == $_limits(${axis}min)} {
395                    set _limits(${axis}min) $val
396                    set _limits(${axis}max) $val
397                } else {
398                    if {$val < $_limits(${axis}min)} {
399                        set _limits(${axis}min) $val
400                    }
401                    if {$val > $_limits(${axis}max)} {
402                        set _limits(${axis}max) $val
403                    }
404                }
405            }
406
407            # create an actor for each atom
408            set aname $this-actor[incr counter]
409            vtkActor $aname
410            $aname SetMapper $this-map
411            eval $aname SetPosition $xyz
412            $this-ren AddActor $aname
413
414            set sfac 0.7
415            set scale [$lib get elements.($symbol).scale]
416            if {$scale != ""} {
417                $aname SetScale [expr {$sfac*$scale}]
418            }
419            set color [$lib get elements.($symbol).color]
420            if {$color != ""} {
421                eval [$aname GetProperty] SetColor [_color2rgb $color]
422            }
423
424            lappend _actors $aname
425
426            # create a label for each atom
427            set lname $this-label$counter
428            vtkTextActor $lname
429            $lname SetInput "$counter $symbol"
430            $lname ScaledTextOff
431
432            set tprop [$lname GetTextProperty]
433            $tprop SetJustificationToCentered
434            $tprop SetVerticalJustificationToCentered
435            $tprop ShadowOn
436            $tprop SetColor 1 1 1
437
438            set _label2atom($lname) $aname
439            lappend _actors $lname
440        }
441        if {[$itk_component(labels) cget -relief] == "sunken"} {
442            emblems on
443        }
444        _zoom reset
445    }
446    $this-ren ResetCamera
447    $_dispatcher event -idle !render
448
449    blt::busy release $itk_component(hull)
450}
451
452# ----------------------------------------------------------------------
453# USAGE: _zoom in
454# USAGE: _zoom out
455# USAGE: _zoom reset
456#
457# Called automatically when the user clicks on one of the zoom
458# controls for this widget.  Changes the zoom for the current view.
459# ----------------------------------------------------------------------
460itcl::body Rappture::MoleculeViewer::_zoom {option} {
461    switch -- $option {
462        in {
463            [$this-ren GetActiveCamera] Zoom 1.25
464        }
465        out {
466            [$this-ren GetActiveCamera] Zoom 0.8
467        }
468        reset {
469            $this-ren ResetCamera
470            [$this-ren GetActiveCamera] SetViewAngle 30
471            _3dView 45 45 0
472        }
473    }
474    $_dispatcher event -later !fixsize
475    $_dispatcher event -idle !render
476}
477
478# ----------------------------------------------------------------------
479# USAGE: _move click <x> <y>
480# USAGE: _move drag <x> <y>
481# USAGE: _move release <x> <y>
482#
483# Called automatically when the user clicks/drags/releases in the
484# plot area.  Moves the plot according to the user's actions.
485# ----------------------------------------------------------------------
486itcl::body Rappture::MoleculeViewer::_move {option x y} {
487    switch -- $option {
488        click {
489            blt::busy configure $itk_component(area) -cursor fleur
490            set _click(x) $x
491            set _click(y) $y
492            set _click(theta) $_view(theta)
493            set _click(phi) $_view(phi)
494            set _click(psi) $_view(psi)
495        }
496        drag {
497            if {[array size _click] == 0} {
498                _move click $x $y
499            } else {
500                set w [winfo width $itk_component(renderer)]
501                set h [winfo height $itk_component(renderer)]
502                if {$w <= 0 || $h <= 0} {
503                    return
504                }
505
506                if {[catch {
507                    # this fails sometimes for no apparent reason
508                    set dx [expr {double($x-$_click(x))/$w}]
509                    set dy [expr {double($y-$_click(y))/$h}]
510                }]} {
511                    return
512                }
513
514                #
515                # Rotate the camera in 3D
516                #
517                if {$_view(psi) > 90 || $_view(psi) < -90} {
518                    # when psi is flipped around, theta moves backwards
519                    set dy [expr {-$dy}]
520                }
521                set theta [expr {$_view(theta) - $dy*180}]
522                while {$theta < 0} { set theta [expr {$theta+180}] }
523                while {$theta > 180} { set theta [expr {$theta-180}] }
524                #if {$theta < 2} { set theta 2 }
525                #if {$theta > 178} { set theta 178 }
526
527                if {$theta > 45 && $theta < 135} {
528                    set phi [expr {$_view(phi) - $dx*360}]
529                    while {$phi < 0} { set phi [expr {$phi+360}] }
530                    while {$phi > 360} { set phi [expr {$phi-360}] }
531                    set psi $_view(psi)
532                } else {
533                    set phi $_view(phi)
534                    set psi [expr {$_view(psi) - $dx*360}]
535                    while {$psi < -180} { set psi [expr {$psi+360}] }
536                    while {$psi > 180} { set psi [expr {$psi-360}] }
537                }
538
539                _3dView $theta $phi $psi
540                emblems fixPosition
541                $_dispatcher event -idle !render
542
543                set _click(x) $x
544                set _click(y) $y
545            }
546        }
547        release {
548            _move drag $x $y
549            blt::busy configure $itk_component(area) -cursor left_ptr
550            catch {unset _click}
551        }
552        default {
553            error "bad option \"$option\": should be click, drag, release"
554        }
555    }
556}
557
558# ----------------------------------------------------------------------
559# USAGE: _3dView <theta> <phi> <psi>
560#
561# Used internally to change the position of the camera for 3D data
562# sets.  Sets the camera according to the angles <theta> (angle from
563# the z-axis) and <phi> (angle from the x-axis in the x-y plane).
564# Both angles are in degrees.
565# ----------------------------------------------------------------------
566itcl::body Rappture::MoleculeViewer::_3dView {theta phi psi} {
567    set deg2rad 0.0174532927778
568    set xp [expr {sin($theta*$deg2rad)*cos($phi*$deg2rad)}]
569    set yp [expr {sin($theta*$deg2rad)*sin($phi*$deg2rad)}]
570    set zp [expr {cos($theta*$deg2rad)}]
571
572    set blank 0
573    foreach lim {xmin xmax ymin ymax zmin zmax} {
574        if {"" == $_limits($lim)} {
575            set blank 1
576            break
577        }
578    }
579    if {$blank} {
580        set xm 0
581        set ym 0
582        set zm 0
583    } else {
584        set xm [expr {0.5*($_limits(xmax)+$_limits(xmin))}]
585        set ym [expr {0.5*($_limits(ymax)+$_limits(ymin))}]
586        set zm [expr {0.5*($_limits(zmax)+$_limits(zmin))}]
587    }
588
589    set cam [$this-ren GetActiveCamera]
590    set zoom [$cam GetViewAngle]
591    $cam SetViewAngle 30
592
593    $cam SetFocalPoint $xm $ym $zm
594    $cam SetPosition [expr {$xm-$xp}] [expr {$ym-$yp}] [expr {$zm+$zp}]
595    $cam ComputeViewPlaneNormal
596    $cam SetViewUp 0 0 1  ;# z-dir is up
597    $cam OrthogonalizeViewUp
598    $cam Azimuth $psi
599    $this-ren ResetCamera
600    $cam SetViewAngle $zoom
601
602    # fix up the labels so they sit over the new atom positions
603    emblems fixPosition
604
605    set _view(theta) $theta
606    set _view(phi) $phi
607    set _view(psi) $psi
608}
609
610# ----------------------------------------------------------------------
611# USAGE: emblems on
612# USAGE: emblems off
613# USAGE: emblems toggle
614# USAGE: emblems fixPosition
615#
616# Used internally to turn labels associated with atoms on/off, and to
617# update the positions of the labels so they sit on top of each atom.
618# ----------------------------------------------------------------------
619itcl::body Rappture::MoleculeViewer::emblems {option} {
620    switch -- $option {
621        on {
622            set state 1
623        }
624        off {
625            set state 0
626        }
627        toggle {
628            if {[$itk_component(labels) cget -relief] == "sunken"} {
629                set state 0
630            } else {
631                set state 1
632            }
633        }
634        fixPosition {
635            foreach lname [array names _label2atom] {
636                set aname $_label2atom($lname)
637                set xyz [$aname GetPosition]
638                eval $this-xyzconv SetValue $xyz
639                set xy [$this-xyzconv GetComputedViewportValue $this-ren]
640                eval $lname SetDisplayPosition $xy
641            }
642            return
643        }
644        default {
645            error "bad option \"$option\": should be on, off, toggle, fixPosition"
646        }
647    }
648
649    if {$state} {
650        $itk_component(labels) configure -relief sunken
651        foreach lname [array names _label2atom] {
652            catch {$this-ren AddActor2D $lname}
653        }
654        emblems fixPosition
655    } else {
656        $itk_component(labels) configure -relief raised
657        foreach lname [array names _label2atom] {
658            catch {$this-ren RemoveActor $lname}
659        }
660    }
661    $_dispatcher event -idle !render
662}
663
664# ----------------------------------------------------------------------
665# USAGE: _color2rgb color
666#
667# Used internally to convert a Tk color name into the r,g,b values
668# used in Vtk (scaled 0-1).
669# ----------------------------------------------------------------------
670itcl::body Rappture::MoleculeViewer::_color2rgb {color} {
671    foreach {r g b} [winfo rgb $itk_component(hull) $color] {}
672    set r [expr {$r/65535.0}]
673    set g [expr {$g/65535.0}]
674    set b [expr {$b/65535.0}]
675    return [list $r $g $b]
676}
677
678# ----------------------------------------------------------------------
679# OPTION: -backdrop
680# ----------------------------------------------------------------------
681itcl::configbody Rappture::MoleculeViewer::backdrop {
682    eval $this-ren SetBackground [_color2rgb $itk_option(-backdrop)]
683    $_dispatcher event -idle !render
684}
685
686# ----------------------------------------------------------------------
687# OPTION: -device
688# ----------------------------------------------------------------------
689itcl::configbody Rappture::MoleculeViewer::device {
690    if {"" != $itk_option(-device)
691          && ![Rappture::library isvalid $itk_option(-device)]} {
692        error "bad value \"$itk_option(-device)\": should be Rappture::library object"
693    }
694    delete
695
696    if {"" != $itk_option(-device)} {
697        add $itk_option(-device)
698        set state [$itk_option(-device) get components.molecule.about.emblems]
699        if {$state == "" || ![string is boolean $state] || !$state} {
700            emblems off
701        } else {
702            emblems on
703        }
704    }
705    $_dispatcher event -idle !redraw
706}
Note: See TracBrowser for help on using the repository browser.