source: branches/1.4/gui/scripts/vtkisosurfaceviewer.tcl @ 5312

Last change on this file since 5312 was 5206, checked in by ldelgass, 10 years ago

merge r5195 from trunk

File size: 110.9 KB
Line 
1# -*- mode: tcl; indent-tabs-mode: nil -*-
2# ----------------------------------------------------------------------
3#  COMPONENT: vtkisosurfaceviewer - Vtk 3D contour object viewer
4#
5#  It connects to the Vtk server running on a rendering farm,
6#  transmits data, and displays the results.
7# ======================================================================
8#  AUTHOR:  Michael McLennan, Purdue University
9#  Copyright (c) 2004-2014  HUBzero Foundation, LLC
10#
11#  See the file "license.terms" for information on usage and
12#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13# ======================================================================
14package require Itk
15package require BLT
16#package require Img
17
18option add *VtkIsosurfaceViewer.width 4i widgetDefault
19option add *VtkIsosurfaceViewer*cursor crosshair widgetDefault
20option add *VtkIsosurfaceViewer.height 4i widgetDefault
21option add *VtkIsosurfaceViewer.foreground black widgetDefault
22option add *VtkIsosurfaceViewer.controlBackground gray widgetDefault
23option add *VtkIsosurfaceViewer.controlDarkBackground #999999 widgetDefault
24option add *VtkIsosurfaceViewer.plotBackground black widgetDefault
25option add *VtkIsosurfaceViewer.plotForeground white widgetDefault
26option add *VtkIsosurfaceViewer.font \
27    -*-helvetica-medium-r-normal-*-12-* widgetDefault
28
29# must use this name -- plugs into Rappture::resources::load
30proc VtkIsosurfaceViewer_init_resources {} {
31    Rappture::resources::register \
32        vtkvis_server Rappture::VtkIsosurfaceViewer::SetServerList
33}
34
35itcl::class Rappture::VtkIsosurfaceViewer {
36    inherit Rappture::VisViewer
37
38    itk_option define -plotforeground plotForeground Foreground ""
39    itk_option define -plotbackground plotBackground Background ""
40
41    constructor { hostlist args } {
42        Rappture::VisViewer::constructor $hostlist
43    } {
44        # defined below
45    }
46    destructor {
47        # defined below
48    }
49    public proc SetServerList { namelist } {
50        Rappture::VisViewer::SetServerList "vtkvis" $namelist
51    }
52    public method add {dataobj {settings ""}}
53    public method camera {option args}
54    public method delete {args}
55    public method disconnect {}
56    public method download {option args}
57    public method get {args}
58    public method isconnected {}
59    public method parameters {title args} {
60        # do nothing
61    }
62    public method scale {args}
63
64    # The following methods are only used by this class.
65    private method AdjustSetting {what {value ""}}
66    private method BuildAxisTab {}
67    private method BuildCameraTab {}
68    private method BuildColormap { name }
69    private method BuildCutplaneTab {}
70    private method BuildDownloadPopup { widget command }
71    private method BuildIsosurfaceTab {}
72    private method Connect {}
73    private method CurrentDatasets {args}
74    private method DisableMouseRotationBindings {}
75    private method Disconnect {}
76    private method DoChangeContourLevels {}
77    private method DoResize {}
78    private method DoRotate {}
79    private method DrawLegend {}
80    private method EnterLegend { x y }
81    private method EventuallyChangeContourLevels {}
82    private method EventuallyRequestLegend {}
83    private method EventuallyResize { w h }
84    private method EventuallyRotate { q }
85    private method EventuallySetCutplane { axis args }
86    private method GenerateContourList {}
87    private method GetImage { args }
88    private method GetVtkData { args }
89    private method InitSettings { args }
90    private method IsValidObject { dataobj }
91    private method LeaveLegend {}
92    private method LegendB1Motion {status x y}
93    private method LegendPointToValue { x y }
94    private method LegendProbeSingleContour { x y }
95    private method LegendRangeAction { option args }
96    private method LegendRangeValidate { widget which value }
97    private method LegendTitleAction { option }
98    private method MotionLegend { x y }
99    private method MouseOver2Which {}
100    private method Pan {option x y}
101    private method PanCamera {}
102    private method Pick {x y}
103    private method QuaternionToView { q } {
104        foreach { _view(-qw) _view(-qx) _view(-qy) _view(-qz) } $q break
105    }
106    private method Rebuild {}
107    private method ReceiveDataset { args }
108    private method ReceiveImage { args }
109    private method ReceiveLegend { colormap title vmin vmax size }
110    private method RequestLegend {}
111    private method Rotate {option x y}
112    private method SetCurrentColormap { color }
113    private method SetCurrentFieldName { dataobj }
114    private method SetLegendTip { x y }
115    private method SetMinMaxGauges { min max }
116    private method SetObjectStyle { dataobj comp }
117    private method SetOrientation { side }
118    private method SetupMouseRotationBindings {}
119    private method SetupMousePanningBindings {}
120    private method SetupKeyboardBindings {}
121    private method Slice {option args}
122    private method ToggleCustomRange { args }
123    private method ViewToQuaternion {} {
124        return [list $_view(-qw) $_view(-qx) $_view(-qy) $_view(-qz)]
125    }
126    private method Zoom {option}
127
128    private variable _arcball ""
129
130    private variable _dlist ""     ;    # list of data objects
131    private variable _obj2ovride   ;    # maps dataobj => style override
132    private variable _datasets     ;    # contains all the dataobj-component
133                                   ;    # datasets in the server
134    private variable _colormaps    ;    # contains all the colormaps
135                                   ;    # in the server.
136    # The name of the current colormap used.  The colormap is global to all
137    # heightmaps displayed.
138    private variable _currentColormap ""
139    private variable _currentNumContours -1
140
141    private variable _click        ;    # info used for rotate operations
142    private variable _limits       ;    # autoscale min/max for all axes
143    private variable _view         ;    # view params for 3D view
144    private variable _settings
145    private variable _changed
146    private variable _reset 1;          # Connection to server has been reset.
147
148    private variable _first ""     ;    # This is the topmost dataset.
149    private variable _start 0
150    private variable _title ""
151    private variable _isolines
152    private variable _contourList
153    private variable _currentLimits ""
154    private variable _widget
155
156    common _downloadPopup;              # download options from popup
157    private common _hardcopy
158    private variable _width 0
159    private variable _height 0
160    private variable _resizePending 0
161    private variable _rotatePending 0
162    private variable _cutplanePending 0
163    private variable _legendPending 0
164    private variable _field      ""
165    private variable _colorMode "scalar";   #  Mode of colormap (vmag or scalar)
166    private variable _fieldNames {}
167    private variable _fields
168    private variable _curFldName ""
169    private variable _curFldLabel ""
170
171    private variable _mouseOver "";     # what called LegendRangeAction, vmin or vmax
172    private variable _customRangeClick 1;   # what called ToggleCustomRange
173}
174
175itk::usual VtkIsosurfaceViewer {
176    keep -background -foreground -cursor -font
177    keep -plotbackground -plotforeground
178}
179
180# ----------------------------------------------------------------------
181# CONSTRUCTOR
182# ----------------------------------------------------------------------
183itcl::body Rappture::VtkIsosurfaceViewer::constructor {hostlist args} {
184    package require vtk
185    set _serverType "vtkvis"
186
187    # Rebuild event
188    $_dispatcher register !rebuild
189    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
190
191    # Resize event
192    $_dispatcher register !resize
193    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
194
195    # Rotate event
196    $_dispatcher register !rotate
197    $_dispatcher dispatch $this !rotate "[itcl::code $this DoRotate]; list"
198
199    # Legend event
200    $_dispatcher register !legend
201    $_dispatcher dispatch $this !legend "[itcl::code $this RequestLegend]; list"
202
203    # Contour levels event
204    $_dispatcher register !contours
205    $_dispatcher dispatch $this !contours \
206        "[itcl::code $this DoChangeContourLevels]; list"
207
208    # X-Cutplane event
209    $_dispatcher register !xcutplane
210    $_dispatcher dispatch $this !xcutplane \
211        "[itcl::code $this AdjustSetting -xcutplaneposition]; list"
212
213    # Y-Cutplane event
214    $_dispatcher register !ycutplane
215    $_dispatcher dispatch $this !ycutplane \
216        "[itcl::code $this AdjustSetting -ycutplaneposition]; list"
217
218    # Z-Cutplane event
219    $_dispatcher register !zcutplane
220    $_dispatcher dispatch $this !zcutplane \
221        "[itcl::code $this AdjustSetting -zcutplaneposition]; list"
222
223    #
224    # Populate parser with commands handle incoming requests
225    #
226    $_parser alias image [itcl::code $this ReceiveImage]
227    $_parser alias dataset [itcl::code $this ReceiveDataset]
228    $_parser alias legend [itcl::code $this ReceiveLegend]
229
230    # Initialize the view to some default parameters.
231    array set _view {
232        -ortho           0
233        -qw              0.853553
234        -qx              -0.353553
235        -qy              0.353553
236        -qz              0.146447
237        -xpan            0
238        -ypan            0
239        -zoom            1.0
240    }
241    set _arcball [blt::arcball create 100 100]
242    $_arcball quaternion [ViewToQuaternion]
243
244    array set _contourList {
245        numLevels       10
246        reqValues       ""
247        updatePending   0
248        values          ""
249    }
250    array set _settings {
251        -axesvisible                1
252        -axislabels                 1
253        -axisminorticks             1
254        -axismode                   "static"
255        -background                 black
256        -colormap                   BCGYR
257        -colormapvisible            1
258        -customrange                0
259        -customrangemin             0
260        -customrangemax             1
261        -cutplaneedges              0
262        -cutplanelighting           1
263        -cutplaneopacity            1.0
264        -cutplanepreinterp          1
265        -cutplanesvisible           0
266        -cutplanewireframe          0
267        -field                      "Default"
268        -isolinecolor               white
269        -isosurfaceedges            0
270        -isosurfacelighting         1
271        -isosurfaceopacity          0.6
272        -isosurfacevisible          1
273        -isosurfacewireframe        0
274        -legendvisible              1
275        -numcontours                10
276        -outline                    0
277        -xcutplaneposition          50
278        -xcutplanevisible           1
279        -xgrid                      0
280        -ycutplaneposition          50
281        -ycutplanevisible           1
282        -ygrid                      0
283        -zcutplaneposition          50
284        -zcutplanevisible           1
285        -zgrid                      0
286    }
287    array set _changed {
288        -colormap                0
289        -cutplaneedges           0
290        -cutplanelighting        0
291        -cutplaneopacity         0
292        -cutplanepreinterp       0
293        -cutplanesvisible        0
294        -cutplanewireframe       0
295        -isosurfaceedges         0
296        -isosurfacelighting      0
297        -isosurfaceopacity       0
298        -isosurfacevisible       0
299        -isosurfacewireframe     0
300        -numcontours             0
301        -outline                 0
302        -xcutplaneposition       0
303        -xcutplanevisible        0
304        -ycutplaneposition       0
305        -ycutplanevisible        0
306        -zcutplaneposition       0
307        -zcutplanevisible        0
308    }
309    array set _widget {
310        -isosurfaceopacity       60
311        -cutplaneopacity         100
312    }
313
314    itk_component add view {
315        canvas $itk_component(plotarea).view \
316            -highlightthickness 0 -borderwidth 0
317    } {
318        usual
319        ignore -highlightthickness -borderwidth  -background
320    }
321
322    itk_component add fieldmenu {
323        menu $itk_component(plotarea).menu -bg black -fg white -relief flat \
324            -tearoff 0
325    } {
326        usual
327        ignore -background -foreground -relief -tearoff
328    }
329
330    # add an editor for adjusting the legend min and max values
331    itk_component add editor {
332        Rappture::Editor $itk_interior.editor \
333            -activatecommand [itcl::code $this LegendRangeAction activate] \
334            -validatecommand [itcl::code $this LegendRangeAction validate] \
335            -applycommand [itcl::code $this LegendRangeAction apply]
336    }
337
338    set c $itk_component(view)
339    bind $c <Configure> [itcl::code $this EventuallyResize %w %h]
340    bind $c <4> [itcl::code $this Zoom in 0.25]
341    bind $c <5> [itcl::code $this Zoom out 0.25]
342    bind $c <KeyPress-Left>  [list %W xview scroll 10 units]
343    bind $c <KeyPress-Right> [list %W xview scroll -10 units]
344    bind $c <KeyPress-Up>    [list %W yview scroll 10 units]
345    bind $c <KeyPress-Down>  [list %W yview scroll -10 units]
346    bind $c <Enter> "focus %W"
347    bind $c <Control-F1> [itcl::code $this ToggleConsole]
348
349    # Fix the scrollregion in case we go off screen
350    $c configure -scrollregion [$c bbox all]
351
352    set _map(id) [$c create image 0 0 -anchor nw -image $_image(plot)]
353    set _map(cwidth) -1
354    set _map(cheight) -1
355    set _map(zoom) 1.0
356    set _map(original) ""
357
358    set f [$itk_component(main) component controls]
359    itk_component add reset {
360        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
361            -highlightthickness 0 \
362            -image [Rappture::icon reset-view] \
363            -command [itcl::code $this Zoom reset]
364    } {
365        usual
366        ignore -highlightthickness
367    }
368    pack $itk_component(reset) -side top -padx 2 -pady 2
369    Rappture::Tooltip::for $itk_component(reset) \
370        "Reset the view to the default zoom level"
371
372    itk_component add zoomin {
373        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
374            -highlightthickness 0 \
375            -image [Rappture::icon zoom-in] \
376            -command [itcl::code $this Zoom in]
377    } {
378        usual
379        ignore -highlightthickness
380    }
381    pack $itk_component(zoomin) -side top -padx 2 -pady 2
382    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
383
384    itk_component add zoomout {
385        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
386            -highlightthickness 0 \
387            -image [Rappture::icon zoom-out] \
388            -command [itcl::code $this Zoom out]
389    } {
390        usual
391        ignore -highlightthickness
392    }
393    pack $itk_component(zoomout) -side top -padx 2 -pady 2
394    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
395
396    itk_component add contour {
397        Rappture::PushButton $f.contour \
398            -onimage [Rappture::icon volume-on] \
399            -offimage [Rappture::icon volume-off] \
400            -variable [itcl::scope _settings(-isosurfacevisible)] \
401            -command [itcl::code $this AdjustSetting -isosurfacevisible]
402    }
403    $itk_component(contour) select
404    Rappture::Tooltip::for $itk_component(contour) \
405        "Hide the isosurface"
406    pack $itk_component(contour) -padx 2 -pady 2
407
408    itk_component add cutplane {
409        Rappture::PushButton $f.cutplane \
410            -onimage [Rappture::icon cutbutton] \
411            -offimage [Rappture::icon cutbutton] \
412            -variable [itcl::scope _settings(-cutplanesvisible)] \
413            -command [itcl::code $this AdjustSetting -cutplanesvisible]
414    }
415    Rappture::Tooltip::for $itk_component(cutplane) \
416        "Show the cutplanes"
417    pack $itk_component(cutplane) -padx 2 -pady 2
418
419
420    if { [catch {
421        BuildIsosurfaceTab
422        BuildCutplaneTab
423        BuildAxisTab
424        BuildCameraTab
425    } errs] != 0 } {
426        puts stderr errs=$errs
427    }
428
429    # Legend
430    set _image(legend) [image create photo]
431    itk_component add legend {
432        canvas $itk_component(plotarea).legend -width 50 -highlightthickness 0
433    } {
434        usual
435        ignore -highlightthickness
436        rename -background -plotbackground plotBackground Background
437    }
438
439    # Hack around the Tk panewindow.  The problem is that the requested
440    # size of the 3d view isn't set until an image is retrieved from
441    # the server.  So the panewindow uses the tiny size.
442    set w 10000
443    pack forget $itk_component(view)
444    blt::table $itk_component(plotarea) \
445        0,0 $itk_component(view) -fill both -reqwidth $w
446    blt::table configure $itk_component(plotarea) c1 -resize none
447
448    SetupMouseRotationBindings
449    SetupMousePanningBindings
450    SetupKeyboardBindings
451
452
453    #bind $itk_component(view) <ButtonRelease-3> \
454    #    [itcl::code $this Pick %x %y]
455
456
457    if {[string equal "x11" [tk windowingsystem]]} {
458        # Bindings for zoom via mouse
459        bind $itk_component(view) <4> [itcl::code $this Zoom out]
460        bind $itk_component(view) <5> [itcl::code $this Zoom in]
461    }
462
463    set _image(download) [image create photo]
464
465    eval itk_initialize $args
466
467    EnableWaitDialog 900
468    Connect
469}
470
471# ----------------------------------------------------------------------
472# DESTRUCTOR
473# ----------------------------------------------------------------------
474itcl::body Rappture::VtkIsosurfaceViewer::destructor {} {
475    Disconnect
476    image delete $_image(plot)
477    image delete $_image(download)
478    catch { blt::arcball destroy $_arcball }
479}
480
481itcl::body Rappture::VtkIsosurfaceViewer::SetupMouseRotationBindings {} {
482    # Bindings for rotation via mouse
483    bind $itk_component(view) <ButtonPress-1> \
484        [itcl::code $this Rotate click %x %y]
485    bind $itk_component(view) <B1-Motion> \
486        [itcl::code $this Rotate drag %x %y]
487    bind $itk_component(view) <ButtonRelease-1> \
488        [itcl::code $this Rotate release %x %y]
489}
490
491itcl::body Rappture::VtkIsosurfaceViewer::DisableMouseRotationBindings {} {
492    # Bindings for rotation via mouse
493    bind $itk_component(view) <ButtonPress-1> ""
494    bind $itk_component(view) <B1-Motion> ""
495    bind $itk_component(view) <ButtonRelease-1> ""
496}
497
498itcl::body Rappture::VtkIsosurfaceViewer::SetupMousePanningBindings {} {
499    # Bindings for panning via mouse
500    bind $itk_component(view) <ButtonPress-2> \
501        [itcl::code $this Pan click %x %y]
502    bind $itk_component(view) <B2-Motion> \
503        [itcl::code $this Pan drag %x %y]
504    bind $itk_component(view) <ButtonRelease-2> \
505        [itcl::code $this Pan release %x %y]
506}
507
508itcl::body Rappture::VtkIsosurfaceViewer::SetupKeyboardBindings {} {
509    # Bindings for panning via keyboard
510    bind $itk_component(view) <KeyPress-Left> \
511        [itcl::code $this Pan set -10 0]
512    bind $itk_component(view) <KeyPress-Right> \
513        [itcl::code $this Pan set 10 0]
514    bind $itk_component(view) <KeyPress-Up> \
515        [itcl::code $this Pan set 0 -10]
516    bind $itk_component(view) <KeyPress-Down> \
517        [itcl::code $this Pan set 0 10]
518    bind $itk_component(view) <Shift-KeyPress-Left> \
519        [itcl::code $this Pan set -2 0]
520    bind $itk_component(view) <Shift-KeyPress-Right> \
521        [itcl::code $this Pan set 2 0]
522    bind $itk_component(view) <Shift-KeyPress-Up> \
523        [itcl::code $this Pan set 0 -2]
524    bind $itk_component(view) <Shift-KeyPress-Down> \
525        [itcl::code $this Pan set 0 2]
526
527    # Bindings for zoom via keyboard
528    bind $itk_component(view) <KeyPress-Prior> \
529        [itcl::code $this Zoom out]
530    bind $itk_component(view) <KeyPress-Next> \
531        [itcl::code $this Zoom in]
532
533    bind $itk_component(view) <Enter> "focus $itk_component(view)"
534}
535
536itcl::body Rappture::VtkIsosurfaceViewer::DoResize {} {
537    if { $_width < 2 } {
538        set _width 500
539    }
540    if { $_height < 2 } {
541        set _height 500
542    }
543    set _start [clock clicks -milliseconds]
544    SendCmd "screen size $_width $_height"
545
546    EventuallyRequestLegend
547    set _resizePending 0
548}
549
550itcl::body Rappture::VtkIsosurfaceViewer::DoChangeContourLevels {} {
551    GenerateContourList
552    SendCmd [list contour3d contourlist $_contourList(values)]
553    SendCmd [list camera reset]
554    DrawLegend
555    set _contourList(updatePending) 0
556}
557
558itcl::body Rappture::VtkIsosurfaceViewer::DoRotate {} {
559    SendCmd "camera orient [ViewToQuaternion]"
560    set _rotatePending 0
561}
562
563itcl::body Rappture::VtkIsosurfaceViewer::EventuallyRequestLegend {} {
564    if { !$_legendPending } {
565        set _legendPending 1
566        $_dispatcher event -idle !legend
567    }
568}
569
570itcl::body Rappture::VtkIsosurfaceViewer::EventuallyResize { w h } {
571    set _width $w
572    set _height $h
573    $_arcball resize $w $h
574    if { !$_resizePending } {
575        set _resizePending 1
576        $_dispatcher event -after 400 !resize
577    }
578}
579
580set rotate_delay 100
581
582itcl::body Rappture::VtkIsosurfaceViewer::EventuallyRotate { q } {
583    QuaternionToView $q
584    if { !$_rotatePending } {
585        set _rotatePending 1
586        global rotate_delay
587        $_dispatcher event -after $rotate_delay !rotate
588    }
589}
590
591itcl::body Rappture::VtkIsosurfaceViewer::EventuallySetCutplane { axis args } {
592    if { !$_cutplanePending } {
593        set _cutplanePending 1
594        $_dispatcher event -after 100 !${axis}cutplane
595    }
596}
597
598itcl::body Rappture::VtkIsosurfaceViewer::EventuallyChangeContourLevels {} {
599    set n $_contourList(numLevels)
600    set _contourList(values) ""
601    if { !$_contourList(updatePending) } {
602        set _contourList(updatePending) 1
603        global rotate_delay
604        $_dispatcher event -after $rotate_delay !contours
605    }
606}
607
608# ----------------------------------------------------------------------
609# USAGE: add <dataobj> ?<settings>?
610#
611# Clients use this to add a data object to the plot.  The optional
612# <settings> are used to configure the plot.  Allowed settings are
613# -color, -brightness, -width, -linestyle, and -raise.
614# ----------------------------------------------------------------------
615itcl::body Rappture::VtkIsosurfaceViewer::add {dataobj {settings ""}} {
616    if { ![$dataobj isvalid] } {
617        return;                         # Object doesn't contain valid data.
618    }
619    array set params {
620        -color auto
621        -width 1
622        -linestyle solid
623        -brightness 0
624        -raise 0
625        -description ""
626        -param ""
627        -type ""
628    }
629    array set params $settings
630    set params(-description) ""
631    set params(-param) ""
632    array set params $settings
633
634    if {$params(-color) == "auto" || $params(-color) == "autoreset"} {
635        # can't handle -autocolors yet
636        set params(-color) black
637    }
638    set pos [lsearch -exact $_dlist $dataobj]
639    if {$pos < 0} {
640        lappend _dlist $dataobj
641    }
642    set _obj2ovride($dataobj-color) $params(-color)
643    set _obj2ovride($dataobj-width) $params(-width)
644    set _obj2ovride($dataobj-raise) $params(-raise)
645    $_dispatcher event -idle !rebuild
646}
647
648# ----------------------------------------------------------------------
649# USAGE: delete ?<dataobj1> <dataobj2> ...?
650#
651#       Clients use this to delete a dataobj from the plot.  If no dataobjs
652#       are specified, then all dataobjs are deleted.  No data objects are
653#       deleted.  They are only removed from the display list.
654#
655# ----------------------------------------------------------------------
656itcl::body Rappture::VtkIsosurfaceViewer::delete {args} {
657    if { [llength $args] == 0} {
658        set args $_dlist
659    }
660    # Delete all specified dataobjs
661    set changed 0
662    foreach dataobj $args {
663        set pos [lsearch -exact $_dlist $dataobj]
664        if { $pos < 0 } {
665            continue;                   # Don't know anything about it.
666        }
667        # Remove it from the dataobj list.
668        set _dlist [lreplace $_dlist $pos $pos]
669        array unset _obj2ovride $dataobj-*
670        array unset _settings $dataobj-*
671        set changed 1
672    }
673    # If anything changed, then rebuild the plot
674    if { $changed } {
675        $_dispatcher event -idle !rebuild
676    }
677}
678
679# ----------------------------------------------------------------------
680# USAGE: get ?-objects?
681# USAGE: get ?-visible?
682# USAGE: get ?-image view?
683#
684# Clients use this to query the list of objects being plotted, in
685# order from bottom to top of this result.  The optional "-image"
686# flag can also request the internal images being shown.
687# ----------------------------------------------------------------------
688itcl::body Rappture::VtkIsosurfaceViewer::get {args} {
689    if {[llength $args] == 0} {
690        set args "-objects"
691    }
692
693    set op [lindex $args 0]
694    switch -- $op {
695        "-objects" {
696            # put the dataobj list in order according to -raise options
697            set dlist {}
698            foreach dataobj $_dlist {
699                if { ![IsValidObject $dataobj] } {
700                    continue
701                }
702                if {[info exists _obj2ovride($dataobj-raise)] &&
703                    $_obj2ovride($dataobj-raise)} {
704                    set dlist [linsert $dlist 0 $dataobj]
705                } else {
706                    lappend dlist $dataobj
707                }
708            }
709            return $dlist
710        }
711        "-visible" {
712            set dlist {}
713            foreach dataobj $_dlist {
714                if { ![IsValidObject $dataobj] } {
715                    continue
716                }
717                if { ![info exists _obj2ovride($dataobj-raise)] } {
718                    # No setting indicates that the object isn't visible.
719                    continue
720                }
721                # Otherwise use the -raise parameter to put the object to
722                # the front of the list.
723                if { $_obj2ovride($dataobj-raise) } {
724                    set dlist [linsert $dlist 0 $dataobj]
725                } else {
726                    lappend dlist $dataobj
727                }
728            }
729            return $dlist
730        }
731        -image {
732            if {[llength $args] != 2} {
733                error "wrong # args: should be \"get -image view\""
734            }
735            switch -- [lindex $args end] {
736                view {
737                    return $_image(plot)
738                }
739                default {
740                    error "bad image name \"[lindex $args end]\": should be view"
741                }
742            }
743        }
744        default {
745            error "bad option \"$op\": should be -objects or -image"
746        }
747    }
748}
749
750# ----------------------------------------------------------------------
751# USAGE: scale ?<data1> <data2> ...?
752#
753# Sets the default limits for the overall plot according to the
754# limits of the data for all of the given <data> objects.  This
755# accounts for all objects--even those not showing on the screen.
756# Because of this, the limits are appropriate for all objects as
757# the user scans through data in the ResultSet viewer.
758# ----------------------------------------------------------------------
759itcl::body Rappture::VtkIsosurfaceViewer::scale { args } {
760    foreach dataobj $args {
761        if { ![$dataobj isvalid] } {
762            continue;                   # Object doesn't contain valid data.
763        }
764        foreach axis { x y z } {
765            set lim [$dataobj limits $axis]
766            if { ![info exists _limits($axis)] } {
767                set _limits($axis) $lim
768                continue
769            }
770            foreach {min max} $lim break
771            foreach {amin amax} $_limits($axis) break
772            if { $amin > $min } {
773                set amin $min
774            }
775            if { $amax < $max } {
776                set amax $max
777            }
778            set _limits($axis) [list $amin $amax]
779        }
780        foreach { fname lim } [$dataobj fieldlimits] {
781            if { ![info exists _limits($fname)] } {
782                set _limits($fname) $lim
783
784                # set reasonable defaults for
785                # customrangevmin and customrangevmax
786                foreach {min max} $lim break
787                SetMinMaxGauges $min $max
788                set _settings(-customrangemin) $min
789                set _settings(-customrangemax) $max
790
791                continue
792            }
793            foreach {min max} $lim break
794            foreach {fmin fmax} $_limits($fname) break
795            if { ! $_settings(-customrange) } {
796                SetMinMaxGauges $fmin $fmax
797            }
798            if { $fmin > $min } {
799                set fmin $min
800            }
801            if { $fmax < $max } {
802                set fmax $max
803            }
804            set _limits($fname) [list $fmin $fmax]
805        }
806    }
807}
808
809# ----------------------------------------------------------------------
810# USAGE: download coming
811# USAGE: download controls <downloadCommand>
812# USAGE: download now
813#
814# Clients use this method to create a downloadable representation
815# of the plot.  Returns a list of the form {ext string}, where
816# "ext" is the file extension (indicating the type of data) and
817# "string" is the data itself.
818# ----------------------------------------------------------------------
819itcl::body Rappture::VtkIsosurfaceViewer::download {option args} {
820    switch $option {
821        coming {
822            if {[catch {
823                blt::winop snap $itk_component(plotarea) $_image(download)
824            }]} {
825                $_image(download) configure -width 1 -height 1
826                $_image(download) put #000000
827            }
828        }
829        controls {
830            set popup .vtkviewerdownload
831            if { ![winfo exists .vtkviewerdownload] } {
832                set inner [BuildDownloadPopup $popup [lindex $args 0]]
833            } else {
834                set inner [$popup component inner]
835            }
836            set _downloadPopup(image_controls) $inner.image_frame
837            set num [llength [get]]
838            set num [expr {($num == 1) ? "1 result" : "$num results"}]
839            set word [Rappture::filexfer::label downloadWord]
840            $inner.summary configure -text "$word $num in the following format:"
841            update idletasks            ;# Fix initial sizes
842            return $popup
843        }
844        now {
845            set popup .vtkviewerdownload
846            if {[winfo exists .vtkviewerdownload]} {
847                $popup deactivate
848            }
849            switch -- $_downloadPopup(format) {
850                "image" {
851                    return [$this GetImage [lindex $args 0]]
852                }
853                "vtk" {
854                    return [$this GetVtkData [lindex $args 0]]
855                }
856            }
857            return ""
858        }
859        default {
860            error "bad option \"$option\": should be coming, controls, now"
861        }
862    }
863}
864
865# ----------------------------------------------------------------------
866# USAGE: Connect ?<host:port>,<host:port>...?
867#
868# Clients use this method to establish a connection to a new
869# server, or to reestablish a connection to the previous server.
870# Any existing connection is automatically closed.
871# ----------------------------------------------------------------------
872itcl::body Rappture::VtkIsosurfaceViewer::Connect {} {
873    set _hosts [GetServerList "vtkvis"]
874    if { "" == $_hosts } {
875        return 0
876    }
877    set _reset 1
878    set result [VisViewer::Connect $_hosts]
879    if { $result } {
880        if { $_reportClientInfo }  {
881            # Tell the server the viewer, hub, user and session.
882            # Do this immediately on connect before buffering any commands
883            global env
884
885            set info {}
886            set user "???"
887            if { [info exists env(USER)] } {
888                set user $env(USER)
889            }
890            set session "???"
891            if { [info exists env(SESSION)] } {
892                set session $env(SESSION)
893            }
894            lappend info "version" "$Rappture::version"
895            lappend info "build" "$Rappture::build"
896            lappend info "svnurl" "$Rappture::svnurl"
897            lappend info "installdir" "$Rappture::installdir"
898            lappend info "hub" [exec hostname]
899            lappend info "client" "vtkisosurfaceviewer"
900            lappend info "user" $user
901            lappend info "session" $session
902            SendCmd "clientinfo [list $info]"
903        }
904
905        set w [winfo width $itk_component(view)]
906        set h [winfo height $itk_component(view)]
907        EventuallyResize $w $h
908    }
909    return $result
910}
911
912#
913# isconnected --
914#
915#       Indicates if we are currently connected to the visualization server.
916#
917itcl::body Rappture::VtkIsosurfaceViewer::isconnected {} {
918    return [VisViewer::IsConnected]
919}
920
921#
922# disconnect --
923#
924itcl::body Rappture::VtkIsosurfaceViewer::disconnect {} {
925    Disconnect
926    set _reset 1
927}
928
929#
930# Disconnect --
931#
932#       Clients use this method to disconnect from the current rendering
933#       server.
934#
935itcl::body Rappture::VtkIsosurfaceViewer::Disconnect {} {
936    VisViewer::Disconnect
937
938    $_dispatcher cancel !rebuild
939    $_dispatcher cancel !resize
940    $_dispatcher cancel !rotate
941    $_dispatcher cancel !xcutplane
942    $_dispatcher cancel !ycutplane
943    $_dispatcher cancel !zcutplane
944    $_dispatcher cancel !legend
945    # disconnected -- no more data sitting on server
946    array unset _datasets
947    array unset _colormaps
948}
949
950# ----------------------------------------------------------------------
951# USAGE: ReceiveImage -bytes <size> -type <type> -token <token>
952#
953# Invoked automatically whenever the "image" command comes in from
954# the rendering server.  Indicates that binary image data with the
955# specified <size> will follow.
956# ----------------------------------------------------------------------
957itcl::body Rappture::VtkIsosurfaceViewer::ReceiveImage { args } {
958    array set info {
959        -token "???"
960        -bytes 0
961        -type image
962    }
963    array set info $args
964    set bytes [ReceiveBytes $info(-bytes)]
965    if { $info(-type) == "image" } {
966        if 0 {
967            set f [open "last.ppm" "w"]
968            fconfigure $f -encoding binary
969            puts -nonewline $f $bytes
970            close $f
971        }
972        $_image(plot) configure -data $bytes
973        #set time [clock seconds]
974        #set date [clock format $time]
975        #set w [image width $_image(plot)]
976        #set h [image height $_image(plot)]
977        #puts stderr "$date: received image ${w}x${h} image"
978        if { $_start > 0 } {
979            set finish [clock clicks -milliseconds]
980            #puts stderr "round trip time [expr $finish -$_start] milliseconds"
981            set _start 0
982        }
983    } elseif { $info(type) == "print" } {
984        set tag $this-print-$info(-token)
985        set _hardcopy($tag) $bytes
986    }
987}
988
989#
990# ReceiveDataset --
991#
992itcl::body Rappture::VtkIsosurfaceViewer::ReceiveDataset { args } {
993    if { ![isconnected] } {
994        return
995    }
996    set option [lindex $args 0]
997    switch -- $option {
998        "scalar" {
999            set option [lindex $args 1]
1000            switch -- $option {
1001                "world" {
1002                    foreach { x y z value tag } [lrange $args 2 end] break
1003                }
1004                "pixel" {
1005                    foreach { x y value tag } [lrange $args 2 end] break
1006                }
1007            }
1008        }
1009        "vector" {
1010            set option [lindex $args 1]
1011            switch -- $option {
1012                "world" {
1013                    foreach { x y z vx vy vz tag } [lrange $args 2 end] break
1014                }
1015                "pixel" {
1016                    foreach { x y vx vy vz tag } [lrange $args 2 end] break
1017                }
1018            }
1019        }
1020        "names" {
1021            foreach { name } [lindex $args 1] {
1022                #puts stderr "Dataset: $name"
1023            }
1024        }
1025        default {
1026            error "unknown dataset option \"$option\" from server"
1027        }
1028    }
1029}
1030
1031# ----------------------------------------------------------------------
1032# USAGE: Rebuild
1033#
1034# Called automatically whenever something changes that affects the
1035# data in the widget.  Clears any existing data and rebuilds the
1036# widget to display new data.
1037# ----------------------------------------------------------------------
1038itcl::body Rappture::VtkIsosurfaceViewer::Rebuild {} {
1039    set w [winfo width $itk_component(view)]
1040    set h [winfo height $itk_component(view)]
1041    if { $w < 2 || $h < 2 } {
1042        update
1043        $_dispatcher event -idle !rebuild
1044        return
1045    }
1046
1047    # Turn on buffering of commands to the server.  We don't want to
1048    # be preempted by a server disconnect/reconnect (which automatically
1049    # generates a new call to Rebuild).
1050    StartBufferingCommands
1051
1052    if { $_reset } {
1053        set _width $w
1054        set _height $h
1055        $_arcball resize $w $h
1056        DoResize
1057
1058        # Reset the camera and other view parameters
1059        $_arcball quaternion [ViewToQuaternion]
1060        InitSettings -ortho
1061        DoRotate
1062        PanCamera
1063        set _first ""
1064        InitSettings -background \
1065            -xgrid -ygrid -zgrid -axismode \
1066            -axesvisible -axislabels -axisminorticks
1067        #SendCmd "axis lformat all %g"
1068        StopBufferingCommands
1069        SendCmd "imgflush"
1070        StartBufferingCommands
1071    }
1072    set _first ""
1073    SendCmd "dataset visible 0"
1074    eval scale $_dlist
1075    foreach dataobj [get -objects] {
1076        if { [info exists _obj2ovride($dataobj-raise)] &&  $_first == "" } {
1077            set _first $dataobj
1078            SetCurrentFieldName $dataobj
1079        }
1080        foreach comp [$dataobj components] {
1081            set tag $dataobj-$comp
1082            if { ![info exists _datasets($tag)] } {
1083                set bytes [$dataobj vtkdata $comp]
1084                if 0 {
1085                    set f [open "/tmp/isosurface.vtk" "w"]
1086                    fconfigure $f -translation binary -encoding binary
1087                    puts -nonewline $f $bytes
1088                    close $f
1089                }
1090                set length [string length $bytes]
1091                if { $_reportClientInfo }  {
1092                    set info {}
1093                    lappend info "tool_id"       [$dataobj hints toolid]
1094                    lappend info "tool_name"     [$dataobj hints toolname]
1095                    lappend info "tool_title"    [$dataobj hints tooltitle]
1096                    lappend info "tool_command"  [$dataobj hints toolcommand]
1097                    lappend info "tool_revision" [$dataobj hints toolrevision]
1098                    lappend info "dataset_label" [$dataobj hints label]
1099                    lappend info "dataset_size"  $length
1100                    lappend info "dataset_tag"   $tag
1101                    SendCmd "clientinfo [list $info]"
1102                }
1103                SendCmd "dataset add $tag data follows $length"
1104                SendData $bytes
1105                set _datasets($tag) 1
1106                SetObjectStyle $dataobj $comp
1107            }
1108            if { [info exists _obj2ovride($dataobj-raise)] } {
1109                SendCmd "contour3d visible 1 $tag"
1110            }
1111        }
1112    }
1113
1114    InitSettings -cutplanesvisible -isosurfacevisible -outline
1115    if { $_reset } {
1116        # These are settings that rely on a dataset being loaded.
1117        InitSettings \
1118            -isosurfacelighting \
1119            -field \
1120            -range \
1121            -isosurfacevisible \
1122            -isosurfaceedges -isosurfacelighting -isosurfaceopacity \
1123            -isosurfacewireframe \
1124            -cutplanesvisible \
1125            -xcutplaneposition -ycutplaneposition -zcutplaneposition \
1126            -xcutplanevisible -ycutplanevisible -zcutplanevisible \
1127            -cutplanepreinterp -numcontours
1128
1129        Zoom reset
1130        foreach axis { x y z } {
1131            set label ""
1132            if { $_first != "" } {
1133                set label [$_first hints ${axis}label]
1134            }
1135            if { $label == "" } {
1136                set label [string toupper $axis]
1137            }
1138            # May be a space in the axis label
1139            SendCmd [list axis name $axis $label]
1140        }
1141        if { [array size _fields] < 2 } {
1142            catch {blt::table forget $itk_component(field) $itk_component(field_l)}
1143        }
1144        set _reset 0
1145    }
1146    # Redraw the legend even if we're using the same colormap. The position
1147    # of the isolines may have changed because the range of data changed.
1148    DrawLegend
1149
1150    # Actually write the commands to the server socket.  If it fails, we don't
1151    # care.  We're finished here.
1152    blt::busy hold $itk_component(hull)
1153    StopBufferingCommands;              # Turn off buffering and send commands.
1154    blt::busy release $itk_component(hull)
1155}
1156
1157# ----------------------------------------------------------------------
1158# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1159#
1160# Returns a list of server IDs for the current datasets being displayed.  This
1161# is normally a single ID, but it might be a list of IDs if the current data
1162# object has multiple components.
1163# ----------------------------------------------------------------------
1164itcl::body Rappture::VtkIsosurfaceViewer::CurrentDatasets {args} {
1165    set flag [lindex $args 0]
1166    switch -- $flag {
1167        "-all" {
1168            if { [llength $args] > 1 } {
1169                error "CurrentDatasets: can't specify dataobj after \"-all\""
1170            }
1171            set dlist [get -objects]
1172        }
1173        "-visible" {
1174            if { [llength $args] > 1 } {
1175                set dlist {}
1176                set args [lrange $args 1 end]
1177                foreach dataobj $args {
1178                    if { [info exists _obj2ovride($dataobj-raise)] } {
1179                        lappend dlist $dataobj
1180                    }
1181                }
1182            } else {
1183                set dlist [get -visible]
1184            }
1185        }
1186        default {
1187            set dlist $args
1188        }
1189    }
1190    set rlist ""
1191    foreach dataobj $dlist {
1192        foreach comp [$dataobj components] {
1193            set tag $dataobj-$comp
1194            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1195                lappend rlist $tag
1196            }
1197        }
1198    }
1199    return $rlist
1200}
1201
1202# ----------------------------------------------------------------------
1203# USAGE: Zoom in
1204# USAGE: Zoom out
1205# USAGE: Zoom reset
1206#
1207# Called automatically when the user clicks on one of the zoom
1208# controls for this widget.  Changes the zoom for the current view.
1209# ----------------------------------------------------------------------
1210itcl::body Rappture::VtkIsosurfaceViewer::Zoom {option} {
1211    switch -- $option {
1212        "in" {
1213            set _view(-zoom) [expr {$_view(-zoom)*1.25}]
1214            SendCmd "camera zoom $_view(-zoom)"
1215        }
1216        "out" {
1217            set _view(-zoom) [expr {$_view(-zoom)*0.8}]
1218            SendCmd "camera zoom $_view(-zoom)"
1219        }
1220        "reset" {
1221            array set _view {
1222                -qw      0.853553
1223                -qx      -0.353553
1224                -qy      0.353553
1225                -qz      0.146447
1226                -xpan    0
1227                -ypan    0
1228                -zoom    1.0
1229            }
1230            if { $_first != "" } {
1231                set location [$_first hints camera]
1232                if { $location != "" } {
1233                    array set _view $location
1234                }
1235            }
1236            $_arcball quaternion [ViewToQuaternion]
1237            DoRotate
1238            SendCmd "camera reset"
1239        }
1240    }
1241}
1242
1243itcl::body Rappture::VtkIsosurfaceViewer::PanCamera {} {
1244    set x $_view(-xpan)
1245    set y $_view(-ypan)
1246    SendCmd "camera pan $x $y"
1247}
1248
1249# ----------------------------------------------------------------------
1250# USAGE: Rotate click <x> <y>
1251# USAGE: Rotate drag <x> <y>
1252# USAGE: Rotate release <x> <y>
1253#
1254# Called automatically when the user clicks/drags/releases in the
1255# plot area.  Moves the plot according to the user's actions.
1256# ----------------------------------------------------------------------
1257itcl::body Rappture::VtkIsosurfaceViewer::Rotate {option x y} {
1258    switch -- $option {
1259        "click" {
1260            $itk_component(view) configure -cursor fleur
1261            set _click(x) $x
1262            set _click(y) $y
1263        }
1264        "drag" {
1265            if {[array size _click] == 0} {
1266                Rotate click $x $y
1267            } else {
1268                set w [winfo width $itk_component(view)]
1269                set h [winfo height $itk_component(view)]
1270                if {$w <= 0 || $h <= 0} {
1271                    return
1272                }
1273
1274                if {[catch {
1275                    # this fails sometimes for no apparent reason
1276                    set dx [expr {double($x-$_click(x))/$w}]
1277                    set dy [expr {double($y-$_click(y))/$h}]
1278                }]} {
1279                    return
1280                }
1281                if { $dx == 0 && $dy == 0 } {
1282                    return
1283                }
1284                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1285                EventuallyRotate $q
1286                set _click(x) $x
1287                set _click(y) $y
1288            }
1289        }
1290        "release" {
1291            Rotate drag $x $y
1292            $itk_component(view) configure -cursor ""
1293            catch {unset _click}
1294        }
1295        default {
1296            error "bad option \"$option\": should be click, drag, release"
1297        }
1298    }
1299}
1300
1301itcl::body Rappture::VtkIsosurfaceViewer::Pick {x y} {
1302    foreach tag [CurrentDatasets -visible] {
1303        SendCmd "dataset getscalar pixel $x $y $tag"
1304    }
1305}
1306
1307# ----------------------------------------------------------------------
1308# USAGE: $this Pan click x y
1309#        $this Pan drag x y
1310#        $this Pan release x y
1311#
1312# Called automatically when the user clicks on one of the zoom
1313# controls for this widget.  Changes the zoom for the current view.
1314# ----------------------------------------------------------------------
1315itcl::body Rappture::VtkIsosurfaceViewer::Pan {option x y} {
1316    switch -- $option {
1317        "set" {
1318            set w [winfo width $itk_component(view)]
1319            set h [winfo height $itk_component(view)]
1320            set x [expr $x / double($w)]
1321            set y [expr $y / double($h)]
1322            set _view(-xpan) [expr $_view(-xpan) + $x]
1323            set _view(-ypan) [expr $_view(-ypan) + $y]
1324            PanCamera
1325            return
1326        }
1327        "click" {
1328            set _click(x) $x
1329            set _click(y) $y
1330            $itk_component(view) configure -cursor hand1
1331        }
1332        "drag" {
1333            if { ![info exists _click(x)] } {
1334                set _click(x) $x
1335            }
1336            if { ![info exists _click(y)] } {
1337                set _click(y) $y
1338            }
1339            set w [winfo width $itk_component(view)]
1340            set h [winfo height $itk_component(view)]
1341            set dx [expr ($_click(x) - $x)/double($w)]
1342            set dy [expr ($_click(y) - $y)/double($h)]
1343            set _click(x) $x
1344            set _click(y) $y
1345            set _view(-xpan) [expr $_view(-xpan) - $dx]
1346            set _view(-ypan) [expr $_view(-ypan) - $dy]
1347            PanCamera
1348        }
1349        "release" {
1350            Pan drag $x $y
1351            $itk_component(view) configure -cursor ""
1352        }
1353        default {
1354            error "unknown option \"$option\": should set, click, drag, or release"
1355        }
1356    }
1357}
1358
1359# ----------------------------------------------------------------------
1360# USAGE: InitSettings <what> ?<value>?
1361#
1362# Used internally to update rendering settings whenever parameters
1363# change in the popup settings panel.  Sends the new settings off
1364# to the back end.
1365# ----------------------------------------------------------------------
1366itcl::body Rappture::VtkIsosurfaceViewer::InitSettings { args } {
1367    foreach spec $args {
1368        if { [info exists _settings($_first-$spec)] } {
1369            # Reset global setting with dataobj specific setting
1370            set _settings($spec) $_settings($_first-$spec)
1371        }
1372        AdjustSetting $spec
1373    }
1374}
1375
1376#
1377# AdjustSetting --
1378#
1379#       Changes/updates a specific setting in the widget.  There are
1380#       usually user-setable option.  Commands are sent to the render
1381#       server.
1382#
1383itcl::body Rappture::VtkIsosurfaceViewer::AdjustSetting {what {value ""}} {
1384    if { ![isconnected] } {
1385        return
1386    }
1387    switch -- $what {
1388        "-axesvisible" {
1389            set bool $_settings($what)
1390            SendCmd "axis visible all $bool"
1391        }
1392        "-axislabels" {
1393            set bool $_settings($what)
1394            SendCmd "axis labels all $bool"
1395        }
1396        "-axisminorticks" {
1397            set bool $_settings($what)
1398            SendCmd "axis minticks all $bool"
1399        }
1400        "-axismode" {
1401            set mode [$itk_component(axisMode) value]
1402            set mode [$itk_component(axisMode) translate $mode]
1403            set _settings($what) $mode
1404            SendCmd "axis flymode $mode"
1405        }
1406        "-background" {
1407            set bgcolor [$itk_component(background) value]
1408            array set fgcolors {
1409                "black" "white"
1410                "white" "black"
1411                "grey"  "black"
1412            }
1413            configure -plotbackground $bgcolor \
1414                -plotforeground $fgcolors($bgcolor)
1415            $itk_component(view) delete "legend"
1416            DrawLegend
1417        }
1418        "-cutplaneedges" {
1419            set _changed($what) 1
1420            set bool $_settings($what)
1421            SendCmd "cutplane edges $bool"
1422        }
1423        "-cutplanelighting" {
1424            set _changed($what) 1
1425            set bool $_settings($what)
1426            SendCmd "cutplane lighting $bool"
1427        }
1428        "-cutplaneopacity" {
1429            set _changed($what) 1
1430            set _settings($what) [expr $_widget($what) * 0.01]
1431            SendCmd "cutplane opacity $_settings($what)"
1432        }
1433        "-cutplanepreinterp" {
1434            set _changed($what) 1
1435            set bool $_settings($what)
1436            SendCmd "cutplane preinterp $bool"
1437        }
1438        "-cutplanesvisible" {
1439            set _changed($what) 1
1440            set bool $_settings($what)
1441            SendCmd "cutplane visible 0"
1442            if { $bool } {
1443                foreach tag [CurrentDatasets -visible] {
1444                    SendCmd "cutplane visible $bool $tag"
1445                }
1446            }
1447            if { $bool } {
1448                Rappture::Tooltip::for $itk_component(cutplane) \
1449                    "Hide the cutplanes"
1450            } else {
1451                Rappture::Tooltip::for $itk_component(cutplane) \
1452                    "Show the cutplanes"
1453            }
1454        }
1455        "-cutplanewireframe" {
1456            set _changed($what) 1
1457            set bool $_settings($what)
1458            SendCmd "cutplane wireframe $bool"
1459        }
1460        "-colormap" {
1461            set _changed($what) 1
1462            StartBufferingCommands
1463            set color [$itk_component(colormap) value]
1464            set _settings($what) $color
1465            if { $color == "none" } {
1466                if { $_settings(-colormapvisible) } {
1467                    SendCmd "contour3d colormode constant {}"
1468                    set _settings(-colormapvisible) 0
1469                }
1470            } else {
1471                if { !$_settings(-colormapvisible) } {
1472                    SendCmd "contour3d colormode $_colorMode $_curFldName"
1473                    set _settings(-colormapvisible) 1
1474                }
1475                SetCurrentColormap $color
1476            }
1477            StopBufferingCommands
1478            EventuallyRequestLegend
1479        }
1480        "-field" {
1481            set label [$itk_component(field) value]
1482            set fname [$itk_component(field) translate $label]
1483            set _settings($what) $fname
1484            if { [info exists _fields($fname)] } {
1485                foreach { label units components } $_fields($fname) break
1486                if { $components > 1 } {
1487                    set _colorMode vmag
1488                } else {
1489                    set _colorMode scalar
1490                }
1491                set _curFldName $fname
1492                set _curFldLabel $label
1493            } else {
1494                puts stderr "unknown field \"$fname\""
1495                return
1496            }
1497            SendCmd "dataset scalar $_curFldName"
1498            if { ![info exists _limits($_curFldName)] } {
1499                SendCmd "dataset maprange all"
1500            } else {
1501                if { $_settings(-customrange) } {
1502                    set vmin [$itk_component(min) value]
1503                    set vmax [$itk_component(max) value]
1504                } else {
1505                    foreach { vmin vmax } $_limits($_curFldName) break
1506                    # set the min / max gauges with limits from the field
1507                    # the legend's min and max text will be updated
1508                    # when the legend is redrawn in DrawLegend
1509                    SetMinMaxGauges $vmin $vmax
1510                }
1511                SendCmd "dataset maprange explicit $vmin $vmax $_curFldName"
1512            }
1513            SendCmd "cutplane colormode $_colorMode $_curFldName"
1514            SendCmd "contour3d colormode $_colorMode $_curFldName"
1515            SendCmd "camera reset"
1516            GenerateContourList
1517            DrawLegend
1518        }
1519        "-isolinecolor" {
1520            set color [$itk_component(isolineColor) value]
1521            set _settings($what) $color
1522            DrawLegend
1523        }
1524        "-isosurfaceedges" {
1525            set _changed($what) 1
1526            set bool $_settings($what)
1527            SendCmd "contour3d edges $bool"
1528        }
1529        "-isosurfacelighting" {
1530            set _changed($what) 1
1531            set bool $_settings($what)
1532            SendCmd "contour3d lighting $bool"
1533        }
1534        "-isosurfaceopacity" {
1535            set _changed($what) 1
1536            set _settings($what) [expr $_widget($what) * 0.01]
1537            SendCmd "contour3d opacity $_settings($what)"
1538        }
1539        "-isosurfacevisible" {
1540            set _changed($what) 1
1541            set bool $_settings($what)
1542            SendCmd "contour3d visible 0"
1543            if { $bool } {
1544                foreach tag [CurrentDatasets -visible] {
1545                    SendCmd "contour3d visible $bool $tag"
1546                }
1547                Rappture::Tooltip::for $itk_component(contour) \
1548                    "Hide the isosurface"
1549            } else {
1550                Rappture::Tooltip::for $itk_component(contour) \
1551                    "Show the isosurface"
1552            }
1553        }
1554        "-isosurfacewireframe" {
1555            set _changed($what) 1
1556            set bool $_settings($what)
1557            SendCmd "contour3d wireframe $bool"
1558        }
1559        "-legendvisible" {
1560            if { !$_settings($what) } {
1561                $itk_component(view) delete legend
1562            }
1563            DrawLegend
1564        }
1565        "-numcontours" {
1566            set _changed($what) 1
1567            set _settings($what) [$itk_component(numcontours) value]
1568            if { $_contourList(numLevels) != $_settings($what) } {
1569                set _contourList(numLevels) $_settings($what)
1570                EventuallyChangeContourLevels
1571            }
1572        }
1573        "-ortho" {
1574            set bool $_view($what)
1575            if { $bool } {
1576                SendCmd "camera mode ortho"
1577            } else {
1578                SendCmd "camera mode persp"
1579            }
1580        }
1581        "-outline" {
1582            set _changed($what) 1
1583            set bool $_settings($what)
1584            SendCmd "outline visible 0"
1585            if { $bool } {
1586                foreach tag [CurrentDatasets -visible] {
1587                    SendCmd "outline visible $bool $tag"
1588                }
1589            }
1590        }
1591        "-range" {
1592            if { $_settings(-customrange) } {
1593                set vmin [$itk_component(min) value]
1594                set vmax [$itk_component(max) value]
1595            } else {
1596                foreach { vmin vmax } $_limits($_curFldName) break
1597            }
1598            GenerateContourList
1599            SendCmd [list contour3d contourlist $_contourList(values)]
1600            SendCmd "dataset maprange explicit $vmin $vmax $_curFldName"
1601            DrawLegend
1602        }
1603        "-xcutplanevisible" - "-ycutplanevisible" - "-zcutplanevisible" {
1604            set _changed($what) 1
1605            set axis [string tolower [string range $what 1 1]]
1606            set bool $_settings($what)
1607            if { $bool } {
1608                $itk_component(${axis}position) configure -state normal \
1609                    -troughcolor white
1610            } else {
1611                $itk_component(${axis}position) configure -state disabled \
1612                    -troughcolor grey82
1613            }
1614            SendCmd "cutplane axis $axis $bool"
1615        }
1616        "-xcutplaneposition" - "-ycutplaneposition" - "-zcutplaneposition" {
1617            set _changed($what) 1
1618            set axis [string tolower [string range $what 1 1]]
1619            set pos [expr $_settings($what) * 0.01]
1620            SendCmd "cutplane slice ${axis} ${pos}"
1621            set _cutplanePending 0
1622        }
1623        "-xgrid" - "-ygrid" - "-zgrid" {
1624            set axis [string tolower [string range $what 1 1]]
1625            set bool $_settings($what)
1626            SendCmd "axis grid $axis $bool"
1627        }
1628        default {
1629            error "don't know how to fix $what"
1630        }
1631    }
1632}
1633
1634#
1635# RequestLegend --
1636#
1637#       Request a new legend from the server.  The size of the legend
1638#       is determined from the height of the canvas.
1639#
1640# This should be called when
1641#   1.  A new current colormap is set.
1642#   2.  Window is resized.
1643#   3.  The limits of the data have changed.  (Just need a redraw).
1644#   4.  Number of isolines have changed. (Just need a redraw).
1645#   5.  Legend becomes visible (Just need a redraw).
1646#
1647itcl::body Rappture::VtkIsosurfaceViewer::RequestLegend {} {
1648    set _legendPending 0
1649    if { ![info exists _fields($_curFldName)] } {
1650        return
1651    }
1652    set fname $_curFldName
1653    set font "Arial 8"
1654    set lineht [font metrics $font -linespace]
1655    set w 12
1656    set h [expr {$_height - 2 * ($lineht + 2)}]
1657    if { $h < 1 } {
1658        return
1659    }
1660    if { [string match "component*" $fname] } {
1661        set title ""
1662    } else {
1663        if { [info exists _fields($fname)] } {
1664            foreach { title units } $_fields($fname) break
1665            if { $units != "" } {
1666                set title [format "%s (%s)" $title $units]
1667            }
1668        } else {
1669            set title $fname
1670        }
1671    }
1672    # If there's a title too, subtract one more line
1673    if { $title != "" } {
1674        incr h -$lineht
1675    }
1676    # Set the legend on the first isosurface dataset.
1677    if { $_currentColormap != ""  } {
1678        set cmap $_currentColormap
1679        if { ![info exists _colormaps($cmap)] } {
1680            BuildColormap $cmap
1681            set _colormaps($cmap) 1
1682        }
1683        #SendCmd "legend $cmap scalar $_curFldName {} $w $h 0"
1684        SendCmd "legend2 $cmap $w $h"
1685    }
1686}
1687
1688# ----------------------------------------------------------------------
1689# CONFIGURATION OPTION: -plotbackground
1690# ----------------------------------------------------------------------
1691itcl::configbody Rappture::VtkIsosurfaceViewer::plotbackground {
1692    if { [isconnected] } {
1693        set rgb [Color2RGB $itk_option(-plotbackground)]
1694        SendCmd "screen bgcolor $rgb"
1695    }
1696}
1697
1698# ----------------------------------------------------------------------
1699# CONFIGURATION OPTION: -plotforeground
1700# ----------------------------------------------------------------------
1701itcl::configbody Rappture::VtkIsosurfaceViewer::plotforeground {
1702    if { [isconnected] } {
1703        set rgb [Color2RGB $itk_option(-plotforeground)]
1704        SendCmd "axis color all $rgb"
1705        SendCmd "outline color $rgb"
1706        SendCmd "cutplane color $rgb"
1707    }
1708}
1709
1710itcl::body Rappture::VtkIsosurfaceViewer::BuildIsosurfaceTab {} {
1711
1712    set fg [option get $itk_component(hull) font Font]
1713    #set bfg [option get $itk_component(hull) boldFont Font]
1714
1715    set inner [$itk_component(main) insert end \
1716        -title "Isosurface Settings" \
1717        -icon [Rappture::icon volume-on]]
1718    $inner configure -borderwidth 4
1719
1720    checkbutton $inner.contour \
1721        -text "Isosurfaces" \
1722        -variable [itcl::scope _settings(-isosurfacevisible)] \
1723        -command [itcl::code $this AdjustSetting -isosurfacevisible] \
1724        -font "Arial 9"
1725
1726    checkbutton $inner.wireframe \
1727        -text "Wireframe" \
1728        -variable [itcl::scope _settings(-isosurfacewireframe)] \
1729        -command [itcl::code $this AdjustSetting -isosurfacewireframe] \
1730        -font "Arial 9"
1731
1732    checkbutton $inner.lighting \
1733        -text "Enable Lighting" \
1734        -variable [itcl::scope _settings(-isosurfacelighting)] \
1735        -command [itcl::code $this AdjustSetting -isosurfacelighting] \
1736        -font "Arial 9"
1737
1738    checkbutton $inner.edges \
1739        -text "Edges" \
1740        -variable [itcl::scope _settings(-isosurfaceedges)] \
1741        -command [itcl::code $this AdjustSetting -isosurfaceedges] \
1742        -font "Arial 9"
1743
1744    checkbutton $inner.outline \
1745        -text "Outline" \
1746        -variable [itcl::scope _settings(-outline)] \
1747        -command [itcl::code $this AdjustSetting -outline] \
1748        -font "Arial 9"
1749
1750    checkbutton $inner.legend \
1751        -text "Legend" \
1752        -variable [itcl::scope _settings(-legendvisible)] \
1753        -command [itcl::code $this AdjustSetting -legendvisible] \
1754        -font "Arial 9"
1755
1756    label $inner.linecolor_l -text "Isolines" -font "Arial 9"
1757    itk_component add isolineColor {
1758        Rappture::Combobox $inner.linecolor -width 10 -editable 0
1759    }
1760    $inner.linecolor choices insert end \
1761        "black"              "black"            \
1762        "blue"               "blue"             \
1763        "cyan"               "cyan"             \
1764        "green"              "green"            \
1765        "grey"               "grey"             \
1766        "magenta"            "magenta"          \
1767        "orange"             "orange"           \
1768        "red"                "red"              \
1769        "white"              "white"            \
1770        "none"               "none"
1771
1772    $itk_component(isolineColor) value "white"
1773    bind $inner.linecolor <<Value>> \
1774        [itcl::code $this AdjustSetting -isolinecolor]
1775
1776    label $inner.background_l -text "Background" -font "Arial 9"
1777    itk_component add background {
1778        Rappture::Combobox $inner.background -width 10 -editable 0
1779    }
1780    $inner.background choices insert end \
1781        "black"              "black"            \
1782        "white"              "white"            \
1783        "grey"               "grey"
1784
1785    $itk_component(background) value $_settings(-background)
1786    bind $inner.background <<Value>> \
1787        [itcl::code $this AdjustSetting -background]
1788
1789    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1790    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1791        -variable [itcl::scope _widget(-isosurfaceopacity)] \
1792        -width 10 \
1793        -showvalue off \
1794        -command [itcl::code $this AdjustSetting -isosurfaceopacity]
1795    $inner.opacity set [expr $_settings(-isosurfaceopacity) * 100.0]
1796
1797    itk_component add field_l {
1798        label $inner.field_l -text "Field" -font "Arial 9"
1799    } {
1800        ignore -font
1801    }
1802    itk_component add field {
1803        Rappture::Combobox $inner.field -width 10 -editable 0
1804    }
1805    bind $inner.field <<Value>> \
1806        [itcl::code $this AdjustSetting -field]
1807
1808    label $inner.colormap_l -text "Colormap" -font "Arial 9"
1809    itk_component add colormap {
1810        Rappture::Combobox $inner.colormap -width 10 -editable 0
1811    }
1812    $inner.colormap choices insert end [GetColormapList]
1813
1814    $itk_component(colormap) value "BCGYR"
1815    bind $inner.colormap <<Value>> \
1816        [itcl::code $this AdjustSetting -colormap]
1817
1818    label $inner.numcontours_l -text "Number of Isosurfaces" -font "Arial 9"
1819    itk_component add numcontours {
1820        Rappture::Spinint $inner.numcontours \
1821            -min 0 -max 50 -font "arial 9"
1822    }
1823    $itk_component(numcontours) value $_settings(-numcontours)
1824    bind $itk_component(numcontours) <<Value>> \
1825        [itcl::code $this AdjustSetting -numcontours]
1826
1827
1828    # add widgets for setting a custom range on the legend
1829
1830    itk_component add crange {
1831        checkbutton $inner.crange \
1832            -text "Use Custom Range:" \
1833            -variable [itcl::scope _settings(-customrange)] \
1834            -command [itcl::code $this ToggleCustomRange] \
1835            -font "Arial 9"
1836    }
1837
1838    itk_component add l_min {
1839        label $inner.l_min -text "Min" -font "Arial 9"
1840    }
1841    itk_component add min {
1842        Rappture::Gauge $inner.min -font "Arial 9" \
1843            -validatecommand [itcl::code $this LegendRangeValidate "" vmin]
1844    }
1845    bind $itk_component(min) <<Value>> \
1846        [itcl::code $this AdjustSetting -range]
1847
1848    itk_component add l_max {
1849        label $inner.l_max -text "Max" -font "Arial 9"
1850    }
1851    itk_component add max {
1852        Rappture::Gauge $inner.max -font "Arial 9" \
1853            -validatecommand [itcl::code $this LegendRangeValidate "" vmax]
1854    }
1855    bind $itk_component(max) <<Value>> \
1856        [itcl::code $this AdjustSetting -range]
1857
1858    $itk_component(min) configure -state disabled
1859    $itk_component(max) configure -state disabled
1860
1861
1862    blt::table $inner \
1863        0,0 $inner.field_l   -anchor w -pady 2  \
1864        0,1 $inner.field     -anchor w -pady 2  -fill x \
1865        1,0 $inner.colormap_l -anchor w -pady 2  \
1866        1,1 $inner.colormap   -anchor w -pady 2  -fill x \
1867        2,0 $inner.linecolor_l  -anchor w -pady 2  \
1868        2,1 $inner.linecolor    -anchor w -pady 2 -fill x  \
1869        3,0 $inner.background_l -anchor w -pady 2 \
1870        3,1 $inner.background -anchor w -pady 2  -fill x \
1871        4,0 $inner.numcontours_l -anchor w -pady 2 \
1872        4,1 $inner.numcontours -anchor w -pady 2 \
1873        5,0 $inner.wireframe -anchor w -pady 2 -cspan 2 \
1874        6,0 $inner.lighting  -anchor w -pady 2 -cspan 2 \
1875        7,0 $inner.edges     -anchor w -pady 2 -cspan 2 \
1876        8,0 $inner.outline   -anchor w -pady 2 -cspan 2 \
1877        9,0 $inner.legend    -anchor w -pady 2 \
1878        10,0 $inner.opacity_l -anchor w -pady 2 \
1879        10,1 $inner.opacity   -fill x   -pady 2 -fill x \
1880        11,0 $inner.crange    -anchor w -pady 2 -cspan 2 \
1881        12,0 $inner.l_min     -anchor w -pady 2 \
1882        12,1 $inner.min       -anchor w -pady 2 -fill x \
1883        13,0 $inner.l_max     -anchor w -pady 2 \
1884        13,1 $inner.max       -anchor w -pady 2 -fill x \
1885
1886    blt::table configure $inner r* c* -resize none
1887    blt::table configure $inner r14 c1 -resize expand
1888}
1889
1890itcl::body Rappture::VtkIsosurfaceViewer::BuildAxisTab {} {
1891
1892    set fg [option get $itk_component(hull) font Font]
1893    #set bfg [option get $itk_component(hull) boldFont Font]
1894
1895    set inner [$itk_component(main) insert end \
1896        -title "Axis Settings" \
1897        -icon [Rappture::icon axis2]]
1898    $inner configure -borderwidth 4
1899
1900    checkbutton $inner.visible \
1901        -text "Axes" \
1902        -variable [itcl::scope _settings(-axesvisible)] \
1903        -command [itcl::code $this AdjustSetting -axesvisible] \
1904        -font "Arial 9"
1905
1906    checkbutton $inner.labels \
1907        -text "Axis Labels" \
1908        -variable [itcl::scope _settings(-axislabels)] \
1909        -command [itcl::code $this AdjustSetting -axislabels] \
1910        -font "Arial 9"
1911    label $inner.grid_l -text "Grid" -font "Arial 9"
1912    checkbutton $inner.xgrid \
1913        -text "X" \
1914        -variable [itcl::scope _settings(-xgrid)] \
1915        -command [itcl::code $this AdjustSetting -xgrid] \
1916        -font "Arial 9"
1917    checkbutton $inner.ygrid \
1918        -text "Y" \
1919        -variable [itcl::scope _settings(-ygrid)] \
1920        -command [itcl::code $this AdjustSetting -ygrid] \
1921        -font "Arial 9"
1922    checkbutton $inner.zgrid \
1923        -text "Z" \
1924        -variable [itcl::scope _settings(-zgrid)] \
1925        -command [itcl::code $this AdjustSetting -zgrid] \
1926        -font "Arial 9"
1927    checkbutton $inner.minorticks \
1928        -text "Minor Ticks" \
1929        -variable [itcl::scope _settings(-axisminorticks)] \
1930        -command [itcl::code $this AdjustSetting -axisminorticks] \
1931        -font "Arial 9"
1932
1933    label $inner.mode_l -text "Mode" -font "Arial 9"
1934
1935    itk_component add axisMode {
1936        Rappture::Combobox $inner.mode -width 10 -editable 0
1937    }
1938    $inner.mode choices insert end \
1939        "static_triad"    "static" \
1940        "closest_triad"   "closest" \
1941        "furthest_triad"  "farthest" \
1942        "outer_edges"     "outer"
1943    $itk_component(axisMode) value $_settings(-axismode)
1944    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting -axismode]
1945
1946    blt::table $inner \
1947        0,0 $inner.visible -anchor w -cspan 4 \
1948        1,0 $inner.labels  -anchor w -cspan 4 \
1949        2,0 $inner.minorticks  -anchor w -cspan 4 \
1950        4,0 $inner.grid_l  -anchor w \
1951        4,1 $inner.xgrid   -anchor w \
1952        4,2 $inner.ygrid   -anchor w \
1953        4,3 $inner.zgrid   -anchor w \
1954        5,0 $inner.mode_l  -anchor w -padx { 2 0 } \
1955        5,1 $inner.mode    -fill x   -cspan 3
1956
1957    blt::table configure $inner r* c* -resize none
1958    blt::table configure $inner r7 c6 -resize expand
1959    blt::table configure $inner r3 -height 0.125i
1960}
1961
1962
1963itcl::body Rappture::VtkIsosurfaceViewer::BuildCameraTab {} {
1964    set inner [$itk_component(main) insert end \
1965        -title "Camera Settings" \
1966        -icon [Rappture::icon camera]]
1967    $inner configure -borderwidth 4
1968
1969    label $inner.view_l -text "view" -font "Arial 9"
1970    set f [frame $inner.view]
1971    foreach side { front back left right top bottom } {
1972        button $f.$side  -image [Rappture::icon view$side] \
1973            -command [itcl::code $this SetOrientation $side]
1974        Rappture::Tooltip::for $f.$side "Change the view to $side"
1975        pack $f.$side -side left
1976    }
1977
1978    blt::table $inner \
1979        0,0 $inner.view_l -anchor e -pady 2 \
1980        0,1 $inner.view -anchor w -pady 2
1981    blt::table configure $inner r0 -resize none
1982
1983    set labels { qx qy qz qw xpan ypan zoom }
1984    set row 1
1985    foreach tag $labels {
1986        label $inner.${tag}label -text $tag -font "Arial 9"
1987        entry $inner.${tag} -font "Arial 9"  -bg white \
1988            -textvariable [itcl::scope _view(-$tag)]
1989        bind $inner.${tag} <Return> \
1990            [itcl::code $this camera set -${tag}]
1991        bind $inner.${tag} <KP_Enter> \
1992            [itcl::code $this camera set -${tag}]
1993        blt::table $inner \
1994            $row,0 $inner.${tag}label -anchor e -pady 2 \
1995            $row,1 $inner.${tag} -anchor w -pady 2
1996        blt::table configure $inner r$row -resize none
1997        incr row
1998    }
1999    checkbutton $inner.ortho \
2000        -text "Orthographic Projection" \
2001        -variable [itcl::scope _view(-ortho)] \
2002        -command [itcl::code $this AdjustSetting -ortho] \
2003        -font "Arial 9"
2004    blt::table $inner \
2005            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
2006    blt::table configure $inner r$row -resize none
2007    incr row
2008
2009    blt::table configure $inner c* -resize none
2010    blt::table configure $inner c2 -resize expand
2011    blt::table configure $inner r$row -resize expand
2012}
2013
2014itcl::body Rappture::VtkIsosurfaceViewer::BuildCutplaneTab {} {
2015
2016    set fg [option get $itk_component(hull) font Font]
2017
2018    set inner [$itk_component(main) insert end \
2019        -title "Cutplane Settings" \
2020        -icon [Rappture::icon cutbutton]]
2021
2022    $inner configure -borderwidth 4
2023
2024    checkbutton $inner.visible \
2025        -text "Cutplanes" \
2026        -variable [itcl::scope _settings(-cutplanesvisible)] \
2027        -command [itcl::code $this AdjustSetting -cutplanesvisible] \
2028        -font "Arial 9"
2029
2030    checkbutton $inner.wireframe \
2031        -text "Wireframe" \
2032        -variable [itcl::scope _settings(-cutplanewireframe)] \
2033        -command [itcl::code $this AdjustSetting -cutplanewireframe] \
2034        -font "Arial 9"
2035
2036    checkbutton $inner.lighting \
2037        -text "Enable Lighting" \
2038        -variable [itcl::scope _settings(-cutplanelighting)] \
2039        -command [itcl::code $this AdjustSetting -cutplanelighting] \
2040        -font "Arial 9"
2041
2042    checkbutton $inner.edges \
2043        -text "Edges" \
2044        -variable [itcl::scope _settings(-cutplaneedges)] \
2045        -command [itcl::code $this AdjustSetting -cutplaneedges] \
2046        -font "Arial 9"
2047
2048    checkbutton $inner.preinterp \
2049        -text "Interpolate Scalars" \
2050        -variable [itcl::scope _settings(-cutplanepreinterp)] \
2051        -command [itcl::code $this AdjustSetting -cutplanepreinterp] \
2052        -font "Arial 9"
2053
2054    label $inner.opacity_l -text "Opacity" -font "Arial 9"
2055    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
2056        -variable [itcl::scope _widget(-cutplaneopacity)] \
2057        -width 10 \
2058        -showvalue off \
2059        -command [itcl::code $this AdjustSetting -cutplaneopacity]
2060    $inner.opacity set [expr $_settings(-cutplaneopacity) * 100.0]
2061
2062    # X-value slicer...
2063    itk_component add xbutton {
2064        Rappture::PushButton $inner.xbutton \
2065            -onimage [Rappture::icon x-cutplane-red] \
2066            -offimage [Rappture::icon x-cutplane-red] \
2067            -command [itcl::code $this AdjustSetting -xcutplanevisible] \
2068            -variable [itcl::scope _settings(-xcutplanevisible)] \
2069    }
2070    Rappture::Tooltip::for $itk_component(xbutton) \
2071        "Toggle the X-axis cutplane on/off"
2072    $itk_component(xbutton) select
2073    itk_component add xposition {
2074        ::scale $inner.xval -from 100 -to 0 \
2075            -width 10 -orient vertical -showvalue 1 \
2076            -borderwidth 1 -highlightthickness 0 \
2077            -command [itcl::code $this EventuallySetCutplane x] \
2078            -variable [itcl::scope _settings(-xcutplaneposition)] \
2079            -foreground red2 -font "Arial 9 bold"
2080    } {
2081        usual
2082        ignore -borderwidth -highlightthickness -foreground -font -background
2083    }
2084    # Set the default cutplane value before disabling the scale.
2085    $itk_component(xposition) set 50
2086    $itk_component(xposition) configure -state disabled
2087    Rappture::Tooltip::for $itk_component(xposition) \
2088        "@[itcl::code $this Slice tooltip x]"
2089
2090    # Y-value slicer...
2091    itk_component add ybutton {
2092        Rappture::PushButton $inner.ybutton \
2093            -onimage [Rappture::icon y-cutplane-green] \
2094            -offimage [Rappture::icon y-cutplane-green] \
2095            -command [itcl::code $this AdjustSetting -ycutplanevisible] \
2096            -variable [itcl::scope _settings(-ycutplanevisible)] \
2097    }
2098    Rappture::Tooltip::for $itk_component(ybutton) \
2099        "Toggle the Y-axis cutplane on/off"
2100    $itk_component(ybutton) select
2101
2102    itk_component add yposition {
2103        ::scale $inner.yval -from 100 -to 0 \
2104            -width 10 -orient vertical -showvalue 1 \
2105            -borderwidth 1 -highlightthickness 0 \
2106            -command [itcl::code $this EventuallySetCutplane y] \
2107            -variable [itcl::scope _settings(-ycutplaneposition)] \
2108            -foreground green3 -font "Arial 9 bold"
2109    } {
2110        usual
2111        ignore -borderwidth -highlightthickness -foreground -font
2112    }
2113    Rappture::Tooltip::for $itk_component(yposition) \
2114        "@[itcl::code $this Slice tooltip y]"
2115    # Set the default cutplane value before disabling the scale.
2116    $itk_component(yposition) set 50
2117    $itk_component(yposition) configure -state disabled
2118
2119    # Z-value slicer...
2120    itk_component add zbutton {
2121        Rappture::PushButton $inner.zbutton \
2122            -onimage [Rappture::icon z-cutplane-blue] \
2123            -offimage [Rappture::icon z-cutplane-blue] \
2124            -command [itcl::code $this AdjustSetting -zcutplanevisible] \
2125            -variable [itcl::scope _settings(-zcutplanevisible)] \
2126    } {
2127        usual
2128        ignore -foreground
2129    }
2130    Rappture::Tooltip::for $itk_component(zbutton) \
2131        "Toggle the Z-axis cutplane on/off"
2132    $itk_component(zbutton) select
2133
2134    itk_component add zposition {
2135        ::scale $inner.zval -from 100 -to 0 \
2136            -width 10 -orient vertical -showvalue 1 \
2137            -borderwidth 1 -highlightthickness 0 \
2138            -command [itcl::code $this EventuallySetCutplane z] \
2139            -variable [itcl::scope _settings(-zcutplaneposition)] \
2140            -foreground blue3 -font "Arial 9 bold"
2141    } {
2142        usual
2143        ignore -borderwidth -highlightthickness -foreground -font
2144    }
2145    $itk_component(zposition) set 50
2146    $itk_component(zposition) configure -state disabled
2147    Rappture::Tooltip::for $itk_component(zposition) \
2148        "@[itcl::code $this Slice tooltip z]"
2149
2150    blt::table $inner \
2151        0,0 $inner.visible              -anchor w -pady 2 -cspan 3 \
2152        1,0 $inner.lighting             -anchor w -pady 2 -cspan 3 \
2153        2,0 $inner.wireframe            -anchor w -pady 2 -cspan 3 \
2154        3,0 $inner.edges                -anchor w -pady 2 -cspan 3 \
2155        4,0 $inner.preinterp            -anchor w -pady 2 -cspan 3 \
2156        5,0 $inner.opacity_l            -anchor w -pady 2 -cspan 1 \
2157        5,1 $inner.opacity              -fill x   -pady 2 -cspan 3 \
2158        6,0 $inner.xbutton              -anchor w -padx 2 -pady 2 \
2159        7,0 $inner.ybutton              -anchor w -padx 2 -pady 2 \
2160        8,0 $inner.zbutton              -anchor w -padx 2 -pady 2 \
2161        6,1 $inner.xval                 -fill y -rspan 4 \
2162        6,2 $inner.yval                 -fill y -rspan 4 \
2163        6,3 $inner.zval                 -fill y -rspan 4 \
2164
2165
2166    blt::table configure $inner r* c* -resize none
2167    blt::table configure $inner r9 c4 -resize expand
2168}
2169
2170#
2171#  camera --
2172#
2173itcl::body Rappture::VtkIsosurfaceViewer::camera {option args} {
2174    switch -- $option {
2175        "show" {
2176            puts [array get _view]
2177        }
2178        "set" {
2179            set what [lindex $args 0]
2180            set x $_view($what)
2181            set code [catch { string is double $x } result]
2182            if { $code != 0 || !$result } {
2183                return
2184            }
2185            switch -- $what {
2186                "-ortho" {
2187                    if {$_view($what)} {
2188                        SendCmd "camera mode ortho"
2189                    } else {
2190                        SendCmd "camera mode persp"
2191                    }
2192                }
2193                "-xpan" - "-ypan" {
2194                    PanCamera
2195                }
2196                "-qx" - "-qy" - "-qz" - "-qw" {
2197                    set q [ViewToQuaternion]
2198                    $_arcball quaternion $q
2199                    EventuallyRotate $q
2200                }
2201                "-zoom" {
2202                    SendCmd "camera zoom $_view($what)"
2203                }
2204             }
2205        }
2206    }
2207}
2208
2209itcl::body Rappture::VtkIsosurfaceViewer::GetVtkData { args } {
2210    set bytes ""
2211    foreach dataobj [get] {
2212        foreach cname [$dataobj components] {
2213            set tag $dataobj-$cname
2214            set contents [$dataobj vtkdata $cname]
2215            append bytes "$contents\n"
2216        }
2217    }
2218    return [list .vtk $bytes]
2219}
2220
2221itcl::body Rappture::VtkIsosurfaceViewer::GetImage { args } {
2222    if { [image width $_image(download)] > 0 &&
2223         [image height $_image(download)] > 0 } {
2224        set bytes [$_image(download) data -format "jpeg -quality 100"]
2225        set bytes [Rappture::encoding::decode -as b64 $bytes]
2226        return [list .jpg $bytes]
2227    }
2228    return ""
2229}
2230
2231itcl::body Rappture::VtkIsosurfaceViewer::BuildDownloadPopup { popup command } {
2232    Rappture::Balloon $popup \
2233        -title "[Rappture::filexfer::label downloadWord] as..."
2234    set inner [$popup component inner]
2235    label $inner.summary -text "" -anchor w
2236    radiobutton $inner.vtk_button -text "VTK data file" \
2237        -variable [itcl::scope _downloadPopup(format)] \
2238        -font "Arial 9 " \
2239        -value vtk
2240    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
2241    radiobutton $inner.image_button -text "Image File" \
2242        -variable [itcl::scope _downloadPopup(format)] \
2243        -font "Arial 9 " \
2244        -value image
2245    Rappture::Tooltip::for $inner.image_button \
2246        "Save as digital image."
2247
2248    button $inner.ok -text "Save" \
2249        -highlightthickness 0 -pady 2 -padx 3 \
2250        -command $command \
2251        -compound left \
2252        -image [Rappture::icon download]
2253
2254    button $inner.cancel -text "Cancel" \
2255        -highlightthickness 0 -pady 2 -padx 3 \
2256        -command [list $popup deactivate] \
2257        -compound left \
2258        -image [Rappture::icon cancel]
2259
2260    blt::table $inner \
2261        0,0 $inner.summary -cspan 2  \
2262        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2263        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2264        4,1 $inner.cancel -width .9i -fill y \
2265        4,0 $inner.ok -padx 2 -width .9i -fill y
2266    blt::table configure $inner r3 -height 4
2267    blt::table configure $inner r4 -pady 4
2268    raise $inner.image_button
2269    $inner.vtk_button invoke
2270    return $inner
2271}
2272
2273itcl::body Rappture::VtkIsosurfaceViewer::SetObjectStyle { dataobj comp } {
2274    # Parse style string.
2275    set tag $dataobj-$comp
2276    array set style {
2277        -color                  BCGYR
2278        -cutplaneedges          0
2279        -cutplanelighting       1
2280        -cutplaneopacity        1.0
2281        -cutplanepreinterp      1
2282        -cutplanesvisible       0
2283        -cutplanewireframe      0
2284        -edgecolor              black
2285        -edges                  0
2286        -isosurfacevisible      1
2287        -levels                 10
2288        -lighting               1
2289        -linewidth              1.0
2290        -opacity                0.6
2291        -outline                0
2292        -wireframe              0
2293        -xcutplaneposition      50
2294        -xcutplanevisible       1
2295        -ycutplaneposition      50
2296        -ycutplanevisible       1
2297        -zcutplaneposition      50
2298        -zcutplanevisible       1
2299    }
2300    array set style [$dataobj style $comp]
2301    if { $dataobj != $_first || $style(-levels) == 1 } {
2302        set style(-opacity) 1.0
2303    }
2304
2305    # This is too complicated.  We want to set the colormap, number of
2306    # isolines and opacity for the dataset.  They can be the default values,
2307    # the style hints loaded with the dataset, or set by user controls.  As
2308    # datasets get loaded, they first use the defaults that are overidden
2309    # by the style hints.  If the user changes the global controls, then that
2310    # overrides everything else.  I don't know what it means when global
2311    # controls are specified as style hints by each dataset.  It complicates
2312    # the code to handle aberrant cases.
2313
2314    if { $_changed(-isosurfaceedges) } {
2315        set style(-edges) $_settings(-isosurfaceedges)
2316    }
2317    if { $_changed(-isosurfacelighting) } {
2318        set style(-lighting) $_settings(-isosurfacelighting)
2319    }
2320    if { $_changed(-isosurfaceopacity) } {
2321        set style(-opacity) $_settings(-isosurfaceopacity)
2322    }
2323    if { $_changed(-isosurfacewireframe) } {
2324        set style(-wireframe) $_settings(-isosurfacewireframe)
2325    }
2326    if { $_changed(-numcontours) } {
2327        set style(-levels) $_settings(-numcontours)
2328    }
2329    if { $_changed(-colormap) } {
2330        set style(-color) $_settings(-colormap)
2331    }
2332    if { $_currentColormap == "" } {
2333        SetCurrentColormap $style(-color)
2334        $itk_component(colormap) value $style(-color)
2335    }
2336    if { $_contourList(numLevels) != $style(-levels) } {
2337        if { [llength $style(-levels)] > 1 } {
2338            set _contourList(reqValues) [lsort -real $style(-levels)]
2339        } else {
2340            set _settings(-numcontours) $style(-levels)
2341            $itk_component(numcontours) value $style(-levels)
2342            set _contourList(numLevels) $style(-levels)
2343        }
2344        EventuallyChangeContourLevels
2345    }
2346    foreach setting {-outline -isosurfacevisible -cutplanesvisible \
2347                     -xcutplanevisible -ycutplanevisible -zcutplanevisible \
2348                     -xcutplaneposition -ycutplaneposition -zcutplaneposition \
2349                     -cutplaneedges -cutplanelighting -cutplaneopacity \
2350                     -cutplanepreinterp -cutplanewireframe} {
2351        if {$_changed($setting)} {
2352            # User-modified UI setting overrides style
2353            set style($setting) $_settings($setting)
2354        } else {
2355            # Set UI control to style setting (tool provided or default)
2356            set _settings($setting) $style($setting)
2357        }
2358    }
2359
2360    SendCmd "cutplane add $tag"
2361    SendCmd "cutplane color [Color2RGB $itk_option(-plotforeground)] $tag"
2362    foreach axis {x y z} {
2363        set pos [expr $style(-${axis}cutplaneposition) * 0.01]
2364        set visible $style(-${axis}cutplanevisible)
2365        SendCmd "cutplane slice $axis $pos $tag"
2366        SendCmd "cutplane axis $axis $visible $tag"
2367    }
2368    SendCmd "cutplane edges $style(-cutplaneedges) $tag"
2369    SendCmd "cutplane lighting $style(-cutplanelighting) $tag"
2370    SendCmd "cutplane opacity $style(-cutplaneopacity) $tag"
2371    SendCmd "cutplane preinterp $style(-cutplanepreinterp) $tag"
2372    SendCmd "cutplane wireframe $style(-cutplanewireframe) $tag"
2373    SendCmd "cutplane visible $style(-cutplanesvisible) $tag"
2374
2375    SendCmd "outline add $tag"
2376    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
2377    SendCmd "outline visible $style(-outline) $tag"
2378
2379    GenerateContourList
2380    SendCmd [list contour3d add contourlist $_contourList(values) $tag]
2381    SendCmd "contour3d visible $style(-isosurfacevisible) $tag"
2382    SendCmd "contour3d edges $style(-edges) $tag"
2383    set _settings(-isosurfaceedges) $style(-edges)
2384    #SendCmd "contour3d color [Color2RGB $style(-color)] $tag"
2385    SendCmd "contour3d lighting $style(-lighting) $tag"
2386    set _settings(-isosurfacelighting) $style(-lighting)
2387    SendCmd "contour3d linecolor [Color2RGB $style(-edgecolor)] $tag"
2388    SendCmd "contour3d linewidth $style(-linewidth) $tag"
2389    SendCmd "contour3d opacity $style(-opacity) $tag"
2390    set _settings(-isosurfaceopacity) $style(-opacity)
2391    SetCurrentColormap $style(-color)
2392    SendCmd "contour3d wireframe $style(-wireframe) $tag"
2393    set _settings(-isosurfacewireframe) $style(-wireframe)
2394}
2395
2396itcl::body Rappture::VtkIsosurfaceViewer::IsValidObject { dataobj } {
2397    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2398        return 0
2399    }
2400    return 1
2401}
2402
2403#
2404# EnterLegend --
2405#
2406itcl::body Rappture::VtkIsosurfaceViewer::EnterLegend { x y } {
2407    SetLegendTip $x $y
2408}
2409
2410#
2411# MotionLegend --
2412#
2413itcl::body Rappture::VtkIsosurfaceViewer::MotionLegend { x y } {
2414    Rappture::Tooltip::tooltip cancel
2415    set c $itk_component(view)
2416    set cw [winfo width $c]
2417    set ch [winfo height $c]
2418    if { $x >= 0 && $x < $cw && $y >= 0 && $y < $ch } {
2419        SetLegendTip $x $y
2420    }
2421}
2422
2423#
2424# LeaveLegend --
2425#
2426itcl::body Rappture::VtkIsosurfaceViewer::LeaveLegend { } {
2427    Rappture::Tooltip::tooltip cancel
2428    .rappturetooltip configure -icon ""
2429}
2430
2431# ----------------------------------------------------------------------
2432# USAGE: LegendB1Motion press <x> <y>
2433# USAGE: LegendB1Motion motion <x> <y>
2434# USAGE: LegendB1Motion release <x> <y>
2435#
2436# Manage actions for Button 1 presses that happen over the legend.
2437# Pressing mouse Button 1 on the legend sends a command to the
2438# visualization server to show a specific isosurface.
2439# ----------------------------------------------------------------------
2440itcl::body Rappture::VtkIsosurfaceViewer::LegendB1Motion { status x y } {
2441
2442    switch -- $status {
2443        "press" {
2444            DisableMouseRotationBindings
2445            LegendProbeSingleContour $x $y
2446        }
2447        "motion" {
2448            DisableMouseRotationBindings
2449            LegendProbeSingleContour $x $y
2450        }
2451        "release" {
2452            AdjustSetting -range
2453            SetupMouseRotationBindings
2454        }
2455        default {
2456            error "bad option \"$option\": should be one of press, motion, release."
2457        }
2458    }
2459}
2460
2461# ----------------------------------------------------------------------
2462# USAGE: LegendPointToValue <x> <y>
2463#
2464# Convert an x,y point on the legend to a numeric isosurface value.
2465# ----------------------------------------------------------------------
2466itcl::body Rappture::VtkIsosurfaceViewer::LegendPointToValue { x y } {
2467
2468    set fname $_curFldName
2469
2470    set font "Arial 8"
2471    set lineht [font metrics $font -linespace]
2472
2473    set ih [image height $_image(legend)]
2474    set iy [expr $y - ($lineht + 2)]
2475
2476    # Compute the value of the point
2477    if { [info exists _limits($fname)] } {
2478        if { $_settings(-customrange) } {
2479            set vmin [$itk_component(min) value]
2480            set vmax [$itk_component(max) value]
2481        } else {
2482            foreach { vmin vmax } $_limits($fname) break
2483        }
2484        set t [expr 1.0 - (double($iy) / double($ih-1))]
2485        set value [expr $t * ($vmax - $vmin) + $vmin]
2486    } else {
2487        set value 0.0
2488    }
2489    return $value
2490}
2491
2492# ----------------------------------------------------------------------
2493# USAGE: LegendProbeSingleContour <x> <y>
2494#
2495# Calculate the isosurface value for the x,y point and send a commands
2496# to the visualization server to show that isosurface.
2497# ----------------------------------------------------------------------
2498itcl::body Rappture::VtkIsosurfaceViewer::LegendProbeSingleContour { x y } {
2499
2500    set value [LegendPointToValue $x $y]
2501    SendCmd [list contour3d contourlist $value]
2502}
2503
2504#
2505# SetLegendTip --
2506#
2507itcl::body Rappture::VtkIsosurfaceViewer::SetLegendTip { x y } {
2508    set fname $_curFldName
2509    set c $itk_component(view)
2510    set w [winfo width $c]
2511    set h [winfo height $c]
2512
2513    set font "Arial 8"
2514    set lineht [font metrics $font -linespace]
2515
2516    set ih [image height $_image(legend)]
2517    set iy [expr $y - ($lineht + 2)]
2518
2519    if { [string match "component*" $fname] } {
2520        set title ""
2521    } else {
2522        if { [info exists _fields($fname)] } {
2523            foreach { title units } $_fields($fname) break
2524            if { $units != "" } {
2525                set title [format "%s (%s)" $title $units]
2526            }
2527        } else {
2528            set title $fname
2529        }
2530    }
2531    # If there's a legend title, increase the offset by the line height.
2532    if { $title != "" } {
2533        incr iy -$lineht
2534    }
2535    # Make a swatch of the selected color
2536    if { [catch { $_image(legend) get 10 $iy } pixel] != 0 } {
2537        return
2538    }
2539    if { ![info exists _image(swatch)] } {
2540        set _image(swatch) [image create photo -width 24 -height 24]
2541    }
2542    set color [eval format "\#%02x%02x%02x" $pixel]
2543    $_image(swatch) put black  -to 0 0 23 23
2544    $_image(swatch) put $color -to 1 1 22 22
2545    .rappturetooltip configure -icon $_image(swatch)
2546
2547    # Compute the value of the point
2548    set value [LegendPointToValue $x $y]
2549
2550    # Setup the location of the tooltip
2551    set tx [expr $x + 15]
2552    set ty [expr $y - 5]
2553
2554    # Setup the text for the tooltip
2555    if { [info exists _isolines($y)] } {
2556        Rappture::Tooltip::text $c [format "$title %g (isosurface)" $_isolines($y)]
2557    } else {
2558        Rappture::Tooltip::text $c [format "$title %g" $value]
2559    }
2560
2561    # Show the tooltip
2562    Rappture::Tooltip::tooltip show $c +$tx,+$ty
2563}
2564
2565# ----------------------------------------------------------------------
2566# USAGE: Slice move x|y|z <newval>
2567#
2568# Called automatically when the user drags the slider to move the
2569# cut plane that slices 3D data.  Gets the current value from the
2570# slider and moves the cut plane to the appropriate point in the
2571# data set.
2572# ----------------------------------------------------------------------
2573itcl::body Rappture::VtkIsosurfaceViewer::Slice {option args} {
2574    switch -- $option {
2575        "move" {
2576            set axis [lindex $args 0]
2577            set newval [lindex $args 1]
2578            if {[llength $args] != 2} {
2579                error "wrong # args: should be \"Slice move x|y|z newval\""
2580            }
2581            set newpos [expr {0.01*$newval}]
2582            SendCmd "cutplane slice $axis $newpos"
2583        }
2584        "tooltip" {
2585            set axis [lindex $args 0]
2586            set val [$itk_component(${axis}position) get]
2587            return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2588        }
2589        default {
2590            error "bad option \"$option\": should be axis, move, or tooltip"
2591        }
2592    }
2593}
2594
2595#
2596# ReceiveLegend --
2597#
2598#   Invoked automatically whenever the "legend" command comes in from
2599#   the rendering server.  Indicates that binary image data with the
2600#   specified <size> will follow.
2601#
2602itcl::body Rappture::VtkIsosurfaceViewer::ReceiveLegend { colormap title min max size } {
2603    # puts stderr "ReceiveLegend colormap=$colormap title=$title range=$min,$max size=$size"
2604    set _title $title
2605    regsub {\(mag\)} $title "" _title
2606    if { [IsConnected] } {
2607        set bytes [ReceiveBytes $size]
2608        if { ![info exists _image(legend)] } {
2609            set _image(legend) [image create photo]
2610        }
2611        $_image(legend) configure -data $bytes
2612        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2613        if { [catch {DrawLegend} errs] != 0 } {
2614            global errorInfo
2615            puts stderr "errs=$errs errorInfo=$errorInfo"
2616        }
2617    }
2618}
2619
2620#
2621# DrawLegend --
2622#
2623#       Draws the legend on the canvas on the right side of the plot area.
2624#
2625itcl::body Rappture::VtkIsosurfaceViewer::DrawLegend {} {
2626    set fname $_curFldName
2627    set c $itk_component(view)
2628    set w [winfo width $c]
2629    set h [winfo height $c]
2630    set font "Arial 8"
2631    set lineht [font metrics $font -linespace]
2632
2633    if { [string match "component*" $fname] } {
2634        set title ""
2635    } else {
2636        if { [info exists _fields($fname)] } {
2637            foreach { title units } $_fields($fname) break
2638            if { $units != "" } {
2639                set title [format "%s (%s)" $title $units]
2640            }
2641        } else {
2642            set title $fname
2643        }
2644    }
2645    set x [expr $w - 2]
2646    if { !$_settings(-legendvisible) } {
2647        $c delete legend
2648        return
2649    }
2650    if { [$c find withtag "legend"] == "" } {
2651        set y 2
2652        # If there's a legend title, create a text item for the title.
2653        $c create text $x $y \
2654            -anchor ne \
2655            -fill $itk_option(-plotforeground) -tags "title legend" \
2656            -font $font
2657        if { $title != "" } {
2658            incr y $lineht
2659        }
2660        $c create text $x $y \
2661            -anchor ne \
2662            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2663            -font $font
2664        incr y $lineht
2665        $c create image $x $y \
2666            -anchor ne \
2667            -image $_image(legend) -tags "colormap legend"
2668        $c create rectangle $x $y 1 1 \
2669            -fill "" -outline "" -tags "sensor legend"
2670        $c create text $x [expr {$h-2}] \
2671            -anchor se \
2672            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2673            -font $font
2674        $c bind sensor <Enter> [itcl::code $this EnterLegend %x %y]
2675        $c bind sensor <Leave> [itcl::code $this LeaveLegend]
2676        $c bind sensor <Motion> [itcl::code $this MotionLegend %x %y]
2677#        $c bind sensor <ButtonPress-1>   [itcl::code $this LegendB1Motion press %x %y]
2678#        $c bind sensor <B1-Motion>       [itcl::code $this LegendB1Motion motion %x %y]
2679#        $c bind sensor <ButtonRelease-1> [itcl::code $this LegendB1Motion release %x %y]
2680
2681    }
2682    $c delete isoline
2683    set x2 $x
2684    set iw [image width $_image(legend)]
2685    set ih [image height $_image(legend)]
2686    set x1 [expr $x2 - ($iw*12)/10]
2687    set color $_settings(-isolinecolor)
2688    # Draw the isolines on the legend.
2689    array unset _isolines
2690    if { $color != "none"  && [info exists _limits($_curFldName)] &&
2691         $_settings(-numcontours) > 0 } {
2692
2693        if { $_settings(-customrange) } {
2694            set vmin [$itk_component(min) value]
2695            set vmax [$itk_component(max) value]
2696        } else {
2697            foreach { vmin vmax } $_limits($_curFldName) break
2698        }
2699        set range [expr double($vmax - $vmin)]
2700        if { $range <= 0.0 } {
2701            set range 1.0;              # Min is greater or equal to max.
2702        }
2703        set tags "isoline legend"
2704        set offset [expr 2 + $lineht]
2705        if { $title != "" } {
2706            incr offset $lineht
2707        }
2708        foreach value $_contourList(values) {
2709            set norm [expr 1.0 - (($value - $vmin) / $range)]
2710            set y1 [expr int(round(($norm * $ih) + $offset))]
2711            for { set off 0 } { $off < 3 } { incr off } {
2712                set _isolines([expr $y1 + $off]) $value
2713                set _isolines([expr $y1 - $off]) $value
2714            }
2715            $c create line $x1 $y1 $x2 $y1 -fill $color -tags $tags
2716        }
2717    }
2718
2719    $c bind title <ButtonPress> [itcl::code $this LegendTitleAction post]
2720    $c bind title <Enter> [itcl::code $this LegendTitleAction enter]
2721    $c bind title <Leave> [itcl::code $this LegendTitleAction leave]
2722    # Reset the item coordinates according the current size of the plot.
2723    $c itemconfigure title -text $title
2724    if { [info exists _limits($_curFldName)] } {
2725        if { $_settings(-customrange) } {
2726            set vmin [$itk_component(min) value]
2727            set vmax [$itk_component(max) value]
2728        } else {
2729            foreach { vmin vmax } $_limits($_curFldName) break
2730        }
2731        $c itemconfigure vmin -text [format %g $vmin]
2732        $c itemconfigure vmax -text [format %g $vmax]
2733    }
2734    set y 2
2735    # If there's a legend title, move the title to the correct position
2736    if { $title != "" } {
2737        $c itemconfigure title -text $title
2738        $c coords title $x $y
2739        incr y $lineht
2740        $c raise title
2741    }
2742    $c coords vmax $x $y
2743    incr y $lineht
2744    $c coords colormap $x $y
2745    $c coords sensor [expr $x - $iw] $y $x [expr $y + $ih]
2746    $c raise sensor
2747    $c coords vmin $x [expr {$h - 2}]
2748
2749    $c bind vmin <ButtonPress> [itcl::code $this LegendRangeAction popup vmin]
2750    $c bind vmin <Enter> [itcl::code $this LegendRangeAction enter vmin]
2751    $c bind vmin <Leave> [itcl::code $this LegendRangeAction leave vmin]
2752
2753    $c bind vmax <ButtonPress> [itcl::code $this LegendRangeAction popup vmax]
2754    $c bind vmax <Enter> [itcl::code $this LegendRangeAction enter vmax]
2755    $c bind vmax <Leave> [itcl::code $this LegendRangeAction leave vmax]
2756}
2757
2758# ----------------------------------------------------------------------
2759# USAGE: LegendTitleAction post
2760# USAGE: LegendTitleAction enter
2761# USAGE: LegendTitleAction leave
2762# USAGE: LegendTitleAction save
2763#
2764# Used internally to handle the dropdown list for the fields menu combobox.
2765# The post option is invoked when the field title is pressed to launch the
2766# dropdown. The enter option is invoked when the user mouses over the field
2767# title. The leave option is invoked when the user moves the mouse away
2768# from the field title.  The save option is invoked whenever there is a
2769# selection from the list, to alert the visualization server.
2770#
2771# ----------------------------------------------------------------------
2772itcl::body Rappture::VtkIsosurfaceViewer::LegendTitleAction {option} {
2773    set c $itk_component(view)
2774    switch -- $option {
2775        post {
2776            foreach { x1 y1 x2 y2 } [$c bbox title] break
2777            set cw [winfo width $itk_component(view)]
2778            set mw [winfo reqwidth $itk_component(fieldmenu)]
2779            set x1 [expr $cw - $mw]
2780            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2781            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2782            tk_popup $itk_component(fieldmenu) $x $y
2783        }
2784        enter {
2785            $c itemconfigure title -fill red
2786        }
2787        leave {
2788            $c itemconfigure title -fill $itk_option(-plotforeground)
2789        }
2790        save {
2791            $itk_component(field) value $_curFldLabel
2792            AdjustSetting -field
2793        }
2794        default {
2795            error "bad option \"$option\": should be post, enter, leave, save"
2796        }
2797    }
2798}
2799
2800# ----------------------------------------------------------------------
2801# USAGE: LegendRangeValidate <widget> <which> <value>
2802#
2803# Used internally to validate a legend range min/max value.
2804# Returns a boolean value telling if <value> was accepted (1) or rejected (0)
2805# If the value is rejected, a tooltip/warning message is popped up
2806# near the widget that asked for the validation, specified by <widget>
2807#
2808# <widget> is the widget where a tooltip/warning message should show up on
2809# <which> is either "vmin" or "vmax".
2810# <value> is the value to be validated.
2811#
2812# ----------------------------------------------------------------------
2813itcl::body Rappture::VtkIsosurfaceViewer::LegendRangeValidate {widget which value} {
2814
2815    #check for a valid value
2816    if {[string is double $value] != 1} {
2817        set msg "should be valid number"
2818        if {$widget != ""} {
2819            Rappture::Tooltip::cue $widget $msg
2820        } else {
2821            # error "bad value \"$value\": $msg"
2822            error $msg
2823        }
2824        return 0
2825    }
2826
2827    switch -- $which {
2828        vmin {
2829            # check for min > max
2830            if {$value > [$itk_component(max) value]} {
2831                set msg "min > max, change max first"
2832                if {$widget != ""} {
2833                    Rappture::Tooltip::cue $widget $msg
2834                } else {
2835                    # error "bad value \"$value\": $msg"
2836                    error $msg
2837                }
2838                return 0
2839            }
2840        }
2841        vmax {
2842            # check for max < min
2843            if {$value < [$itk_component(min) value]} {
2844                set msg "max < min, change min first"
2845                if {$widget != ""} {
2846                    Rappture::Tooltip::cue $widget $msg
2847                } else {
2848                    # error "bad value \"$value\": $msg"
2849                    error $msg
2850                }
2851                return 0
2852            }
2853        }
2854        default {
2855            error "bad option \"$which\": should be vmin, vmax"
2856        }
2857    }
2858}
2859
2860itcl::body Rappture::VtkIsosurfaceViewer::MouseOver2Which {} {
2861    switch -- $_mouseOver {
2862        vmin {
2863            set which min
2864        }
2865        vmax {
2866            set which max
2867        }
2868        default {
2869            error "bad _mouseOver \"$_mouseOver\": should be vmin, vmax"
2870        }
2871    }
2872    return $which
2873}
2874
2875# ----------------------------------------------------------------------
2876# USAGE: LegendRangeAction enter <which>
2877# USAGE: LegendRangeAction leave <which>
2878#
2879# USAGE: LegendRangeAction popup <which>
2880# USAGE: LegendRangeAction activate
2881# USAGE: LegendRangeAction validate <value>
2882# USAGE: LegendRangeAction apply <value>
2883#
2884# Used internally to handle the mouseover and popup entry for the field range
2885# inputs.  The enter option is invoked when the user moves the mouse over the
2886# min or max field range. The leave option is invoked when the user moves the
2887# mouse away from the min or max field range. The popup option is invoked when
2888# the user click's on a field range. The popup option stores internally which
2889# widget is requesting a popup ( in the _mouseOver variable) and calls the
2890# activate command of the widget. The widget's activate command calls back to
2891# this method to get the xywh dimensions of the popup editor. After the user
2892# changes focus or sets the value in the editor, the editor calls this methods
2893# validate and apply options to set the value.
2894#
2895# ----------------------------------------------------------------------
2896itcl::body Rappture::VtkIsosurfaceViewer::LegendRangeAction {option args} {
2897    set c $itk_component(view)
2898
2899    switch -- $option {
2900        enter {
2901            set which [lindex $args 0]
2902            $c itemconfigure $which -fill red
2903        }
2904        leave {
2905            set which [lindex $args 0]
2906            $c itemconfigure $which -fill $itk_option(-plotforeground)
2907        }
2908        popup {
2909            DisableMouseRotationBindings
2910            set which [lindex $args 0]
2911            set _mouseOver $which
2912            $itk_component(editor) activate
2913        }
2914        activate {
2915            foreach { x1 y1 x2 y2 } [$c bbox $_mouseOver] break
2916            set which [MouseOver2Which]
2917            set info(text) [$itk_component($which) value]
2918            set info(x) [expr $x1 + [winfo rootx $c]]
2919            set info(y) [expr $y1 + [winfo rooty $c]]
2920            set info(w) [expr $x2 - $x1]
2921            set info(h) [expr $y2 - $y1]
2922            return [array get info]
2923        }
2924        validate {
2925            if {[llength $args] != 1} {
2926                error "wrong # args: should be \"editor validate value\""
2927            }
2928
2929            set value [lindex $args 0]
2930            if {[LegendRangeValidate $itk_component(editor) $_mouseOver $value] == 0} {
2931                return 0
2932            }
2933
2934            # value was good, apply it
2935            # reset the mouse rotation bindings
2936            SetupMouseRotationBindings
2937        }
2938        apply {
2939            if {[llength $args] != 1} {
2940                error "wrong # args: should be \"editor apply value\""
2941            }
2942            set value [string trim [lindex $args 0]]
2943
2944            set which [MouseOver2Which]
2945
2946            # only set custom range if value changed
2947            if {[$itk_component($which) value] != $value} {
2948                # set the flag stating the custom range came from the legend
2949                # change the value in the gauge
2950                # turn on crange to enable the labels and gauges
2951                # call AdjustSetting -range (inside ToggleCustomRange)
2952                # to update drawing and legend
2953                set _customRangeClick 0
2954                $itk_component($which) value $value
2955                $itk_component(crange) select
2956                ToggleCustomRange
2957            }
2958        }
2959        default {
2960            error "bad option \"$option\": should be enter, leave, activate, validate, apply"
2961        }
2962    }
2963}
2964
2965# ----------------------------------------------------------------------
2966# USAGE: ToggleCustomRange
2967#
2968# Called whenever the custom range is turned on or off. Used to save
2969# the custom min and custom max set by the user. When the -customrange
2970# setting is turned on, the range min and range max gauges are set
2971# with the last value set by the user, or the default range if no
2972# previous min and max were set.
2973#
2974# When the custom range is turned on, we check how it was turned on
2975# by querying _customRangeClick. If the variable is 1, this means
2976# the user clicked the crange checkbutton and we should pull the
2977# custom range values from our backup variables. If the variable is 0,
2978# the custom range was enabled through the user manipulating the
2979# min and max value in the legend.
2980#
2981# ----------------------------------------------------------------------
2982itcl::body Rappture::VtkIsosurfaceViewer::ToggleCustomRange {args} {
2983    if { ! $_settings(-customrange) } {
2984        # custom range was turned off
2985
2986        # disable the min/max labels and gauge widgets
2987        $itk_component(l_min) configure -state disabled
2988        $itk_component(min) configure -state disabled
2989        $itk_component(l_max) configure -state disabled
2990        $itk_component(max) configure -state disabled
2991
2992        # backup the custom range
2993        set _settings(-customrangemin) [$itk_component(min) value]
2994        set _settings(-customrangemax) [$itk_component(max) value]
2995
2996        # set the gauges to dataset's min and max
2997        foreach { vmin vmax } $_limits($_curFldName) break
2998        SetMinMaxGauges $vmin $vmax
2999    } else {
3000        # custom range was turned on
3001
3002        # enable the min/max labels and gauge widgets
3003        $itk_component(l_min) configure -state normal
3004        $itk_component(min) configure -state normal
3005        $itk_component(l_max) configure -state normal
3006        $itk_component(max) configure -state normal
3007
3008        # if the custom range is being turned on by clicking the
3009        # checkbox, restore the min and max gauges from the backup
3010        # variables. otherwise, new values for the min and max
3011        # widgets will be set later from the legend's editor.
3012        if { $_customRangeClick } {
3013            SetMinMaxGauges $_settings(-customrangemin) $_settings(-customrangemax)
3014        }
3015
3016        # reset the click flag
3017        set _customRangeClick 1
3018    }
3019    AdjustSetting -range
3020}
3021
3022# ----------------------------------------------------------------------
3023# USAGE: SetMinMaxGauges <min> <max>
3024#
3025# Set the min and max gauges in the correct order, avoiding the
3026# error where you try to set the min > max before updating the max or
3027# set the max < min before updating the min.
3028#
3029# There are five range cases to consider with our current range validation.
3030# For example:
3031# [2,3] -> [0,1]       : update min first, max last
3032# [2,3] -> [4,5]       : update max first, min last
3033# [2,3] -> [0,2.5]     : update min or max first
3034# [2,3] -> [2.5,5]     : update min or max first
3035# [2,3] -> [2.25,2.75] : update min or max first
3036#
3037# In 4 of the cases we can update min first and max last, so we only
3038# need to check the case where old max < new min, where we update
3039# max first and min last.
3040# ----------------------------------------------------------------------
3041itcl::body Rappture::VtkIsosurfaceViewer::SetMinMaxGauges {min max} {
3042
3043    if { [$itk_component(max) value] < $min} {
3044        # old max < new min
3045        # shift range toward right
3046        # extend max first, then update min
3047        $itk_component(max) value $max
3048        $itk_component(min) value $min
3049    } else {
3050        # extend min first, then update max
3051        $itk_component(min) value $min
3052        $itk_component(max) value $max
3053    }
3054}
3055
3056#
3057# SetCurrentColormap --
3058#
3059itcl::body Rappture::VtkIsosurfaceViewer::SetCurrentColormap { name } {
3060    # Keep track of the colormaps that we build.
3061    if { ![info exists _colormaps($name)] } {
3062        BuildColormap $name
3063        set _colormaps($name) 1
3064    }
3065    set _currentColormap $name
3066    SendCmd "contour3d colormap $_currentColormap"
3067    SendCmd "cutplane colormap $_currentColormap"
3068}
3069
3070#
3071# BuildColormap --
3072#
3073#       Build the designated colormap on the server.
3074#
3075itcl::body Rappture::VtkIsosurfaceViewer::BuildColormap { name } {
3076    set cmap [ColorsToColormap $name]
3077    if { [llength $cmap] == 0 } {
3078        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
3079    }
3080    set amap "0.0 1.0 1.0 1.0"
3081    SendCmd "colormap add $name { $cmap } { $amap }"
3082}
3083
3084itcl::body Rappture::VtkIsosurfaceViewer::SetOrientation { side } {
3085    array set positions {
3086        front "1 0 0 0"
3087        back  "0 0 1 0"
3088        left  "0.707107 0 -0.707107 0"
3089        right "0.707107 0 0.707107 0"
3090        top   "0.707107 -0.707107 0 0"
3091        bottom "0.707107 0.707107 0 0"
3092    }
3093    foreach name { -qw -qx -qy -qz } value $positions($side) {
3094        set _view($name) $value
3095    }
3096    set q [ViewToQuaternion]
3097    $_arcball quaternion $q
3098    SendCmd "camera orient $q"
3099    SendCmd "camera reset"
3100    set _view(-xpan) 0
3101    set _view(-ypan) 0
3102    set _view(-zoom) 1.0
3103}
3104
3105itcl::body Rappture::VtkIsosurfaceViewer::GenerateContourList {} {
3106    if { ![info exists _limits($_curFldName)] } {
3107        puts stderr "no _curFldName"
3108        return ""
3109    }
3110    if { $_contourList(numLevels) < 1 } {
3111        # There are tools that set 0 levels to get cutplanes only
3112        #puts stderr "numLevels < 1"
3113        return ""
3114    }
3115    if { [llength $_contourList(reqValues)] > 1 } {
3116        set values $_contourList(reqValues)
3117    } else {
3118        # if custom range has been set, use the custom min and max
3119        # to generate contour list values
3120        if { $_settings(-customrange) } {
3121            set vmin [$itk_component(min) value]
3122            set vmax [$itk_component(max) value]
3123        } else {
3124            # use the field limits to calculate the contour list values
3125            foreach { vmin vmax } $_limits($_curFldName) break
3126        }
3127
3128        set v [blt::vector create \#auto]
3129        $v seq $vmin $vmax [expr $_contourList(numLevels)+2]
3130        $v delete end 0
3131        set values [$v range 0 end]
3132        blt::vector destroy $v
3133    }
3134    set _contourList(values) $values
3135}
3136
3137itcl::body Rappture::VtkIsosurfaceViewer::SetCurrentFieldName { dataobj } {
3138    set _first $dataobj
3139    $itk_component(field) choices delete 0 end
3140    $itk_component(fieldmenu) delete 0 end
3141    array unset _fields
3142    set _curFldName ""
3143    foreach cname [$_first components] {
3144        foreach fname [$_first fieldnames $cname] {
3145            if { [info exists _fields($fname)] } {
3146                continue
3147            }
3148            foreach { label units components } \
3149                [$_first fieldinfo $fname] break
3150            $itk_component(field) choices insert end "$fname" "$label"
3151            $itk_component(fieldmenu) add radiobutton -label "$label" \
3152                -value $label -variable [itcl::scope _curFldLabel] \
3153                -selectcolor red \
3154                -activebackground $itk_option(-plotbackground) \
3155                -activeforeground $itk_option(-plotforeground) \
3156                -font "Arial 8" \
3157                -command [itcl::code $this LegendTitleAction save]
3158            set _fields($fname) [list $label $units $components]
3159            if { $_curFldName == "" } {
3160                set _curFldName $fname
3161                set _curFldLabel $label
3162            }
3163        }
3164    }
3165    $itk_component(field) value $_curFldLabel
3166    if { $_settings(-customrange) } {
3167        set limits [list [$itk_component(min) value] [$itk_component(max) value]]
3168        SendCmd "dataset maprange explicit $limits $_curFldName"
3169        if { $limits != $_currentLimits } {
3170            set _currentLimits $limits
3171            EventuallyChangeContourLevels
3172        }
3173    } else {
3174        if { ![info exists _limits($_curFldName)] } {
3175            SendCmd "dataset maprange all"
3176        } else {
3177            set limits $_limits($_curFldName)
3178            SendCmd "dataset maprange explicit $limits $_curFldName"
3179            if { $limits != $_currentLimits } {
3180                set _currentLimits $limits
3181                EventuallyChangeContourLevels
3182            }
3183        }
3184    }
3185}
Note: See TracBrowser for help on using the repository browser.