[GRASS-SVN] r42683 - in grass/trunk: gui/wxpython/gui_modules include lib/nviz lib/ogsf

svn_grass at osgeo.org svn_grass at osgeo.org
Thu Jul 1 07:41:04 EDT 2010


Author: martinl
Date: 2010-07-01 11:41:04 +0000 (Thu, 01 Jul 2010)
New Revision: 42683

Modified:
   grass/trunk/gui/wxpython/gui_modules/__init__.py
   grass/trunk/gui/wxpython/gui_modules/mapdisp.py
   grass/trunk/gui/wxpython/gui_modules/mapdisp_window.py
   grass/trunk/gui/wxpython/gui_modules/nviz_mapdisp.py
   grass/trunk/gui/wxpython/gui_modules/nviz_tools.py
   grass/trunk/gui/wxpython/gui_modules/preferences.py
   grass/trunk/gui/wxpython/gui_modules/toolbars.py
   grass/trunk/gui/wxpython/gui_modules/wxnviz.py
   grass/trunk/include/nviz.h
   grass/trunk/lib/nviz/nviz.c
   grass/trunk/lib/ogsf/GS2.c
Log:
wxNviz: various bugfixes, raster querying in progress


Modified: grass/trunk/gui/wxpython/gui_modules/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/__init__.py	2010-07-01 11:39:39 UTC (rev 42682)
+++ grass/trunk/gui/wxpython/gui_modules/__init__.py	2010-07-01 11:41:04 UTC (rev 42683)
@@ -23,7 +23,7 @@
     "menudata.py",
     "menuform.py",
     "nviz_mapdisp.py",
-    "nviz.py",
+    "nviz_preferences.py",
     "nviz_tools.py",
     "ogc_services.py",
     "preferences.py",
@@ -37,4 +37,5 @@
     "vclean.py",
     "vdigit.py",
     "workspace.py",
+    "wxnviz.py",
 ]

Modified: grass/trunk/gui/wxpython/gui_modules/mapdisp.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/mapdisp.py	2010-07-01 11:39:39 UTC (rev 42682)
+++ grass/trunk/gui/wxpython/gui_modules/mapdisp.py	2010-07-01 11:41:04 UTC (rev 42683)
@@ -82,17 +82,14 @@
 cmdfilename = None
 
 class MapFrame(wx.Frame):
+    """!Main frame for map display window. Drawing takes place in
+    child double buffered drawing window.
     """
-    Main frame for map display window. Drawing takes place in child double buffered
-    drawing window.
-    """
-
     def __init__(self, parent=None, id=wx.ID_ANY, title=_("GRASS GIS - Map display"),
                  style=wx.DEFAULT_FRAME_STYLE, toolbars=["map"],
                  tree=None, notebook=None, lmgr=None, page=None,
                  Map=None, auimgr=None, **kwargs):
-        """
-        Main map display window with toolbars, statusbar and
+        """!Main map display window with toolbars, statusbar and
         DrawWindow
 
         @param toolbars array of activated toolbars, e.g. ['map', 'digit']
@@ -111,9 +108,11 @@
         self.layerbook  = notebook  # Layer Manager layer tree notebook
         self.parent     = parent
         
-        #
+        if not kwargs.has_key('name'):
+            kwargs['name'] = 'MapWindow'
+        wx.Frame.__init__(self, parent, id, title, style = style, **kwargs)
+        
         # available cursors
-        #
         self.cursors = {
             # default: cross
             # "default" : wx.StockCursor(wx.CURSOR_DEFAULT),
@@ -124,10 +123,6 @@
             "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
             }
         
-        if not kwargs.has_key('name'):
-            kwargs['name'] = 'MapWindow'
-        wx.Frame.__init__(self, parent, id, title, style = style, **kwargs)
-        
         #
         # set the size & system icon
         #
@@ -248,7 +243,6 @@
                                           Map=self.Map, tree=self.tree, lmgr=self._layerManager)
         # default is 2D display mode
         self.MapWindow = self.MapWindow2D
-        self.MapWindow.Bind(wx.EVT_MOTION, self.OnMotion)
         self.MapWindow.SetCursor(self.cursors["default"])
         # used by Nviz (3D display mode)
         self.MapWindow3D = None 
@@ -419,6 +413,7 @@
                 self.MapWindow3D = nviz.GLWindow(self, id=wx.ID_ANY,
                                                  Map=self.Map, tree=self.tree, lmgr=self._layerManager)
                 self.MapWindow = self.MapWindow3D
+                self.MapWindow.SetCursor(self.cursors["default"])
                 
                 # add Nviz notebookpage
                 self._layerManager.AddNviz()
@@ -534,86 +529,20 @@
                     self.layerbook.SetSelection(pgnum)
         
         event.Skip()
-
-    def OnMotion(self, event):
-        """
-        Mouse moved
-        Track mouse motion and update status bar
-        """
-        # update statusbar if required
-        if self.statusbarWin['toggle'].GetSelection() == 0: # Coordinates
-            precision = int(UserSettings.Get(group = 'projection', key = 'format',
-                                             subkey = 'precision'))
-            format = UserSettings.Get(group = 'projection', key = 'format',
-                                      subkey = 'll')
-            try:
-                e, n = self.MapWindow.Pixel2Cell(event.GetPositionTuple())
-            except AttributeError:
-                return
-            if self.toolbars['vdigit'] and \
-                    self.toolbars['vdigit'].GetAction() == 'addLine' and \
-                    self.toolbars['vdigit'].GetAction('type') in ('line', 'boundary') and \
-                    len(self.MapWindow.polycoords) > 0:
-                # for linear feature show segment and total length
-                distance_seg = self.MapWindow.Distance(self.MapWindow.polycoords[-1],
-                                                       (e, n), screen=False)[0]
-                distance_tot = distance_seg
-                for idx in range(1, len(self.MapWindow.polycoords)):
-                    distance_tot += self.MapWindow.Distance(self.MapWindow.polycoords[idx-1],
-                                                            self.MapWindow.polycoords[idx],
-                                                            screen=False )[0]
-                self.statusbar.SetStatusText("%.*f, %.*f (seg: %.*f; tot: %.*f)" % \
-                                                 (precision, e, precision, n,
-                                                  precision, distance_seg,
-                                                  precision, distance_tot), 0)
-            else:
-                if self.statusbarWin['projection'].IsChecked():
-                    if not UserSettings.Get(group='projection', key='statusbar', subkey='proj4'):
-                        self.statusbar.SetStatusText(_("Projection not defined (check the settings)"), 0)
-                    else:
-                        proj, coord  = utils.ReprojectCoordinates(coord = (e, n),
-                                                                  projOut = UserSettings.Get(group='projection',
-                                                                                             key='statusbar',
-                                                                                             subkey='proj4'),
-                                                                  flags = 'd')
-                    
-                        if coord:
-                            e, n = coord
-                            if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
-                                self.statusbar.SetStatusText("%s" % \
-                                                                 utils.Deg2DMS(e, n, precision = precision),
-                                                             0)
-                            else:
-                                self.statusbar.SetStatusText("%.*f; %.*f" % \
-                                                                 (precision, e, precision, n), 0)
-                        else:
-                            self.statusbar.SetStatusText(_("Error in projection (check the settings)"), 0)
-                else:
-                    if self.Map.projinfo['proj'] == 'll' and format == 'DMS':
-                        self.statusbar.SetStatusText("%s" % \
-                                                         utils.Deg2DMS(e, n, precision = precision),
-                                                     0)
-                    else:
-                        self.statusbar.SetStatusText("%.*f; %.*f" % \
-                                                         (precision, e, precision, n), 0)
-                
-        event.Skip()
-
+        
     def OnDraw(self, event):
+        """!Re-display current map composition
         """
-        Re-display current map composition
-        """
-        self.MapWindow.UpdateMap(render=False)
+        self.MapWindow.UpdateMap(render = False)
         
     def OnRender(self, event):
