Salome HOME
patch for correct compilation (Windows)
[modules/hydro.git] / src / HYDROData / HYDROData_Bathymetry.cxx
index 14e6a24af744e33d274ce3c545a5ac1a777d4a53..c62352ef36f4412e359ef28151d9a45d3c4a92ea 100644 (file)
@@ -1,26 +1,68 @@
+// Copyright (C) 2014-2015  EDF-R&D
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
 
 #include "HYDROData_Bathymetry.h"
+#include "HYDROData_Document.h"
 #include "HYDROData_Tool.h"
+#include "HYDROData_PolylineXY.h"
 
 #include <gp_XY.hxx>
 #include <gp_XYZ.hxx>
 
 #include <TDataStd_RealArray.hxx>
 #include <TDataStd_AsciiString.hxx>
+#include <TDataStd_Integer.hxx>
 
+#include <QColor>
 #include <QFile>
 #include <QFileInfo>
 #include <QPointF>
 #include <QPolygonF>
 #include <QStringList>
 
-#define INVALID_ALTITUDE_VALUE -9999.0
+#include <vtkPoints.h>
+#include <vtkDelaunay2D.h>
+#include <vtkPolyData.h>
+#include <vtkSmartPointer.h>
+#include <vtkIdList.h>
 
+#include <iostream>
+
+#include <math.h>
+
+// #define _TIMER
+#ifdef _TIMER
+#include <OSD_Timer.hxx>
+#endif
+
+#define _DEVDEBUG_
+#include "HYDRO_trace.hxx"
+
+IMPLEMENT_STANDARD_HANDLE(HYDROData_Bathymetry, HYDROData_IAltitudeObject)
+IMPLEMENT_STANDARD_RTTIEXT(HYDROData_Bathymetry, HYDROData_IAltitudeObject)
+
+//HYDROData_QuadtreeNode* HYDROData_Bathymetry::myQuadtree = 0;
+std::map<int, HYDROData_QuadtreeNode*> HYDROData_Bathymetry::myQuadtrees;
+std::map<int, vtkPolyData*> HYDROData_Bathymetry::myDelaunay2D;
 
-IMPLEMENT_STANDARD_HANDLE(HYDROData_Bathymetry, HYDROData_Object)
-IMPLEMENT_STANDARD_RTTIEXT(HYDROData_Bathymetry, HYDROData_Object)
 
 HYDROData_Bathymetry::HYDROData_Bathymetry()
+: HYDROData_IAltitudeObject()
 {
 }
 
@@ -28,47 +70,66 @@ HYDROData_Bathymetry::~HYDROData_Bathymetry()
 {
 }
 
-double HYDROData_Bathymetry::GetInvalidAltitude()
+QStringList HYDROData_Bathymetry::DumpToPython( const QString& thePyScriptPath,
+                                                MapOfTreatedObjects& theTreatedObjects ) const
 {
-  return INVALID_ALTITUDE_VALUE;
+  QStringList aResList = dumpObjectCreation( theTreatedObjects );
+  QString aBathymetryName = GetObjPyName();
+
+  aResList << QString( "%1.SetAltitudesInverted( %2 )" )
+              .arg( aBathymetryName ).arg( IsAltitudesInverted() );
+
+  TCollection_AsciiString aFilePath = GetFilePath();
+  aResList << QString( "if not(%1.ImportFromFile( \"%2\" )):" )
+              .arg( aBathymetryName ).arg( aFilePath.ToCString() );
+  aResList << QString( "  raise ValueError('problem while loading bathymetry')" );
+  aResList << QString( "" );
+  aResList << QString( "%1.Update()" ).arg( aBathymetryName );
+  aResList << QString( "" );
+
+  return aResList;
 }
 
 void HYDROData_Bathymetry::SetAltitudePoints( const AltitudePoints& thePoints )
 {
   RemoveAltitudePoints();
 
-  if ( thePoints.isEmpty() )
+  if ( thePoints.IsEmpty() )
     return;
 
   // Save coordinates
   Handle(TDataStd_RealArray) aCoordsArray = 
-    TDataStd_RealArray::Set( myLab.FindChild( DataTag_AltitudePoints ), 0, thePoints.size() * 3 - 1 );
+    TDataStd_RealArray::Set( myLab.FindChild( DataTag_AltitudePoints ), 0, thePoints.Length() * 3 - 1 );
 
-  AltitudePoints::const_iterator aListItBeg =  thePoints.constBegin();
-  AltitudePoints::const_iterator aListItEnd =  thePoints.constEnd();
-  for ( int i = 0 ; aListItBeg != aListItEnd; ++i, ++aListItBeg )
+  AltitudePoints::Iterator anIter( thePoints );
+  for ( int i = 0 ; anIter.More(); ++i, anIter.Next() )
   {
-    const AltitudePoint& aPoint = *aListItBeg;
+    const AltitudePoint& aPoint = anIter.Value();
 
     aCoordsArray->SetValue( i * 3, aPoint.X() );
     aCoordsArray->SetValue( i * 3 + 1, aPoint.Y() );
     aCoordsArray->SetValue( i * 3 + 2, aPoint.Z() );
   }
+
+  Changed( Geom_Z );
 }
 
