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

Last change on this file since 1343 was 1343, checked in by gah, 16 years ago

fixed comment

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 the image data (as base64) and decode it back to binary.
496            # This is better than writing to temporary files.  When we switch
497            # to the BLT picture image it won't be necessary to decode the
498            # image data.
499            set bytes [$_image(download) data -format "jpeg -quality 100"]
500            set bytes [Rappture::encoding::decode -as b64 $bytes]
501            return [list .jpg $bytes]
502        }
503        default {
504            error "bad option \"$option\": should be coming, controls, now"
505        }
506    }
507}
508
509# ----------------------------------------------------------------------
510# USAGE: Connect ?<host:port>,<host:port>...?
511#
512# Clients use this method to establish a connection to a new
513# server, or to reestablish a connection to the previous server.
514# Any existing connection is automatically closed.
515# ----------------------------------------------------------------------
516itcl::body Rappture::HeightmapViewer::Connect {} {
517    Disconnect
518    set _hosts [GetServerList "nanovis"]
519    if { "" == $_hosts } {
520        return 0
521    }
522    set result [VisViewer::Connect $_hosts]
523    return $result
524}
525
526# ----------------------------------------------------------------------
527# USAGE: Disconnect
528#
529# Clients use this method to disconnect from the current rendering
530# server.
531# ----------------------------------------------------------------------
532itcl::body Rappture::HeightmapViewer::Disconnect {} {
533    VisViewer::Disconnect
534
535    set outbuf_ ""
536    # disconnected -- no more data sitting on server
537    catch {unset obj2id_}
538    array unset id2obj_
539    set obj2id_(count) 0
540    set id2obj_(cound) 0
541    set sendobjs_ ""
542}
543
544#
545# _send
546#
547#       Send commands off to the rendering server.  If we're currently
548#       sending data objects to the server, buffer the commands to be
549#       sent later.
550#
551itcl::body Rappture::HeightmapViewer::_send {string} {
552    if {[llength $sendobjs_] > 0} {
553        append outbuf_ $string "\n"
554    } else {
555        if {[SendBytes $string]} {
556            foreach line [split $string \n] {
557                SendEcho >>line $line
558            }
559        }
560    }
561}
562
563# ----------------------------------------------------------------------
564# USAGE: _send_dataobjs
565#
566# Used internally to send a series of volume objects off to the
567# server.  Sends each object, a little at a time, with updates in
568# between so the interface doesn't lock up.
569# ----------------------------------------------------------------------
570itcl::body Rappture::HeightmapViewer::_send_dataobjs {} {
571    blt::busy hold $itk_component(hull); update idletasks
572
573    # Reset the overall limits
574    if { $sendobjs_ != "" } {
575        set limits_(vmin) ""
576        set limits_(vmax) ""
577    }
578    foreach dataobj $sendobjs_ {
579        foreach comp [$dataobj components] {
580            set data [$dataobj blob $comp]
581
582            foreach { vmin vmax }  [$dataobj limits v] break
583            if { $limits_(vmin) == "" || $vmin < $limits_(vmin) } {
584                set limits_(vmin) $vmin
585            }
586            if { $limits_(vmax) == "" || $vmax > $limits_(vmax) } {
587                set limits_(vmax) $vmax
588            }
589
590            # tell the engine to expect some data
591            set nbytes [string length $data]
592            if { ![SendBytes "heightmap data follows $nbytes"] } {
593                return
594
595            }
596            if { ![SendBytes $data] } {
597                return
598            }
599            set id $obj2id_(count)
600            incr obj2id_(count)
601            set id2obj_($id) [list $dataobj $comp]
602            set obj2id_($dataobj-$comp) $id
603            set receiveIds_($id) 1
604
605            #
606            # Determine the transfer function needed for this volume
607            # and make sure that it's defined on the server.
608            #
609            foreach {sname cmap wmap} [_getTransfuncData $dataobj $comp] break
610            set cmdstr [list "transfunc" "define" $sname $cmap $wmap]
611            if {![SendBytes $cmdstr]} {
612                return
613            }
614            set obj2style_($dataobj-$comp) $sname
615        }
616    }
617    set sendobjs_ ""
618    blt::busy release $itk_component(hull)
619
620    # activate the proper volume
621    set first [lindex [get] 0]
622    if {"" != $first} {
623        set axis [$first hints updir]
624        if {"" != $axis} {
625            _send "up $axis"
626        }
627    }
628
629    foreach key [array names obj2id_ *-*] {
630        set state [string match $first-* $key]
631        _send "heightmap data visible $state $obj2id_($key)"
632        if {[info exists obj2style_($key)]} {
633            _send "heightmap transfunc $obj2style_($key) $obj2id_($key)"
634        }
635    }
636
637    # if there are any commands in the buffer, send them now that we're done
638    SendBytes $outbuf_
639    set outbuf_ ""
640
641    $_dispatcher event -idle !legend
642}
643
644# ----------------------------------------------------------------------
645# USAGE: ReceiveImage -bytes <size>
646#
647# Invoked automatically whenever the "image" command comes in from
648# the rendering server.  Indicates that binary image data with the
649# specified <size> will follow.
650# ----------------------------------------------------------------------
651itcl::body Rappture::HeightmapViewer::ReceiveImage {option size} {
652    if {[IsConnected]} {
653        set bytes [ReceiveBytes $size]
654        $_image(plot) configure -data $bytes
655        ReceiveEcho <<line "<read $size bytes for [image width $_image(plot)]x[image height $_image(plot)] image>"
656    }
657}
658
659# ----------------------------------------------------------------------
660# USAGE: _ReceiveLegend <tf> <vmin> <vmax> <size>
661#
662# Invoked automatically whenever the "legend" command comes in from
663# the rendering server.  Indicates that binary image data with the
664# specified <size> will follow.
665# ----------------------------------------------------------------------
666itcl::body Rappture::HeightmapViewer::_ReceiveLegend {tf vmin vmax size} {
667    if { [IsConnected] } {
668        set bytes [ReceiveBytes $size]
669        ReceiveEcho <<line "<read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
670        if 1 {
671        set src [image create photo -data $bytes]
672        blt::winop image rotate $src $_image(legend) 90
673        set dst $_image(legend)
674        } else {
675        $_image(legend) configure -data $bytes
676        }
677        set c $itk_component(legend)
678        set w [winfo width $c]
679        set h [winfo height $c]
680        set lineht [expr [font metrics $itk_option(-font) -linespace] + 4]
681        if {"" == [$c find withtag transfunc]} {
682            $c create image 0 [expr $lineht] -anchor ne \
683                 -image $_image(legend) -tags transfunc
684            $c create text 10 [expr {$h-8}] -anchor se \
685                 -fill $itk_option(-plotforeground) -tags vmin
686            $c create text [expr {$w-10}] [expr {$h-8}] -anchor ne \
687                 -fill $itk_option(-plotforeground) -tags vmax
688        }
689        $c coords transfunc [expr $w - 5] [expr $lineht]
690        $c itemconfigure vmin -text $vmin
691        $c itemconfigure vmax -text $vmax
692        $c coords vmax [expr $w - 5] 2
693        $c coords vmin [expr $w - 5] [expr $h - 2]
694    }
695}
696
697# ----------------------------------------------------------------------
698# USAGE: _rebuild
699#
700# Called automatically whenever something changes that affects the
701# data in the widget.  Clears any existing data and rebuilds the
702# widget to display new data.
703# ----------------------------------------------------------------------
704itcl::body Rappture::HeightmapViewer::_rebuild {} {
705    # in the midst of sending data? then bail out
706    if {[llength $sendobjs_] > 0} {
707        return
708    }
709    # Find any new data that needs to be sent to the server.  Queue this up on
710    # the sendobjs_ list, and send it out a little at a time.  Do this first,
711    # before we rebuild the rest.
712    foreach dataobj [get] {
713        set comp [lindex [$dataobj components] 0]
714        if {![info exists obj2id_($dataobj-$comp)]} {
715            set i [lsearch -exact $sendobjs_ $dataobj]
716            if {$i < 0} {
717                lappend sendobjs_ $dataobj
718            }
719        }
720    }
721    if {[llength $sendobjs_] > 0} {
722        # Send off new data objects
723        $_dispatcher event -idle !send_dataobjs
724    } else {
725        # Nothing to send -- activate the proper volume
726        set first [lindex [get] 0]
727        if {"" != $first} {
728            set axis [$first hints updir]
729            if {"" != $axis} {
730                _send "up $axis"
731            }
732        }
733        foreach key [array names obj2id_ *-*] {
734            set state [string match $first-* $key]
735            _send "heightmap data visible $state $obj2id_($key)"
736            if {[info exists obj2style_($key)]} {
737                _send "heightmap transfunc $obj2style_($key) $obj2id_($key)"
738            }
739        }
740        $_dispatcher event -idle !legend
741    }
742
743    # Reset the screen size. 
744    set w [winfo width $itk_component(3dview)]
745    set h [winfo height $itk_component(3dview)]
746    _send "screen $w $h"
747
748    # Reset the camera and other view parameters
749    set xyz [Euler2XYZ $view_(theta) $view_(phi) $view_(psi)]
750    _send "camera angle $xyz"
751    _PanCamera
752    _send "camera zoom $view_(zoom)"
753
754     if {"" == $itk_option(-plotoutline)} {
755         _send "grid linecolor [Color2RGB $itk_option(-plotoutline)]"
756     }
757    set settings_($this-theta) $view_(theta)
758    set settings_($this-phi) $view_(phi)
759    set settings_($this-psi) $view_(psi)
760    set settings_($this-pan-x) $view_(pan-x)
761    set settings_($this-pan-y) $view_(pan-y)
762    set settings_($this-zoom) $view_(zoom)
763
764    _fixSettings wireframe
765    _fixSettings grid
766    _fixSettings axes
767    _fixSettings contourlines
768}
769
770# ----------------------------------------------------------------------
771# USAGE: _zoom in
772# USAGE: _zoom out
773# USAGE: _zoom reset
774#
775# Called automatically when the user clicks on one of the zoom
776# controls for this widget.  Changes the zoom for the current view.
777# ----------------------------------------------------------------------
778itcl::body Rappture::HeightmapViewer::_zoom {option} {
779    switch -- $option {
780        "in" {
781            set view_(zoom) [expr {$view_(zoom)*1.25}]
782            set settings_($this-zoom) $view_(zoom)
783        }
784        "out" {
785            set view_(zoom) [expr {$view_(zoom)*0.8}]
786            set settings_($this-zoom) $view_(zoom)
787        }
788        "reset" {
789            array set view_ {
790                theta   45
791                phi     45
792                psi     0
793                zoom    1.0
794                pan-x   0
795                pan-y   0
796            }
797            set first [lindex [get] 0]
798            if { $first != "" } {
799                set location [$first hints camera]
800                if { $location != "" } {
801                    array set view_ $location
802                }
803            }
804            set xyz [Euler2XYZ $view_(theta) $view_(phi) $view_(psi)]
805            _send "camera angle $xyz"
806            _PanCamera
807            set settings_($this-theta) $view_(theta)
808            set settings_($this-phi) $view_(phi)
809            set settings_($this-psi) $view_(psi)
810            set settings_($this-pan-x) $view_(pan-x)
811            set settings_($this-pan-y) $view_(pan-y)
812            set settings_($this-zoom) $view_(zoom)
813        }
814    }
815    _send "camera zoom $view_(zoom)"
816}
817
818# ----------------------------------------------------------------------
819# USAGE: $this _pan click x y
820#        $this _pan drag x y
821#        $this _pan release x y
822#
823# Called automatically when the user clicks on one of the zoom
824# controls for this widget.  Changes the zoom for the current view.
825# ----------------------------------------------------------------------
826itcl::body Rappture::HeightmapViewer::_pan {option x y} {
827    # Experimental stuff
828    set w [winfo width $itk_component(3dview)]
829    set h [winfo height $itk_component(3dview)]
830    if { $option == "set" } {
831        set x [expr ($x / double($w)) * $limits_(xrange)]
832        set y [expr ($y / double($h)) * $limits_(yrange)]
833        set view_(pan-x) [expr $view_(pan-x) + $x]
834        set view_(pan-y) [expr $view_(pan-y) + $y]
835        _PanCamera
836        set settings_($this-pan-x) $view_(pan-x)
837        set settings_($this-pan-y) $view_(pan-y)
838        return
839    }
840    if { $option == "click" } {
841        set click_(x) $x
842        set click_(y) $y
843        $itk_component(3dview) configure -cursor hand1
844    }
845    if { $option == "drag" || $option == "release" } {
846        set dx [expr (($click_(x) - $x)/double($w)) * $limits_(xrange)]
847        set dy [expr (($click_(y) - $y)/double($h)) * $limits_(yrange)]
848        set click_(x) $x
849        set click_(y) $y
850        set view_(pan-x) [expr $view_(pan-x) - $dx]
851        set view_(pan-y) [expr $view_(pan-y) - $dy]
852        _PanCamera
853        set settings_($this-pan-x) $view_(pan-x)
854        set settings_($this-pan-y) $view_(pan-y)
855    }
856    if { $option == "release" } {
857        $itk_component(3dview) configure -cursor ""
858    }
859}
860
861itcl::body Rappture::HeightmapViewer::_PanCamera {} {
862    set x [expr ($view_(pan-x)) / $limits_(xrange)]
863    set y [expr ($view_(pan-y)) / $limits_(yrange)]
864    _send "camera pan $x $y"
865}
866
867# ----------------------------------------------------------------------
868# USAGE: _rotate click <x> <y>
869# USAGE: _rotate drag <x> <y>
870# USAGE: _rotate release <x> <y>
871#
872# Called automatically when the user clicks/drags/releases in the
873# plot area.  Moves the plot according to the user's actions.
874# ----------------------------------------------------------------------
875itcl::body Rappture::HeightmapViewer::_rotate {option x y} {
876    switch -- $option {
877        click {
878            $itk_component(3dview) configure -cursor fleur
879            array set click_ [subst {
880                x       $x
881                y       $y
882                theta   $view_(theta)
883                phi     $view_(phi)
884            }]
885        }
886        drag {
887            if {[array size click_] == 0} {
888                _rotate click $x $y
889            } else {
890                set w [winfo width $itk_component(3dview)]
891                set h [winfo height $itk_component(3dview)]
892                if {$w <= 0 || $h <= 0} {
893                    return
894                }
895
896                if {[catch {
897                    # this fails sometimes for no apparent reason
898                    set dx [expr {double($x-$click_(x))/$w}]
899                    set dy [expr {double($y-$click_(y))/$h}]
900                }] != 0 } {
901                    return
902                }
903
904                #
905                # Rotate the camera in 3D
906                #
907                if {$view_(psi) > 90 || $view_(psi) < -90} {
908                    # when psi is flipped around, theta moves backwards
909                    set dy [expr {-$dy}]
910                }
911                set theta [expr {$view_(theta) - $dy*180}]
912                while {$theta < 0} { set theta [expr {$theta+180}] }
913                while {$theta > 180} { set theta [expr {$theta-180}] }
914
915                if {abs($theta) >= 30 && abs($theta) <= 160} {
916                    set phi [expr {$view_(phi) - $dx*360}]
917                    while {$phi < 0} { set phi [expr {$phi+360}] }
918                    while {$phi > 360} { set phi [expr {$phi-360}] }
919                    set psi $view_(psi)
920                } else {
921                    set phi $view_(phi)
922                    set psi [expr {$view_(psi) - $dx*360}]
923                    while {$psi < -180} { set psi [expr {$psi+360}] }
924                    while {$psi > 180} { set psi [expr {$psi-360}] }
925                }
926
927                set view_(theta)        $theta
928                set view_(phi)          $phi
929                set view_(psi)          $psi
930                set xyz [Euler2XYZ $view_(theta) $view_(phi) $view_(psi)]
931                set settings_($this-theta) $view_(theta)
932                set settings_($this-phi) $view_(phi)
933                set settings_($this-psi) $view_(psi)
934                _send "camera angle $xyz"
935                set click_(x) $x
936                set click_(y) $y
937            }
938        }
939        release {
940            _rotate drag $x $y
941            $itk_component(3dview) configure -cursor ""
942            catch {unset click_}
943        }
944        default {
945            error "bad option \"$option\": should be click, drag, release"
946        }
947    }
948}
949
950# ----------------------------------------------------------------------
951# USAGE: _state <component>
952#
953# Used internally to determine the state of a toggle button.
954# The <component> is the itk component name of the button.
955# Returns on/off for the state of the button.
956# ----------------------------------------------------------------------
957itcl::body Rappture::HeightmapViewer::_state {comp} {
958    if {[$itk_component($comp) cget -relief] == "sunken"} {
959        return "on"
960    }
961    return "off"
962}
963
964# ----------------------------------------------------------------------
965# USAGE: _fixSettings <what> ?<value>?
966#
967# Used internally to update rendering settings whenever parameters
968# change in the popup settings panel.  Sends the new settings off
969# to the back end.
970# ----------------------------------------------------------------------
971itcl::body Rappture::HeightmapViewer::_fixSettings { what {value ""} } {
972    switch -- $what {
973        "legend" {
974            if { $settings_($this-legend) } {
975                pack $itk_component(legend) -side right -fill y
976            } else {
977                pack forget $itk_component(legend)
978            }
979            set lineht [expr [font metrics $itk_option(-font) -linespace] + 4]
980            set w [expr {[winfo height $itk_component(legend)] - 2*$lineht}]
981            set h [expr {[winfo width $itk_component(legend)] - 16}]
982            set imap ""
983            set dataobj [lindex [get] 0]
984            if {"" != $dataobj} {
985                set comp [lindex [$dataobj components] 0]
986                if {[info exists obj2id_($dataobj-$comp)]} {
987                    set imap $obj2id_($dataobj-$comp)
988                }
989            }
990            if {$w > 0 && $h > 0 && "" != $imap} {
991                _send "heightmap legend $imap $w $h"
992            } else {
993                $itk_component(legend) delete all
994            }
995        }
996        "grid" {
997            if { [IsConnected] } {
998                _send "grid visible $settings_($this-grid)"
999            }
1000        }
1001        "axes" {
1002            if { [IsConnected] } {
1003                _send "axis visible $settings_($this-axes)"
1004            }
1005        }
1006        "wireframe" {
1007            if { [IsConnected] } {
1008                _send "heightmap polygon $settings_($this-wireframe)"
1009            }
1010        }
1011        "contourlines" {
1012            if {[IsConnected]} {
1013                set dataobj [lindex [get] 0]
1014                if {"" != $dataobj} {
1015                    set comp [lindex [$dataobj components] 0]
1016                    if {[info exists obj2id_($dataobj-$comp)]} {
1017                        set i $obj2id_($dataobj-$comp)
1018                        set bool $settings_($this-contourlines)
1019                        _send "heightmap linecontour visible $bool $i"
1020                    }
1021                }
1022            }
1023        }
1024        default {
1025            error "don't know how to fix $what: should be grid, axes, contourlines, or legend"
1026        }
1027    }
1028}
1029
1030# ----------------------------------------------------------------------
1031# USAGE: _getTransfuncData <dataobj> <comp>
1032#
1033# Used internally to compute the colormap and alpha map used to define
1034# a transfer function for the specified component in a data object.
1035# Returns: name {v r g b ...} {v w ...}
1036# ----------------------------------------------------------------------
1037itcl::body Rappture::HeightmapViewer::_getTransfuncData {dataobj comp} {
1038    array set style {
1039        -color rainbow
1040        -levels 6
1041        -opacity 0.5
1042    }
1043    array set style [lindex [$dataobj components -style $comp] 0]
1044    set sname "$style(-color):$style(-levels):$style(-opacity)"
1045
1046    if {$style(-color) == "rainbow"} {
1047        set style(-color) "white:yellow:green:cyan:blue:magenta"
1048    }
1049    set clist [split $style(-color) :]
1050    set color white
1051    set cmap "0.0 [Color2RGB $color] "
1052    set range [expr $limits_(vmax) - $limits_(vmin)]
1053    for {set i 0} {$i < [llength $clist]} {incr i} {
1054        set xval [expr {double($i+1)/([llength $clist]+1)}]
1055        set color [lindex $clist $i]
1056        append cmap "$xval [Color2RGB $color] "
1057    }
1058    append cmap "1.0 [Color2RGB $color] "
1059
1060    set opacity $style(-opacity)
1061    set levels $style(-levels)
1062    set wmap {}
1063    if {[string is int $levels]} {
1064        lappend wmap 0.0 0.0
1065        set delta [expr {0.125/($levels+1)}]
1066        for {set i 1} {$i <= $levels} {incr i} {
1067            # add spikes in the middle
1068            set xval [expr {double($i)/($levels+1)}]
1069            lappend wmap [expr {$xval-$delta-0.01}] 0.0
1070            lappend wmap [expr {$xval-$delta}] $opacity
1071            lappend wmap [expr {$xval+$delta}] $opacity
1072            lappend wmap [expr {$xval+$delta+0.01}] 0.0
1073        }
1074        lappend wmap 1.0 0.0
1075    } else {
1076        lappend wmap 0.0 0.0
1077        set delta 0.05
1078        foreach xval [split $levels ,] {
1079            lappend wmap [expr {$xval-$delta}] 0.0
1080            lappend $xval $opacity
1081            lappend [expr {$xval+$delta}] 0.0
1082        }
1083        lappend wmap 1.0 0.0
1084    }
1085    return [list $sname $cmap $wmap]
1086}
1087
1088# ----------------------------------------------------------------------
1089# CONFIGURATION OPTION: -plotbackground
1090# ----------------------------------------------------------------------
1091itcl::configbody Rappture::HeightmapViewer::plotbackground {
1092    foreach {r g b} [Color2RGB $itk_option(-plotbackground)] break
1093    #fix this!
1094    #_send "color background $r $g $b"
1095}
1096
1097# ----------------------------------------------------------------------
1098# CONFIGURATION OPTION: -plotforeground
1099# ----------------------------------------------------------------------
1100itcl::configbody Rappture::HeightmapViewer::plotforeground {
1101    foreach {r g b} [Color2RGB $itk_option(-plotforeground)] break
1102    #fix this!
1103    #_send "color background $r $g $b"
1104}
1105
1106# ----------------------------------------------------------------------
1107# CONFIGURATION OPTION: -plotoutline
1108# ----------------------------------------------------------------------
1109itcl::configbody Rappture::HeightmapViewer::plotoutline {
1110    if {[IsConnected]} {
1111        _send "grid linecolor [Color2RGB $itk_option(-plotoutline)]"
1112    }
1113}
1114
1115
1116
1117#  camera --
1118#
1119itcl::body Rappture::HeightmapViewer::camera {option args} {
1120    switch -- $option {
1121        "show" {
1122            puts [array get view_]
1123        }
1124        "set" {
1125            set who [lindex $args 0]
1126            set x $settings_($this-$who)
1127            set code [catch { string is double $x } result]
1128            if { $code != 0 || !$result } {
1129                set settings_($this-$who) $view_($who)
1130                return
1131            }
1132            switch -- $who {
1133                "pan-x" - "pan-y" {
1134                    set view_($who) $settings_($this-$who)
1135                    _PanCamera
1136                }
1137                "phi" - "theta" - "psi" {
1138                    set view_($who) $settings_($this-$who)
1139                    set xyz [Euler2XYZ $view_(theta) $view_(phi) $view_(psi)]
1140                    _send "camera angle $xyz"
1141                }
1142                "zoom" {
1143                    set view_($who) $settings_($this-$who)
1144                    _send "camera zoom $view_(zoom)"
1145                }
1146            }
1147        }
1148    }
1149}
1150
1151itcl::body Rappture::HeightmapViewer::_BuildSettingsDrawer {} {
1152
1153    itk_component add settings {
1154        Rappture::Scroller $itk_component(drawer).scrl \
1155            -xscrollmode auto -yscrollmode auto \
1156            -width 200 -height 100
1157    }
1158
1159    itk_component add settings_canvas {
1160        canvas $itk_component(settings).canvas -highlightthickness 0
1161    }
1162    $itk_component(settings) contents $itk_component(settings_canvas)
1163
1164    itk_component add settings_frame {
1165        frame $itk_component(settings_canvas).frame -bg white \
1166            -highlightthickness 0
1167    }
1168    $itk_component(settings_canvas) create window 0 0 \
1169        -anchor nw -window $itk_component(settings_frame)
1170    bind $itk_component(settings_frame) <Configure> \
1171        [itcl::code $this drawer resize settings]
1172
1173    set fg [option get $itk_component(hull) font Font]
1174
1175    set inner $itk_component(settings_frame)
1176
1177    foreach { key value } {
1178        grid            1
1179        axes            0
1180        contourlines    1
1181        wireframe       fill
1182        legend          1
1183    } {
1184        set settings_($this-$key) $value
1185    }
1186    set inner $itk_component(settings_frame)
1187    label $inner.title -text "View Settings" -font "Arial 10 bold"
1188    checkbutton $inner.grid \
1189        -text "grid" \
1190        -variable [itcl::scope settings_($this-grid)] \
1191        -command [itcl::code $this _fixSettings grid] \
1192        -font "Arial 9"
1193    checkbutton $inner.axes \
1194        -text "axes" \
1195        -variable ::Rappture::HeightmapViewer::settings_($this-axes) \
1196        -command [itcl::code $this _fixSettings axes] \
1197        -font "Arial 9"
1198    checkbutton $inner.contourlines \
1199        -text "contour lines" \
1200        -variable ::Rappture::HeightmapViewer::settings_($this-contourlines) \
1201        -command [itcl::code $this _fixSettings contourlines]\
1202        -font "Arial 9"
1203    checkbutton $inner.wireframe \
1204        -text "wireframe" \
1205        -onvalue "wireframe" -offvalue "fill" \
1206        -variable ::Rappture::HeightmapViewer::settings_($this-wireframe) \
1207        -command [itcl::code $this _fixSettings wireframe]\
1208        -font "Arial 9"
1209    checkbutton $inner.legend \
1210        -text "legend" \
1211        -variable ::Rappture::HeightmapViewer::settings_($this-legend) \
1212        -command [itcl::code $this _fixSettings legend]\
1213        -font "Arial 9"
1214
1215    blt::table $inner \
1216        0,0 $inner.title -anchor w -columnspan 2 \
1217        1,1 $inner.grid -anchor w  \
1218        2,1 $inner.axes -anchor w \
1219        3,1 $inner.contourlines -anchor w \
1220        4,1 $inner.wireframe -anchor w \
1221        5,1 $inner.legend -anchor w
1222
1223    blt::table configure $inner c0 -resize expand -width 2
1224    blt::table configure $inner c2 -resize expand
1225    blt::table configure $inner c1 -resize none
1226
1227}
1228
1229itcl::body Rappture::HeightmapViewer::_BuildCameraDrawer {} {
1230
1231    itk_component add camera {
1232        Rappture::Scroller $itk_component(drawer).camerascrl \
1233            -xscrollmode auto -yscrollmode auto \
1234            -highlightthickness 0
1235    }
1236
1237    itk_component add camera_canvas {
1238        canvas $itk_component(camera).canvas -highlightthickness 0
1239    } {
1240        ignore -highlightthickness
1241    }
1242    $itk_component(camera) contents $itk_component(camera_canvas)
1243
1244    itk_component add camera_frame {
1245        frame $itk_component(camera_canvas).frame \
1246            -highlightthickness 0
1247    }
1248    $itk_component(camera_canvas) create window 0 0 \
1249        -anchor nw -window $itk_component(camera_frame)
1250    bind $itk_component(camera_frame) <Configure> \
1251        [itcl::code $this drawer resize camera]
1252
1253    set inner $itk_component(camera_frame)
1254
1255    label $inner.title -text "Camera Settings" -font "Arial 10 bold"
1256
1257    set labels { phi theta psi pan-x pan-y zoom }
1258    blt::table $inner \
1259        0,0 $inner.title -anchor w  -columnspan 4
1260    set row 1
1261    foreach tag $labels {
1262        label $inner.${tag}label -text $tag -font "Arial 9"
1263        entry $inner.${tag} -font "Arial 9"  -bg white \
1264            -textvariable [itcl::scope settings_($this-$tag)]
1265        bind $inner.${tag} <KeyPress-Return> \
1266            [itcl::code $this camera set ${tag}]
1267        blt::table $inner \
1268            $row,1 $inner.${tag}label -anchor e \
1269            $row,2 $inner.${tag} -anchor w
1270        incr row
1271    }
1272    bind $inner.title <Shift-ButtonPress> \
1273        [itcl::code $this camera show]
1274    blt::table configure $inner c0 -resize expand -width 4
1275    blt::table configure $inner c1 c2 -resize none
1276    blt::table configure $inner c3 -resize expand
1277
1278}
1279
1280itcl::body Rappture::HeightmapViewer::drawer { what who } {
1281    switch -- ${what} {
1282        "activate" {
1283            $itk_component(drawer) add $itk_component($who) -sticky nsew
1284            after idle [list focus $itk_component($who)]
1285            if { ![info exists initialized_($who)] } {
1286                set w [winfo width $itk_component(drawer)]
1287                set x [expr $w - 120]
1288                $itk_component(drawer) sash place 0 $x 0
1289                set initialized_($who) 1
1290            }
1291            $itk_component(${who}_button) configure -relief sunken
1292        }
1293        "deactivate" {
1294            $itk_component(drawer) forget $itk_component($who)
1295            $itk_component(${who}_button) configure -relief raised
1296        }
1297        "toggle" {
1298            set slaves [$itk_component(drawer) panes]
1299            if { [lsearch $slaves $itk_component($who)] >= 0 } {
1300                drawer deactivate $who
1301            } else {
1302                drawer activate $who
1303            }
1304        }
1305        "resize" {
1306            set bbox [$itk_component(${who}_canvas) bbox all]
1307            set wid [winfo width $itk_component(${who}_frame)]
1308            $itk_component(${who}_canvas) configure -width $wid \
1309                -scrollregion $bbox -yscrollincrement 0.1i
1310        }
1311    }
1312}
1313
Note: See TracBrowser for help on using the repository browser.