+        """!Re-render map composition (each map layer)
         """
-        Re-render map composition (each map layer)
-        """
         # delete tmp map layers (queries)
         qlayer = self.Map.GetListOfLayers(l_name=globalvar.QUERYLAYER)
         for layer in qlayer:
             self.Map.DeleteLayer(layer)
-
+        
         # delete tmp lines
         if self.MapWindow.mouse["use"] in ("measure",
                                            "profile"):
@@ -631,9 +560,8 @@
         self.StatusbarUpdate()
 
     def OnPointer(self, event):
+        """!Pointer button clicked
         """
-        Pointer button clicked
-        """
         if self.toolbars['map']:
             if event:
                 self.toolbars['map'].OnTool(event)
@@ -1270,9 +1198,8 @@
         return self.MapWindow
     
     def OnQueryDisplay(self, event):
+        """!Query currrent raster/vector map layers (display mode)
         """
-        Query currrent raster/vector map layers (display mode)
-        """
         if self.toolbars['map'].GetAction() == 'displayAttrb': # select previous action
             self.toolbars['map'].SelectDefault(event)
             return
@@ -1309,7 +1236,7 @@
         
     def QueryMap(self, x, y):
         """!Query map layer features
-
+        
         Currently only raster and vector map layers are supported.
         
         @param x,y coordinates
@@ -1317,7 +1244,7 @@
         #set query snap distance for v.what at mapunit equivalent of 10 pixels
         qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
         east, north = self.MapWindow.Pixel2Cell((x, y))
-
+        
         num = 0
         for layer in self.tree.GetSelections():
             type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
@@ -1326,10 +1253,10 @@
                 num += 1
         
         if num < 1:
-            dlg = wx.MessageDialog(parent=self,
-                                   message=_('No raster or vector map layer selected for querying.'),
-                                   caption=_('No map layer selected'),
-                                   style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
+            dlg = wx.MessageDialog(parent = self,
+                                   message = _('No raster or vector map layer selected for querying.'),
+                                   caption = _('No map layer selected'),
+                                   style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
             dlg.ShowModal()
             dlg.Destroy()
             return
@@ -1349,7 +1276,7 @@
                 raststr += "%s," % name
             elif type in ('vector', 'thememap', 'themechart'):
                 vectstr += "%s," % name
-
+        
         # use display region settings instead of computation region settings
         self.tmpreg = os.getenv("GRASS_REGION")
         os.environ["GRASS_REGION"] = self.Map.SetRegion(windres=False)
@@ -1373,7 +1300,7 @@
                         continue
                     vect.append(vector)
                 vectstr = ','.join(vect)
-                
+            
             if len(vectstr) <= 1:
                 self._layerManager.goutput.WriteCmdLog("Nothing to query.")
                 return
@@ -1663,11 +1590,9 @@
                                                 style)
 
     def MeasureDist(self, beginpt, endpt):
-        """
-        Calculate map distance from screen distance
+        """!Calculate map distance from screen distance
         and print to output window
         """
-
         if self._layerManager.notebook.GetSelection() != 1:
             self._layerManager.notebook.SetSelection(1)
 

Modified: grass/trunk/gui/wxpython/gui_modules/mapdisp_window.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/mapdisp_window.py	2010-07-01 11:39:39 UTC (rev 42682)
+++ grass/trunk/gui/wxpython/gui_modules/mapdisp_window.py	2010-07-01 11:41:04 UTC (rev 42683)
@@ -45,23 +45,20 @@
 from vdigit import PseudoDC as VDigitPseudoDC
 
 class MapWindow(object):
-    """!
-    Abstract map window class
+    """!Abstract map window class
 
     Parent for BufferedWindow class (2D display mode) and
     GLWindow (3D display mode)
     """
     def __init__(self, parent, id = wx.ID_ANY,
-                 Map = None, tree = None, lmgr = None):
+                 Map = None, tree = None, lmgr = None, **kwargs):
         self.parent = parent # MapFrame
         self.Map    = Map
         self.tree   = tree
         self.lmgr   = lmgr
         
-        #
         # mouse attributes -- position on the screen, begin and end of
         # dragging, and type of drawing
-        #
         self.mouse = {
             'begin': [0, 0], # screen coordinates
             'end'  : [0, 0],
@@ -70,14 +67,12 @@
             }
         
     def EraseMap(self):
-        """!
-        Erase the canvas (virtual method)
+        """!Erase the canvas (virtual method)
         """
         pass
 
     def UpdateMap(self):
-        """!
-        Updates the canvas anytime there is a change to the
+        """!Updates the canvas anytime there is a change to the
         underlaying images or to the geometry of the canvas.
         """
         pass
@@ -91,8 +86,66 @@
     def OnKeyDown(self, event):
         pass
     
-    def OnMouseMotion(self, event):
-        pass
+    def OnMotion(self, event):
+        """!Mouse moved
+        Track mouse motion and update status bar
+        """
+        if self.parent.statusbarWin['toggle'].GetSelection() == 0: # Coordinates
+            precision = int(UserSettings.Get(group = 'projection', key = 'format',
+                                             subkey = 'precision'))
+            format = UserSettings.Get(group = 'projection', key = 'format',
+                                      subkey = 'll')
+            try:
+                e, n = self.Pixel2Cell(event.GetPositionTuple())
+            except (TypeError, ValueError):
+                self.parent.statusbar.SetStatusText("", 0)
+                return
+            
+            if self.parent.toolbars['vdigit'] and \
+                    self.parent.toolbars['vdigit'].GetAction() == 'addLine' and \
+                    self.parent.toolbars['vdigit'].GetAction('type') in ('line', 'boundary') and \
+                    len(self.polycoords) > 0:
+                # for linear feature show segment and total length
+                distance_seg = self.Distance(self.polycoords[-1],
+                                             (e, n), screen=False)[0]
+                distance_tot = distance_seg
+                for idx in range(1, len(self.polycoords)):
+                    distance_tot += self.Distance(self.polycoords[idx-1],
+                                                  self.polycoords[idx],
+                                                  screen=False )[0]
+                self.parent.statusbar.SetStatusText("%.*f, %.*f (seg: %.*f; tot: %.*f)" % \
+                                                 (precision, e, precision, n,
+                                                  precision, distance_seg,
+                                                  precision, distance_tot), 0)
+            else:
+                if self.parent.statusbarWin['projection'].IsChecked():
+                    if not UserSettings.Get(group='projection', key='statusbar', subkey='proj4'):
+                        self.parent.statusbar.SetStatusText(_("Projection not defined (check the settings)"), 0)
+                    else:
+                        proj, coord  = utils.ReprojectCoordinates(coord = (e, n),
+                                                                  projOut = UserSettings.Get(group='projection',
+                                                                                             key='statusbar',
+                                                                                             subkey='proj4'),
+                                                                  flags = 'd')
+                    
+                        if coord:
+                            e, n = coord
+                            if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
+                                self.parent.statusbar.SetStatusText(utils.Deg2DMS(e, n, precision = precision),
+                                                                    0)
+                            else:
+                                self.parent.statusbar.SetStatusText("%.*f; %.*f" % \
+                                                                        (precision, e, precision, n), 0)
+                        else:
+                            self.parent.statusbar.SetStatusText(_("Error in projection (check the settings)"), 0)
+                else:
+                    if self.parent.Map.projinfo['proj'] == 'll' and format == 'DMS':
+                        self.parent.statusbar.SetStatusText(utils.Deg2DMS(e, n, precision = precision),
+                                                            0)
+                    else:
+                        self.parent.statusbar.SetStatusText("%.*f; %.*f" % \
+                                                                (precision, e, precision, n), 0)
+        event.Skip()
 
     def OnZoomToMap(self, event):
         pass
