source: trunk/gui/scripts/heightmapviewer.tcl @ 1342

Last change on this file since 1342 was 1342, checked in by gah, 15 years ago

preliminary HQ output from molvisviewer; unexpand tabs; all jpeg generation at 100%

File size: 40.7 KB
Line 
1
2# ----------------------------------------------------------------------
3#  COMPONENT: heightmapviewer - 3D volume rendering
4#
5#  This widget performs volume rendering on 3D scalar/vector datasets.
6#  It connects to the Nanovis server running on a rendering farm,
7#  transmits data, and displays the results.
8# ======================================================================
9#  AUTHOR:  Michael McLennan, Purdue University
10#  Copyright (c) 2004-2005  Purdue Research Foundation
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# ======================================================================
15
16package require Itk
17package require BLT
18package require Img
19
20option add *HeightmapViewer.width 4i widgetDefault
21option add *HeightmapViewer.height 4i widgetDefault
22option add *HeightmapViewer.foreground black widgetDefault
23option add *HeightmapViewer.controlBackground gray widgetDefault
24option add *HeightmapViewer.controlDarkBackground #999999 widgetDefault
25option add *HeightmapViewer.plotBackground black widgetDefault
26option add *HeightmapViewer.plotForeground white widgetDefault
27option add *HeightmapViewer.plotOutline white widgetDefault
28option add *HeightmapViewer.font \
29    -*-helvetica-medium-r-normal-*-12-* widgetDefault
30
31# must use this name -- plugs into Rappture::resources::load
32proc HeightmapViewer_init_resources {} {
33    Rappture::resources::register \
34        nanovis_server Rappture::HeightmapViewer::SetServerList
35}
36
37itcl::class Rappture::HeightmapViewer {
38    inherit Rappture::VisViewer
39
40    itk_option define -plotforeground plotForeground Foreground ""
41    itk_option define -plotbackground plotBackground Background ""
42    itk_option define -plotoutline plotOutline PlotOutline ""
43
44    constructor { hostlist args } {
45        Rappture::VisViewer::constructor $hostlist
46    } {
47        # defined below
48    }
49    destructor {
50        # defined below
51    }
52
53    public proc SetServerList { namelist } {
54        Rappture::VisViewer::SetServerList "nanovis" $namelist
55    }
56    public method add {dataobj {settings ""}}
57    public method get {args}
58    public method delete {args}
59    public method scale {args}
60    public method download {option args}
61    public method parameters {title args} {
62        # do nothing
63    }
64    public method drawer {what who}
65    public method camera {option args}
66    protected method Connect {}
67    protected method Disconnect {}
68
69    protected method _send {string}
70    protected method _send_dataobjs {}
71    protected method ReceiveImage {option size}
72    private method _ReceiveLegend {tf vmin vmax size}
73    private method _BuildSettingsDrawer {}
74    private method _BuildCameraDrawer {}
75    private method _PanCamera {}
76    protected method _receive_echo {channel {data ""}}
77
78    protected method _rebuild {}
79    protected method _zoom {option}
80    protected method _pan {option x y}
81    protected method _rotate {option x y}
82
83    protected method _state {comp}
84    protected method _fixSettings {what {value ""}}
85    protected method _getTransfuncData {dataobj comp}
86
87
88    private variable outbuf_       ;# buffer for outgoing commands
89
90    private variable dlist_ ""     ;# list of data objects
91    private variable obj2style_    ;# maps dataobj => style settings
92    private variable obj2ovride_   ;# maps dataobj => style override
93    private variable obj2id_       ;# maps dataobj => heightmap ID in server
94    private variable id2obj_       ;# maps heightmap ID => dataobj in server
95    private variable sendobjs_ ""  ;# list of data objs to send to server
96    private variable receiveIds_   ;# list of data responses from the server
97    private variable click_        ;# info used for _rotate operations
98    private variable limits_       ;# autoscale min/max for all axes
99    private variable view_         ;# view params for 3D view
100    private common settings_      ;# Array used for checkbuttons and radiobuttons
101    private variable initialized_
102}
103
104itk::usual HeightmapViewer {
105    keep -background -foreground -cursor -font
106    keep -plotbackground -plotforeground
107}
108
109# ----------------------------------------------------------------------
110# CONSTRUCTOR
111# ----------------------------------------------------------------------
112itcl::body Rappture::HeightmapViewer::constructor {hostlist args} {
113    # Draw legend event
114    $_dispatcher register !legend
115    $_dispatcher dispatch $this !legend \
116        "[itcl::code $this _fixSettings legend]; list"
117    # Send dataobjs event
118    $_dispatcher register !send_dataobjs
119    $_dispatcher dispatch $this !send_dataobjs \
120        "[itcl::code $this _send_dataobjs]; list"
121    # Rebuild event
122    $_dispatcher register !rebuild
123    $_dispatcher dispatch $this !rebuild "[itcl::code $this _rebuild]; list"
124
125    set outbuf_ ""
126
127    #
128    # Populate parser with commands handle incoming requests
129    #
130    $_parser alias image [itcl::code $this ReceiveImage]
131    $_parser alias legend [itcl::code $this _ReceiveLegend]
132
133    # Initialize the view to some default parameters.
134    array set view_ {
135        theta   45
136        phi     45
137        psi     0
138        zoom    1.0
139        pan-x   0
140        pan-y   0
141    }
142    set obj2id_(count) 0
143
144    itk_component add zoom {
145        frame $itk_component(controls).zoom
146    } {
147        usual
148        rename -background -controlbackground controlBackground Background
149    }
150    pack $itk_component(zoom) -side top
151
152    itk_component add reset {
153        button $itk_component(zoom).reset \
154            -borderwidth 1 -padx 1 -pady 1 \
155            -image [Rappture::icon reset-view] \
156            -command [itcl::code $this _zoom reset]
157    } {
158        usual
159        ignore -borderwidth
160        rename -highlightbackground -controlbackground controlBackground Background
161    }
162    pack $itk_component(reset) -side top -padx 2 -pady { 2 0 }
163    Rappture::Tooltip::for $itk_component(reset) "Reset the view to the default zoom level"
164
165    itk_component add zoomin {
166        button $itk_component(zoom).zin \
167            -borderwidth 1 -padx 1 -pady 1 \
168            -image [Rappture::icon zoom-in] \
169            -command [itcl::code $this _zoom in]
170    } {
171        usual
172        ignore -borderwidth
173        rename -highlightbackground -controlbackground controlBackground Background
174    }
175    pack $itk_component(zoomin) -side top -padx 2 -pady { 2 0 }
176    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
177
178    itk_component add zoomout {
179        button $itk_component(zoom).zout \
180            -borderwidth 1 -padx 1 -pady 1 \
181            -image [Rappture::icon zoom-out] \
182            -command [itcl::code $this _zoom out]
183    } {
184        usual
185        ignore -borderwidth
186        rename -highlightbackground -controlbackground controlBackground Background
187    }
188    pack $itk_component(zoomout) -side top -padx 2 -pady { 2 0 }
189    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
190
191    itk_component add settings_button {
192        label $itk_component(controls).settingsbutton \
193            -borderwidth 1 -padx 1 -pady 1 \
194            -relief "raised" -image [Rappture::icon wrench]
195    } {
196        usual
197        ignore -borderwidth
198        rename -highlightbackground -controlbackground controlBackground \
199            Background
200    }
201    pack $itk_component(settings_button) -padx 2 -pady { 0 2 } \
202        -ipadx 1 -ipady 1
203    Rappture::Tooltip::for $itk_component(settings_button) \
204        "Configure settings"
205    bind $itk_component(settings_button) <ButtonPress> \
206        [itcl::code $this drawer toggle settings]
207    pack $itk_component(settings_button) -side bottom \
208        -padx 2 -pady 2 -anchor e
209
210    itk_component add camera_button {
211        label $itk_component(controls).camerabutton \
212            -borderwidth 1 -padx 1 -pady 1 \
213            -relief "raised" -image [Rappture::icon camera]
214    } {
215        usual
216        ignore -borderwidth
217        rename -highlightbackground -controlbackground controlBackground \
218            Background
219    }
220    Rappture::Tooltip::for $itk_component(camera_button) \
221        "Camera settings"
222    bind $itk_component(camera_button) <ButtonPress> \
223        [itcl::code $this drawer toggle camera]
224    pack $itk_component(camera_button) -side bottom \
225        -padx 2 -pady { 0 2 } -ipadx 1 -ipady 1
226
227    _BuildSettingsDrawer
228    _BuildCameraDrawer
229
230    # Legend
231    set _image(legend) [image create photo]
232    itk_component add legend {
233        canvas $itk_component(area).legend -width 30 -highlightthickness 0
234    } {
235        usual
236        ignore -highlightthickness
237        rename -background -plotbackground plotBackground Background
238    }
239    pack $itk_component(legend) -side right -fill y
240    pack $itk_component(3dview) -side left -expand yes -fill both
241    bind $itk_component(legend) <Configure> \
242        [list $_dispatcher event -idle !legend]
243
244    # Bindings for rotation via mouse
245    bind $itk_component(3dview) <ButtonPress-1> \
246        [itcl::code $this _rotate click %x %y]
247    bind $itk_component(3dview) <B1-Motion> \
248        [itcl::code $this _rotate drag %x %y]
249    bind $itk_component(3dview) <ButtonRelease-1> \
250        [itcl::code $this _rotate release %x %y]
251    bind $itk_component(3dview) <Configure> \
252        [itcl::code $this _send "screen %w %h"]
253
254    # Bindings for panning via mouse
255    bind $itk_component(3dview) <ButtonPress-2> \
256        [itcl::code $this _pan click %x %y]
257    bind $itk_component(3dview) <B2-Motion> \
258        [itcl::code $this _pan drag %x %y]
259    bind $itk_component(3dview) <ButtonRelease-2> \
260        [itcl::code $this _pan release %x %y]
261
262    # Bindings for panning via keyboard
263    bind $itk_component(3dview) <KeyPress-Left> \
264        [itcl::code $this _pan set -10 0]
265    bind $itk_component(3dview) <KeyPress-Right> \
266        [itcl::code $this _pan set 10 0]
267    bind $itk_component(3dview) <KeyPress-Up> \
268        [itcl::code $this _pan set 0 -10]
269    bind $itk_component(3dview) <KeyPress-Down> \
270        [itcl::code $this _pan set 0 10]
271    bind $itk_component(3dview) <Shift-KeyPress-Left> \
272        [itcl::code $this _pan set -2 0]
273    bind $itk_component(3dview) <Shift-KeyPress-Right> \
274        [itcl::code $this _pan set 2 0]
275    bind $itk_component(3dview) <Shift-KeyPress-Up> \
276        [itcl::code $this _pan set 0 -2]
277    bind $itk_component(3dview) <Shift-KeyPress-Down> \
278        [itcl::code $this _pan set 0 2]
279
280    # Bindings for zoom via keyboard
281    bind $itk_component(3dview) <KeyPress-Prior> \
282        [itcl::code $this _zoom out]
283    bind $itk_component(3dview) <KeyPress-Next> \
284        [itcl::code $this _zoom in]
285
286    bind $itk_component(3dview) <Enter> "focus $itk_component(3dview)"
287
288    if {[string equal "x11" [tk windowingsystem]]} {
289        # Bindings for zoom via mouse
290        bind $itk_component(3dview) <4> [itcl::code $this _zoom out]
291        bind $itk_component(3dview) <5> [itcl::code $this _zoom in]
292    }
293
294    set _image(download) [image create photo]
295
296    eval itk_initialize $args
297
298    Connect
299}
300
301# ----------------------------------------------------------------------
302# DESTRUCTOR
303# ----------------------------------------------------------------------
304itcl::body Rappture::HeightmapViewer::destructor {} {
305    set sendobjs_ ""  ;# stop any send in progress
306    $_dispatcher cancel !rebuild
307    $_dispatcher cancel !send_dataobjs
308    image delete $_image(plot)
309    image delete $_image(legend)
310    image delete $_image(download)
311}
312
313# ----------------------------------------------------------------------
314# USAGE: add <dataobj> ?<settings>?
315#
316# Clients use this to add a data object to the plot.  The optional
317# <settings> are used to configure the plot.  Allowed settings are
318# -color, -brightness, -width, -linestyle, and -raise.
319# ----------------------------------------------------------------------
320itcl::body Rappture::HeightmapViewer::add {dataobj {settings ""}} {
321    array set params {
322        -color auto
323        -width 1
324        -linestyle solid
325        -brightness 0
326        -raise 0
327        -description ""
328        -param ""
329    }
330    foreach {opt val} $settings {
331        if {![info exists params($opt)]} {
332            error "bad setting \"$opt\": should be [join [lsort [array names params]] {, }]"
333        }
334        set params($opt) $val
335    }
336    if {$params(-color) == "auto" || $params(-color) == "autoreset"} {
337        # can't handle -autocolors yet
338        set params(-color) black
339    }
340    set location [$dataobj hints camera]
341    if { $location != "" } {
342        array set view_ $location
343    }
344    set pos [lsearch -exact $dataobj $dlist_]
345    if {$pos < 0} {
346        lappend dlist_ $dataobj
347        set obj2ovride_($dataobj-color) $params(-color)
348        set obj2ovride_($dataobj-width) $params(-width)
349        set obj2ovride_($dataobj-raise) $params(-raise)
350        $_dispatcher event -idle !rebuild
351    }
352}
353
354# ----------------------------------------------------------------------
355# USAGE: get ?-objects?
356# USAGE: get ?-image 3dview|legend?
357#
358# Clients use this to query the list of objects being plotted, in
359# order from bottom to top of this result.  The optional "-image"
360# flag can also request the internal images being shown.
361# ----------------------------------------------------------------------
362itcl::body Rappture::HeightmapViewer::get {args} {
363    if {[llength $args] == 0} {
364        set args "-objects"
365    }
366
367    set op [lindex $args 0]
368    switch -- $op {
369      -objects {
370        # put the dataobj list in order according to -raise options
371        set dlist $dlist_
372        foreach obj $dlist {
373            if { [info exists obj2ovride_($obj-raise)] &&
374                 $obj2ovride_($obj-raise)} {
375                set i [lsearch -exact $dlist $obj]
376                if {$i >= 0} {
377                    set dlist [lreplace $dlist $i $i]
378                    lappend dlist $obj
379                }
380            }
381        }
382        return $dlist
383      }
384      -image {
385        if {[llength $args] != 2} {
386            error "wrong # args: should be \"get -image 3dview|legend\""
387        }
388        switch -- [lindex $args end] {
389            3dview {
390                return $_image(plot)
391            }
392            legend {
393                return $_image(legend)
394            }
395            default {
396                error "bad image name \"[lindex $args end]\": should be 3dview or legend"
397            }
398        }
399      }
400      default {
401        error "bad option \"$op\": should be -objects or -image"
402      }
403    }
404}
405
406# ----------------------------------------------------------------------
407# USAGE: delete ?<dataobj1> <dataobj2> ...?
408#
409# Clients use this to delete a dataobj from the plot.  If no dataobjs
410# are specified, then all dataobjs are deleted.
411# ----------------------------------------------------------------------
412itcl::body Rappture::HeightmapViewer::delete {args} {
413    if {[llength $args] == 0} {
414        set args $dlist_
415    }
416
417    # delete all specified dataobjs
418    set changed 0
419    foreach dataobj $args {
420        set pos [lsearch -exact $dlist_ $dataobj]
421        if {$pos >= 0} {
422            set dlist_ [lreplace $dlist_ $pos $pos]
423            foreach key [array names obj2ovride_ $dataobj-*] {
424                unset obj2ovride_($key)
425            }
426            set changed 1
427        }
428    }
429
430    # if anything changed, then rebuild the plot
431    if {$changed} {
432        $_dispatcher event -idle !rebuild
433    }
434}
435
436# ----------------------------------------------------------------------
437# USAGE: scale ?<data1> <data2> ...?
438#
439# Sets the default limits for the overall plot according to the
440# limits of the data for all of the given <data> objects.  This
441# accounts for all objects--even those not showing on the screen.
442# Because of this, the limits are appropriate for all objects as
443# the user scans through data in the ResultSet viewer.
444# ----------------------------------------------------------------------
445itcl::body Rappture::HeightmapViewer::scale {args} {
446    foreach val {xmin xmax ymin ymax zmin zmax vmin vmax} {
447        set limits_($val) ""
448    }
449    foreach obj $args {
450        foreach axis {x y z v} {
451            foreach {min max} [$obj limits $axis] break
452            if {"" != $min && "" != $max} {
453                if {"" == $limits_(${axis}min)} {
454                    set limits_(${axis}min) $min
455                    set limits_(${axis}max) $max
456                } else {
457                    if {$min < $limits_(${axis}min)} {
458                        set limits_(${axis}min) $min
459                    }
460                    if {$max > $limits_(${axis}max)} {
461                        set limits_(${axis}max) $max
462                    }
463                }
464                set limits_(${axis}range) [expr {$max - $min}]
465            }
466        }
467    }
468}
469
470# ----------------------------------------------------------------------
471# USAGE: download coming
472# USAGE: download controls <downloadCommand>
473# USAGE: download now
474#
475# Clients use this method to create a downloadable representation
476# of the plot.  Returns a list of the form {ext string}, where
477# "ext" is the file extension (indicating the type of data) and
478# "string" is the data itself.
479# ----------------------------------------------------------------------
480itcl::body Rappture::HeightmapViewer::download {option args} {
481    switch $option {
482        coming {
483            if {[catch {
484                blt::winop snap $itk_component(area) $_image(download)
485            }]} {
486                $_image(download) configure -width 1 -height 1
487                $_image(download) put #000000
488            }
489        }
490        controls {
491            # no controls for this download yet
492            return ""
493        }
494        now {
495            # Get image data (as base64) and decode back to binary.  This is
496            # better than writing to temporary files.  When we switch the BLT
497            # picture image it won't be necessary to decode the image data.
498            set bytes [$_image(download) data -format "jpeg -quality 100"]
499            set bytes [Rappture::encoding::decode -as b64 $bytes]
500            return [list .jpg $bytes]
501        }
502        default {
503            error "bad option \"$option\": should be coming, controls, now"
504        }
505    }
506}
507
508# ----------------------------------------------------------------------
509# USAGE: Connect ?<host:port>,<host:port>...?
510#
511# Clients use this method to establish a connection to a new
512# server, or to reestablish a connection to the previous server.
513# Any existing connection is automatically closed.
514# ----------------------------------------------------------------------
515itcl::body Rappture::HeightmapViewer::Connect {} {
516    Disconnect
517    set _hosts [GetServerList "nanovis"]
518    if { "" == $_hosts } {
519        return 0
520    }
521    set result [VisViewer::Connect $_hosts]
522    return $result
523}
524
525# ----------------------------------------------------------------------
526# USAGE: Disconnect
527#
528# Clients use this method to disconnect from the current rendering
529# server.
530# ----------------------------------------------------------------------
531itcl::body Rappture::HeightmapViewer::Disconnect {} {
532    VisViewer::Disconnect
533
534    set outbuf_ ""
535    # disconnected -- no more data sitting on server
536    catch {unset obj2id_}
537    array unset id2obj_
538    set obj2id_(count) 0
539    set id2obj_(cound) 0
540    set sendobjs_ ""
541}
542
543#
544# _send
545#
546#       Send commands off to the rendering server.  If we're currently
547#       sending data objects to the server, buffer the commands to be
548#       sent later.
549#
550itcl::body Rappture::HeightmapViewer::_send {string} {
551    if {[llength $sendobjs_] > 0} {
552        append outbuf_ $string "\n"
553    } else {
554        if {[SendBytes $string]} {
555            foreach line [split $string \n] {
556                SendEcho >>line $line
557            }
558        }
559    }
560}
561
562# ----------------------------------------------------------------------
563# USAGE: _send_dataobjs
564#
565# Used internally to send a series of volume objects off to the
566# server.  Sends each object, a little at a time, with updates in
567# between so the interface doesn't lock up.
568# ----------------------------------------------------------------------
569itcl::body Rappture::HeightmapViewer::_send_dataobjs {} {
570    blt::busy hold $itk_component(hull); update idletasks
571
572    # Reset the overall limits
573    if { $sendobjs_ != "" } {
574        set limits_(vmin) ""
575        set limits_(vmax) ""
576    }
577    foreach dataobj $sendobjs_ {
578        foreach comp [$dataobj components] {
579            set data [$dataobj blob $comp]
580
581            foreach { vmin vmax }  [$dataobj limits v] break
582            if { $limits_(vmin) == "" || $vmin < $limits_(vmin) } {
583                set limits_(vmin) $vmin
584            }
585            if { $limits_(vmax) == "" || $vmax > $limits_(vmax) } {
586                set limits_(vmax) $vmax
587            }
588
589            # tell the engine to expect some data
590            set nbytes [string length $data]
591            if { ![SendBytes "heightmap data follows $nbytes"] } {
592                return
593
594            }
595            if { ![SendBytes $data] } {
596                return
597            }
598            set id $obj2id_(count)
599            incr obj2id_(count)
600            set id2obj_($id) [list $dataobj $comp]
601            set obj2id_($dataobj-$comp) $id
602            set receiveIds_($id) 1
603
604            #
605            # Determine the transfer function needed for this volume
606            # and make sure that it's defined on the server.
607            #
608            foreach {sname cmap wmap} [_getTransfuncData $dataobj $comp] break
609            set cmdstr [list "transfunc" "define" $sname $cmap $wmap]
610            if {![SendBytes $cmdstr]} {
611                return
612            }
613            set obj2style_($dataobj-$comp) $sname
614        }
615    }
616    set sendobjs_ ""
617    blt::busy release $itk_component(hull)
618
619    # activate the proper volume
620    set first [lindex [get] 0]
621    if {"" != $first} {
622        set axis [$first hints updir]
623        if {"" != $axis} {
624            _send "up $axis"
625        }
626    }
627
628    foreach key [array names obj2id_ *-*] {
629        set state [string match $first-* $key]
630        _send "heightmap data visible $state $obj2id_($key)"
631        if {[info exists obj2style_($key)]} {
632            _send "heightmap transfunc $obj2style_($key) $obj2id_($key)"
633        }
634    }
635
636    # if there are any commands in the buffer, send them now that we're done
637    SendBytes $outbuf_
638    set outbuf_ ""
639
640    $_dispatcher event -idle !legend
641}
642
643# ----------------------------------------------------------------------
644# USAGE: ReceiveImage -bytes <size>
645#
646# Invoked automatically whenever the "image" command comes in from
647# the rendering server.  Indicates that binary image data with the
648# specified <size> will follow.
649# ----------------------------------------------------------------------
650itcl::body Rappture::HeightmapViewer::ReceiveImage {option size} {
651    if {[IsConnected]} {
652        set bytes [ReceiveBytes $size]
653        $_image(plot) configure -data $bytes
654        ReceiveEcho <<line "<read $size bytes for [image width $_image(plot)]x[image height $_image(plot)] image>"
655    }
656}
657
658# ----------------------------------------------------------------------
659# USAGE: _ReceiveLegend <tf> <vmin> <vmax> <size>
660#
661# Invoked automatically whenever the "legend" command comes in from
662# the rendering server.  Indicates that binary image data with the
663# specified <size> will follow.
664# ----------------------------------------------------------------------
665itcl::body Rappture::HeightmapViewer::_ReceiveLegend {tf vmin vmax size} {
666    if { [IsConnected] } {
667        set bytes [ReceiveBytes $size]
668        ReceiveEcho <<line "<read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
669        if 1 {
670        set src [image create photo -data $bytes]
671        blt::winop image rotate $src $_image(legend) 90
672        set dst $_image(legend)
673        } else {
674        $_image(legend) configure -data $bytes
675        }
676        set c $itk_component(legend)
677        set w [winfo width $c]
678        set h [winfo height $c]
679        set lineht [expr [font metrics $itk_option(-font) -linespace] + 4]
680        if {"" == [$c find withtag transfunc]} {
681            $c create image 0 [expr $lineht] -anchor ne \
682                 -image $_image(legend) -tags transfunc
683            $c create text 10 [expr {$h-8}] -anchor se \
684                 -fill $itk_option(-plotforeground) -tags vmin
685            $c create text [expr {$w-10}] [expr {$h-8}] -anchor ne \
686                 -fill $itk_option(-plotforeground) -tags vmax
687        }
688        $c coords transfunc [expr $w - 5] [expr $lineht]
689        $c itemconfigure vmin -text $vmin
690        $c itemconfigure vmax -text $vmax
691        $c coords vmax [expr $w - 5] 2
692        $c coords vmin [expr $w - 5] [expr $h - 2]
693    }
694}
695
696# ----------------------------------------------------------------------
697# USAGE: _rebuild
698#
699# Called automatically whenever something changes that affects the
700# data in the widget.  Clears any existing data and rebuilds the
701# widget to display new data.
702# ----------------------------------------------------------------------
703itcl::body Rappture::HeightmapViewer::_rebuild {} {
704    # in the midst of sending data? then bail out
705    if {[llength $sendobjs_] > 0} {
706        return
707    }
708    # Find any new data that needs to be sent to the server.  Queue this up on
709    # the sendobjs_ list, and send it out a little at a time.  Do this first,
710    # before we rebuild the rest.
711    foreach dataobj [get] {
712        set comp [lindex [$dataobj components] 0]
713        if {![info exists obj2id_($dataobj-$comp)]} {
714            set i [lsearch -exact $sendobjs_ $dataobj]
715            if {$i < 0} {
716                lappend sendobjs_ $dataobj
717            }
718        }
719    }
720    if {[llength $sendobjs_] > 0} {
721        # Send off new data objects
722        $_dispatcher event -idle !send_dataobjs
723    } else {
724        # Nothing to send -- activate the proper volume
725        set first [lindex [get] 0]
726        if {"" != $first} {
727            set axis [$first hints updir]
728            if {"" != $axis} {
729                _send "up $axis"
730            }
731        }
732        foreach key [array names obj2id_ *-*] {
733            set state [string match $first-* $key]
734            _send "heightmap data visible $state $obj2id_($key)"
735            if {[info exists obj2style_($key)]} {
736                _send "heightmap transfunc $obj2style_($key) $obj2id_($key)"
737            }
738        }
739        $_dispatcher event -idle !legend
740    }
741
742    # Reset the screen size. 
743    set w [winfo width $itk_component(3dview)]
744    set h [winfo height $itk_component(3dview)]
745    _send "screen $w $h"
746
747    # Reset the camera and other view parameters
748    set xyz [Euler2XYZ $view_(theta) $view_(phi) $view_(psi)]
749    _send "camera angle $xyz"
750    _PanCamera
751    _send "camera zoom $view_(zoom)"
752
753     if {"" == $itk_option(-plotoutline)} {
754         _send "grid linecolor [Color2RGB $itk_option(-plotoutline)]"
755     }
756    set settings_($this-theta) $view_(theta)
757    set settings_($this-phi) $view_(phi)
758    set settings_($this-psi) $view_(psi)
759    set settings_($this-pan-x) $view_(pan-x)
760    set settings_($this-pan-y) $view_(pan-y)
761    set settings_($this-zoom) $view_(zoom)
762
763    _fixSettings wireframe
764    _fixSettings grid
765    _fixSettings axes
766    _fixSettings contourlines
767}
768
769# ----------------------------------------------------------------------
770# USAGE: _zoom in
771# USAGE: _zoom out
772# USAGE: _zoom reset
773#
774# Called automatically when the user clicks on one of the zoom
775# controls for this widget.  Changes the zoom for the current view.
776# ----------------------------------------------------------------------
777itcl::body Rappture::HeightmapViewer::_zoom {option} {
778    switch -- $option {
779        "in" {
780            set view_(zoom) [expr {$view_(zoom)*1.25}]
781            set settings_($this-zoom) $view_(zoom)
782        }
783        "out" {
784            set view_(zoom) [expr {$view_(zoom)*0.8}]
785            set settings_($this-zoom) $view_(zoom)
786        }
787        "reset" {
788            array set view_ {
789                theta   45
790                phi     45
791                psi     0
792                zoom    1.0
793                pan-x   0
794                pan-y   0
795            }
796            set first [lindex [get] 0]
797            if { $first != "" } {
798                set location [$first hints camera]
799                if { $location != "" } {
800                    array set view_ $location
801                }
802            }
803            set xyz [Euler2XYZ $view_(theta) $view_(phi) $view_(psi)]
804            _send "camera angle $xyz"
805            _PanCamera
806            set settings_($this-theta) $view_(theta)
807            set settings_($this-phi) $view_(phi)
808            set settings_($this-psi) $view_(psi)
809            set settings_($this-pan-x) $view_(pan-x)
810            set settings_($this-pan-y) $view_(pan-y)
811            set settings_($this-zoom) $view_(zoom)
812        }
813    }
814    _send "camera zoom $view_(zoom)"
815}
816
817# ----------------------------------------------------------------------
818# USAGE: $this _pan click x y
819#        $this _pan drag x y
820#        $this _pan release x y
821#
822# Called automatically when the user clicks on one of the zoom
823# controls for this widget.  Changes the zoom for the current view.
824# ----------------------------------------------------------------------
825itcl::body Rappture::HeightmapViewer::_pan {option x y} {
826    # Experimental stuff
827    set w [winfo width $itk_component(3dview)]
828    set h [winfo height $itk_component(3dview)]
829    if { $option == "set" } {
830        set x [expr ($x / double($w)) * $limits_(xrange)]
831        set y [expr ($y / double($h)) * $limits_(yrange)]
832        set view_(pan-x) [expr $view_(pan-x) + $x]
833        set view_(pan-y) [expr $view_(pan-y) + $y]
834        _PanCamera
835        set settings_($this-pan-x) $view_(pan-x)
836        set settings_($this-pan-y) $view_(pan-y)
837        return
838    }
839    if { $option == "click" } {
840        set click_(x) $x
841        set click_(y) $y
842        $itk_component(3dview) configure -cursor hand1
843    }
844    if { $option == "drag" || $option == "release" } {
845        set dx [expr (($click_(x) - $x)/double($w)) * $limits_(xrange)]
846        set dy [expr (($click_(y) - $y)/double($h)) * $limits_(yrange)]
847        set click_(x) $x
848        set click_(y) $y
849        set view_(pan-x) [expr $view_(pan-x) - $dx]
850        set view_(pan-y) [expr $view_(pan-y) - $dy]
851        _PanCamera
852        set settings_($this-pan-x) $view_(pan-x)
853        set settings_($this-pan-y) $view_(pan-y)
854    }
855    if { $option == "release" } {
856        $itk_component(3dview) configure -cursor ""
857    }
858}
859
860itcl::body Rappture::HeightmapViewer::_PanCamera {} {
861    set x [expr ($view_(pan-x)) / $limits_(xrange)]
862    set y [expr ($view_(pan-y)) / $limits_(yrange)]
863    _send "camera pan $x $y"
864}
865
866# ----------------------------------------------------------------------
867# USAGE: _rotate click <x> <y>
868# USAGE: _rotate drag <x> <y>
869# USAGE: _rotate release <x> <y>
870#
871# Called automatically when the user clicks/drags/releases in the
872# plot area.  Moves the plot according to the user's actions.
873# ----------------------------------------------------------------------
874itcl::body Rappture::HeightmapViewer::_rotate {option x y} {
875    switch -- $option {
876        click {
877            $itk_component(3dview) configure -cursor fleur
878            array set click_ [subst {
879                x       $x
880                y       $y
881                theta   $view_(theta)
882                phi     $view_(phi)
883            }]
884        }
885        drag {
886            if {[array size click_] == 0} {
887                _rotate click $x $y
888            } else {
889                set w [winfo width $itk_component(3dview)]
890                set h [winfo height $itk_component(3dview)]
891                if {$w <= 0 || $h <= 0} {
892                    return
893                }
894
895                if {[catch {
896                    # this fails sometimes for no apparent reason
897                    set dx [expr {double($x-$click_(x))/$w}]
898                    set dy [expr {double($y-$click_(y))/$h}]
899                }] != 0 } {
900                    return
901                }
902
903                #
904                # Rotate the camera in 3D
905                #
906                if {$view_(psi) > 90 || $view_(psi) < -90} {
907                    # when psi is flipped around, theta moves backwards
908                    set dy [expr {-$dy}]
909                }
910                set theta [expr {$view_(theta) - $dy*180}]
911                while {$theta < 0} { set theta [expr {$theta+180}] }
912                while {$theta > 180} { set theta [expr {$theta-180}] }
913
914                if {abs($theta) >= 30 && abs($theta) <= 160} {
915                    set phi [expr {$view_(phi) - $dx*360}]
916                    while {$phi < 0} { set phi [expr {$phi+360}] }
917                    while {$phi > 360} { set phi [expr {$phi-360}] }
918                    set psi $view_(psi)
919                } else {
920                    set phi $view_(phi)
921                    set psi [expr {$view_(psi) - $dx*360}]
922                    while {$psi < -180} { set psi [expr {$psi+360}] }
923                    while {$psi > 180} { set psi [expr {$psi-360}] }
924                }
925
926                set view_(theta)        $theta
927                set view_(phi)          $phi
928                set view_(psi)          $psi
929                set xyz [Euler2XYZ $view_(theta) $view_(phi) $view_(psi)]
930                set settings_($this-theta) $view_(theta)
931                set settings_($this-phi) $view_(phi)
932                set settings_($this-psi) $view_(psi)
933                _send "camera angle $xyz"
934                set click_(x) $x
935                set click_(y) $y
936            }
937        }
938        release {
939            _rotate drag $x $y
940            $itk_component(3dview) configure -cursor ""
941            catch {unset click_}
942        }
943        default {
944            error "bad option \"$option\": should be click, drag, release"
945        }
946    }
947}
948
949# ----------------------------------------------------------------------
950# USAGE: _state <component>
951#
952# Used internally to determine the state of a toggle button.
953# The <component> is the itk component name of the button.
954# Returns on/off for the state of the button.
955# ----------------------------------------------------------------------
956itcl::body Rappture::HeightmapViewer::_state {comp} {
957    if {[$itk_component($comp) cget -relief] == "sunken"} {
958        return "on"
959    }
960    return "off"
961}
962
963# ----------------------------------------------------------------------
964# USAGE: _fixSettings <what> ?<value>?
965#
966# Used internally to update rendering settings whenever parameters
967# change in the popup settings panel.  Sends the new settings off
968# to the back end.
969# ----------------------------------------------------------------------
970itcl::body Rappture::HeightmapViewer::_fixSettings { what {value ""} } {
971    switch -- $what {
972        "legend" {
973            if { $settings_($this-legend) } {
974                pack $itk_component(legend) -side right -fill y
975            } else {
976                pack forget $itk_component(legend)
977            }
978            set lineht [expr [font metrics $itk_option(-font) -linespace] + 4]
979            set w [expr {[winfo height $itk_component(legend)] - 2*$lineht}]
980            set h [expr {[winfo width $itk_component(legend)] - 16}]
981            set imap ""
982            set dataobj [lindex [get] 0]
983            if {"" != $dataobj} {
984                set comp [lindex [$dataobj components] 0]
985                if {[info exists obj2id_($dataobj-$comp)]} {
986                    set imap $obj2id_($dataobj-$comp)
987                }
988            }
989            if {$w > 0 && $h > 0 && "" != $imap} {
990                _send "heightmap legend $imap $w $h"
991            } else {
992                $itk_component(legend) delete all
993            }
994        }
995        "grid" {
996            if { [IsConnected] } {
997                _send "grid visible $settings_($this-grid)"
998            }
999        }
1000        "axes" {
1001            if { [IsConnected] } {
1002                _send "axis visible $settings_($this-axes)"
1003            }
1004        }
1005        "wireframe" {
1006            if { [IsConnected] } {
1007                _send "heightmap polygon $settings_($this-wireframe)"
1008            }
1009        }
1010        "contourlines" {
1011            if {[IsConnected]} {
1012                set dataobj [lindex [get] 0]
1013                if {"" != $dataobj} {
1014                    set comp [lindex [$dataobj components] 0]
1015                    if {[info exists obj2id_($dataobj-$comp)]} {
1016                        set i $obj2id_($dataobj-$comp)
1017                        set bool $settings_($this-contourlines)
1018                        _send "heightmap linecontour visible $bool $i"
1019                    }
1020                }
1021            }
1022        }
1023        default {
1024            error "don't know how to fix $what: should be grid, axes, contourlines, or legend"
1025        }
1026    }
1027}
1028
1029# ----------------------------------------------------------------------
1030# USAGE: _getTransfuncData <dataobj> <comp>
1031#
1032# Used internally to compute the colormap and alpha map used to define
1033# a transfer function for the specified component in a data object.
1034# Returns: name {v r g b ...} {v w ...}
1035# ----------------------------------------------------------------------
1036itcl::body Rappture::HeightmapViewer::_getTransfuncData {dataobj comp} {
1037    array set style {
1038        -color rainbow
1039        -levels 6
1040        -opacity 0.5
1041    }
1042    array set style [lindex [$dataobj components -style $comp] 0]
1043    set sname "$style(-color):$style(-levels):$style(-opacity)"
1044
1045    if {$style(-color) == "rainbow"} {
1046        set style(-color) "white:yellow:green:cyan:blue:magenta"
1047    }
1048    set clist [split $style(-color) :]
1049    set color white
1050    set cmap "0.0 [Color2RGB $color] "
1051    set range [expr $limits_(vmax) - $limits_(vmin)]
1052    for {set i 0} {$i < [llength $clist]} {incr i} {
1053        set xval [expr {double($i+1)/([llength $clist]+1)}]
1054        set color [lindex $clist $i]
1055        append cmap "$xval [Color2RGB $color] "
1056    }
1057    append cmap "1.0 [Color2RGB $color] "
1058
1059    set opacity $style(-opacity)
1060    set levels $style(-levels)
1061    set wmap {}
1062    if {[string is int $levels]} {
1063        lappend wmap 0.0 0.0
1064        set delta [expr {0.125/($levels+1)}]
1065        for {set i 1} {$i <= $levels} {incr i} {
1066            # add spikes in the middle
1067            set xval [expr {double($i)/($levels+1)}]
1068            lappend wmap [expr {$xval-$delta-0.01}] 0.0
1069            lappend wmap [expr {$xval-$delta}] $opacity
1070            lappend wmap [expr {$xval+$delta}] $opacity
1071            lappend wmap [expr {$xval+$delta+0.01}] 0.0
1072        }
1073        lappend wmap 1.0 0.0
1074    } else {
1075        lappend wmap 0.0 0.0
1076        set delta 0.05
1077        foreach xval [split $levels ,] {
1078            lappend wmap [expr {$xval-$delta}] 0.0
1079            lappend $xval $opacity
1080            lappend [expr {$xval+$delta}] 0.0
1081        }
1082        lappend wmap 1.0 0.0
1083    }
1084    return [list $sname $cmap $wmap]
1085}
1086
1087# ----------------------------------------------------------------------
1088# CONFIGURATION OPTION: -plotbackground
1089# ----------------------------------------------------------------------
1090itcl::configbody Rappture::HeightmapViewer::plotbackground {
1091    foreach {r g b} [Color2RGB $itk_option(-plotbackground)] break
1092    #fix this!
1093    #_send "color background $r $g $b"
1094}
1095
1096# ----------------------------------------------------------------------
1097# CONFIGURATION OPTION: -plotforeground
1098# ----------------------------------------------------------------------
1099itcl::configbody Rappture::HeightmapViewer::plotforeground {
1100    foreach {r g b} [Color2RGB $itk_option(-plotforeground)] break
1101    #fix this!
1102    #_send "color background $r $g $b"
1103}
1104
1105# ----------------------------------------------------------------------
1106# CONFIGURATION OPTION: -plotoutline
1107# ----------------------------------------------------------------------
1108itcl::configbody Rappture::HeightmapViewer::plotoutline {
1109    if {[IsConnected]} {
1110        _send "grid linecolor [Color2RGB $itk_option(-plotoutline)]"
1111    }
1112}
1113
1114
1115
1116#  camera --
1117#
1118itcl::body Rappture::HeightmapViewer::camera {option args} {
1119    switch -- $option {
1120        "show" {
1121            puts [array get view_]
1122        }
1123        "set" {
1124            set who [lindex $args 0]
1125            set x $settings_($this-$who)
1126            set code [catch { string is double $x } result]
1127            if { $code != 0 || !$result } {
1128                set settings_($this-$who) $view_($who)
1129                return
1130            }
1131            switch -- $who {
1132                "pan-x" - "pan-y" {
1133                    set view_($who) $settings_($this-$who)
1134                    _PanCamera
1135                }
1136                "phi" - "theta" - "psi" {
1137                    set view_($who) $settings_($this-$who)
1138                    set xyz [Euler2XYZ $view_(theta) $view_(phi) $view_(psi)]
1139                    _send "camera angle $xyz"
1140                }
1141                "zoom" {
1142                    set view_($who) $settings_($this-$who)
1143                    _send "camera zoom $view_(zoom)"
1144                }
1145            }
1146        }
1147    }
1148}
1149
1150itcl::body Rappture::HeightmapViewer::_BuildSettingsDrawer {} {
1151
1152    itk_component add settings {
1153        Rappture::Scroller $itk_component(drawer).scrl \
1154            -xscrollmode auto -yscrollmode auto \
1155            -width 200 -height 100
1156    }
1157
1158    itk_component add settings_canvas {
1159        canvas $itk_component(settings).canvas -highlightthickness 0
1160    }
1161    $itk_component(settings) contents $itk_component(settings_canvas)
1162
1163    itk_component add settings_frame {
1164        frame $itk_component(settings_canvas).frame -bg white \
1165            -highlightthickness 0
1166    }
1167    $itk_component(settings_canvas) create window 0 0 \
1168        -anchor nw -window $itk_component(settings_frame)
1169    bind $itk_component(settings_frame) <Configure> \
1170        [itcl::code $this drawer resize settings]
1171
1172    set fg [option get $itk_component(hull) font Font]
1173
1174    set inner $itk_component(settings_frame)
1175
1176    foreach { key value } {
1177        grid            1
1178        axes            0
1179        contourlines    1
1180        wireframe       fill
1181        legend          1
1182    } {
1183        set settings_($this-$key) $value
1184    }
1185    set inner $itk_component(settings_frame)
1186    label $inner.title -text "View Settings" -font "Arial 10 bold"
1187    checkbutton $inner.grid \
1188        -text "grid" \
1189        -variable [itcl::scope settings_($this-grid)] \
1190        -command [itcl::code $this _fixSettings grid] \
1191        -font "Arial 9"
1192    checkbutton $inner.axes \
1193        -text "axes" \
1194        -variable ::Rappture::HeightmapViewer::settings_($this-axes) \
1195        -command [itcl::code $this _fixSettings axes] \
1196        -font "Arial 9"
1197    checkbutton $inner.contourlines \
1198        -text "contour lines" \
1199        -variable ::Rappture::HeightmapViewer::settings_($this-contourlines) \
1200        -command [itcl::code $this _fixSettings contourlines]\
1201        -font "Arial 9"
1202    checkbutton $inner.wireframe \
1203        -text "wireframe" \
1204        -onvalue "wireframe" -offvalue "fill" \
1205        -variable ::Rappture::HeightmapViewer::settings_($this-wireframe) \
1206        -command [itcl::code $this _fixSettings wireframe]\
1207        -font "Arial 9"
1208    checkbutton $inner.legend \
1209        -text "legend" \
1210        -variable ::Rappture::HeightmapViewer::settings_($this-legend) \
1211        -command [itcl::code $this _fixSettings legend]\
1212        -font "Arial 9"
1213
1214    blt::table $inner \
1215        0,0 $inner.title -anchor w -columnspan 2 \
1216        1,1 $inner.grid -anchor w  \
1217        2,1 $inner.axes -anchor w \
1218        3,1 $inner.contourlines -anchor w \
1219        4,1 $inner.wireframe -anchor w \
1220        5,1 $inner.legend -anchor w
1221
1222    blt::table configure $inner c0 -resize expand -width 2
1223    blt::table configure $inner c2 -resize expand
1224    blt::table configure $inner c1 -resize none
1225
1226}
1227
1228itcl::body Rappture::HeightmapViewer::_BuildCameraDrawer {} {
1229
1230    itk_component add camera {
1231        Rappture::Scroller $itk_component(drawer).camerascrl \
1232            -xscrollmode auto -yscrollmode auto \
1233            -highlightthickness 0
1234    }
1235
1236    itk_component add camera_canvas {
1237        canvas $itk_component(camera).canvas -highlightthickness 0
1238    } {
1239        ignore -highlightthickness
1240    }
1241    $itk_component(camera) contents $itk_component(camera_canvas)
1242
1243    itk_component add camera_frame {
1244        frame $itk_component(camera_canvas).frame \
1245            -highlightthickness 0
1246    }
1247    $itk_component(camera_canvas) create window 0 0 \
1248        -anchor nw -window $itk_component(camera_frame)
1249    bind $itk_component(camera_frame) <Configure> \
1250        [itcl::code $this drawer resize camera]
1251
1252    set inner $itk_component(camera_frame)
1253
1254    label $inner.title -text "Camera Settings" -font "Arial 10 bold"
1255
1256    set labels { phi theta psi pan-x pan-y zoom }
1257    blt::table $inner \
1258        0,0 $inner.title -anchor w  -columnspan 4
1259    set row 1
1260    foreach tag $labels {
1261        label $inner.${tag}label -text $tag -font "Arial 9"
1262        entry $inner.${tag} -font "Arial 9"  -bg white \
1263            -textvariable [itcl::scope settings_($this-$tag)]
1264        bind $inner.${tag} <KeyPress-Return> \
1265            [itcl::code $this camera set ${tag}]
1266        blt::table $inner \
1267            $row,1 $inner.${tag}label -anchor e \
1268            $row,2 $inner.${tag} -anchor w
1269        incr row
1270    }
1271    bind $inner.title <Shift-ButtonPress> \
1272        [itcl::code $this camera show]
1273    blt::table configure $inner c0 -resize expand -width 4
1274    blt::table configure $inner c1 c2 -resize none
1275    blt::table configure $inner c3 -resize expand
1276
1277}
1278
1279itcl::body Rappture::HeightmapViewer::drawer { what who } {
1280    switch -- ${what} {
1281        "activate" {
1282            $itk_component(drawer) add $itk_component($who) -sticky nsew
1283            after idle [list focus $itk_component($who)]
1284            if { ![info exists initialized_($who)] } {
1285                set w [winfo width $itk_component(drawer)]
1286                set x [expr $w - 120]
1287                $itk_component(drawer) sash place 0 $x 0
1288                set initialized_($who) 1
1289            }
1290            $itk_component(${who}_button) configure -relief sunken
1291        }
1292        "deactivate" {
1293            $itk_component(drawer) forget $itk_component($who)
1294            $itk_component(${who}_button) configure -relief raised
1295        }
1296        "toggle" {
1297            set slaves [$itk_component(drawer) panes]
1298            if { [lsearch $slaves $itk_component($who)] >= 0 } {
1299                drawer deactivate $who
1300            } else {
1301                drawer activate $who
1302            }
1303        }
1304        "resize" {
1305            set bbox [$itk_component(${who}_canvas) bbox all]
1306            set wid [winfo width $itk_component(${who}_frame)]
1307            $itk_component(${who}_canvas) configure -width $wid \
1308                -scrollregion $bbox -yscrollincrement 0.1i
1309        }
1310    }
1311}
1312
Note: See TracBrowser for help on using the repository browser.