-HYDROData_Bathymetry::AltitudePoints HYDROData_Bathymetry::GetAltitudePoints() const
+HYDROData_Bathymetry::AltitudePoints HYDROData_Bathymetry::GetAltitudePoints(bool IsConvertToGlobal) const
 {
   AltitudePoints aPoints;
 
+  TDF_Label aLabel = myLab.FindChild( DataTag_AltitudePoints, false );
+  if ( aLabel.IsNull() )
+    return aPoints;
+
   Handle(TDataStd_RealArray) aCoordsArray;
-  if ( !myLab.FindChild( DataTag_AltitudePoints ).FindAttribute( TDataStd_RealArray::GetID(), aCoordsArray ) )
+  if ( !aLabel.FindAttribute( TDataStd_RealArray::GetID(), aCoordsArray ) )
     return aPoints;
 
-  int aLowerIdx = aCoordsArray->Lower();
-  int anUpperIdx = aCoordsArray->Upper();
+  Handle(HYDROData_Document) aDoc = HYDROData_Document::Document( myLab );
   for ( int i = aCoordsArray->Lower(), n = aCoordsArray->Upper(); i <= n; )
   {
-    if ( i + 3 > n )
+    if ( i + 3 > n + 1 )
       break;
 
     AltitudePoint aPoint;
@@ -76,16 +137,115 @@ HYDROData_Bathymetry::AltitudePoints HYDROData_Bathymetry::GetAltitudePoints() c
     aPoint.SetY( aCoordsArray->Value( i++ ) );
     aPoint.SetZ( aCoordsArray->Value( i++ ) );
 
-    aPoints << aPoint;
+    if( IsConvertToGlobal )
+      aDoc->Transform( aPoint, false );
+    aPoints.Append( aPoint );
   }
 
   return aPoints;
 }
 