@@ -101,8 +154,7 @@
         pass
     
     def GetSelectedLayer(self, type = 'layer', multi = False):
-        """!
-        Get selected layer from layer tree
+        """!Get selected layer from layer tree
 
         @param type 'item' / 'layer' / 'nviz'
         @param multi return first selected layer or all
@@ -148,8 +200,7 @@
         return ret
     
 class BufferedWindow(MapWindow, wx.Window):
-    """!
-    A Buffered window class.
+    """!A Buffered window class.
 
     When the drawing needs to change, you app needs to call the
     UpdateMap() method. Since the drawing is stored in a bitmap, you
@@ -157,9 +208,9 @@
     SaveToFile(self,file_name,file_type) method.
     """
     def __init__(self, parent, id = wx.ID_ANY,
-                 style = wx.NO_FULL_REPAINT_ON_RESIZE,
-                 Map = None, tree = None, lmgr = None, **kwargs):
-        MapWindow.__init__(self, parent, id, Map, tree, lmgr)
+                 Map = None, tree = None, lmgr = None,
+                 style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
+        MapWindow.__init__(self, parent, id, Map, tree, lmgr, **kwargs)
         wx.Window.__init__(self, parent, id, style = style, **kwargs)
         
         # flags
@@ -180,8 +231,10 @@
         self.Bind(wx.EVT_PAINT,        self.OnPaint)
         self.Bind(wx.EVT_SIZE,         self.OnSize)
         self.Bind(wx.EVT_IDLE,         self.OnIdle)
-        self.Bind(wx.EVT_MOTION,       self.MouseActions)
+        ### self.Bind(wx.EVT_MOTION,       self.MouseActions)
         self.Bind(wx.EVT_MOUSE_EVENTS, self.MouseActions)
+        self.Bind(wx.EVT_MOTION,       self.OnMotion)
+        
         self.processMouse = True
         
         # render output objects
@@ -1842,8 +1895,7 @@
             self.UpdateMap(render=False)
         
     def OnLeftUp(self, event):
-        """!
-        Left mouse button released
+        """!Left mouse button released
         """
         Debug.msg (5, "BufferedWindow.OnLeftUp(): use=%s" % \
                        self.mouse["use"])
@@ -2406,61 +2458,52 @@
         return True
 
     def Pixel2Cell(self, (x, y)):
-        """!
-        Convert image coordinates to real word coordinates
+        """!Convert image coordinates to real word coordinates
 
-        Input : int x, int y
-        Output: float x, float y
+        @param x, y image coordinates
+        
+        @return easting, northing
+        @return None on error
         """
-
         try:
             x = int(x)
             y = int(y)
         except:
             return None
-
+        
         if self.Map.region["ewres"] > self.Map.region["nsres"]:
             res = self.Map.region["ewres"]
         else:
             res = self.Map.region["nsres"]
-
+        
         w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
         n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
-
+        
         east  = w + x * res
         north = n - y * res
-
-        # extent does not correspond with whole map canvas area...
-        # east  = self.Map.region['w'] + x * self.Map.region["ewres"]
-        # north = self.Map.region['n'] - y * self.Map.region["nsres"]
-
+        
         return (east, north)
 
     def Cell2Pixel(self, (east, north)):
-        """!
-        Convert real word coordinates to image coordinates
+        """!Convert real word coordinates to image coordinates
         """
-
         try:
             east  = float(east)
             north = float(north)
         except:
             return None
-
+        
         if self.Map.region["ewres"] > self.Map.region["nsres"]:
             res = self.Map.region["ewres"]
         else:
             res = self.Map.region["nsres"]
-
+        
         w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
         n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
-
-        # x = int((east  - w) / res)
-        # y = int((n - north) / res)
-
+        
         x = (east  - w) / res
         y = (n - north) / res
-
+        
         return (x, y)
 
     def Zoom(self, begin, end, zoomtype):

Modified: grass/trunk/gui/wxpython/gui_modules/nviz_mapdisp.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/nviz_mapdisp.py	2010-07-01 11:39:39 UTC (rev 42682)
+++ grass/trunk/gui/wxpython/gui_modules/nviz_mapdisp.py	2010-07-01 11:41:04 UTC (rev 42683)
@@ -22,6 +22,7 @@
 import sys
 import time
 import copy
+import math
 
 from threading import Thread
 
@@ -69,7 +70,6 @@
     """!OpenGL canvas for Map Display Window"""
     def __init__(self, parent, id = wx.ID_ANY,
                  Map = None, tree = None, lmgr = None):
-        
         self.parent = parent # MapFrame
         
         glcanvas.GLCanvas.__init__(self, parent, id)
@@ -87,7 +87,9 @@
                         'vpoints' : False }
         
         # list of loaded map layers (layer tree items)
-        self.layers = []
+        self.layers  = list()
+        # list of query points
+        self.qpoints = list()
         
         #
         # use display region instead of computational
@@ -123,14 +125,12 @@
         self.nvizDefault = NvizDefault()
         self.light = copy.deepcopy(UserSettings.Get(group = 'nviz', key = 'light')) # copy
         
-        self.size = None
         self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
-        self.Bind(wx.EVT_SIZE, self.OnSize)
-        self.Bind(wx.EVT_PAINT, self.OnPaint)
-        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
-        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
-        self.Bind(wx.EVT_MOTION, self.OnMouseAction)
-        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseAction)
+        self.Bind(wx.EVT_SIZE,             self.OnSize)
+        self.Bind(wx.EVT_PAINT,            self.OnPaint)
+        self.Bind(wx.EVT_LEFT_UP,          self.OnLeftUp)
+        self.Bind(wx.EVT_MOUSE_EVENTS,     self.OnMouseAction)
+        self.Bind(wx.EVT_MOTION,           self.OnMotion)
         
         self.Bind(EVT_UPDATE_PROP,  self.UpdateMapObjProperties)
         self.Bind(EVT_UPDATE_VIEW,  self.UpdateView)
@@ -146,13 +146,13 @@
         pass # do nothing, to avoid flashing on MSW
     
     def OnSize(self, event):
-        self.size = self.GetClientSize()
+        size = self.GetClientSize()
         if self.GetContext():
             Debug.msg(3, "GLCanvas.OnSize(): w = %d, h = %d" % \
-                      (self.size.width, self.size.height))
+                      (size.width, size.height))
             self.SetCurrent()
-            self._display.ResizeWindow(self.size.width,
-                                       self.size.height)
+            self._display.ResizeWindow(size.width,
+                                       size.height)
         
         event.Skip()
 
@@ -195,13 +195,6 @@
         self.UpdateMap()
         
     def OnMouseAction(self, event):
