source: branches/blt4/gui/scripts/nanovisviewer.tcl @ 1695

Last change on this file since 1695 was 1646, checked in by gah, 15 years ago
File size: 64.3 KB
Line 
1
2# ----------------------------------------------------------------------
3#  COMPONENT: nanovisviewer - 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# ======================================================================
15package require Itk
16package require BLT
17#package require Img
18                                       
19#
20# FIXME:
21#       Need to Add DX readers this client to examine the data before
22#       it's sent to the server.  This will eliminate 90% of the insanity in
23#       computing the limits of all the volumes.  I can rip out all the
24#       "receive data" "send transfer function" event crap.
25#
26#       This means we can compute the transfer function (relative values) and
27#       draw the legend min/max values without waiting for the information to
28#       come from the server.  This will also prevent the flashing that occurs
29#       when a new volume is drawn (using the default transfer function) and
30#       then when the correct transfer function has been sent and linked to
31#       the volume. 
32#
33option add *NanovisViewer.width 4i widgetDefault
34option add *NanovisViewer*cursor crosshair widgetDefault
35option add *NanovisViewer.height 4i widgetDefault
36option add *NanovisViewer.foreground black widgetDefault
37option add *NanovisViewer.controlBackground gray widgetDefault
38option add *NanovisViewer.controlDarkBackground #999999 widgetDefault
39option add *NanovisViewer.plotBackground black widgetDefault
40option add *NanovisViewer.plotForeground white widgetDefault
41option add *NanovisViewer.plotOutline gray widgetDefault
42option add *NanovisViewer.font \
43    -*-helvetica-medium-r-normal-*-12-* widgetDefault
44
45# must use this name -- plugs into Rappture::resources::load
46proc NanovisViewer_init_resources {} {
47    Rappture::resources::register \
48        nanovis_server Rappture::NanovisViewer::SetServerList
49}
50
51itcl::class Rappture::NanovisViewer {
52    inherit Rappture::VisViewer
53
54    itk_option define -plotforeground plotForeground Foreground ""
55    itk_option define -plotbackground plotBackground Background ""
56    itk_option define -plotoutline plotOutline PlotOutline ""
57
58    constructor { hostlist args } {
59        Rappture::VisViewer::constructor $hostlist
60    } {
61        # defined below
62    }
63    destructor {
64        # defined below
65    }
66    public proc SetServerList { namelist } {
67        Rappture::VisViewer::SetServerList "nanovis" $namelist
68    }
69    public method add {dataobj {settings ""}}
70    public method camera {option args}
71    public method delete {args}
72    public method disconnect {}
73    public method download {option args}
74    public method get {args}
75    public method isconnected {}
76    public method limits { tf }
77    public method overmarker { m x }
78    public method sendto { string }
79    public method parameters {title args} {
80        # do nothing
81    }
82    public method rmdupmarker { m x }
83    public method scale {args}
84    public method updatetransferfuncs {}
85
86    protected method Connect {}
87    protected method CurrentVolumes {{what -all}}
88    protected method Disconnect {}
89    protected method DoResize {}
90    protected method FixLegend {}
91    protected method FixSettings {what {value ""}}
92    protected method Pan {option x y}
93    protected method Rebuild {}
94    protected method ReceiveData { args }
95    protected method ReceiveImage { args }
96    protected method ReceiveLegend { tf vmin vmax size }
97    protected method Rotate {option x y}
98    protected method SendCmd {string}
99    protected method SendTransferFuncs {}
100    protected method Slice {option args}
101    protected method SlicerTip {axis}
102    protected method Zoom {option}
103
104    # The following methods are only used by this class.
105    private method AddIsoMarker { x y }
106    private method BuildCameraTab {}
107    private method BuildCutplanesTab {}
108    private method BuildViewTab {}
109    private method BuildVolumeTab {}
110    private method ComputeTransferFunc { tf }
111    private method EventuallyResize { w h }
112    private method EventuallyResizeLegend { }
113    private method NameTransferFunc { dataobj comp }
114    private method PanCamera {}
115    private method ParseLevelsOption { tf levels }
116    private method ParseMarkersOption { tf markers }
117    private method volume { tag name }
118    private method GetVolumeInfo { w }
119
120    private variable _outbuf       ;# buffer for outgoing commands
121
122    private variable _dlist ""     ;# list of data objects
123    private variable _allDataObjs
124    private variable _obj2ovride   ;# maps dataobj => style override
125    private variable _serverVols   ;# contains all the dataobj-component
126                                   ;# to volumes in the server
127    private variable _serverTfs    ;# contains all the transfer functions
128                                   ;# in the server.
129    private variable _recvdVols    ;# list of data objs to send to server
130    private variable _vol2style    ;# maps dataobj-component to transfunc
131    private variable _style2vols   ;# maps tf back to list of
132                                    # dataobj-components using the tf.
133
134    private variable _click        ;# info used for rotate operations
135    private variable _limits       ;# autoscale min/max for all axes
136    private variable _view         ;# view params for 3D view
137    private variable _isomarkers    ;# array of isosurface level values 0..1
138    private common   _settings
139    # Array of transfer functions in server.  If 0 the transfer has been
140    # defined but not loaded.  If 1 the transfer function has been named
141    # and loaded.
142    private variable _activeTfs
143    private variable _first ""     ;# This is the topmost volume.
144    private variable _buffering 0
145
146    # This
147    # indicates which isomarkers and transfer
148    # function to use when changing markers,
149    # opacity, or thickness.
150    common _downloadPopup          ;# download options from popup
151    private common _hardcopy
152    private variable _width 0
153    private variable _height 0
154    private variable _resizePending 0
155    private variable _resizeLegendPending 0
156}
157
158itk::usual NanovisViewer {
159    keep -background -foreground -cursor -font
160    keep -plotbackground -plotforeground
161}
162
163# ----------------------------------------------------------------------
164# CONSTRUCTOR
165# ----------------------------------------------------------------------
166itcl::body Rappture::NanovisViewer::constructor {hostlist args} {
167
168    # Draw legend event
169    $_dispatcher register !legend
170    $_dispatcher dispatch $this !legend "[itcl::code $this FixLegend]; list"
171
172    # Send transfer functions event
173    $_dispatcher register !send_transfunc
174    $_dispatcher dispatch $this !send_transfunc \
175        "[itcl::code $this SendTransferFuncs]; list"
176
177    # Rebuild event
178    $_dispatcher register !rebuild
179    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
180
181    # Resize event
182    $_dispatcher register !resize
183    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
184
185    set _outbuf ""
186
187    #
188    # Populate parser with commands handle incoming requests
189    #
190    $_parser alias image [itcl::code $this ReceiveImage]
191    $_parser alias legend [itcl::code $this ReceiveLegend]
192    $_parser alias data [itcl::code $this ReceiveData]
193
194    # Initialize the view to some default parameters.
195    array set _view {
196        theta   45
197        phi     45
198        psi     0
199        zoom    1.0
200        pan-x   0
201        pan-y   0
202    }
203    set _limits(vmin) 0.0
204    set _limits(vmax) 1.0
205
206    array set _settings [subst {
207        $this-pan-x             $_view(pan-x)
208        $this-pan-y             $_view(pan-y)
209        $this-phi               $_view(phi)
210        $this-psi               $_view(psi)
211        $this-theta             $_view(theta)
212        $this-volume            1
213        $this-xcutplane         0
214        $this-xcutposition      0
215        $this-ycutplane         0
216        $this-ycutposition      0
217        $this-zcutplane         0
218        $this-zcutposition      0
219        $this-zoom              $_view(zoom)
220    }]
221
222    itk_component add 3dview {
223        label $itk_component(plotarea).vol -image $_image(plot) \
224            -highlightthickness 0 -borderwidth 0
225    } {
226        usual
227        ignore -highlightthickness -borderwidth  -background
228    }
229
230    set f [$itk_component(main) component controls]
231    itk_component add reset {
232        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
233            -highlightthickness 0 \
234            -image [Rappture::icon reset-view] \
235            -command [itcl::code $this Zoom reset]
236    } {
237        usual
238        ignore -highlightthickness
239    }
240    pack $itk_component(reset) -side top -padx 2 -pady 2
241    Rappture::Tooltip::for $itk_component(reset) "Reset the view to the default zoom level"
242
243    itk_component add zoomin {
244        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
245            -highlightthickness 0 \
246            -image [Rappture::icon zoom-in] \
247            -command [itcl::code $this Zoom in]
248    } {
249        usual
250        ignore -highlightthickness
251    }
252    pack $itk_component(zoomin) -side top -padx 2 -pady 2
253    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
254
255    itk_component add zoomout {
256        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
257            -highlightthickness 0 \
258            -image [Rappture::icon zoom-out] \
259            -command [itcl::code $this Zoom out]
260    } {
261        usual
262        ignore -highlightthickness
263    }
264    pack $itk_component(zoomout) -side top -padx 2 -pady 2
265    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
266
267    itk_component add volume {
268        Rappture::PushButton $f.volume \
269            -onimage [Rappture::icon volume-on] \
270            -offimage [Rappture::icon volume-off] \
271            -command [itcl::code $this FixSettings volume] \
272            -variable [itcl::scope _settings($this-volume)]
273    }
274    $itk_component(volume) select
275    Rappture::Tooltip::for $itk_component(volume) \
276        "Toggle the volume cloud on/off"
277    pack $itk_component(volume) -padx 2 -pady 2
278
279    BuildViewTab
280    BuildVolumeTab
281    BuildCutplanesTab
282    BuildCameraTab
283
284    # Legend
285
286    set _image(legend) [image create picture]
287    itk_component add legend {
288        canvas $itk_component(plotarea).legend -height 50 -highlightthickness 0
289    } {
290        usual
291        ignore -highlightthickness
292        rename -background -plotbackground plotBackground Background
293    }
294    bind $itk_component(legend) <Configure> \
295        [itcl::code $this EventuallyResizeLegend]
296
297    # Hack around the Tk panewindow.  The problem is that the requested
298    # size of the 3d view isn't set until an image is retrieved from
299    # the server.  So the panewindow uses the tiny size.
300    set w 10000
301    pack forget $itk_component(3dview)
302    blt::table $itk_component(plotarea) \
303        0,0 $itk_component(3dview) -fill both -reqwidth $w \
304        1,0 $itk_component(legend) -fill x
305    blt::table configure $itk_component(plotarea) r1 -resize none
306
307    # Bindings for rotation via mouse
308    bind $itk_component(3dview) <ButtonPress-1> \
309        [itcl::code $this Rotate click %x %y]
310    bind $itk_component(3dview) <B1-Motion> \
311        [itcl::code $this Rotate drag %x %y]
312    bind $itk_component(3dview) <ButtonRelease-1> \
313        [itcl::code $this Rotate release %x %y]
314    bind $itk_component(3dview) <Configure> \
315        [itcl::code $this EventuallyResize %w %h]
316
317    # Bindings for panning via mouse
318    bind $itk_component(3dview) <ButtonPress-2> \
319        [itcl::code $this Pan click %x %y]
320    bind $itk_component(3dview) <B2-Motion> \
321        [itcl::code $this Pan drag %x %y]
322    bind $itk_component(3dview) <ButtonRelease-2> \
323        [itcl::code $this Pan release %x %y]
324
325    # Bindings for panning via keyboard
326    bind $itk_component(3dview) <KeyPress-Left> \
327        [itcl::code $this Pan set -10 0]
328    bind $itk_component(3dview) <KeyPress-Right> \
329        [itcl::code $this Pan set 10 0]
330    bind $itk_component(3dview) <KeyPress-Up> \
331        [itcl::code $this Pan set 0 -10]
332    bind $itk_component(3dview) <KeyPress-Down> \
333        [itcl::code $this Pan set 0 10]
334    bind $itk_component(3dview) <Shift-KeyPress-Left> \
335        [itcl::code $this Pan set -2 0]
336    bind $itk_component(3dview) <Shift-KeyPress-Right> \
337        [itcl::code $this Pan set 2 0]
338    bind $itk_component(3dview) <Shift-KeyPress-Up> \
339        [itcl::code $this Pan set 0 -2]
340    bind $itk_component(3dview) <Shift-KeyPress-Down> \
341        [itcl::code $this Pan set 0 2]
342
343    # Bindings for zoom via keyboard
344    bind $itk_component(3dview) <KeyPress-Prior> \
345        [itcl::code $this Zoom out]
346    bind $itk_component(3dview) <KeyPress-Next> \
347        [itcl::code $this Zoom in]
348
349    bind $itk_component(3dview) <Enter> "focus $itk_component(3dview)"
350
351    if {[string equal "x11" [tk windowingsystem]]} {
352        # Bindings for zoom via mouse
353        bind $itk_component(3dview) <4> [itcl::code $this Zoom out]
354        bind $itk_component(3dview) <5> [itcl::code $this Zoom in]
355    }
356
357    set _image(download) [image create picture]
358
359    eval itk_initialize $args
360
361    Connect
362}
363
364# ----------------------------------------------------------------------
365# DESTRUCTOR
366# ----------------------------------------------------------------------
367itcl::body Rappture::NanovisViewer::destructor {} {
368    $_dispatcher cancel !rebuild
369    $_dispatcher cancel !send_transfunc
370    $_dispatcher cancel !resize
371    image delete $_image(plot)
372    image delete $_image(legend)
373    image delete $_image(download)
374    array unset _settings $this-*
375}
376
377# ----------------------------------------------------------------------
378# USAGE: add <dataobj> ?<settings>?
379#
380# Clients use this to add a data object to the plot.  The optional
381# <settings> are used to configure the plot.  Allowed settings are
382# -color, -brightness, -width, -linestyle, and -raise.
383# ----------------------------------------------------------------------
384itcl::body Rappture::NanovisViewer::add {dataobj {settings ""}} {
385    array set params {
386        -color auto
387        -width 1
388        -linestyle solid
389        -brightness 0
390        -raise 0
391        -description ""
392        -param ""
393    }
394    foreach {opt val} $settings {
395        if {![info exists params($opt)]} {
396            error "bad setting \"$opt\": should be [join [lsort [array names params]] {, }]"
397        }
398        set params($opt) $val
399    }
400    if {$params(-color) == "auto" || $params(-color) == "autoreset"} {
401        # can't handle -autocolors yet
402        set params(-color) black
403    }
404    set pos [lsearch -exact $dataobj $_dlist]
405    if {$pos < 0} {
406        lappend _dlist $dataobj
407        set _allDataObjs($dataobj) 1
408        set _obj2ovride($dataobj-color) $params(-color)
409        set _obj2ovride($dataobj-width) $params(-width)
410        set _obj2ovride($dataobj-raise) $params(-raise)
411        $_dispatcher event -idle !rebuild
412    }
413}
414
415# ----------------------------------------------------------------------
416# USAGE: get ?-objects?
417# USAGE: get ?-image 3dview|legend?
418#
419# Clients use this to query the list of objects being plotted, in
420# order from bottom to top of this result.  The optional "-image"
421# flag can also request the internal images being shown.
422# ----------------------------------------------------------------------
423itcl::body Rappture::NanovisViewer::get {args} {
424    if {[llength $args] == 0} {
425        set args "-objects"
426    }
427
428    set op [lindex $args 0]
429    switch -- $op {
430      -objects {
431        # put the dataobj list in order according to -raise options
432        set dlist $_dlist
433        foreach obj $dlist {
434            if {[info exists _obj2ovride($obj-raise)] && $_obj2ovride($obj-raise)} {
435                set i [lsearch -exact $dlist $obj]
436                if {$i >= 0} {
437                    set dlist [lreplace $dlist $i $i]
438                    lappend dlist $obj
439                }
440            }
441        }
442        return $dlist
443      }
444      -image {
445        if {[llength $args] != 2} {
446            error "wrong # args: should be \"get -image 3dview|legend\""
447        }
448        switch -- [lindex $args end] {
449            3dview {
450                return $_image(plot)
451            }
452            legend {
453                return $_image(legend)
454            }
455            default {
456                error "bad image name \"[lindex $args end]\": should be 3dview or legend"
457            }
458        }
459      }
460      default {
461        error "bad option \"$op\": should be -objects or -image"
462      }
463    }
464}
465
466# ----------------------------------------------------------------------
467# USAGE: delete ?<dataobj1> <dataobj2> ...?
468#
469#       Clients use this to delete a dataobj from the plot.  If no dataobjs
470#       are specified, then all dataobjs are deleted.  No data objects are
471#       deleted.  They are only removed from the display list.
472#
473# ----------------------------------------------------------------------
474itcl::body Rappture::NanovisViewer::delete {args} {
475    if {[llength $args] == 0} {
476        set args $_dlist
477    }
478    # Delete all specified dataobjs
479    set changed 0
480    foreach dataobj $args {
481        set pos [lsearch -exact $_dlist $dataobj]
482        if { $pos >= 0 } {
483            set _dlist [lreplace $_dlist $pos $pos]
484            array unset _limits $dataobj*
485            array unset _obj2ovride $dataobj-*
486            array unset _vol2style $dataobj-*
487            set changed 1
488        }
489    }
490    # If anything changed, then rebuild the plot
491    if {$changed} {
492        $_dispatcher event -idle !rebuild
493    }
494}
495
496# ----------------------------------------------------------------------
497# USAGE: scale ?<data1> <data2> ...?
498#
499# Sets the default limits for the overall plot according to the
500# limits of the data for all of the given <data> objects.  This
501# accounts for all objects--even those not showing on the screen.
502# Because of this, the limits are appropriate for all objects as
503# the user scans through data in the ResultSet viewer.
504# ----------------------------------------------------------------------
505itcl::body Rappture::NanovisViewer::scale {args} {
506    foreach val {xmin xmax ymin ymax zmin zmax vmin vmax} {
507        set _limits($val) ""
508    }
509    foreach obj $args {
510        foreach axis {x y z v} {
511
512            foreach { min max } [$obj limits $axis] break
513
514            if {"" != $min && "" != $max} {
515                if {"" == $_limits(${axis}min)} {
516                    set _limits(${axis}min) $min
517                    set _limits(${axis}max) $max
518                } else {
519                    if {$min < $_limits(${axis}min)} {
520                        set _limits(${axis}min) $min
521                    }
522                    if {$max > $_limits(${axis}max)} {
523                        set _limits(${axis}max) $max
524                    }
525                }
526            }
527        }
528    }
529}
530
531# ----------------------------------------------------------------------
532# USAGE: download coming
533# USAGE: download controls <downloadCommand>
534# USAGE: download now
535#
536# Clients use this method to create a downloadable representation
537# of the plot.  Returns a list of the form {ext string}, where
538# "ext" is the file extension (indicating the type of data) and
539# "string" is the data itself.
540# ----------------------------------------------------------------------
541itcl::body Rappture::NanovisViewer::download {option args} {
542    switch $option {
543        coming {
544            if {[catch { $_image(download) snap $itk_component(plotarea)}]} {
545                $_image(download) blank #000000
546            }
547        }
548        controls {
549            # no controls for this download yet
550            return ""
551        }
552        now {
553            $_image(plot) export jpg -quality 100 -data bytes
554            return [list .jpg $bytes]
555        }
556        default {
557            error "bad option \"$option\": should be coming, controls, now"
558        }
559    }
560}
561
562# ----------------------------------------------------------------------
563# USAGE: Connect ?<host:port>,<host:port>...?
564#
565# Clients use this method to establish a connection to a new
566# server, or to reestablish a connection to the previous server.
567# Any existing connection is automatically closed.
568# ----------------------------------------------------------------------
569itcl::body Rappture::NanovisViewer::Connect {} {
570    set _hosts [GetServerList "nanovis"]
571    if { "" == $_hosts } {
572        return 0
573    }
574    set result [VisViewer::Connect $_hosts]
575    if { $result } {
576        set w [winfo width $itk_component(3dview)]
577        set h [winfo height $itk_component(3dview)]
578        EventuallyResize $w $h
579    }
580    return $result
581}
582
583#
584# isconnected --
585#
586#       Indicates if we are currently connected to the visualization server.
587#
588itcl::body Rappture::NanovisViewer::isconnected {} {
589    return [VisViewer::IsConnected]
590}
591
592#
593# disconnect --
594#
595itcl::body Rappture::NanovisViewer::disconnect {} {
596    Disconnect
597}
598
599#
600# Disconnect --
601#
602#       Clients use this method to disconnect from the current rendering
603#       server.
604#
605itcl::body Rappture::NanovisViewer::Disconnect {} {
606    VisViewer::Disconnect
607
608    # disconnected -- no more data sitting on server
609    set _outbuf ""
610    array unset _serverVols
611}
612
613#
614# sendto --
615#
616itcl::body Rappture::NanovisViewer::sendto { bytes } {
617    SendBytes "$bytes\n"
618}
619
620#
621# SendCmd
622#
623#       Send commands off to the rendering server.  If we're currently
624#       sending data objects to the server, buffer the commands to be
625#       sent later.
626#
627itcl::body Rappture::NanovisViewer::SendCmd {string} {
628    if { $_buffering } {
629        append _outbuf $string "\n"
630    } else {
631        foreach line [split $string \n] {
632            SendEcho >>line $line
633        }
634        SendBytes "$string\n"
635    }
636}
637
638
639# ----------------------------------------------------------------------
640# USAGE: SendTransferFuncs
641# ----------------------------------------------------------------------
642itcl::body Rappture::NanovisViewer::SendTransferFuncs {} {
643    if { $_first == "" } {
644        puts stderr "first not set"
645        return
646    }
647    # Insure that the global opacity and thickness settings (in the slider
648    # settings widgets) are used for the active transfer-function.  Update
649    # the values in the _settings varible.
650    set opacity [expr { double($_settings($this-opacity)) * 0.01 }]
651    # Scale values between 0.00001 and 0.01000
652    set thickness [expr {double($_settings($this-thickness)) * 0.0001}]
653
654    foreach vol [CurrentVolumes] {
655        if { ![info exists _serverVols($vol)] || !$_serverVols($vol) } {
656            # The volume hasn't reached the server yet.  How did we get
657            # here?
658            continue
659        }
660        if { ![info exists _vol2style($vol)] } {
661            puts stderr "unknown volume $vol"
662            continue;                   # How does this happen?
663        }
664        set tf $_vol2style($vol)
665        set _settings($this-$tf-opacity) $opacity
666        set _settings($this-$tf-thickness) $thickness
667        ComputeTransferFunc $tf
668        # FIXME: Need to the send information as to what transfer functions
669        #        to update so that we only update the transfer function
670        #        as necessary.  Right now, all transfer functions are
671        #        updated. This makes moving the isomarker slider chunky.
672        if { ![info exists _activeTfs($tf)] || !$_activeTfs($tf) } {
673            set _activeTfs($tf) 1
674        }
675        SendCmd "volume shading transfunc $tf $vol"
676    }
677    FixLegend
678}
679
680# ----------------------------------------------------------------------
681# USAGE: ReceiveImage -bytes <size> -type <type> -token <token>
682#
683# Invoked automatically whenever the "image" command comes in from
684# the rendering server.  Indicates that binary image data with the
685# specified <size> will follow.
686# ----------------------------------------------------------------------
687itcl::body Rappture::NanovisViewer::ReceiveImage { args } {
688    array set info {
689        -token "???"
690        -bytes 0
691        -type image
692    }
693    array set info $args
694    set bytes [ReceiveBytes $info(-bytes)]
695    ReceiveEcho <<line "<read $info(-bytes) bytes"
696    if { $info(-type) == "image" } {
697        ReceiveEcho "for [image width $_image(plot)]x[image height $_image(plot)] image>"       
698        $_image(plot) configure -data $bytes
699    } elseif { $info(type) == "print" } {
700        set tag $this-print-$info(-token)
701        set _hardcopy($tag) $bytes
702    }
703}
704
705#
706# ReceiveLegend --
707#
708#       The procedure is the response from the render server to each "legend"
709#       command.  The server sends back a "legend" command invoked our
710#       the slave interpreter.  The purpose is to collect data of the image
711#       representing the legend in the canvas.  In addition, the isomarkers
712#       of the active transfer function are displayed.
713#
714#       I don't know is this is the right place to display the isomarkers.
715#       I don't know all the different paths used to draw the plot. There's
716#       "Rebuild", "add", etc.
717#
718itcl::body Rappture::NanovisViewer::ReceiveLegend { tf vmin vmax size } {
719    if { ![isconnected] } {
720        return
721    }
722    set bytes [ReceiveBytes $size]
723    $_image(legend) configure -data $bytes
724    ReceiveEcho <<line "<read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
725
726    set c $itk_component(legend)
727    set w [winfo width $c]
728    set h [winfo height $c]
729    set lx 10
730    set ly [expr {$h - 1}]
731    if {"" == [$c find withtag transfunc]} {
732        $c create image 10 10 -anchor nw \
733            -image $_image(legend) -tags transfunc
734        $c create text $lx $ly -anchor sw \
735            -fill $itk_option(-plotforeground) -tags "limits vmin"
736        $c create text [expr {$w-$lx}] $ly -anchor se \
737            -fill $itk_option(-plotforeground) -tags "limits vmax"
738        $c lower transfunc
739        $c bind transfunc <ButtonRelease-1> \
740            [itcl::code $this AddIsoMarker %x %y]
741    }
742    # Display the markers used by the active transfer function.
743
744    array set limits [limits $tf]
745    $c itemconfigure vmin -text [format %.2g $limits(min)]
746    $c coords vmin $lx $ly
747
748    $c itemconfigure vmax -text [format %.2g $limits(max)]
749    $c coords vmax [expr {$w-$lx}] $ly
750
751    if { [info exists _isomarkers($tf)] } {
752        foreach m $_isomarkers($tf) {
753            $m visible yes
754        }
755    }
756}
757
758#
759# ReceiveData --
760#
761#       The procedure is the response from the render server to each "data
762#       follows" command.  The server sends back a "data" command invoked our
763#       the slave interpreter.  The purpose is to collect the min/max of the
764#       volume sent to the render server.  Since the client (nanovisviewer)
765#       doesn't parse 3D data formats, we rely on the server (nanovis) to
766#       tell us what the limits are.  Once we've received the limits to all
767#       the data we've sent (tracked by _recvdVols) we can then determine
768#       what the transfer functions are for these volumes.
769#
770#
771#       Note: There is a considerable tradeoff in having the server report
772#             back what the data limits are.  It means that much of the code
773#             having to do with transfer-functions has to wait for the data
774#             to come back, since the isomarkers are calculated based upon
775#             the data limits.  The client code is much messier because of
776#             this.  The alternative is to parse any of the 3D formats on the
777#             client side.
778#
779itcl::body Rappture::NanovisViewer::ReceiveData { args } {
780    if { ![isconnected] } {
781        return
782    }
783    # Arguments from server are name value pairs. Stuff them in an array.
784    array set info $args
785
786    set tag $info(tag)
787    set parts [split $tag -]
788
789    #
790    # Volumes don't exist until we're told about them.
791    #
792    set dataobj [lindex $parts 0]
793    set _serverVols($tag) 1
794    if { $_settings($this-volume) && $dataobj == $_first } {
795        SendCmd "volume state 1 $tag"
796    }
797    set _limits($tag-min) $info(min);  # Minimum value of the volume.
798    set _limits($tag-max) $info(max);  # Maximum value of the volume.
799    set _limits(vmin)      $info(vmin); # Overall minimum value.
800    set _limits(vmax)      $info(vmax); # Overall maximum value.
801
802    unset _recvdVols($tag)
803    if { [array size _recvdVols] == 0 } {
804        # The active transfer function is by default the first component of
805        # the first data object.  This assumes that the data is always
806        # successfully transferred.
807        updatetransferfuncs
808    }
809}
810
811# ----------------------------------------------------------------------
812# USAGE: Rebuild
813#
814# Called automatically whenever something changes that affects the
815# data in the widget.  Clears any existing data and rebuilds the
816# widget to display new data.
817# ----------------------------------------------------------------------
818itcl::body Rappture::NanovisViewer::Rebuild {} {
819
820    # Turn on buffering of commands to the server.  We don't want to
821    # be preempted by a server disconnect/reconnect (which automatically
822    # generates a new call to Rebuild).   
823    set _buffering 1
824
825    # Hide all the isomarkers. Can't remove them. Have to remember the
826    # settings since the user may have created/deleted/moved markers.
827
828    foreach tf [array names _isomarkers] {
829        foreach m $_isomarkers($tf) {
830            $m visible no
831        }
832    }
833
834    set w [winfo width $itk_component(3dview)]
835    set h [winfo height $itk_component(3dview)]
836    EventuallyResize $w $h
837
838    foreach dataobj [get] {
839        foreach comp [$dataobj components] {
840            set vol $dataobj-$comp
841            if { ![info exists _serverVols($vol)] } {
842                # Send the data as one huge base64-encoded mess -- yuck!
843                set data [$dataobj values $comp]
844                set nbytes [string length $data]
845                append _outbuf "volume data follows $nbytes $vol\n"
846                append _outbuf $data
847                set _recvdVols($vol) 1
848                set _serverVols($vol) 0
849            }
850            NameTransferFunc $dataobj $comp
851        }
852    }
853    #
854    # Reset the camera and other view parameters
855    #
856
857    set _settings($this-theta) $_view(theta)
858    set _settings($this-phi)   $_view(phi)
859    set _settings($this-psi)   $_view(psi)
860    set _settings($this-pan-x) $_view(pan-x)
861    set _settings($this-pan-y) $_view(pan-y)
862    set _settings($this-zoom)  $_view(zoom)
863
864    set xyz [Euler2XYZ $_view(theta) $_view(phi) $_view(psi)]
865    SendCmd "camera angle $xyz"
866    PanCamera
867    SendCmd "camera zoom $_view(zoom)"
868    FixSettings light
869    FixSettings transp
870    FixSettings isosurface
871    FixSettings grid
872    FixSettings axes
873    FixSettings outline
874
875    # nothing to send -- activate the proper ivol
876    SendCmd "volume state 0"
877    set _first [lindex [get] 0]
878    if {"" != $_first} {
879        set axis [$_first hints updir]
880        if { "" != $axis } {
881            SendCmd "up $axis"
882        }
883        set location [$_first hints camera]
884        if { $location != "" } {
885            array set _view $location
886        }
887        set vols [array names _serverVols $_first-*]
888        if { $vols != "" } {
889            SendCmd "volume state 1 $vols"
890        }
891    }
892    # If the first volume already exists on the server, then make sure we
893    # display the proper transfer function in the legend.
894    set comp [lindex [$_first components] 0]
895    if { [info exists _serverVols($_first-$comp)] } {
896        updatetransferfuncs
897    }
898
899    # Sync the state of slicers
900    set vols [CurrentVolumes -cutplanes]
901    foreach axis {x y z} {
902        SendCmd "cutplane state $_settings($this-${axis}cutplane) $axis $vols"
903        set pos [expr {0.01*$_settings($this-${axis}cutposition)}]
904        SendCmd "cutplane position $pos $axis $vols"
905    }
906    SendCmd "volume data state $_settings($this-volume) $vols"
907    set _buffering 0;                   # Turn off buffering.
908    # Actually write the commands to the server socket.  If it fails, we don't
909    # care.  We're finished here.
910    blt::busy hold $itk_component(hull)
911    SendBytes $_outbuf;                 
912    blt::busy release $itk_component(hull)
913    set _outbuf "";                     # Clear the buffer.             
914}
915
916# ----------------------------------------------------------------------
917# USAGE: CurrentVolumes ?-cutplanes?
918#
919# Returns a list of volume server IDs for the current volume being
920# displayed.  This is normally a single ID, but it might be a list
921# of IDs if the current data object has multiple components.
922# ----------------------------------------------------------------------
923itcl::body Rappture::NanovisViewer::CurrentVolumes {{what -all}} {
924    set rlist ""
925    if { $_first == "" } {
926        return
927    }
928    foreach comp [$_first components] {
929        set vol $_first-$comp
930        if { [info exists _serverVols($vol)] && $_serverVols($vol) } {
931            array set style {
932                -cutplanes 1
933            }
934            array set style [lindex [$_first components -style $comp] 0]
935            if {$what != "-cutplanes" || $style(-cutplanes)} {
936                lappend rlist $vol
937            }
938        }
939    }
940    return $rlist
941}
942
943# ----------------------------------------------------------------------
944# USAGE: Zoom in
945# USAGE: Zoom out
946# USAGE: Zoom reset
947#
948# Called automatically when the user clicks on one of the zoom
949# controls for this widget.  Changes the zoom for the current view.
950# ----------------------------------------------------------------------
951itcl::body Rappture::NanovisViewer::Zoom {option} {
952    switch -- $option {
953        "in" {
954            set _view(zoom) [expr {$_view(zoom)*1.25}]
955            set _settings($this-zoom) $_view(zoom)
956        }
957        "out" {
958            set _view(zoom) [expr {$_view(zoom)*0.8}]
959            set _settings($this-zoom) $_view(zoom)
960        }
961        "reset" {
962            array set _view {
963                theta   45
964                phi     45
965                psi     0
966                zoom    1.0
967                pan-x   0
968                pan-y   0
969            }
970            if { $_first != "" } {
971                set location [$_first hints camera]
972                if { $location != "" } {
973                    array set _view $location
974                }
975            }
976            set xyz [Euler2XYZ $_view(theta) $_view(phi) $_view(psi)]
977            SendCmd "camera angle $xyz"
978            PanCamera
979            set _settings($this-theta) $_view(theta)
980            set _settings($this-phi)   $_view(phi)
981            set _settings($this-psi)   $_view(psi)
982            set _settings($this-pan-x) $_view(pan-x)
983            set _settings($this-pan-y) $_view(pan-y)
984            set _settings($this-zoom)  $_view(zoom)
985        }
986    }
987    SendCmd "camera zoom $_view(zoom)"
988}
989
990itcl::body Rappture::NanovisViewer::PanCamera {} {
991    #set x [expr ($_view(pan-x)) / $_limits(xrange)]
992    #set y [expr ($_view(pan-y)) / $_limits(yrange)]
993    set x $_view(pan-x)
994    set y $_view(pan-y)
995    SendCmd "camera pan $x $y"
996}
997
998
999# ----------------------------------------------------------------------
1000# USAGE: Rotate click <x> <y>
1001# USAGE: Rotate drag <x> <y>
1002# USAGE: Rotate release <x> <y>
1003#
1004# Called automatically when the user clicks/drags/releases in the
1005# plot area.  Moves the plot according to the user's actions.
1006# ----------------------------------------------------------------------
1007itcl::body Rappture::NanovisViewer::Rotate {option x y} {
1008    switch -- $option {
1009        click {
1010            $itk_component(3dview) configure -cursor fleur
1011            set _click(x) $x
1012            set _click(y) $y
1013            set _click(theta) $_view(theta)
1014            set _click(phi) $_view(phi)
1015        }
1016        drag {
1017            if {[array size _click] == 0} {
1018                Rotate click $x $y
1019            } else {
1020                set w [winfo width $itk_component(3dview)]
1021                set h [winfo height $itk_component(3dview)]
1022                if {$w <= 0 || $h <= 0} {
1023                    return
1024                }
1025
1026                if {[catch {
1027                    # this fails sometimes for no apparent reason
1028                    set dx [expr {double($x-$_click(x))/$w}]
1029                    set dy [expr {double($y-$_click(y))/$h}]
1030                }]} {
1031                    return
1032                }
1033
1034                #
1035                # Rotate the camera in 3D
1036                #
1037                if {$_view(psi) > 90 || $_view(psi) < -90} {
1038                    # when psi is flipped around, theta moves backwards
1039                    set dy [expr {-$dy}]
1040                }
1041                set theta [expr {$_view(theta) - $dy*180}]
1042                while {$theta < 0} { set theta [expr {$theta+180}] }
1043                while {$theta > 180} { set theta [expr {$theta-180}] }
1044
1045                if {abs($theta) >= 30 && abs($theta) <= 160} {
1046                    set phi [expr {$_view(phi) - $dx*360}]
1047                    while {$phi < 0} { set phi [expr {$phi+360}] }
1048                    while {$phi > 360} { set phi [expr {$phi-360}] }
1049                    set psi $_view(psi)
1050                } else {
1051                    set phi $_view(phi)
1052                    set psi [expr {$_view(psi) - $dx*360}]
1053                    while {$psi < -180} { set psi [expr {$psi+360}] }
1054                    while {$psi > 180} { set psi [expr {$psi-360}] }
1055                }
1056
1057                set _view(theta)        $theta
1058                set _view(phi)          $phi
1059                set _view(psi)          $psi
1060                set xyz [Euler2XYZ $theta $phi $psi]
1061                set _settings($this-theta) $_view(theta)
1062                set _settings($this-phi)   $_view(phi)
1063                set _settings($this-psi)   $_view(psi)
1064                SendCmd "camera angle $xyz"
1065                set _click(x) $x
1066                set _click(y) $y
1067            }
1068        }
1069        release {
1070            Rotate drag $x $y
1071            $itk_component(3dview) configure -cursor ""
1072            catch {unset _click}
1073        }
1074        default {
1075            error "bad option \"$option\": should be click, drag, release"
1076        }
1077    }
1078}
1079
1080# ----------------------------------------------------------------------
1081# USAGE: $this Pan click x y
1082#        $this Pan drag x y
1083#        $this Pan release x y
1084#
1085# Called automatically when the user clicks on one of the zoom
1086# controls for this widget.  Changes the zoom for the current view.
1087# ----------------------------------------------------------------------
1088itcl::body Rappture::NanovisViewer::Pan {option x y} {
1089    # Experimental stuff
1090    set w [winfo width $itk_component(3dview)]
1091    set h [winfo height $itk_component(3dview)]
1092    if { $option == "set" } {
1093        set x [expr $x / double($w)]
1094        set y [expr $y / double($h)]
1095        set _view(pan-x) [expr $_view(pan-x) + $x]
1096        set _view(pan-y) [expr $_view(pan-y) + $y]
1097        PanCamera
1098        set _settings($this-pan-x) $_view(pan-x)
1099        set _settings($this-pan-y) $_view(pan-y)
1100        return
1101    }
1102    if { $option == "click" } {
1103        set _click(x) $x
1104        set _click(y) $y
1105        $itk_component(3dview) configure -cursor hand1
1106    }
1107    if { $option == "drag" || $option == "release" } {
1108        set dx [expr ($_click(x) - $x)/double($w)]
1109        set dy [expr ($_click(y) - $y)/double($h)]
1110        set _click(x) $x
1111        set _click(y) $y
1112        set _view(pan-x) [expr $_view(pan-x) - $dx]
1113        set _view(pan-y) [expr $_view(pan-y) - $dy]
1114        PanCamera
1115        set _settings($this-pan-x) $_view(pan-x)
1116        set _settings($this-pan-y) $_view(pan-y)
1117    }
1118    if { $option == "release" } {
1119        $itk_component(3dview) configure -cursor ""
1120    }
1121}
1122
1123# ----------------------------------------------------------------------
1124# USAGE: FixSettings <what> ?<value>?
1125#
1126# Used internally to update rendering settings whenever parameters
1127# change in the popup settings panel.  Sends the new settings off
1128# to the back end.
1129# ----------------------------------------------------------------------
1130itcl::body Rappture::NanovisViewer::FixSettings {what {value ""}} {
1131    switch -- $what {
1132        light {
1133            if {[isconnected]} {
1134                set val $_settings($this-light)
1135                set sval [expr {0.1*$val}]
1136                SendCmd "volume shading diffuse $sval"
1137                set sval [expr {sqrt($val+1.0)}]
1138                SendCmd "volume shading specular $sval"
1139            }
1140        }
1141        transp {
1142            if {[isconnected]} {
1143                set val $_settings($this-transp)
1144                set sval [expr {0.2*$val+1}]
1145                SendCmd "volume shading opacity $sval"
1146            }
1147        }
1148        opacity {
1149            if {[isconnected] && [array size _activeTfs] > 0 } {
1150                set val $_settings($this-opacity)
1151                set sval [expr { 0.01 * double($val) }]
1152                foreach tf [array names _activeTfs] {
1153                    set _settings($this-$tf-opacity) $sval
1154                    set _activeTfs($tf) 0
1155                }
1156                updatetransferfuncs
1157            }
1158        }
1159
1160        thickness {
1161            if {[isconnected] && [array names _activeTfs] > 0 } {
1162                set val $_settings($this-thickness)
1163                # Scale values between 0.00001 and 0.01000
1164                set sval [expr {0.0001*double($val)}]
1165                foreach tf [array names _activeTfs] {
1166                    set _settings($this-$tf-thickness) $sval
1167                    set _activeTfs($tf) 0
1168                }
1169                updatetransferfuncs
1170            }
1171        }
1172        "outline" {
1173            if {[isconnected]} {
1174                SendCmd "volume outline state $_settings($this-outline)"
1175            }
1176        }
1177        "isosurface" {
1178            if {[isconnected]} {
1179                SendCmd "volume shading isosurface $_settings($this-isosurface)"
1180            }
1181        }
1182        "grid" {
1183            if { [isconnected] } {
1184                SendCmd "grid visible $_settings($this-grid)"
1185            }
1186        }
1187        "axes" {
1188            if { [isconnected] } {
1189                SendCmd "axis visible $_settings($this-axes)"
1190            }
1191        }
1192        "legend" {
1193            if { $_settings($this-legend) } {
1194                blt::table $itk_component(plotarea) \
1195                    0,0 $itk_component(3dview) -fill both \
1196                    1,0 $itk_component(legend) -fill x
1197                blt::table configure $itk_component(plotarea) r1 -resize none
1198            } else {
1199                blt::table forget $itk_component(legend)
1200            }
1201        }
1202        "volume" {
1203            if { [isconnected] } {
1204                set vols [CurrentVolumes -cutplanes]
1205                SendCmd "volume data state $_settings($this-volume) $vols"
1206            }
1207        }
1208        "xcutplane" - "ycutplane" - "zcutplane" {
1209            set axis [string range $what 0 0]
1210            set bool $_settings($this-$what)
1211            if { [isconnected] } {
1212                set vols [CurrentVolumes -cutplanes]
1213                SendCmd "cutplane state $bool $axis $vols"
1214            }
1215            if { $bool } {
1216                $itk_component(${axis}CutScale) configure -state normal \
1217                    -troughcolor white
1218            } else {
1219                $itk_component(${axis}CutScale) configure -state disabled \
1220                    -troughcolor grey82
1221            }
1222        }
1223        default {
1224            error "don't know how to fix $what"
1225        }
1226    }
1227}
1228
1229# ----------------------------------------------------------------------
1230# USAGE: FixLegend
1231#
1232# Used internally to update the legend area whenever it changes size
1233# or when the field changes.  Asks the server to send a new legend
1234# for the current field.
1235# ----------------------------------------------------------------------
1236itcl::body Rappture::NanovisViewer::FixLegend {} {
1237    set _resizeLegendPending 0
1238    set lineht [font metrics $itk_option(-font) -linespace]
1239    set w [expr {$_width-20}]
1240    set h [expr {[winfo height $itk_component(legend)]-20-$lineht}]
1241    if {$w > 0 && $h > 0 && [array names _activeTfs] > 0 && $_first != "" } {
1242        set vol [lindex [CurrentVolumes] 0]
1243        if { [info exists _vol2style($vol)] } {
1244            SendCmd "legend $_vol2style($vol) $w $h"
1245        }
1246    } else {
1247        # Can't do this as this will remove the items associated with the
1248        # isomarkers.
1249       
1250        #$itk_component(legend) delete all
1251    }
1252}
1253
1254#
1255# NameTransferFunc --
1256#
1257#       Creates a transfer function name based on the <style> settings in the
1258#       library run.xml file. This placeholder will be used later to create
1259#       and send the actual transfer function once the data info has been sent
1260#       to us by the render server. [We won't know the volume limits until the
1261#       server parses the 3D data and sends back the limits via ReceiveData.]
1262#
1263#       FIXME: The current way we generate transfer-function names completely
1264#              ignores the -markers option.  The problem is that we are forced
1265#              to compute the name from an increasing complex set of values:
1266#              color, levels, marker, opacity.  I think we're stuck doing it
1267#              now.
1268#
1269itcl::body Rappture::NanovisViewer::NameTransferFunc { dataobj comp } {
1270    array set style {
1271        -color rainbow
1272        -levels 6
1273        -opacity 1.0
1274    }
1275    array set style [lindex [$dataobj components -style $comp] 0]
1276    set tf "$style(-color):$style(-levels):$style(-opacity)"
1277    set _vol2style($dataobj-$comp) $tf
1278    lappend _style2vols($tf) $dataobj-$comp
1279    return $tf
1280}
1281
1282#
1283# ComputeTransferFunc --
1284#
1285#   Computes and sends the transfer function to the render server.  It's
1286#   assumed that the volume data limits are known and that the global
1287#   transfer-functions slider values have be setup.  Both parts are
1288#   needed to compute the relative value (location) of the marker, and
1289#   the alpha map of the transfer function.
1290#
1291itcl::body Rappture::NanovisViewer::ComputeTransferFunc { tf } {
1292    array set style {
1293        -color rainbow
1294        -levels 6
1295        -opacity 1.0
1296    }
1297    foreach {dataobj comp} [split $_style2vols($tf) -] break
1298    array set style [lindex [$dataobj components -style $comp] 0]
1299
1300
1301    # We have to parse the style attributes for a volume using this
1302    # transfer-function *once*.  This sets up the initial isomarkers for the
1303    # transfer function.  The user may add/delete markers, so we have to
1304    # maintain a list of markers for each transfer-function.  We use the one
1305    # of the volumes (the first in the list) using the transfer-function as a
1306    # reference.
1307    #
1308    # FIXME: The current way we generate transfer-function names completely
1309    #        ignores the -markers option.  The problem is that we are forced
1310    #        to compute the name from an increasing complex set of values:
1311    #        color, levels, marker, opacity.  I think the cow's out of the
1312    #        barn on this one.
1313
1314    if { ![info exists _isomarkers($tf)] } {
1315        # Have to defer creation of isomarkers until we have data limits
1316        if { [info exists style(-markers)] } {
1317            ParseMarkersOption $tf $style(-markers)
1318        } else {
1319            ParseLevelsOption $tf $style(-levels)
1320        }
1321    }
1322    if {$style(-color) == "rainbow"} {
1323        set style(-color) "white:yellow:green:cyan:blue:magenta"
1324    }
1325    set clist [split $style(-color) :]
1326    set cmap "0.0 [Color2RGB white] "
1327    for {set i 0} {$i < [llength $clist]} {incr i} {
1328        set x [expr {double($i+1)/([llength $clist]+1)}]
1329        set color [lindex $clist $i]
1330        append cmap "$x [Color2RGB $color] "
1331    }
1332    append cmap "1.0 [Color2RGB $color]"
1333
1334    set tag $this-$tf
1335    if { ![info exists _settings($tag-opacity)] } {
1336        set _settings($tag-opacity) $style(-opacity)
1337    }
1338    set max $_settings($tag-opacity)
1339
1340    set isovalues {}
1341    foreach m $_isomarkers($tf) {
1342        lappend isovalues [$m relval]
1343    }
1344    # Sort the isovalues
1345    set isovalues [lsort -real $isovalues]
1346
1347    if { ![info exists _settings($tag-thickness)]} {
1348        set _settings($tag-thickness) 0.05
1349    }
1350    set delta $_settings($tag-thickness)
1351
1352    set first [lindex $isovalues 0]
1353    set last [lindex $isovalues end]
1354    set wmap ""
1355    if { $first == "" || $first != 0.0 } {
1356        lappend wmap 0.0 0.0
1357    }
1358    foreach x $isovalues {
1359        set x1 [expr {$x-$delta-0.00001}]
1360        set x2 [expr {$x-$delta}]
1361        set x3 [expr {$x+$delta}]
1362        set x4 [expr {$x+$delta+0.00001}]
1363        if { $x1 < 0.0 } {
1364            set x1 0.0
1365        } elseif { $x1 > 1.0 } {
1366            set x1 1.0
1367        }
1368        if { $x2 < 0.0 } {
1369            set x2 0.0
1370        } elseif { $x2 > 1.0 } {
1371            set x2 1.0
1372        }
1373        if { $x3 < 0.0 } {
1374            set x3 0.0
1375        } elseif { $x3 > 1.0 } {
1376            set x3 1.0
1377        }
1378        if { $x4 < 0.0 } {
1379            set x4 0.0
1380        } elseif { $x4 > 1.0 } {
1381            set x4 1.0
1382        }
1383        # add spikes in the middle
1384        lappend wmap $x1 0.0
1385        lappend wmap $x2 $max
1386        lappend wmap $x3 $max
1387        lappend wmap $x4 0.0
1388    }
1389    if { $last == "" || $last != 1.0 } {
1390        lappend wmap 1.0 0.0
1391    }
1392    SendCmd "transfunc define $tf { $cmap } { $wmap }"
1393}
1394
1395# ----------------------------------------------------------------------
1396# CONFIGURATION OPTION: -plotbackground
1397# ----------------------------------------------------------------------
1398itcl::configbody Rappture::NanovisViewer::plotbackground {
1399    if { [isconnected] } {
1400        foreach {r g b} [Color2RGB $itk_option(-plotbackground)] break
1401        #fix this!
1402        #SendCmd "color background $r $g $b"
1403    }
1404}
1405
1406# ----------------------------------------------------------------------
1407# CONFIGURATION OPTION: -plotforeground
1408# ----------------------------------------------------------------------
1409itcl::configbody Rappture::NanovisViewer::plotforeground {
1410    if { [isconnected] } {
1411        foreach {r g b} [Color2RGB $itk_option(-plotforeground)] break
1412        #fix this!
1413        #SendCmd "color background $r $g $b"
1414    }
1415}
1416
1417# ----------------------------------------------------------------------
1418# CONFIGURATION OPTION: -plotoutline
1419# ----------------------------------------------------------------------
1420itcl::configbody Rappture::NanovisViewer::plotoutline {
1421    # Must check if we are connected because this routine is called from the
1422    # class body when the -plotoutline itk_option is defined.  At that point
1423    # the NanovisViewer class constructor hasn't been called, so we can't
1424    # start sending commands to visualization server.
1425    if { [isconnected] } {
1426        if {"" == $itk_option(-plotoutline)} {
1427            SendCmd "volume outline state off"
1428        } else {
1429            SendCmd "volume outline state on"
1430            SendCmd "volume outline color [Color2RGB $itk_option(-plotoutline)]"
1431        }
1432    }
1433}
1434
1435#
1436# The -levels option takes a single value that represents the number
1437# of evenly distributed markers based on the current data range. Each
1438# marker is a relative value from 0.0 to 1.0.
1439#
1440itcl::body Rappture::NanovisViewer::ParseLevelsOption { tf levels } {
1441    set c $itk_component(legend)
1442    regsub -all "," $levels " " levels
1443    if {[string is int $levels]} {
1444        for {set i 1} { $i <= $levels } {incr i} {
1445            set x [expr {double($i)/($levels+1)}]
1446            set m [Rappture::IsoMarker \#auto $c $this $tf]
1447            $m relval $x
1448            lappend _isomarkers($tf) $m
1449        }
1450    } else {
1451        foreach x $levels {
1452            set m [Rappture::IsoMarker \#auto $c $this $tf]
1453            $m relval $x
1454            lappend _isomarkers($tf) $m
1455        }
1456    }
1457}
1458
1459#
1460# The -markers option takes a list of zero or more values (the values
1461# may be separated either by spaces or commas) that have the following
1462# format:
1463#
1464#   N%  Percent of current total data range.  Converted to
1465#       to a relative value between 0.0 and 1.0.
1466#   N   Absolute value of marker.  If the marker is outside of
1467#       the current range, it will be displayed on the outer
1468#       edge of the legends, but it range it represents will
1469#       not be seen.
1470#
1471itcl::body Rappture::NanovisViewer::ParseMarkersOption { tf markers } {
1472    set c $itk_component(legend)
1473    regsub -all "," $markers " " markers
1474    foreach marker $markers {
1475        set n [scan $marker "%g%s" value suffix]
1476        if { $n == 2 && $suffix == "%" } {
1477            # ${n}% : Set relative value.
1478            set value [expr {$value * 0.01}]
1479            set m [Rappture::IsoMarker \#auto $c $this $tf]
1480            $m relval $value
1481            lappend _isomarkers($tf) $m
1482        } else {
1483            # ${n} : Set absolute value.
1484            set m [Rappture::IsoMarker \#auto $c $this $tf]
1485            $m absval $value
1486            lappend _isomarkers($tf) $m
1487        }
1488    }
1489}
1490
1491# ----------------------------------------------------------------------
1492# USAGE: UndateTransferFuncs
1493# ----------------------------------------------------------------------
1494itcl::body Rappture::NanovisViewer::updatetransferfuncs {} {
1495    $_dispatcher event -idle !send_transfunc
1496}
1497
1498itcl::body Rappture::NanovisViewer::AddIsoMarker { x y } {
1499    if { $_first == "" } {
1500        error "active transfer function isn't set"
1501    }
1502    set vol [lindex [CurrentVolumes] 0]
1503    set tf $_vol2style($vol)
1504    set c $itk_component(legend)
1505    set m [Rappture::IsoMarker \#auto $c $this $tf]
1506    set w [winfo width $c]
1507    $m relval [expr {double($x-10)/($w-20)}]
1508    lappend _isomarkers($tf) $m
1509    updatetransferfuncs
1510    return 1
1511}
1512
1513itcl::body Rappture::NanovisViewer::rmdupmarker { marker x } {
1514    set tf [$marker transferfunc]
1515    set bool 0
1516    if { [info exists _isomarkers($tf)] } {
1517        set list {}
1518        set marker [namespace tail $marker]
1519        foreach m $_isomarkers($tf) {
1520            set sx [$m screenpos]
1521            if { $m != $marker } {
1522                if { $x >= ($sx-3) && $x <= ($sx+3) } {
1523                    $marker relval [$m relval]
1524                    itcl::delete object $m
1525                    bell
1526                    set bool 1
1527                    continue
1528                }
1529            }
1530            lappend list $m
1531        }
1532        set _isomarkers($tf) $list
1533        updatetransferfuncs
1534    }
1535    return $bool
1536}
1537
1538itcl::body Rappture::NanovisViewer::overmarker { marker x } {
1539    set tf [$marker transferfunc]
1540    if { [info exists _isomarkers($tf)] } {
1541        set marker [namespace tail $marker]
1542        foreach m $_isomarkers($tf) {
1543            set sx [$m screenpos]
1544            if { $m != $marker } {
1545                set bool [expr { $x >= ($sx-3) && $x <= ($sx+3) }]
1546                $m activate $bool
1547            }
1548        }
1549    }
1550    return ""
1551}
1552
1553itcl::body Rappture::NanovisViewer::limits { tf } {
1554    set _limits(min) 0.0
1555    set _limits(max) 1.0
1556    if { ![info exists _style2vols($tf)] } {
1557        return [array get _limits]
1558    }
1559    set min ""; set max ""
1560    foreach vol $_style2vols($tf) {
1561        if { ![info exists _serverVols($vol)] } {
1562            continue
1563        }
1564        if { ![info exists _limits($vol-min)] } {
1565            continue
1566        }
1567        if { $min == "" || $min > $_limits($vol-min) } {
1568            set min $_limits($vol-min)
1569        }
1570        if { $max == "" || $max < $_limits($vol-max) } {
1571            set max $_limits($vol-max)
1572        }
1573    }
1574    if { $min != "" } {
1575        set _limits(min) $min
1576    }
1577    if { $max != "" } {
1578        set _limits(max) $max
1579    }
1580    return [array get _limits]
1581}
1582
1583
1584itcl::body Rappture::NanovisViewer::BuildViewTab {} {
1585    foreach { key value } {
1586        grid            0
1587        axes            1
1588        outline         1
1589        volume          1
1590        legend          1
1591        particles       1
1592        lic             1
1593    } {
1594        set _settings($this-$key) $value
1595    }
1596
1597    set fg [option get $itk_component(hull) font Font]
1598    #set bfg [option get $itk_component(hull) boldFont Font]
1599
1600    set inner [$itk_component(main) insert end \
1601        -title "View Settings" \
1602        -icon [Rappture::icon wrench]]
1603    $inner configure -borderwidth 4
1604
1605    set ::Rappture::NanovisViewer::_settings($this-isosurface) 0
1606    checkbutton $inner.isosurface \
1607        -text "Isosurface shading" \
1608        -variable [itcl::scope _settings($this-isosurface)] \
1609        -command [itcl::code $this FixSettings isosurface] \
1610        -font "Arial 9"
1611
1612    checkbutton $inner.axes \
1613        -text "Axes" \
1614        -variable [itcl::scope _settings($this-axes)] \
1615        -command [itcl::code $this FixSettings axes] \
1616        -font "Arial 9"
1617
1618    checkbutton $inner.grid \
1619        -text "Grid" \
1620        -variable [itcl::scope _settings($this-grid)] \
1621        -command [itcl::code $this FixSettings grid] \
1622        -font "Arial 9"
1623
1624    checkbutton $inner.outline \
1625        -text "Outline" \
1626        -variable [itcl::scope _settings($this-outline)] \
1627        -command [itcl::code $this FixSettings outline] \
1628        -font "Arial 9"
1629
1630    checkbutton $inner.legend \
1631        -text "Legend" \
1632        -variable [itcl::scope _settings($this-legend)] \
1633        -command [itcl::code $this FixSettings legend] \
1634        -font "Arial 9"
1635
1636    checkbutton $inner.volume \
1637        -text "Volume" \
1638        -variable [itcl::scope _settings($this-volume)] \
1639        -command [itcl::code $this FixSettings volume] \
1640        -font "Arial 9"
1641
1642    blt::table $inner \
1643        0,0 $inner.axes  -columnspan 2 -anchor w \
1644        1,0 $inner.grid  -columnspan 2 -anchor w \
1645        2,0 $inner.outline  -columnspan 2 -anchor w \
1646        3,0 $inner.volume  -columnspan 2 -anchor w \
1647        4,0 $inner.legend  -columnspan 2 -anchor w
1648
1649    if 0 {
1650    bind $inner <Map> [itcl::code $this GetVolumeInfo $inner]
1651    }
1652    blt::table configure $inner r* -resize none
1653    blt::table configure $inner r5 -resize expand
1654}
1655
1656itcl::body Rappture::NanovisViewer::BuildVolumeTab {} {
1657    foreach { key value } {
1658        light           40
1659        transp          50
1660        opacity         100
1661        thickness       350
1662    } {
1663        set _settings($this-$key) $value
1664    }
1665
1666    set inner [$itk_component(main) insert end \
1667        -title "Volume Settings" \
1668        -icon [Rappture::icon volume-on]]
1669    $inner configure -borderwidth 4
1670
1671    set fg [option get $itk_component(hull) font Font]
1672    #set bfg [option get $itk_component(hull) boldFont Font]
1673
1674    checkbutton $inner.vol -text "Show volume" -font $fg \
1675        -variable [itcl::scope _settings($this-volume)] \
1676        -command [itcl::code $this FixSettings volume]
1677    label $inner.shading -text "Shading:" -font $fg
1678
1679    label $inner.dim -text "Dim" -font $fg
1680    ::scale $inner.light -from 0 -to 100 -orient horizontal \
1681        -variable [itcl::scope _settings($this-light)] \
1682        -width 10 \
1683        -showvalue off -command [itcl::code $this FixSettings light]
1684    label $inner.bright -text "Bright" -font $fg
1685
1686    label $inner.fog -text "Fog" -font $fg
1687    ::scale $inner.transp -from 0 -to 100 -orient horizontal \
1688        -variable [itcl::scope _settings($this-transp)] \
1689        -width 10 \
1690        -showvalue off -command [itcl::code $this FixSettings transp]
1691    label $inner.plastic -text "Plastic" -font $fg
1692
1693    label $inner.clear -text "Clear" -font $fg
1694    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1695        -variable [itcl::scope _settings($this-opacity)] \
1696        -width 10 \
1697        -showvalue off -command [itcl::code $this FixSettings opacity]
1698    label $inner.opaque -text "Opaque" -font $fg
1699
1700    label $inner.thin -text "Thin" -font $fg
1701    ::scale $inner.thickness -from 0 -to 1000 -orient horizontal \
1702        -variable [itcl::scope _settings($this-thickness)] \
1703        -width 10 \
1704        -showvalue off -command [itcl::code $this FixSettings thickness]
1705    label $inner.thick -text "Thick" -font $fg
1706
1707    blt::table $inner \
1708        0,0 $inner.vol -columnspan 4 -anchor w -pady 2 \
1709        1,0 $inner.shading -columnspan 4 -anchor w -pady {10 2} \
1710        2,0 $inner.dim -anchor e -pady 2 \
1711        2,1 $inner.light -columnspan 2 -pady 2 -fill x \
1712        2,3 $inner.bright -anchor w -pady 2 \
1713        3,0 $inner.fog -anchor e -pady 2 \
1714        3,1 $inner.transp -columnspan 2 -pady 2 -fill x \
1715        3,3 $inner.plastic -anchor w -pady 2 \
1716        4,0 $inner.clear -anchor e -pady 2 \
1717        4,1 $inner.opacity -columnspan 2 -pady 2 -fill x\
1718        4,3 $inner.opaque -anchor w -pady 2 \
1719        5,0 $inner.thin -anchor e -pady 2 \
1720        5,1 $inner.thickness -columnspan 2 -pady 2 -fill x\
1721        5,3 $inner.thick -anchor w -pady 2
1722
1723    blt::table configure $inner c0 c1 c3 r* -resize none
1724    blt::table configure $inner r6 -resize expand
1725}
1726
1727itcl::body Rappture::NanovisViewer::BuildCutplanesTab {} {
1728    set inner [$itk_component(main) insert end \
1729        -title "Cutplane Settings" \
1730        -icon [Rappture::icon cutbutton]]
1731    $inner configure -borderwidth 4
1732
1733    # X-value slicer...
1734    itk_component add xCutButton {
1735        Rappture::PushButton $inner.xbutton \
1736            -onimage [Rappture::icon x-cutplane] \
1737            -offimage [Rappture::icon x-cutplane] \
1738            -command [itcl::code $this FixSettings xcutplane] \
1739            -variable [itcl::scope _settings($this-xcutplane)]
1740    }
1741    Rappture::Tooltip::for $itk_component(xCutButton) \
1742        "Toggle the X cut plane on/off"
1743
1744    itk_component add xCutScale {
1745        ::scale $inner.xval -from 100 -to 0 \
1746            -width 10 -orient vertical -showvalue off \
1747            -borderwidth 1 -highlightthickness 0 \
1748            -command [itcl::code $this Slice move x] \
1749            -variable [itcl::scope _settings($this-xcutposition)]
1750    } {
1751        usual
1752        ignore -borderwidth -highlightthickness
1753    }
1754    # Set the default cutplane value before disabling the scale.
1755    $itk_component(xCutScale) set 50
1756    $itk_component(xCutScale) configure -state disabled
1757    Rappture::Tooltip::for $itk_component(xCutScale) \
1758        "@[itcl::code $this SlicerTip x]"
1759
1760    # Y-value slicer...
1761    itk_component add yCutButton {
1762        Rappture::PushButton $inner.ybutton \
1763            -onimage [Rappture::icon y-cutplane] \
1764            -offimage [Rappture::icon y-cutplane] \
1765            -command [itcl::code $this FixSettings ycutplane] \
1766            -variable [itcl::scope _settings($this-ycutplane)]
1767    }
1768    Rappture::Tooltip::for $itk_component(yCutButton) \
1769        "Toggle the Y cut plane on/off"
1770
1771    itk_component add yCutScale {
1772        ::scale $inner.yval -from 100 -to 0 \
1773            -width 10 -orient vertical -showvalue off \
1774            -borderwidth 1 -highlightthickness 0 \
1775            -command [itcl::code $this Slice move y] \
1776            -variable [itcl::scope _settings($this-ycutposition)]
1777    } {
1778        usual
1779        ignore -borderwidth -highlightthickness
1780    }
1781    Rappture::Tooltip::for $itk_component(yCutScale) \
1782        "@[itcl::code $this SlicerTip y]"
1783    # Set the default cutplane value before disabling the scale.
1784    $itk_component(yCutScale) set 50
1785    $itk_component(yCutScale) configure -state disabled
1786
1787    # Z-value slicer...
1788    itk_component add zCutButton {
1789        Rappture::PushButton $inner.zbutton \
1790            -onimage [Rappture::icon z-cutplane] \
1791            -offimage [Rappture::icon z-cutplane] \
1792            -command [itcl::code $this FixSettings zcutplane] \
1793            -variable [itcl::scope _settings($this-zcutplane)]
1794    }
1795    Rappture::Tooltip::for $itk_component(zCutButton) \
1796        "Toggle the Z cut plane on/off"
1797
1798    itk_component add zCutScale {
1799        ::scale $inner.zval -from 100 -to 0 \
1800            -width 10 -orient vertical -showvalue off \
1801            -borderwidth 1 -highlightthickness 0 \
1802            -command [itcl::code $this Slice move z] \
1803            -variable [itcl::scope _settings($this-zcutposition)]
1804    } {
1805        usual
1806        ignore -borderwidth -highlightthickness
1807    }
1808    $itk_component(zCutScale) set 50
1809    $itk_component(zCutScale) configure -state disabled
1810    #$itk_component(zCutScale) configure -state disabled
1811    Rappture::Tooltip::for $itk_component(zCutScale) \
1812        "@[itcl::code $this SlicerTip z]"
1813
1814    blt::table $inner \
1815        1,1 $itk_component(xCutButton) \
1816        1,2 $itk_component(yCutButton) \
1817        1,3 $itk_component(zCutButton) \
1818        0,1 $itk_component(xCutScale) \
1819        0,2 $itk_component(yCutScale) \
1820        0,3 $itk_component(zCutScale) \
1821
1822    blt::table configure $inner r0 r1 c* -resize none
1823    blt::table configure $inner r2 c4 -resize expand
1824    blt::table configure $inner c0 -width 2
1825    blt::table configure $inner c1 c2 c3 -padx 2
1826}
1827
1828itcl::body Rappture::NanovisViewer::BuildCameraTab {} {
1829    set inner [$itk_component(main) insert end \
1830        -title "Camera Settings" \
1831        -icon [Rappture::icon camera]]
1832    $inner configure -borderwidth 4
1833
1834    set labels { phi theta psi pan-x pan-y zoom }
1835    set row 0
1836    foreach tag $labels {
1837        label $inner.${tag}label -text $tag -font "Arial 9"
1838        entry $inner.${tag} -font "Arial 9"  -bg white \
1839            -textvariable [itcl::scope _settings($this-$tag)]
1840        bind $inner.${tag} <KeyPress-Return> \
1841            [itcl::code $this camera set ${tag}]
1842        blt::table $inner \
1843            $row,0 $inner.${tag}label -anchor e -pady 2 \
1844            $row,1 $inner.${tag} -anchor w -pady 2
1845        blt::table configure $inner r$row -resize none
1846        incr row
1847    }
1848    blt::table configure $inner c0 c1 -resize none
1849    blt::table configure $inner c2 -resize expand
1850    blt::table configure $inner r$row -resize expand
1851}
1852
1853
1854# ----------------------------------------------------------------------
1855# USAGE: Slice move x|y|z <newval>
1856#
1857# Called automatically when the user drags the slider to move the
1858# cut plane that slices 3D data.  Gets the current value from the
1859# slider and moves the cut plane to the appropriate point in the
1860# data set.
1861# ----------------------------------------------------------------------
1862itcl::body Rappture::NanovisViewer::Slice {option args} {
1863    switch -- $option {
1864        move {
1865            if {[llength $args] != 2} {
1866                error "wrong # args: should be \"Slice move x|y|z newval\""
1867            }
1868            set axis [lindex $args 0]
1869            set newval [lindex $args 1]
1870
1871            set newpos [expr {0.01*$newval}]
1872            set vols [CurrentVolumes -cutplanes]
1873            SendCmd "cutplane position $newpos $axis $vols"
1874        }
1875        default {
1876            error "bad option \"$option\": should be axis, move, or volume"
1877        }
1878    }
1879}
1880
1881# ----------------------------------------------------------------------
1882# USAGE: SlicerTip <axis>
1883#
1884# Used internally to generate a tooltip for the x/y/z slicer controls.
1885# Returns a message that includes the current slicer value.
1886# ----------------------------------------------------------------------
1887itcl::body Rappture::NanovisViewer::SlicerTip {axis} {
1888    set val [$itk_component(${axis}CutScale) get]
1889#    set val [expr {0.01*($val-50)
1890#        *($_limits(${axis}max)-$_limits(${axis}min))
1891#          + 0.5*($_limits(${axis}max)+$_limits(${axis}min))}]
1892    return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
1893}
1894
1895
1896itcl::body Rappture::NanovisViewer::DoResize {} {
1897    SendCmd "screen $_width $_height"
1898    set _resizePending 0
1899}
1900
1901itcl::body Rappture::NanovisViewer::EventuallyResize { w h } {
1902    set _width $w
1903    set _height $h
1904    if { !$_resizePending } {
1905        $_dispatcher event -idle !resize
1906        set _resizePending 1
1907    }
1908}
1909
1910itcl::body Rappture::NanovisViewer::EventuallyResizeLegend {} {
1911    if { !$_resizeLegendPending } {
1912        $_dispatcher event -idle !legend
1913        set _resizeLegendPending 1
1914    }
1915}
1916
1917
1918#  camera --
1919#
1920itcl::body Rappture::NanovisViewer::camera {option args} {
1921    switch -- $option {
1922        "show" {
1923            puts [array get _view]
1924        }
1925        "set" {
1926            set who [lindex $args 0]
1927            set x $_settings($this-$who)
1928            set code [catch { string is double $x } result]
1929            if { $code != 0 || !$result } {
1930                set _settings($this-$who) $_view($who)
1931                return
1932            }
1933            switch -- $who {
1934                "pan-x" - "pan-y" {
1935                    set _view($who) $_settings($this-$who)
1936                    PanCamera
1937                }
1938                "phi" - "theta" - "psi" {
1939                    set _view($who) $_settings($this-$who)
1940                    set xyz [Euler2XYZ $_view(theta) $_view(phi) $_view(psi)]
1941                    SendCmd "camera angle $xyz"
1942                }
1943                "zoom" {
1944                    set _view($who) $_settings($this-$who)
1945                    SendCmd "camera zoom $_view(zoom)"
1946                }
1947            }
1948        }
1949    }
1950}
1951
1952itcl::body Rappture::NanovisViewer::GetVolumeInfo { w } {
1953    set flowobj ""
1954    foreach key [array names _obj2flow] {
1955        set flowobj $_obj2flow($key)
1956        break
1957    }
1958    if { $flowobj == "" } {
1959        return
1960    }
1961    if { [winfo exists $w.frame] } {
1962        destroy $w.frame
1963    }
1964    set inner [frame $w.frame]
1965    blt::table $w \
1966        5,0 $inner -fill both -columnspan 2 -anchor nw
1967    array set hints [$dataobj hints]
1968
1969    label $inner.volumes -text "Volumes" -font "Arial 9 bold"
1970    blt::table $inner \
1971        1,0 $inner.volumes  -anchor w \
1972    blt::table configure $inner c0 c1 -resize none
1973    blt::table configure $inner c2 -resize expand
1974
1975    set row 3
1976    set volumes [get]
1977    if { [llength $volumes] > 0 } {
1978        blt::table $inner $row,0 $inner.volumes  -anchor w
1979        incr row
1980    }
1981    foreach vol $volumes {
1982        array unset info
1983        array set info $vol
1984        set name $info(name)
1985        if { ![info exists _settings($this-volume-$name)] } {
1986            set _settings($this-volume-$name) $info(hide)
1987        }
1988        checkbutton $inner.vol$row -text $info(label) \
1989            -variable [itcl::scope _settings($this-volume-$name)] \
1990            -onvalue 0 -offvalue 1 \
1991            -command [itcl::code $this volume $key $name] \
1992            -font "Arial 9"
1993        Rappture::Tooltip::for $inner.vol$row $info(description)
1994        blt::table $inner $row,0 $inner.vol$row -anchor w
1995        if { !$_settings($this-volume-$name) } {
1996            $inner.vol$row select
1997        }
1998        incr row
1999    }
2000    blt::table configure $inner r* -resize none
2001    blt::table configure $inner r$row -resize expand
2002    blt::table configure $inner c3 -resize expand
2003    event generate [winfo parent [winfo parent $w]] <Configure>
2004}
2005
2006itcl::body Rappture::NanovisViewer::volume { tag name } {
2007    set bool $_settings($this-volume-$name)
2008    SendCmd "volume statue $bool $name"
2009}
2010
Note: See TracBrowser for help on using the repository browser.