+HYDROData_QuadtreeNode* HYDROData_Bathymetry::GetQuadtreeNodes() const
+{
+  TDF_Label aLabel = myLab.FindChild(DataTag_AltitudePoints, false);
+  if (aLabel.IsNull())
+    return 0;
+  int labkey = myLab.Tag();
+  //int altkey = aLabel.Tag();
+  //DEBTRACE("GetQuadtreeNodes this labkey altkey "<<this<<" "<<labkey<<" "<<altkey);
+  // if (myQuadtree->isEmpty() )
+  if (myQuadtrees.find(labkey) == myQuadtrees.end())
+    {
+      DEBTRACE("GetQuadtreeNodes init " << this << " " << labkey);
+      HYDROData_QuadtreeNode* aQuadtree = new HYDROData_QuadtreeNode(0, 30, 5, 0.);
+      myQuadtrees[labkey] = aQuadtree;
+      TDF_Label aLabel = myLab.FindChild(DataTag_AltitudePoints, false);
+      if (aLabel.IsNull())
+        return 0;
+
+      Handle(TDataStd_RealArray) aCoordsArray;
+      if (!aLabel.FindAttribute(TDataStd_RealArray::GetID(), aCoordsArray))
+        return 0;
+
+      Nodes_3D* aListOfNodes = new Nodes_3D();
+
+      int index =0;
+      for (int i = aCoordsArray->Lower(), n = aCoordsArray->Upper(); i <= n;)
+        {
+          if (i + 3 > n + 1)
+            break;
+
+          double x = aCoordsArray->Value(i++);
+          double y = aCoordsArray->Value(i++);
+          double z = aCoordsArray->Value(i++);
+          gpi_XYZ* aPoint = new gpi_XYZ(x, y, z, index);
+          index++;
+          aListOfNodes->push_back(aPoint);
+        }
+      DEBTRACE("  GetQuadtreeNodes call setNodesAndCompute");
+      aQuadtree->setNodesAndCompute(aListOfNodes);
+      return aQuadtree;
+    }
+  else
+    return myQuadtrees[labkey];
+}
+
+vtkPolyData* HYDROData_Bathymetry::GetVtkDelaunay2D() const
+{
+  TDF_Label aLabel = myLab.FindChild(DataTag_AltitudePoints, false);
+  if (aLabel.IsNull())
+    return 0;
+  int labkey = myLab.Tag();
+  //int altkey = aLabel.Tag();
+  //DEBTRACE("GetVtkDelaunay2D this labkey altkey "<<this<<" "<<labkey<<" "<<altkey);
+  if (myDelaunay2D.find(labkey) == myDelaunay2D.end())
+    {
+      DEBTRACE("GetVtkDelaunay2D init " << this << " " << labkey);
+
+      TDF_Label aLabel = myLab.FindChild(DataTag_AltitudePoints, false);
+      if (aLabel.IsNull())
+        return 0;
+      Handle(TDataStd_RealArray) aCoordsArray;
+      if (!aLabel.FindAttribute(TDataStd_RealArray::GetID(), aCoordsArray))
+        return 0;
+
+      vtkPoints *points = vtkPoints::New();
+      points->Allocate(aCoordsArray->Upper() +1);
+      for (int i = aCoordsArray->Lower(), n = aCoordsArray->Upper(); i <= n;)
+        {
+          if (i + 3 > n + 1)
+            break;
+          double x = aCoordsArray->Value(i++);
+          double y = aCoordsArray->Value(i++);
+          double z = aCoordsArray->Value(i++);
+          vtkIdType index = points->InsertNextPoint(x, y, z); // same index than in GetQuadtreeNodes
+          //DEBTRACE("  " << index);
+        }
+      vtkPolyData* profile = vtkPolyData::New();
+      profile->SetPoints(points);
+      DEBTRACE("Number of Points: "<< points->GetNumberOfPoints());
+
+      vtkDelaunay2D* delaunay2D = vtkDelaunay2D::New();
+      delaunay2D->SetInputData(profile);
+      delaunay2D->Update();
+      vtkPolyData* data = delaunay2D->GetOutput();
+      data->BuildLinks();
+      myDelaunay2D[labkey] = data;
+      return data;
+    }
+  else
+    return myDelaunay2D[labkey];
+
+}
+
 void HYDROData_Bathymetry::RemoveAltitudePoints()
 {
-  TDF_Label aLab = myLab.FindChild( DataTag_AltitudePoints );
-  aLab.ForgetAllAttributes();
+  TDF_Label aLabel = myLab.FindChild( DataTag_AltitudePoints, false );
+  if ( !aLabel.IsNull() )
+  {
+    aLabel.ForgetAllAttributes();
+    Changed( Geom_Z );
+  }
 }
 
 void interpolateAltitudeForPoints( const gp_XY&                               thePoint,
@@ -141,161 +301,188 @@ void interpolateAltitudeForPoints( const gp_XY&                               th
   theResPoint.SetZ( aResVal );
 }
 
-double HYDROData_Bathymetry::GetAltitudeForPoint( const QPointF& thePoint ) const
+bool interpolZtriangle(const gp_XY& point, vtkPolyData* delaunay2D, vtkIdList* triangle, double& z)
 {
-  gp_XY aGpPoint( thePoint.x(), thePoint.y() );
-  return GetAltitudeForPoint( aGpPoint );
+
+  int nbPts = triangle->GetNumberOfIds();
+  if (nbPts != 3)
+    {
+      DEBTRACE("not a triangle ?");
+      return false;
+    }
+  vtkIdType s[3];
+  double v[3][3]; // v[i][j] = j coordinate of node i
+  for (int i=0; i<3; i++)
+    {
+      s[i] = triangle->GetId(i);
+      delaunay2D->GetPoint(s[i],v[i]);
+    }
+  //DEBTRACE("triangle node id: " << s[0] << " " << s[1] << " " << s[2]);
+  //DEBTRACE("triangle node 0: " << v[0][0]  << " " << v[0][1] << " " << v[0][2]);
+  //DEBTRACE("triangle node 1: " << v[1][0]  << " " << v[1][1] << " " << v[1][2]);
+  //DEBTRACE("triangle node 2: " << v[2][0]  << " " << v[2][1] << " " << v[2][2]);
+
+  // compute barycentric coordinates (https://en.wikipedia.org/wiki/Barycentric_coordinate_system)
+  //     det = (y2-y3)(x1-x3)+(x3-x2)(y1-y3)
+  double det = (v[1][1]-v[2][1])*(v[0][0]-v[2][0]) + (v[2][0]-v[1][0])*(v[0][1]-v[2][1]);
+  if (det == 0)
+    {
+      DEBTRACE("flat triangle ?");
+      return false;
+    }
+
+  //     l0  = ((y2-y3)(x -x3)+(x3-x2)(y -y3))/det
+  double l0  = (v[1][1]-v[2][1])*(point.X()-v[2][0]) + (v[2][0]-v[1][0])*(point.Y()-v[2][1]);
+  l0 = l0/det;
+
+  //     l1  = ((y3-y1)(x -x3)+(x1-x3)(y -y3))/det
+  double l1  = (v[2][1]-v[0][1])*(point.X()-v[2][0]) + (v[0][0]-v[2][0])*(point.Y()-v[2][1]);
+  l1 = l1/det;
+
+  double l2  = 1 -l0 -l1;
+  //DEBTRACE("l0, l1, l2: " << l0  << " "  << l1  << " "  << l2);
+
+  if ((l0>=0) && (l0<=1) && (l1>=0) && (l1<=1) && (l2>=0) && (l2<=1))
+    {
+      z = l0*v[0][2] + l1*v[1][2] + l2*v[2][2];
+      return true;
+    }
+  return false;
 }
 
-double HYDROData_Bathymetry::GetAltitudeForPoint( const gp_XY& thePoint ) const
+double HYDROData_Bathymetry::GetAltitudeForPoint(const gp_XY& thePoint, int theMethod) const
 {
-  double aResAltitude = -9999.90;
-  
-  AltitudePoints anAltitudePoints = GetAltitudePoints();
-  if ( anAltitudePoints.isEmpty() )
-    return aResAltitude;
-
-  QPolygonF aBoundingRect;
-
-  // Boundary plane
-  // [ 0 (top-left) ]          [ 1 (top-right) ]
-  //                  thePoint
-  // [ 2 (bot-left) ]          [ 3 (bot-right) ] 
-  AltitudePoint aBounds[ 4 ] = { AltitudePoint( -DBL_MAX, -DBL_MAX, INVALID_ALTITUDE_VALUE ),
-                                 AltitudePoint(  DBL_MAX, -DBL_MAX, INVALID_ALTITUDE_VALUE ),
-                                 AltitudePoint( -DBL_MAX,  DBL_MAX, INVALID_ALTITUDE_VALUE ),
-                                 AltitudePoint(  DBL_MAX,  DBL_MAX, INVALID_ALTITUDE_VALUE ) }; 
-
-  AltitudePoints::const_iterator aListItBeg = anAltitudePoints.constBegin();
-  AltitudePoints::const_iterator aListItEnd = anAltitudePoints.constEnd();
-  for ( ; aListItBeg != aListItEnd; ++aListItBeg )
-  {
-    const AltitudePoint& aPoint = *aListItBeg;
+  DEBTRACE("GetAltitudeForPoint p(" << thePoint.X() << ", " << thePoint.Y() << "), interpolation method: " << theMethod);
+  double anInvalidAltitude = GetInvalidAltitude();
+  double aResAltitude = anInvalidAltitude;
 
-    double aDeltaX = Abs( aPoint.X() ) - Abs( thePoint.X() );
-    double aDeltaY = Abs( aPoint.Y() ) - Abs( thePoint.Y() );
+  // --- find the nearest point in the bathymetry cloud, with quadtree
 
-    if ( ValuesEquals( aDeltaX, 0.0 ) ) // Both left and right sides
+  HYDROData_QuadtreeNode* aQuadtree = GetQuadtreeNodes();
+  if (!aQuadtree)
     {
-      if ( ValuesEquals( aDeltaY, 0.0 ) ) // Both top and bottom sides
-      {
-        aResAltitude = aPoint.Z();
-        return aResAltitude;
-      }
-      else if ( aDeltaY < 0 ) // top side
-      {
-        // top border
-        if ( ValuesMoreEquals( aPoint.X(), aBounds[ 0 ].X() ) && ValuesMoreEquals( aPoint.Y(), aBounds[ 0 ].Y() ) )
-          aBounds[ 0 ] = aPoint;
-        if ( ValuesLessEquals( aPoint.X(), aBounds[ 1 ].X() ) && ValuesMoreEquals( aPoint.Y(), aBounds[ 1 ].Y() ) )
-          aBounds[ 1 ] = aPoint;
-      }
-      else
-      {
-        // bottom border
-        if ( ValuesMoreEquals( aPoint.X(), aBounds[ 2 ].X() ) && ValuesLessEquals( aPoint.Y(), aBounds[ 2 ].Y() ) )
-          aBounds[ 2 ] = aPoint;
-        if ( ValuesLessEquals( aPoint.X(), aBounds[ 3 ].X() ) && ValuesLessEquals( aPoint.Y(), aBounds[ 3 ].Y() ) )
-          aBounds[ 3 ] = aPoint;
-      }
+      DEBTRACE("  no Quadtree");
+      return aResAltitude;
     }
-    else if ( aDeltaX < 0 ) // left side
+
+  std::map<double, const gpi_XYZ*> dist2nodes;
+  aQuadtree->NodesAround(thePoint, dist2nodes, aQuadtree->getPrecision());
+  while (dist2nodes.size() == 0)
     {
-      if ( ValuesEquals( aDeltaY, 0.0 ) )
-      {
-        // Left border
-        if ( ValuesMoreEquals( aPoint.X(), aBounds[ 0 ].X() ) && ValuesMoreEquals( aPoint.Y(), aBounds[ 0 ].Y() ) )
-          aBounds[ 0 ] = aPoint;
-        if ( ValuesMoreEquals( aPoint.X(), aBounds[ 2 ].X() ) && ValuesLessEquals( aPoint.Y(), aBounds[ 2 ].Y() ) )
-          aBounds[ 2 ] = aPoint;
-      }
-      else if ( aDeltaY < 0 )
-      {
-        // top left corner
-        if ( ValuesMoreEquals( aPoint.X(), aBounds[ 0 ].X() ) && ValuesMoreEquals( aPoint.Y(), aBounds[ 0 ].Y() ) )
-          aBounds[ 0 ] = aPoint;
-      }
-      else
-      {
-        // bottom left corner
-        if ( ValuesMoreEquals( aPoint.X(), aBounds[ 2 ].X() ) && ValuesLessEquals( aPoint.Y(), aBounds[ 2 ].Y() ) )
-          aBounds[ 2 ] = aPoint;
-      }
+      aQuadtree->setPrecision(aQuadtree->getPrecision() *2);
+      DEBTRACE("adjust precision to: " << aQuadtree->getPrecision());
+      aQuadtree->NodesAround(thePoint, dist2nodes, aQuadtree->getPrecision());
     }
-    else // right side
+  std::map<double, const gpi_XYZ*>::const_iterator it = dist2nodes.begin();
+  aResAltitude = it->second->Z();
+  int nodeIndex = it->second->getIndex();
+  DEBTRACE("  number of points found: " << dist2nodes.size() << " nearest z: " << aResAltitude << " point index: " << nodeIndex);
+
+  // --- for coarse bathymetry clouds (when the TELEMAC mesh is more refined than the bathymetry cloud)
+  //     interpolation is required.
+  //     - get a Delaunay2D mesh on the bathymetry cloud,
+  //     - get the triangle containing the point in the Delaunay2D mesh,
+  //     - interpolate altitude
+
+  bool isBathyInterpolRequired = false;
+  if (theMethod)
+    isBathyInterpolRequired =true;
+  if (isBathyInterpolRequired)
     {
-      if ( ValuesEquals( aDeltaY, 0.0 ) )
-      {
-        // Right border
-        if ( ValuesLessEquals( aPoint.X(), aBounds[ 1 ].X() ) && ValuesMoreEquals( aPoint.Y(), aBounds[ 1 ].Y() ) )
-          aBounds[ 1 ] = aPoint;
-        if ( ValuesLessEquals( aPoint.X(), aBounds[ 3 ].X() ) && ValuesLessEquals( aPoint.Y(), aBounds[ 3 ].Y() ) )
-          aBounds[ 3 ] = aPoint;
-      }
-      else if ( aDeltaY < 0 )
-      {
-        // top right corner
-        if ( ValuesLessEquals( aPoint.X(), aBounds[ 1 ].X() ) && ValuesMoreEquals( aPoint.Y(), aBounds[ 1 ].Y() ) )
-          aBounds[ 1 ] = aPoint;
-      }
-      else
-      {
-        // bottom right corner
-        if ( ValuesLessEquals( aPoint.X(), aBounds[ 3 ].X() ) && ValuesLessEquals( aPoint.Y(), aBounds[ 3 ].Y() ) )
-          aBounds[ 3 ] = aPoint;
-      }
+      vtkPolyData* aDelaunay2D = GetVtkDelaunay2D();
+      vtkIdList* cells= vtkIdList::New();
+      cells->Allocate(64);
+      vtkIdList* points= vtkIdList::New();
+      points->Allocate(64);
+      aDelaunay2D->GetPointCells(nodeIndex, cells);
+      vtkIdType nbCells = cells->GetNumberOfIds();
+      DEBTRACE("  triangles on nearest point: " << nbCells);
+      bool isInside = false;
+      for (int i=0; i<nbCells; i++)
+        {
+          aDelaunay2D->GetCellPoints(cells->GetId(i), points);
+          double z = 0;
+          isInside = interpolZtriangle(thePoint, aDelaunay2D, points, z);
+          if (isInside)
+            {
+              aResAltitude = z;
+              DEBTRACE("  interpolated z: " << z);
+              break;
+            }
+        }
+      if (!isInside) DEBTRACE("  point outside triangles, nearest z kept");
     }
+  return aResAltitude;
+}
+
+void HYDROData_Bathymetry::SetFilePath( const TCollection_AsciiString& theFilePath )
+{
+  TDataStd_AsciiString::Set( myLab.FindChild( DataTag_FilePath ), theFilePath );
+}
 
-    // Update bounding rectangle of our global grid
-    aBoundingRect << QPointF( aPoint.X(), aPoint.Y() );
+TCollection_AsciiString HYDROData_Bathymetry::GetFilePath() const
+{
+  TCollection_AsciiString aRes;
+
+  TDF_Label aLabel = myLab.FindChild( DataTag_FilePath, false );
+  if ( !aLabel.IsNull() )
+  {
+    Handle(TDataStd_AsciiString) anAsciiStr;
+    if ( aLabel.FindAttribute( TDataStd_AsciiString::GetID(), anAsciiStr ) )
+      aRes = anAsciiStr->Get();
   }
 
-  // Check if requested point is inside of our bounding rectangle
-  if ( !aBoundingRect.boundingRect().contains( thePoint.X(), thePoint.Y() ) )
-    return INVALID_ALTITUDE_VALUE;
+  return aRes;
+}
 
-  // Calculate result altitude for point
-  AltitudePoint aFirstPoint( aBounds[ 0 ] ), aSecPoint( aBounds[ 1 ] );
+void HYDROData_Bathymetry::SetAltitudesInverted( const bool theIsInverted,
+                                                 const bool theIsUpdate )
+{
+  bool anIsAltitudesInverted = IsAltitudesInverted();
+  if ( anIsAltitudesInverted == theIsInverted )
+    return;
 
-  // At first we merge top and bottom borders
-  if ( aBounds[ 0 ].Y() != aBounds[ 2 ].Y() || aBounds[ 0 ].X() != aBounds[ 2 ].X() )
-    interpolateAltitudeForPoints( thePoint, aBounds[ 0 ], aBounds[ 2 ], aFirstPoint, true );
+  TDataStd_Integer::Set( myLab.FindChild( DataTag_AltitudesInverted ), (Standard_Integer)theIsInverted );
 
-  if ( aBounds[ 1 ].Y() != aBounds[ 3 ].Y() || aBounds[ 1 ].X() != aBounds[ 3 ].X() )
-    interpolateAltitudeForPoints( thePoint, aBounds[ 1 ], aBounds[ 3 ], aSecPoint, true );
+  Changed( Geom_Z );
 
-  AltitudePoint aResPoint( aFirstPoint );
+  if ( !theIsUpdate )
+    return;
 
-  // At last we merge left and right borders
-  if ( aFirstPoint.Y() != aSecPoint.Y() || aFirstPoint.X() != aSecPoint.X() )
-    interpolateAltitudeForPoints( thePoint, aFirstPoint, aSecPoint, aResPoint, false );
-    
-  aResAltitude = aResPoint.Z();
+  // Update altitude points
+  AltitudePoints anAltitudePoints = GetAltitudePoints();
+  if ( anAltitudePoints.IsEmpty() )
+    return;
 
-  return aResAltitude;
-}
+  AltitudePoints::Iterator anIter( anAltitudePoints );
+  for ( ; anIter.More(); anIter.Next() )
+  {
+    AltitudePoint& aPoint = anIter.ChangeValue();
+    aPoint.SetZ( aPoint.Z() * -1 );
+  }
 
-void HYDROData_Bathymetry::SetFilePath(const QString& theFilePath)
-{
-  TCollection_AsciiString anAsciiStr( theFilePath.toStdString().c_str() );
-  TDataStd_AsciiString::Set( myLab.FindChild( DataTag_FilePath ), anAsciiStr );
+  SetAltitudePoints( anAltitudePoints );
 }
 
-QString HYDROData_Bathymetry::GetFilePath() const
+bool HYDROData_Bathymetry::IsAltitudesInverted() const
 {
-  QString aRes;
+  bool aRes = false;
 
-  Handle(TDataStd_AsciiString) anAsciiStr;
-  if ( myLab.FindChild( DataTag_FilePath ).FindAttribute( TDataStd_AsciiString::GetID(), anAsciiStr ) )
-    aRes = QString( anAsciiStr->Get().ToCString() );
+  TDF_Label aLabel = myLab.FindChild( DataTag_AltitudesInverted, false );
+  if ( !aLabel.IsNull() )
+  {
+    Handle(TDataStd_Integer) anIntVal;
+    if ( aLabel.FindAttribute( TDataStd_Integer::GetID(), anIntVal ) )
+      aRes = (bool)anIntVal->Get();
+  }
 
   return aRes;
 }
 
-bool HYDROData_Bathymetry::ImportFromFile( const QString& theFileName )
+bool HYDROData_Bathymetry::ImportFromFile( const TCollection_AsciiString& theFileName )
 {
   // Try to open the file
-  QFile aFile( theFileName );
+  QFile aFile( theFileName.ToCString() );
   if ( !aFile.exists() || !aFile.open( QIODevice::ReadOnly ) )
     return false;
 
@@ -308,9 +495,21 @@ bool HYDROData_Bathymetry::ImportFromFile( const QString& theFileName )
   // Try to import the file
   if ( aFileSuf == "xyz" )
     aRes = importFromXYZFile( aFile, aPoints );
-    
+  else if ( aFileSuf == "asc" )
+    aRes = importFromASCFile( aFile, aPoints );
+
   // Close the file
   aFile.close();
+  
+
+  // Convert from global to local CS
+  Handle_HYDROData_Document aDoc = HYDROData_Document::Document( myLab );
+  AltitudePoints::Iterator anIter( aPoints );
+  for ( ; anIter.More(); anIter.Next() )
+  {
+    AltitudePoint& aPoint = anIter.ChangeValue();
+    aDoc->Transform( aPoint, true );
+  }
 
   if ( aRes )
   {
@@ -319,11 +518,11 @@ bool HYDROData_Bathymetry::ImportFromFile( const QString& theFileName )
     SetAltitudePoints( aPoints );
   }
 
-  return aRes && !aPoints.isEmpty();
+  return aRes && !aPoints.IsEmpty();
 }
 
 bool HYDROData_Bathymetry::importFromXYZFile( QFile&          theFile,
-                                              AltitudePoints& thePoints )
+                                              AltitudePoints& thePoints ) const
 {
   if ( !theFile.isOpen() )
     return false;
@@ -333,13 +532,19 @@ bool HYDROData_Bathymetry::importFromXYZFile( QFile&          theFile,
   //  2. X(float) Y(float) Z(float)
   //  ...
 
+#ifdef _TIMER
+  OSD_Timer aTimer;
+  aTimer.Start();
+#endif
+
+  bool anIsAltitudesInverted = IsAltitudesInverted();
   while ( !theFile.atEnd() )
   {
     QString aLine = theFile.readLine().simplified();
     if ( aLine.isEmpty() )
       continue;
 
-    QStringList aValues = aLine.split( QRegExp( "\\s+" ), QString::SkipEmptyParts );
+    QStringList aValues = aLine.split( ' ', QString::SkipEmptyParts );
     if ( aValues.length() < 3 )
       return false;
 
@@ -353,17 +558,182 @@ bool HYDROData_Bathymetry::importFromXYZFile( QFile&          theFile,
 
     aPoint.SetX( anX.toDouble( &isXOk ) );
     aPoint.SetY( anY.toDouble( &isYOk ) );
-    aPoint.SetZ(  aZ.toDouble( &isZOk ) );
+    aPoint.SetZ( aZ.toDouble( &isZOk ) );
 
     if ( !isXOk || !isYOk || !isZOk )
       return false;
 
-    thePoints << aPoint;
+    if ( HYDROData_Tool::IsNan( aPoint.X() ) || HYDROData_Tool::IsInf( aPoint.X() ) ||
+         HYDROData_Tool::IsNan( aPoint.Y() ) || HYDROData_Tool::IsInf( aPoint.Y() ) ||
+         HYDROData_Tool::IsNan( aPoint.Z() ) || HYDROData_Tool::IsInf( aPoint.Z() ) )
+      return false;
+
+    // Invert the z value if requested
+    if ( anIsAltitudesInverted )
+      aPoint.SetZ( -aPoint.Z() );
+
+    thePoints.Append( aPoint );
+  }
+
+#ifdef _TIMER
+  aTimer.Stop();
+  std::ofstream stream( "W:/HYDRO/WORK/log.txt", std::ofstream::out );
+  aTimer.Show( stream );
+#endif
+
+  return true;
+}
+
+bool HYDROData_Bathymetry::importFromASCFile( QFile&          theFile,
+                                              AltitudePoints& thePoints ) const
+{
+  if ( !theFile.isOpen() )
+    return false;
+
+  QString aLine;
+  QStringList aStrList;
+
+  int aNCols;
+  int aNRows;
+  double anXllCorner; 
+  double anYllCorner; 
+  double aCellSize; 
+  double aNoDataValue;
+
+  aLine = theFile.readLine().simplified();
+  aStrList = aLine.split( ' ', QString::SkipEmptyParts );
+  if ( aStrList.length() != 2 && aStrList[0].toLower() != "ncols" )
+    return false;
+  aNCols = aStrList[1].toInt();
+
+  aLine = theFile.readLine().simplified();
+  aStrList = aLine.split( ' ', QString::SkipEmptyParts );
+  if ( aStrList.length() != 2 && aStrList[0].toLower() != "nrows" )
+    return false;
+  aNRows = aStrList[1].toInt();
+
+  aLine = theFile.readLine().simplified();
+  aStrList = aLine.split( ' ', QString::SkipEmptyParts );
+  if ( aStrList.length() != 2 && aStrList[0].toLower() != "xllcorner" )
+    return false;
+  anXllCorner = aStrList[1].toDouble();
+
+  aLine = theFile.readLine().simplified();
+  aStrList = aLine.split( ' ', QString::SkipEmptyParts );
+  if ( aStrList.length() != 2 && aStrList[0].toLower() != "yllcorner" )
+    return false;
+  anYllCorner = aStrList[1].toDouble();
+
+  aLine = theFile.readLine().simplified();
+  aStrList = aLine.split( ' ', QString::SkipEmptyParts );
+  if ( aStrList.length() != 2 && aStrList[0].toLower() != "cellsize" )
+    return false;
+  aCellSize = aStrList[1].toDouble();
+
+  aLine = theFile.readLine().simplified();
+  aStrList = aLine.split( ' ', QString::SkipEmptyParts );
+  if ( aStrList.length() != 2 && aStrList[0].toLower() != "nodata_value" )
+    return false;
+  aNoDataValue = aStrList[1].toDouble();
+
+  bool anIsAltitudesInverted = IsAltitudesInverted();
+
+  int i = 0;
+  int aStrLength = 0;
+  while ( !theFile.atEnd() )
+  {
+    aLine = theFile.readLine().simplified();
+    aStrList = aLine.split( ' ', QString::SkipEmptyParts );
+
+    aStrLength =  aStrList.length();
+    if ( aStrLength == 0 )
+      continue;
+
+    if ( aStrLength != aNRows )
+      return false;
+
+    for (int j = 0; j < aNCols; j++)
+    {
+      if (aStrList[j].toDouble() != aNoDataValue)
+      {
+        AltitudePoint aPoint;
+        aPoint.SetX(anXllCorner + aCellSize*(j + 0.5));
+        aPoint.SetY(anYllCorner + aCellSize*(aNRows - i + 0.5));
+        aPoint.SetZ(aStrList[j].toDouble());
+
+        if ( anIsAltitudesInverted )
+         aPoint.SetZ( -aPoint.Z() );
+
+        thePoints.Append(aPoint);
+      }
+    }
+    i++;
+
   }
 
   return true;
+
 }
 
 
+Handle_HYDROData_PolylineXY HYDROData_Bathymetry::CreateBoundaryPolyline() const
+{
+  Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
+  Handle_HYDROData_PolylineXY aResult = 
+    Handle_HYDROData_PolylineXY::DownCast( aDocument->CreateObject( KIND_POLYLINEXY ) );
+
+  if( aResult.IsNull() )
+    return aResult;
+
+  //search free name
+  QString aPolylinePref = GetName() + "_Boundary";
+  QString aPolylineName = HYDROData_Tool::GenerateObjectName( aDocument, aPolylinePref );
+  aResult->SetName( aPolylineName );
+
+  double Xmin = 0.0, Xmax = 0.0, Ymin = 0.0, Ymax = 0.0;
+  bool isFirst = true;
+  AltitudePoints aPoints = GetAltitudePoints();
+
+  AltitudePoints::Iterator anIter( aPoints );
+  for ( ; anIter.More(); anIter.Next() )
+  {
+    const AltitudePoint& aPoint = anIter.Value();
+
+    double x = aPoint.X(), y = aPoint.Y();
+    if( isFirst || x<Xmin )
+      Xmin = x;
+    if( isFirst || x>Xmax )
+      Xmax = x;
+    if( isFirst || y<Ymin )
+      Ymin = y;
+    if( isFirst || y>Ymax )
+      Ymax = y;
+    isFirst = false;
+  }
 
+  aResult->AddSection( "bound", HYDROData_IPolyline::SECTION_POLYLINE, true );
+  aResult->AddPoint( 0, HYDROData_IPolyline::Point( Xmin, Ymin ) );
+  aResult->AddPoint( 0, HYDROData_IPolyline::Point( Xmin, Ymax ) );
+  aResult->AddPoint( 0, HYDROData_IPolyline::Point( Xmax, Ymax ) );
+  aResult->AddPoint( 0, HYDROData_IPolyline::Point( Xmax, Ymin ) );
+  
+  aResult->SetWireColor( HYDROData_PolylineXY::DefaultWireColor() );
+  
+  aResult->Update();
+
+  return aResult;
+}
+
+void HYDROData_Bathymetry::UpdateLocalCS( double theDx, double theDy )
+{
+  gp_XYZ aDelta( theDx, theDy, 0 );
+  AltitudePoints aPoints = GetAltitudePoints();
+  AltitudePoints::Iterator anIter( aPoints );
+  for ( int i = 0 ; anIter.More(); ++i, anIter.Next() )
+  {
+    AltitudePoint& aPoint = anIter.ChangeValue();
+    aPoint += aDelta;
+  }
+  SetAltitudePoints( aPoints );
+}