-        # change position
-        if event.Dragging() and event.LeftIsDown():
-            ### self.lastX = self.lastY = self.x = self.y
-            ### self.x, self.y = event.GetPosition()
-            ### self.Refresh(False)
-            pass
-        
         # change perspective with mouse wheel
         wheel = event.GetWheelRotation()
         
@@ -233,12 +226,62 @@
                 
                 # update statusbar
                 ### self.parent.StatusbarUpdate()
-            
-    def OnLeftDown(self, event):
-        self.CaptureMouse()
-                
+        
+        event.Skip()
+
+    def Pixel2Cell(self, (x, y)):
+        """!Convert image coordinates to real word coordinates
+
+        @param x, y image coordinates
+        
+        @return easting, northing
+        @return None on error
+        """
+        size = self.GetClientSize()
+        # UL -> LL
+        sid, x, y, z = self._display.GetPointOnSurface(x, y)
+        
+        if not sid:
+            return None
+        
+        return (x, y)
+    
     def OnLeftUp(self, event):
         self.ReleaseMouse()
+        if self.mouse["use"] == "query":
+            result = self._display.QueryMap(event.GetX(), event.GetY())
+            log = self.lmgr.goutput
+            if result:
+                self.qpoints.append((result['x'], result['y'], result['z']))
+                log.WriteLog("%-30s: %.3f" % (_("Easting"),   result['x']))
+                log.WriteLog("%-30s: %.3f" % (_("Northing"),  result['y']))
+                log.WriteLog("%-30s: %.3f" % (_("Elevation"), result['z']))
+                log.WriteLog("%-30s: %s" % (_("Surface map elevation"), result['elevation']))
+                log.WriteLog("%-30s: %s" % (_("Surface map color"), result['color']))
+                if len(self.qpoints) > 1:
+                    prev = self.qpoints[-2]
+                    curr = self.qpoints[-1]
+                    dxy = math.sqrt(pow(prev[0]-curr[0], 2) +
+                                    pow(prev[1]-curr[1], 2))
+                    dxyz = math.sqrt(pow(prev[0]-curr[0], 2) +
+                                     pow(prev[1]-curr[1], 2) +
+                                     pow(prev[2]-curr[2], 2))
+                    log.WriteLog("%-30s: %.3f" % (_("XY distance from previous"), dxy))
+                    log.WriteLog("%-30s: %.3f" % (_("XYZ distance from previous"), dxyz))
+                    log.WriteLog("%-30s: %.3f" % (_("Distance along surface"),
+                                                self._display.GetDistanceAlongSurface(result['id'],
+                                                                                      (curr[0], curr[1]),
+                                                                                      (prev[0], prev[1]),
+                                                                                      useExag = False)))
+                    log.WriteLog("%-30s: %.3f" % (_("Distance along exag. surface"),
+                                                self._display.GetDistanceAlongSurface(result['id'],
+                                                                                      (curr[0], curr[1]),
+                                                                                      (prev[0], prev[1]),
+                                                                                      useExag = True)))
+                log.WriteLog('-' * 80)
+            else:
+                log.WriteLog(_("No point on surface"))
+                log.WriteLog('-' * 80)
         
     def UpdateView(self, event):
         """!Change view settings"""

Modified: grass/trunk/gui/wxpython/gui_modules/nviz_tools.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/nviz_tools.py	2010-07-01 11:39:39 UTC (rev 42682)
+++ grass/trunk/gui/wxpython/gui_modules/nviz_tools.py	2010-07-01 11:41:04 UTC (rev 42683)
@@ -8,7 +8,6 @@
  - PositionWindow
  - ViewPositionWindow
  - LightPositionWindow
- - NvizPreferencesDialog
 
 (C) 2008-2010 by the GRASS Development Team
 
@@ -36,13 +35,10 @@
 import gselect
 import gcmd
 from preferences import globalSettings as UserSettings
-from preferences import PreferencesBaseDialog
 from nviz_mapdisp import wxUpdateView, wxUpdateLight, wxUpdateProperties
 from debug import Debug
 
 import wxnviz
-# sys.path.append(os.path.join(globalvar.ETCWXDIR, "nviz"))
-# import grass7_wxnviz as wxnviz
 
 class NvizToolWindow(FN.FlatNotebook):
     """!Nviz (3D view) tools panel
@@ -256,8 +252,13 @@
 
     def _createDataPage(self):
         """!Create data (surface, vector, volume) settings page"""
-        self.notebookData = FN.FlatNotebook(parent = self, id = wx.ID_ANY,
-                                            style = globalvar.FNPageDStyle)         
+        if globalvar.hasAgw:
+            self.notebookData = FN.FlatNotebook(parent = self, id = wx.ID_ANY,
+                                                agwStyle = globalvar.FNPageDStyle)
+        else:
+            self.notebookData = FN.FlatNotebook(parent = self, id = wx.ID_ANY,
+                                                agwStyle = globalvar.FNPageDStyle)
+        
         # surface page
         self.notebookData.AddPage(page = self._createSurfacePage(),
                                   text = " %s " % _("Surface"))
@@ -272,8 +273,13 @@
     
     def _createAppearancePage(self):
         """!Create data (surface, vector, volume) settings page"""
-        self.notebookAppearance = FN.FlatNotebook(parent = self, id = wx.ID_ANY,
-                                                  style = globalvar.FNPageDStyle)         
+        if globalvar.hasAgw:
+            self.notebookAppearance = FN.FlatNotebook(parent = self, id = wx.ID_ANY,
+                                                      agwStyle = globalvar.FNPageDStyle)
+        else:
+            self.notebookAppearance = FN.FlatNotebook(parent = self, id = wx.ID_ANY,
+                                                      style = globalvar.FNPageDStyle)
+        
         # light page
         self.notebookAppearance.AddPage(page = self._createLightPage(),
                                         text = " %s " % _("Lighting"))
@@ -2851,512 +2857,3 @@
         if event.LeftUp():
             self.mapWindow.render['quick'] = False
             self.mapWindow.Refresh(eraseBackground = False)
-        
-class NvizPreferencesDialog(PreferencesBaseDialog):
-    """!Nviz preferences dialog"""
-    def __init__(self, parent, title = _("3D view settings"),
-                 settings = UserSettings):
-        PreferencesBaseDialog.__init__(self, parent = parent, title = title,
-                                       settings = settings)
-        self.toolWin = self.parent.GetLayerManager().nviz
-        self.win = dict()
-        
-        # create notebook pages
-        self._createViewPage(self.notebook)
-        self._createVectorPage(self.notebook)
-        
-        self.SetMinSize(self.GetBestSize())
-        self.SetSize(self.size)
-        
-    def _createViewPage(self, notebook):
-        """!Create notebook page for general settings"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        
-        notebook.AddPage(page = panel,
-                         text = " %s " % _("View"))
-        
-        pageSizer = wx.BoxSizer(wx.VERTICAL)
-        
-        self.win['general'] = {}
-        self.win['view'] = {}
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("View")))
-        boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
-        # perspective
-        self.win['view']['persp'] = {}
-        pvals = UserSettings.Get(group = 'nviz', key = 'view', subkey = 'persp')
-        ipvals = UserSettings.Get(group = 'nviz', key = 'view', subkey = 'persp', internal = True)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Perspective:")),
-                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("(value)")),
-                      pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        pval = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = pvals['value'],
-                           min = ipvals['min'],
-                           max = ipvals['max'])
-        self.win['view']['persp']['value'] = pval.GetId()
-        gridSizer.Add(item = pval, pos = (0, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("(step)")),
-                      pos = (0, 3), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        pstep = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = pvals['step'],
-                           min = ipvals['min'],
-                           max = ipvals['max']-1)
-        self.win['view']['persp']['step'] = pstep.GetId()
-        gridSizer.Add(item = pstep, pos = (0, 4),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        # position
-        self.win['view']['pos'] = {}
-        posvals = UserSettings.Get(group = 'nviz', key = 'view', subkey = 'pos')
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Position:")),
-                      pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("(x)")),
-                      pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        px = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = posvals['x'] * 100,
-                           min = 0,
-                           max = 100)
-        self.win['view']['pos']['x'] = px.GetId()
-        gridSizer.Add(item = px, pos = (1, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = "(y)"),
-                      pos = (1, 3), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        py = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = posvals['y'] * 100,
-                           min = 0,
-                           max = 100)
-        self.win['view']['pos']['y'] = py.GetId()
-        gridSizer.Add(item = py, pos = (1, 4),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        # height
-        self.win['view']['height'] = {}
-        hvals = UserSettings.Get(group = 'nviz', key = 'view', subkey = 'height')
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Height:")),
-                      pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("(step)")),
-                      pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        hstep = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = hvals['step'],
-                           min = 1,
-                           max = 1e6)
-        self.win['view']['height']['step'] = hstep.GetId()
-        gridSizer.Add(item = hstep, pos = (2, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        # twist
-        self.win['view']['twist'] = {}
-        tvals = UserSettings.Get(group = 'nviz', key = 'view', subkey = 'twist')
-        itvals = UserSettings.Get(group = 'nviz', key = 'view', subkey = 'twist', internal = True)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Twist:")),
-                      pos = (3, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("(value)")),
-                      pos = (3, 1), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        tval = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = tvals['value'],
-                           min = itvals['min'],
-                           max = itvals['max'])
-        self.win['view']['twist']['value'] = tval.GetId()
-        gridSizer.Add(item = tval, pos = (3, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("(step)")),
-                      pos = (3, 3), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        tstep = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = tvals['step'],
-                           min = itvals['min'],
-                           max = itvals['max']-1)
-        self.win['view']['twist']['step'] = tstep.GetId()
-        gridSizer.Add(item = tstep, pos = (3, 4),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        # z-exag
-        self.win['view']['z-exag'] = {}
-        zvals = UserSettings.Get(group = 'nviz', key = 'view', subkey = 'z-exag')
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Z-exag:")),
-                      pos = (4, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("(value)")),
-                      pos = (4, 1), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        zval = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = zvals['value'],
-                           min = -1e6,
-                           max = 1e6)
-        self.win['view']['z-exag']['value'] = zval.GetId()
-        gridSizer.Add(item = zval, pos = (4, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("(step)")),
-                      pos = (4, 3), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        zstep = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = zvals['step'],
-                           min = -1e6,
-                           max = 1e6)
-        self.win['view']['z-exag']['step'] = zstep.GetId()
-        gridSizer.Add(item = zstep, pos = (4, 4),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 3)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-
-        box = wx.StaticBox(parent = panel, id = wx.ID_ANY,
-                           label = " %s " % (_("Image Appearance")))
-        boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        gridSizer.AddGrowableCol(0)
-        
-        # background color
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Background color:")),
-                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        color = csel.ColourSelect(panel, id = wx.ID_ANY,
-                                  colour = UserSettings.Get(group = 'nviz', key = 'settings',
-                                                            subkey = ['general', 'bgcolor']),
-                                  size = globalvar.DIALOG_COLOR_SIZE)
-        self.win['general']['bgcolor'] = color.GetId()
-        gridSizer.Add(item = color, pos = (0, 1))
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 3)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL,
-                      border = 3)
-        
-        panel.SetSizer(pageSizer)
-        
-        return panel
-    
-    def _createVectorPage(self, notebook):
-        """!Create notebook page for general settings"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        
-        notebook.AddPage(page = panel,
-                         text = " %s " % _("Vector"))
-        
-        pageSizer = wx.BoxSizer(wx.VERTICAL)
-        
-        # vector lines
-        self.win['vector'] = {}
-        self.win['vector']['lines'] = {}
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Vector lines")))
-        boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
-        # show
-        row = 0
-        showLines = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                label = _("Show lines"))
-        self.win['vector']['lines']['show'] = showLines.GetId()
-        showLines.SetValue(UserSettings.Get(group = 'nviz', key = 'vector',
-                                            subkey = ['lines', 'show']))
-        gridSizer.Add(item = showLines, pos = (row, 0))
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 3)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-        
-        # vector points
-        self.win['vector']['points'] = {}
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Vector points")))
-        boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 5)
-        
-        # show
-        row = 0
-        showPoints = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                 label = _("Show points"))
-        showPoints.SetValue(UserSettings.Get(group = 'nviz', key = 'vector',
-                                             subkey = ['points', 'show']))
-        self.win['vector']['points']['show'] = showPoints.GetId()
-        gridSizer.Add(item = showPoints, pos = (row, 0), span = (1, 8))
-        
-        # icon size
-        row += 1 
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Size:")),
-                      pos = (row, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        isize = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                            initial = 100,
-                            min = 1,
-                            max = 1e6)
-        self.win['vector']['points']['size'] = isize.GetId()
-        isize.SetValue(UserSettings.Get(group = 'nviz', key = 'vector',
-                                        subkey = ['points', 'size']))
-        gridSizer.Add(item = isize, pos = (row, 1),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        # icon width
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Width:")),
-                      pos = (row, 2), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        iwidth = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                            initial = 2,
-                            min = 1,
-                            max = 1e6)
-        self.win['vector']['points']['width'] = isize.GetId()
-        iwidth.SetValue(UserSettings.Get(group = 'nviz', key = 'vector',
-                                         subkey = ['points', 'width']))
-        gridSizer.Add(item = iwidth, pos = (row, 3),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        # icon symbol
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Marker:")),
-                      pos = (row, 4), flag = wx.ALIGN_CENTER_VERTICAL)
-        isym = wx.Choice (parent = panel, id = wx.ID_ANY, size = (100, -1),
-                          choices = UserSettings.Get(group = 'nviz', key = 'vector',
-                                                   subkey = ['points', 'marker'], internal = True))
-        isym.SetName("selection")
-        self.win['vector']['points']['marker'] = isym.GetId()
-        isym.SetSelection(UserSettings.Get(group = 'nviz', key = 'vector',
-                                           subkey = ['points', 'marker']))
-        gridSizer.Add(item = isym, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 5))
-        
-        # icon color
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Color:")),
-                      pos = (row, 6), flag = wx.ALIGN_CENTER_VERTICAL)
-        icolor = csel.ColourSelect(panel, id = wx.ID_ANY)
-        icolor.SetName("color")
-        self.win['vector']['points']['color'] = icolor.GetId()
-        icolor.SetColour(UserSettings.Get(group = 'nviz', key = 'vector',
-                                          subkey = ['points', 'color']))
-        gridSizer.Add(item = icolor, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 7))
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 3)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-        
-        panel.SetSizer(pageSizer)
-        
-        return panel
-    
-    def OnDefault(self, event):
-        """Restore default settings"""
-        settings = copy.deepcopy(UserSettings.GetDefaultSettings()['nviz'])
-        UserSettings.Set(group = 'nviz',
-                         value = settings)
-        
-        for subgroup, key in settings.iteritems(): # view, surface, vector...
-            if subgroup != 'view':
-                continue
-            for subkey, value in key.iteritems():
-                for subvalue in value.keys():
-                    win = self.FindWindowById(self.win[subgroup][subkey][subvalue])
-                    val = settings[subgroup][subkey][subvalue]
-                    if subkey == 'pos':
-                        val = int(val * 100)
-                    
-                    win.SetValue(val)
-        
-        event.Skip()
-        
-    def OnApply(self, event):
-        """Apply Nviz settings for current session"""
-        settings = UserSettings.Get(group = 'nviz')
-        for subgroup, key in settings.iteritems(): # view, surface, vector...
-            for subkey, value in key.iteritems():
-                for subvalue in value.keys():
-                    try: # TODO
-                        win = self.FindWindowById(self.win[subgroup][subkey][subvalue])
-                    except:
-                        # print 'e', subgroup, subkey, subvalue
-                        continue
-                    
-                    if win.GetName() == "selection":
-                        value = win.GetSelection()
-                    elif win.GetName() == "color":
-                        value = tuple(win.GetColour())
-                    else:
-                        value = win.GetValue()
-                    if subkey == 'pos':
-                        value = float(value) / 100
-                    
-                    settings[subgroup][subkey][subvalue] = value
-                    
-    def OnSave(self, event):
-        """!Apply changes, update map and save settings of selected
-        layer
-        """
-        # apply changes
-        self.OnApply(None)
-        
-        if self.GetSelection() == self.page['id']:
-            fileSettings = {}
-            UserSettings.ReadSettingsFile(settings = fileSettings)
-            fileSettings['nviz'] = UserSettings.Get(group = 'nviz')
-            file = UserSettings.SaveToFile(fileSettings)
-            self.parent.goutput.WriteLog(_('Nviz settings saved to file <%s>.') % file)
-        
-    def OnLoad(self, event):
-        """!Apply button pressed"""
-        self.LoadSettings()
-        
-        if event:
-            event.Skip()
-
-    def LoadSettings(self):
-        """!Load saved Nviz settings and apply to current session"""
-        UserSettings.ReadSettingsFile()
-        settings = copy.deepcopy(UserSettings.Get(group = 'nviz'))
-        
-        for subgroup, key in settings.iteritems(): # view, surface, vector...
-            for subkey, value in key.iteritems():
-                for subvalue in value.keys():
-                    if subvalue == 'step':
-                        continue
-                    else:
-                        insetting = value[subvalue]                                                    
-                    if subgroup == 'view':
-                        for viewkey, viewitem in self.mapWindow.view[subkey].iteritems(): 
-                            if viewkey == subvalue:
-                                self.mapWindow.view[subkey][viewkey] = insetting 
-                            else:
-                                continue
-                    else:
-                        for otherkey, otheritem in self.win[subgroup][subkey].iteritems():
-                            if type(otheritem) == data:
-                                for endkey, enditem in otheritem.iteritems():
-                                    if endkey == subvalue:
-                                        paramwin = self.FindWindowById(enditem)
-                                    else:
-                                        continue
-                            else:
-                                if otherkey == subvalue:
-                                    paramwin = self.FindWindowById(otheritem)
-                                else:
-                                    continue
-                            if type(insetting) in [tuple, list] and len(insetting) > 2:
-                                insetting = tuple(insetting)
-                                paramwin.SetColour(insetting)
-                            else:
-                                try:
-                                    paramwin.SetValue(insetting)
-                                except:
-                                    try:
-                                        paramwin.SetStringSelection(insetting)
-                                    except:
-                                        continue
-                                
-        self.toolWin.UpdateSettings()
-        self.FindWindowById(self.win['view']['pos']).Draw()
-        self.FindWindowById(self.win['view']['pos']).Refresh(False)
-        
-        self.mapWindow.render['quick'] = False
-        self.mapWindow.Refresh(False)
-        
-    def OnSave(self, event):
-        """!Save button pressed
-        
-        Save settings to configuration file
-        """
-        fileSettings = {}
-        UserSettings.ReadSettingsFile(settings = fileSettings)
-        
-        self.toolWin.UpdateSettings()
-        
-        nvsettings = UserSettings.Get(group = 'nviz')
-        for subgroup, key in nvsettings.iteritems(): # view, surface, vector...
-            for subkey, value in key.iteritems():
-                if subkey == 'height': continue
-                for subvalue in value.keys():
-                    if subvalue == 'step':
-                        #no way to change steps for sliders or spinctrls on non-MSW systems
-                        nvsettings[subgroup][subkey][subvalue] = 1 
-                    else:
-                        if subgroup == 'view':
-                            nvsettings[subgroup][subkey][subvalue] = self.mapWindow.view[subkey][subvalue]                            
-                        elif subvalue == 'map':
-                            if subkey == 'shine': 
-                                nvsettings[subgroup][subkey][subvalue] = False
-                            if subkey == 'color': 
-                                nvsettings[subgroup][subkey][subvalue] = True
-                        else:
-                            for otherkey, otheritem in self.win[subgroup][subkey].iteritems():
-                                if type(otheritem) == data:
-                                    for endkey, enditem in otheritem.iteritems():
-                                        if endkey == subvalue:
-                                            if self.FindWindowById(enditem).GetClassName() == 'wxChoice':
-                                                outsetting = self.FindWindowById(enditem).GetSelection()
-                                            else:
-                                                try:
-                                                    outsetting = self.FindWindowById(enditem).GetColour()
-                                                    outsetting = str(outsetting.Red())+':'+str(outsetting.Green())+':'+str(outsetting.Blue())
-                                                except:
-                                                    try:
-                                                        outsetting = self.FindWindowById(enditem).GetValue()
-                                                    except:
-                                                        try:
-                                                            outsetting = self.FindWindowById(enditem).GetString()
-                                                        except:
-                                                            outsetting = ''
-                                            if (type(outsetting) == list or type(outsetting) == tuple) and len(outsetting) > 2:
-                                                outsetting = str(outsetting[0])+':'+str(outsetting[1])+':'+str(outsetting[2])
-                                                
-                                            nvsettings[subgroup][subkey][subvalue][endkey] = outsetting
-                                else:
-                                    if otherkey == subvalue:
-                                        if self.FindWindowById(otheritem).GetClassName() == 'wxChoice':
-                                            outsetting = self.FindWindowById(otheritem).GetSelection()
-                                        else:
-                                            try:
-                                                outsetting = self.FindWindowById(otheritem).GetColour()
-                                                outsetting = str(outsetting.Red())+':'+str(outsetting.Green())+':'+str(outsetting.Blue())
-                                            except:
-                                                try:
-                                                    outsetting = self.FindWindowById(otheritem).GetValue()
-                                                except:
-                                                    try:
-                                                        outsetting = self.FindWindowById(enditem).GetString()
-                                                    except:
-                                                        outsetting = ''
-                                        if (type(outsetting) == list or type(outsetting) == tuple) and len(outsetting) > 2:
-                                            outsetting = str(outsetting[0])+':'+str(outsetting[1])+':'+str(outsetting[2])
-
-                                        nvsettings[subgroup][subkey][subvalue] = outsetting
-                               
-        UserSettings.Set(group = 'nviz', value = nvsettings)
-        file = UserSettings.SaveToFile()
-        self.parent.goutput.WriteLog(_('Nviz settings saved to file <%s>.') % file)

Modified: grass/trunk/gui/wxpython/gui_modules/preferences.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/preferences.py	2010-07-01 11:39:39 UTC (rev 42682)
+++ grass/trunk/gui/wxpython/gui_modules/preferences.py	2010-07-01 11:41:04 UTC (rev 42683)
@@ -26,6 +26,7 @@
 import sys
 import copy
 import stat
+import types
 try:
     import pwd
     havePwd = True
@@ -449,6 +450,9 @@
                     'z-exag' : {
                         'step' : 1,
                         },
+                    'background' : {
+                        'color' : (255, 255, 255, 255), # white
+                        },
                     },
                 'surface' : {
                     'shine': {
@@ -505,22 +509,14 @@
                         'value' : 60.0,
                         },
                     },
-                'settings': {
-                    'general' : {
-                        'bgcolor' : (255, 255, 255, 255), # white
-                        },
-                    },
-                    'light' : {
-                        'color' : (255, 255, 255, 255), # white
-                    },
                 'light' : {
                     'pos' : {
                         'x' : 0.68,
                         'y' : 0.68,
                         'z' : 80,
                         },
-                    'color' : (255, 255, 255, 255), # white
-                    'bright' : 80,
+                    'color'   : (255, 255, 255, 255), # white
+                    'bright'  : 80,
                     'ambient' : 20,
                     },
                 'fringe' : {
@@ -864,16 +860,21 @@
         @param subkey subkey (value or list)
         @param value value
         """
+        print dict
+        print group, key, subkey, value
+        print 'x'
         if not dict.has_key(group):
             dict[group] = {}
 
         if not dict[group].has_key(key):
             dict[group][key] = {}
 
-        if type(subkey) == type([]):
+        if type(subkey) == types.ListType:
             # TODO: len(subkey) > 2
             if not dict[group][key].has_key(subkey[0]):
                 dict[group][key][subkey[0]] = {}
+            print group, key, subkey, value
+            print dict[group][key]
             dict[group][key][subkey[0]][subkey[1]] = value
         else:
             dict[group][key][subkey] = value

Modified: grass/trunk/gui/wxpython/gui_modules/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/toolbars.py	2010-07-01 11:39:39 UTC (rev 42682)
+++ grass/trunk/gui/wxpython/gui_modules/toolbars.py	2010-07-01 11:41:04 UTC (rev 42683)
@@ -39,7 +39,7 @@
 from vdigit import VDigitSettingsDialog as VDigitSettingsDialog
 from debug import Debug as Debug
 from preferences import globalSettings as UserSettings
-from nviz_tools import NvizPreferencesDialog
+from nviz_preferences import NvizPreferencesDialog
 
 gmpath = os.path.join(globalvar.ETCWXDIR, "icons")
 sys.path.append(gmpath)
@@ -301,7 +301,6 @@
     def Enable2D(self, enabled):
         """!Enable/Disable 2D display mode specific tools"""
         for tool in (self.pointer,
-                     self.query,
                      self.pan,
                      self.zoomin,
                      self.zoomout,
@@ -1435,12 +1434,6 @@
             (self.relation, 'relation', Icons['modelRelation'].GetBitmap(),
              wx.ITEM_NORMAL, Icons['modelRelation'].GetLabel(), Icons['modelRelation'].GetDesc(),
              self.parent.OnDefineRelation),
-            # (self.properties, "properties", Icons["modelProperties"].GetBitmap(),
-            #  wx.ITEM_NORMAL, Icons["modelProperties"].GetLabel(), Icons["modelProperties"].GetDesc(),
-            #  self.parent.OnModelProperties),
-            (self.variables, "variables", Icons["modelVariables"].GetBitmap(),
-             wx.ITEM_NORMAL, Icons["modelVariables"].GetLabel(), Icons["modelVariables"].GetDesc(),
-             self.parent.OnModelVariables),
             ('', '', '', '', '', '', ''),
             (self.run, 'run', Icons['modelRun'].GetBitmap(),
              wx.ITEM_NORMAL, Icons['modelRun'].GetLabel(), Icons['modelRun'].GetDesc(),

Modified: grass/trunk/gui/wxpython/gui_modules/wxnviz.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/wxnviz.py	2010-07-01 11:39:39 UTC (rev 42682)
+++ grass/trunk/gui/wxpython/gui_modules/wxnviz.py	2010-07-01 11:41:04 UTC (rev 42683)
@@ -146,8 +146,8 @@
     def EraseMap(self):
         """!Erase map display (with background color)
         """
-        GS_clear(self.data.bgcolor)
         Debug.msg(1, "Nviz::EraseMap()")
+        GS_clear(Nviz_get_bgcolor(self.data))
         
     def InitView(self):
         """!Initialize view"""
@@ -159,6 +159,7 @@
         # set background color
         Nviz_set_bgcolor(self.data, Nviz_color_from_str("white"))
         
+        GS_clear(Nviz_get_bgcolor(self.data))
         # initialize view, lights
         Nviz_init_view(self.data)
         
@@ -554,12 +555,12 @@
         @return -2 setting attributes failed
         """
         Debug.msg(3, "Nviz::SetSurfaceRes(): id=%d, fine=%d, coarse=%d",
-                id, fine, coarse)
+                  id, fine, coarse)
         
         if id > 0:
             if not GS_surf_exists(id):
                 return -1
-        
+            
             if GS_set_drawres(id, fine, fine, coarse, coarse) < 0:
                 return -2
         else:
@@ -1126,3 +1127,49 @@
         Nviz_set_fringe(self.data,
                         sid, Nviz_color_from_str(scolor),
                         elev, int(nw), int(ne), int(sw), int(se))
+        
+    def GetPointOnSurface(self, sx, sy):
+        """!Get point on surface
+
+        @param sx,sy canvas coordinates (LL)
+        """
+        sid = c_int()
+        x   = c_float()
+        y   = c_float()
+        z   = c_float()
+        Debug.msg(5, "GLWindow.GetPointOnSurface(): sx=%d sy=%d" % (sx, sy))
+        num = GS_get_selected_point_on_surface(sx, sy, byref(sid), byref(x), byref(y), byref(z))
+        if num == 0:
+            return (None, None, None, None)
+        
+        return (sid.value, x.value, y.value, z.value)
+
+    def QueryMap(self, sx, sy):
+        """!Query surface map
+
+        @param sx,sy canvas coordinates (LL)
+        """
+        sid, x, y, z = self.GetPointOnSurface(sx, sy)
+        if not sid:
+            return None
+        
+        catstr = c_char * 256
+        valstr = c_char * 256
+        #GS_get_cat_at_xy(sid, MAP_ATT, pointer(catstr), x, y)
+        #GS_get_val_at_xy(sid, MAP_ATT, pointer(valstr), x, y)
+        
+        return { 'id' : sid,
+                 'x'  : x,
+                 'y'  : y,
+                 'z'  : z,
+                 'elevation' : catstr.value,
+                 'color'     : valstr.value }
+    
+    def GetDistanceAlongSurface(self, sid, p1, p2, useExag = True):
+        """!Get distance measured along surface"""
+        d = c_float()
+        
+        GS_get_distance_alongsurf(sid, p1[0], p1[1], p2[0], p2[1],
+                                  byref(d), int(useExag))
+        
+        return d.value

Modified: grass/trunk/include/nviz.h
===================================================================
--- grass/trunk/include/nviz.h	2010-07-01 11:39:39 UTC (rev 42682)
+++ grass/trunk/include/nviz.h	2010-07-01 11:41:04 UTC (rev 42683)
@@ -171,6 +171,7 @@
 void Nviz_init_data(nv_data *);
 void Nviz_destroy_data(nv_data *);
 void Nviz_set_bgcolor(nv_data *, int);
+int Nviz_get_bgcolor(nv_data *);
 int Nviz_color_from_str(const char *);
 struct fringe_data *Nviz_new_fringe(nv_data *, int, unsigned long,
 				    double, int, int, int, int);

Modified: grass/trunk/lib/nviz/nviz.c
===================================================================
--- grass/trunk/lib/nviz/nviz.c	2010-07-01 11:39:39 UTC (rev 42682)
+++ grass/trunk/lib/nviz/nviz.c	2010-07-01 11:41:04 UTC (rev 42683)
@@ -79,6 +79,18 @@
 }
 
 /*!
+   \brief Get background color
+
+   \param data nviz data
+
+   \return color color value
+ */
+int Nviz_get_bgcolor(nv_data * data)
+{
+    return data->bgcolor;
+}
+
+/*!
    \brief Get color value from color string (name or RGB triplet)
 
    \param color_str color string

Modified: grass/trunk/lib/ogsf/GS2.c
===================================================================
--- grass/trunk/lib/ogsf/GS2.c	2010-07-01 11:39:39 UTC (rev 42682)
+++ grass/trunk/lib/ogsf/GS2.c	2010-07-01 11:41:04 UTC (rev 42683)
@@ -1151,23 +1151,23 @@
     return (-1);
 }
 
-#define CATSREADY
-#ifdef CATSREADY
 /*!
-   \brief Print categories on given position
+   \brief Get surface category on given position
 
-   prints "no data" or a description (i.e., "coniferous forest") to catstr
-   Usually call after GS_get_selected_point_on_surface
-   att_src must be MAP_ATT
+   Prints "no data" or a description (i.e., "coniferous forest") to
+   <i>catstr</i>. Usually call after GS_get_selected_point_on_surface().
+   Define <i>att</i> as MAP_ATT
 
+   \todo Allocate catstr using G_store()
+   
    \param id surface id
-   \param att
+   \param att attribute id (MAP_ATT)
    \param catstr cat string (must be allocated, dim?)
    \param x,y real coordinates
 
    \return -1 if no category info or point outside of window
    \return 1 on success
- */
+*/
 int GS_get_cat_at_xy(int id, int att, char *catstr, float x, float y)
 {
     int offset, drow, dcol, vrow, vcol;
@@ -1179,7 +1179,7 @@
     gs = gs_get_surf(id);
 
     if (NULL == gs) {
-	return (-1);
+	return -1;
     }
 
     pt[X] = x;
@@ -1187,16 +1187,16 @@
 
     gsd_real2surf(gs, pt);
     if (gs_point_is_masked(gs, pt)) {
-	return (-1);
+	return -1;
     }
 
     if (!in_vregion(gs, pt)) {
-	return (-1);
+	return -1;
     }
 
     if (MAP_ATT != gs_get_att_src(gs, att)) {
-	sprintf(catstr, "no category info");
-	return (-1);
+	sprintf(catstr, _("no category info"));
+	return -1;
     }
 
     buff = gs_get_att_typbuff(gs, att, 0);
@@ -1207,17 +1207,16 @@
     dcol = VCOL2DCOL(gs, vcol);
 
     offset = DRC2OFF(gs, drow, dcol);
-
-
+    
     if (GET_MAPATT(buff, offset, ftmp)) {
 	return
-	    (Gs_get_cat_label
-	     (gsds_get_name(gs->att[att].hdata), drow, dcol, catstr));
+	    (Gs_get_cat_label(gsds_get_name(gs->att[att].hdata),
+			      drow, dcol, catstr));
     }
 
-    sprintf(catstr, "no data");
+    sprintf(catstr, _("no data"));
 
-    return (1);
+    return 1;
 }
 
 /*!
@@ -1281,20 +1280,18 @@
 }
 
 /*!
-   \brief Get RGB color  at given point
+   \brief Get RGB color at given point
 
-   Colors are translated to rgb and returned as Rxxx Gxxx Bxxx
-   Usually call after GS_get_selected_point_on_surface()
+   Colors are translated to rgb and returned as Rxxx Gxxx Bxxx Usually
+   call after GS_get_selected_point_on_surface().
 
-   Prints "NULL" or the value (i.e., "921.5") to valstr
+   Prints NULL or the value (i.e., "921.5") to valstr
 
-   Usually call after GS_get_selected_point_on_surface()
-
    \param id surface id
-   \param att
+   \param att attribute id
    \param[out] valstr value string (allocated, dim?)
    \param x,y real coordinates
-
+   
    \return -1 if point outside of window or masked
    \return 1 on success
  */
@@ -1307,9 +1304,9 @@
 
     *valstr = '\0';
     gs = gs_get_surf(id);
-
+    
     if (NULL == gs) {
-	return (-1);
+	return -1;
     }
 
     pt[X] = x;
@@ -1318,7 +1315,7 @@
     gsd_real2surf(gs, pt);
 
     if (gs_point_is_masked(gs, pt)) {
-	return (-1);
+	return -1;
     }
 
     if (!in_vregion(gs, pt)) {
@@ -1337,10 +1334,10 @@
 	    sprintf(valstr, "%f", gs->att[att].constant);
 	}
 
-	return (1);
+	return 1;
     }
     else if (MAP_ATT != gs_get_att_src(gs, att)) {
-	return (-1);
+	return -1;
     }
 
     buff = gs_get_att_typbuff(gs, att, 0);
@@ -1373,8 +1370,6 @@
     return (1);
 }
 
-#endif
-
 /*!
    \brief Unset attribute
 
@@ -3200,14 +3195,15 @@
 }
 
 /*!
-   \brief Measure distance "as the ball rolls" between two points on surface
+   \brief Measure distance "as the ball rolls" between two points on
+   surface
 
-   \param hs
-   \param x1,y1,x2,y2 distance line nodes
-   \param dist ?
-   \param use_exag use exag ?
+   \param hs surface id
+   \param x1,y1,x2,y2 two points on surface
+   \param[out] dist measured distance
+   \param use_exag use exag. surface
 
-   \return 0 on error or if one or more points is not in region,
+   \return 0 on error or if one or more points is not in region
    \return distance following terrain
  */
 int GS_get_distance_alongsurf(int hs, float x1, float y1, float x2, float y2,
@@ -3215,11 +3211,12 @@
 {
     geosurf *gs;
     float p1[2], p2[2];
-
-    if (NULL == (gs = gs_get_surf(hs))) {
-	return (0);
+    
+    gs = gs_get_surf(hs);
+    if (gs == NULL) {
+	return 0;
     }
-
+    
     p1[X] = x1;
     p1[Y] = y1;
     p2[X] = x2;
@@ -3227,7 +3224,9 @@
     gsd_real2surf(gs, p1);
     gsd_real2surf(gs, p2);
 
-    return (gs_distance_onsurf(gs, p1, p2, dist, use_exag));
+    G_debug(3, "GS_get_distance_alongsurf(): hs=%d p1=%f,%f p2=%f,%f",
+	    hs, x1, y1, x2, y2);
+    return gs_distance_onsurf(gs, p1, p2, dist, use_exag);
 }
 
 /*!



More information about the grass-commit mailing list