Salome HOME
68d14dafc10ae3e52d273e3724677c6d90775fa0
[modules/hydro.git] / src / HYDROData / HYDROData_Bathymetry.cxx
1 // Copyright (C) 2014-2015  EDF-R&D
2 // This library is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU Lesser General Public
4 // License as published by the Free Software Foundation; either
5 // version 2.1 of the License, or (at your option) any later version.
6 //
7 // This library is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10 // Lesser General Public License for more details.
11 //
12 // You should have received a copy of the GNU Lesser General Public
13 // License along with this library; if not, write to the Free Software
14 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
15 //
16 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
17 //
18
19 #include "HYDROData_Bathymetry.h"
20 #include "HYDROData_Document.h"
21 #include "HYDROData_Tool.h"
22 #include "HYDROData_PolylineXY.h"
23
24 #include <gp_XY.hxx>
25 #include <gp_XYZ.hxx>
26
27 #include <TDataStd_RealArray.hxx>
28 #include <TDataStd_AsciiString.hxx>
29 #include <TDataStd_Integer.hxx>
30
31 #include <QColor>
32 #include <QFile>
33 #include <QFileInfo>
34 #include <QPointF>
35 #include <QPolygonF>
36 #include <QStringList>
37
38 #include <vtkPoints.h>
39 #include <vtkDelaunay2D.h>
40 #include <vtkPolyData.h>
41 #include <vtkSmartPointer.h>
42 #include <vtkIdList.h>
43 #include <vtkInformation.h>
44 #include <vtkExecutive.h>
45
46 #include <iostream>
47
48 #include <math.h>
49
50 // #define _TIMER
51 #ifdef _TIMER
52 #include <OSD_Timer.hxx>
53 #endif
54
55 #define _DEVDEBUG_
56 #include "HYDRO_trace.hxx"
57
58 IMPLEMENT_STANDARD_HANDLE(HYDROData_Bathymetry, HYDROData_IAltitudeObject)
59 IMPLEMENT_STANDARD_RTTIEXT(HYDROData_Bathymetry, HYDROData_IAltitudeObject)
60
61 //HYDROData_QuadtreeNode* HYDROData_Bathymetry::myQuadtree = 0;
62 std::map<int, HYDROData_QuadtreeNode*> HYDROData_Bathymetry::myQuadtrees;
63 std::map<int, vtkPolyData*> HYDROData_Bathymetry::myDelaunay2D;
64
65
66 hydroDelaunay2D* hydroDelaunay2D::New()
67 {
68   DEBTRACE("hydroDelaunay2D::New()");
69   return new hydroDelaunay2D();
70 }
71 hydroDelaunay2D::hydroDelaunay2D() :
72     vtkDelaunay2D()
73 {
74   DEBTRACE("hydroDelaunay2D");
75 }
76
77 hydroDelaunay2D::~hydroDelaunay2D()
78 {
79   DEBTRACE("~hydroDelaunay2D");
80 }
81
82 int hydroDelaunay2D::RequestData(vtkInformation *request , vtkInformationVector **inv, vtkInformationVector *outv)
83 {
84   DEBTRACE("hydroDelaunay2D::RequestData");
85   vtkDelaunay2D::RequestData(request, inv, outv);
86 }
87
88 int hydroDelaunay2D::ProcessRequest(vtkInformation *request , vtkInformationVector **inv, vtkInformationVector *outv)
89 {
90   DEBTRACE("hydroDelaunay2D::ProcessRequest");
91   vtkDelaunay2D::ProcessRequest(request, inv, outv);
92 }
93
94
95 HYDROData_Bathymetry::HYDROData_Bathymetry()
96 : HYDROData_IAltitudeObject()
97 {
98   //DEBTRACE("HYDROData_Bathymetry constructor start " << this);
99 //  if (! myQuadtree)
100 //    myQuadtree = new HYDROData_QuadtreeNode(0, 30, 5, 0.);
101   //DEBTRACE("HYDROData_Bathymetry constructor end   " << this);
102 }
103
104 HYDROData_Bathymetry::~HYDROData_Bathymetry()
105 {
106   //DEBTRACE("HYDROData_Bathymetry destructor start " << this);
107 //  if (myQuadtree)
108 //    delete myQuadtree;
109 //      Nodes_3D::iterator it = myListOfNodes.begin();
110 //      for( ; it != myListOfNodes.end(); ++it)
111 //              delete *it;
112 //    myListOfNodes.clear();
113 }
114
115 QStringList HYDROData_Bathymetry::DumpToPython( const QString& thePyScriptPath,
116                                                 MapOfTreatedObjects& theTreatedObjects ) const
117 {
118   QStringList aResList = dumpObjectCreation( theTreatedObjects );
119   QString aBathymetryName = GetObjPyName();
120
121   aResList << QString( "%1.SetAltitudesInverted( %2 )" )
122               .arg( aBathymetryName ).arg( IsAltitudesInverted() );
123
124   TCollection_AsciiString aFilePath = GetFilePath();
125   aResList << QString( "if not(%1.ImportFromFile( \"%2\" )):" )
126               .arg( aBathymetryName ).arg( aFilePath.ToCString() );
127   aResList << QString( "  raise ValueError('problem while loading bathymetry')" );
128   aResList << QString( "" );
129   aResList << QString( "%1.Update()" ).arg( aBathymetryName );
130   aResList << QString( "" );
131
132   return aResList;
133 }
134
135 void HYDROData_Bathymetry::SetAltitudePoints( const AltitudePoints& thePoints )
136 {
137   RemoveAltitudePoints();
138
139   if ( thePoints.IsEmpty() )
140     return;
141
142   // Save coordinates
143   Handle(TDataStd_RealArray) aCoordsArray = 
144     TDataStd_RealArray::Set( myLab.FindChild( DataTag_AltitudePoints ), 0, thePoints.Length() * 3 - 1 );
145
146   AltitudePoints::Iterator anIter( thePoints );
147   for ( int i = 0 ; anIter.More(); ++i, anIter.Next() )
148   {
149     const AltitudePoint& aPoint = anIter.Value();
150
151     aCoordsArray->SetValue( i * 3, aPoint.X() );
152     aCoordsArray->SetValue( i * 3 + 1, aPoint.Y() );
153     aCoordsArray->SetValue( i * 3 + 2, aPoint.Z() );
154   }
155
156   Changed( Geom_Z );
157 }
158
159 HYDROData_Bathymetry::AltitudePoints HYDROData_Bathymetry::GetAltitudePoints(bool IsConvertToGlobal) const
160 {
161   AltitudePoints aPoints;
162
163   TDF_Label aLabel = myLab.FindChild( DataTag_AltitudePoints, false );
164   if ( aLabel.IsNull() )
165     return aPoints;
166
167   Handle(TDataStd_RealArray) aCoordsArray;
168   if ( !aLabel.FindAttribute( TDataStd_RealArray::GetID(), aCoordsArray ) )
169     return aPoints;
170
171   Handle(HYDROData_Document) aDoc = HYDROData_Document::Document( myLab );
172   for ( int i = aCoordsArray->Lower(), n = aCoordsArray->Upper(); i <= n; )
173   {
174     if ( i + 3 > n + 1 )
175       break;
176
177     AltitudePoint aPoint;
178     aPoint.SetX( aCoordsArray->Value( i++ ) );
179     aPoint.SetY( aCoordsArray->Value( i++ ) );
180     aPoint.SetZ( aCoordsArray->Value( i++ ) );
181
182     if( IsConvertToGlobal )
183       aDoc->Transform( aPoint, false );
184     aPoints.Append( aPoint );
185   }
186
187   return aPoints;
188 }
189
190 HYDROData_QuadtreeNode* HYDROData_Bathymetry::GetQuadtreeNodes() const
191 {
192   TDF_Label aLabel = myLab.FindChild(DataTag_AltitudePoints, false);
193   if (aLabel.IsNull())
194     return 0;
195   int labkey = myLab.Tag();
196   //int altkey = aLabel.Tag();
197   //DEBTRACE("GetQuadtreeNodes this labkey altkey "<<this<<" "<<labkey<<" "<<altkey);
198   // if (myQuadtree->isEmpty() )
199   if (myQuadtrees.find(labkey) == myQuadtrees.end())
200     {
201       DEBTRACE("GetQuadtreeNodes init " << this << " " << labkey);
202       HYDROData_QuadtreeNode* aQuadtree = new HYDROData_QuadtreeNode(0, 30, 5, 0.);
203       myQuadtrees[labkey] = aQuadtree;
204       TDF_Label aLabel = myLab.FindChild(DataTag_AltitudePoints, false);
205       if (aLabel.IsNull())
206         return 0;
207
208       Handle(TDataStd_RealArray) aCoordsArray;
209       if (!aLabel.FindAttribute(TDataStd_RealArray::GetID(), aCoordsArray))
210         return 0;
211
212       Nodes_3D* aListOfNodes = new Nodes_3D();
213
214       int index =0;
215       for (int i = aCoordsArray->Lower(), n = aCoordsArray->Upper(); i <= n;)
216         {
217           if (i + 3 > n + 1)
218             break;
219
220           double x = aCoordsArray->Value(i++);
221           double y = aCoordsArray->Value(i++);
222           double z = aCoordsArray->Value(i++);
223           gpi_XYZ* aPoint = new gpi_XYZ(x, y, z, index);
224           index++;
225           aListOfNodes->push_back(aPoint);
226         }
227       DEBTRACE("  GetQuadtreeNodes call setNodesAndCompute");
228       aQuadtree->setNodesAndCompute(aListOfNodes);
229       return aQuadtree;
230     }
231   else
232     return myQuadtrees[labkey];
233 }
234
235 vtkPolyData* HYDROData_Bathymetry::GetVtkDelaunay2D() const
236 {
237   TDF_Label aLabel = myLab.FindChild(DataTag_AltitudePoints, false);
238   if (aLabel.IsNull())
239     return 0;
240   int labkey = myLab.Tag();
241   //int altkey = aLabel.Tag();
242   //DEBTRACE("GetVtkDelaunay2D this labkey altkey "<<this<<" "<<labkey<<" "<<altkey);
243   if (myDelaunay2D.find(labkey) == myDelaunay2D.end())
244     {
245       DEBTRACE("GetVtkDelaunay2D init " << this << " " << labkey);
246
247       TDF_Label aLabel = myLab.FindChild(DataTag_AltitudePoints, false);
248       if (aLabel.IsNull())
249         return 0;
250       DEBTRACE("---");
251       Handle(TDataStd_RealArray) aCoordsArray;
252       if (!aLabel.FindAttribute(TDataStd_RealArray::GetID(), aCoordsArray))
253         return 0;
254       DEBTRACE("---");
255
256       vtkPoints *points = vtkPoints::New();
257       points->Allocate(aCoordsArray->Upper() +1);
258       for (int i = aCoordsArray->Lower(), n = aCoordsArray->Upper(); i <= n;)
259         {
260           if (i + 3 > n + 1)
261             break;
262           double x = aCoordsArray->Value(i++);
263           double y = aCoordsArray->Value(i++);
264           double z = aCoordsArray->Value(i++);
265           vtkIdType index = points->InsertNextPoint(x, y, z); // same index than in GetQuadtreeNodes
266           //DEBTRACE("  " << index);
267         }
268       vtkPolyData* profile = vtkPolyData::New();
269       profile->SetPoints(points);
270       DEBTRACE("Number of Points: "<< points->GetNumberOfPoints());
271
272       hydroDelaunay2D* delaunay2D = hydroDelaunay2D::New();
273       delaunay2D->GetInputPortInformation(0)->Print(std::cerr);
274       DEBTRACE("set the input data");
275       delaunay2D->SetInputData(profile);
276       delaunay2D->GetInputPortInformation(0)->Print(std::cerr);
277       delaunay2D->GetOutputPortInformation(0)->Print(std::cerr);
278       DEBTRACE("---");
279       delaunay2D->GetOutputInformation(0)->Print(std::cerr);
280       delaunay2D->GetExecutive()->GetOutputInformation(0)->Print(std::cerr);
281       DEBTRACE("---");
282       vtkInformationVector** inv = delaunay2D->GetExecutive()->GetInputInformation();
283       vtkInformationVector* outv = delaunay2D->GetExecutive()->GetOutputInformation();
284       delaunay2D->GetExecutive()->GetInputInformation(0,0)->Print(std::cerr);
285       delaunay2D->GetExecutive()->GetOutputInformation(0)->Print(std::cerr);
286       vtkInformation* request = vtkInformation::New();
287
288       //delaunay2D->ProcessRequest(request, inv,outv);
289
290       delaunay2D->GetOutputPortInformation(0)->Print(std::cerr);
291       delaunay2D->GetExecutive()->GetInputInformation(0,0)->Print(std::cerr);
292       delaunay2D->GetExecutive()->GetOutputInformation(0)->Print(std::cerr);
293
294       DEBTRACE("---");
295       delaunay2D->Update();
296
297       DEBTRACE("---");
298       delaunay2D->UpdateDataObject();
299
300       vtkPolyData* data = delaunay2D->GetOutput();
301
302       data->BuildLinks();
303       myDelaunay2D[labkey] = data;
304       DEBTRACE("---");
305       return data;
306     }
307   else
308     return myDelaunay2D[labkey];
309
310 }
311
312 void HYDROData_Bathymetry::RemoveAltitudePoints()
313 {
314   TDF_Label aLabel = myLab.FindChild( DataTag_AltitudePoints, false );
315   if ( !aLabel.IsNull() )
316   {
317     aLabel.ForgetAllAttributes();
318     Changed( Geom_Z );
319   }
320 }
321
322 void interpolateAltitudeForPoints( const gp_XY&                               thePoint,
323                                    const HYDROData_Bathymetry::AltitudePoint& theFirstPoint,
324                                    const HYDROData_Bathymetry::AltitudePoint& theSecPoint,
325                                    HYDROData_Bathymetry::AltitudePoint&       theResPoint,
326                                    const bool&                                theIsVertical )
327 {
328   double aCoordX = thePoint.X();
329   double aCoordY = thePoint.Y();
330
331   if ( theIsVertical )
332   {
333     aCoordX = theFirstPoint.X();
334
335     if ( !ValuesEquals( theFirstPoint.X(), theSecPoint.X() ) )
336     {
337       // Recalculate X coordinate by equation of line from two points
338       aCoordX = ( ( ( thePoint.Y() - theFirstPoint.Y() ) * ( theSecPoint.X() - theFirstPoint.X() ) ) /
339                   ( theSecPoint.Y() - theFirstPoint.Y() ) ) + theFirstPoint.X();
340     }
341   }
342   else
343   {
344     aCoordY = theFirstPoint.Y();
345
346     if ( !ValuesEquals( theFirstPoint.Y(), theSecPoint.Y() ) )
347     {
348       // Recalculate y by equation of line from two points
349       aCoordY = ( ( ( thePoint.X() - theFirstPoint.X() ) * ( theSecPoint.Y() - theFirstPoint.Y() ) ) /
350                   ( theSecPoint.X() - theFirstPoint.X() ) ) + theFirstPoint.Y();
351     }
352   }
353
354   theResPoint.SetX( aCoordX );
355   theResPoint.SetY( aCoordY );
356
357   // Calculate coefficient for interpolation
358   double aLength = Sqrt( Pow( theSecPoint.Y() - theFirstPoint.Y(), 2 ) +
359                          Pow( theSecPoint.X() - theFirstPoint.X(), 2 ) );
360
361   double aInterCoeff = 0;
362   if ( aLength != 0 )
363    aInterCoeff = ( theSecPoint.Z() - theFirstPoint.Z() ) / aLength;
364
365
366   double aNewLength = Sqrt( Pow( theResPoint.Y() - theFirstPoint.Y(), 2 ) +
367                             Pow( theResPoint.X() - theFirstPoint.X(), 2 ) );
368
369   // Calculate interpolated value
370   double aResVal = theFirstPoint.Z() + aInterCoeff * aNewLength;
371
372   theResPoint.SetZ( aResVal );
373 }
374
375 bool interpolZtriangle(const gp_XY& point, vtkPolyData* delaunay2D, vtkIdList* triangle, double& z)
376 {
377
378   int nbPts = triangle->GetNumberOfIds();
379   if (nbPts != 3)
380     {
381       DEBTRACE("not a triangle ?");
382       return false;
383     }
384   vtkIdType s[3];
385   double v[3][3]; // v[i][j] = j coordinate of node i
386   for (int i=0; i<3; i++)
387     {
388       s[i] = triangle->GetId(i);
389       delaunay2D->GetPoint(s[i],v[i]);
390     }
391   //DEBTRACE("triangle node id: " << s[0] << " " << s[1] << " " << s[2]);
392   //DEBTRACE("triangle node 0: " << v[0][0]  << " " << v[0][1] << " " << v[0][2]);
393   //DEBTRACE("triangle node 1: " << v[1][0]  << " " << v[1][1] << " " << v[1][2]);
394   //DEBTRACE("triangle node 2: " << v[2][0]  << " " << v[2][1] << " " << v[2][2]);
395   // compute barycentric coordinates (https://en.wikipedia.org/wiki/Barycentric_coordinate_system)
396   //     det = (y2-y3)(x1-x3)+(x3-x2)(y1-y3)
397   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]);
398   if (det == 0)
399     {
400       DEBTRACE("flat triangle ?");
401       return false;
402     }
403
404   //     l0  = ((y2-y3)(x -x3)+(x3-x2)(y -y3))/det
405   double l0  = (v[1][1]-v[2][1])*(point.X()-v[2][0]) + (v[2][0]-v[1][0])*(point.Y()-v[2][1]);
406   l0 = l0/det;
407
408   //     l1  = ((y3-y1)(x -x3)+(x1-x3)(y -y3))/det
409   double l1  = (v[2][1]-v[0][1])*(point.X()-v[2][0]) + (v[0][0]-v[2][0])*(point.Y()-v[2][1]);
410   l1 = l1/det;
411
412   double l2  = 1 -l0 -l1;
413   //DEBTRACE("l0, l1, l2: " << l0  << " "  << l1  << " "  << l2);
414
415   if ((l0>=0) and (l0<=1) and (l1>=0) and (l1<=1) and (l2>=0) and (l2<=1))
416     {
417       z = l0*v[0][2] + l1*v[1][2] + l2*v[2][2];
418       return true;
419     }
420   return false;
421 }
422
423 double HYDROData_Bathymetry::GetAltitudeForPoint(const gp_XY& thePoint) const
424 {
425   DEBTRACE("GetAltitudeForPoint p(" << thePoint.X() << ", " << thePoint.Y() << ")");
426   double anInvalidAltitude = GetInvalidAltitude();
427   double aResAltitude = anInvalidAltitude;
428
429   // --- find the nearest point in the bathymetry cloud, with quadtree
430
431   HYDROData_QuadtreeNode* aQuadtree = GetQuadtreeNodes();
432   if (!aQuadtree)
433     {
434       DEBTRACE("  no Quadtree");
435       return aResAltitude;
436     }
437
438   std::map<double, const gpi_XYZ*> dist2nodes;
439   aQuadtree->NodesAround(thePoint, dist2nodes, aQuadtree->getPrecision());
440   while (dist2nodes.size() == 0)
441     {
442       aQuadtree->setPrecision(aQuadtree->getPrecision() *2);
443       DEBTRACE("adjust precision to: " << aQuadtree->getPrecision());
444       aQuadtree->NodesAround(thePoint, dist2nodes, aQuadtree->getPrecision());
445     }
446   //aQuadtree->NodesAround(thePoint, dist2nodes, 5.0);
447   std::map<double, const gpi_XYZ*>::const_iterator it = dist2nodes.begin();
448   aResAltitude = it->second->Z();
449   int nodeIndex = it->second->getIndex();
450   DEBTRACE("  number of points found: " << dist2nodes.size() << " nearest z: " << aResAltitude << " point index: " << nodeIndex);
451
452   // --- for coarse bathymetry clouds (when the TELEMAC mesh is more refined than the bathymetry cloud)
453   //     interpolation is required.
454   //     - get a Delaunay2D mesh on the bathymetry cloud,
455   //     - get the triangle containing the point in the Delaunay2D mesh,
456   //     - interpolate altitude
457
458   bool isBathyInterpolRequired = true;
459   if (isBathyInterpolRequired)
460     {
461       vtkPolyData* aDelaunay2D = GetVtkDelaunay2D();
462       vtkIdList* cells= vtkIdList::New();
463       cells->Allocate(64);
464       vtkIdList* points= vtkIdList::New();
465       points->Allocate(64);
466       DEBTRACE("---");
467       aDelaunay2D->GetPointCells(nodeIndex, cells);
468       vtkIdType nbCells = cells->GetNumberOfIds();
469       DEBTRACE(nbCells);
470       for (int i=0; i<nbCells; i++)
471         {
472           aDelaunay2D->GetCellPoints(cells->GetId(i), points);
473           double z = 0;
474           if (interpolZtriangle(thePoint, aDelaunay2D, points, z))
475             {
476               aResAltitude = z;
477               DEBTRACE("interpolated z: " << z);
478               break;
479             }
480           else
481             {
482               DEBTRACE("point outside triangles, nearest z kept");
483             }
484         }
485     }
486   return aResAltitude;
487 }
488
489 void HYDROData_Bathymetry::SetFilePath( const TCollection_AsciiString& theFilePath )
490 {
491   TDataStd_AsciiString::Set( myLab.FindChild( DataTag_FilePath ), theFilePath );
492 }
493
494 TCollection_AsciiString HYDROData_Bathymetry::GetFilePath() const
495 {
496   TCollection_AsciiString aRes;
497
498   TDF_Label aLabel = myLab.FindChild( DataTag_FilePath, false );
499   if ( !aLabel.IsNull() )
500   {
501     Handle(TDataStd_AsciiString) anAsciiStr;
502     if ( aLabel.FindAttribute( TDataStd_AsciiString::GetID(), anAsciiStr ) )
503       aRes = anAsciiStr->Get();
504   }
505
506   return aRes;
507 }
508
509 void HYDROData_Bathymetry::SetAltitudesInverted( const bool theIsInverted,
510                                                  const bool theIsUpdate )
511 {
512   bool anIsAltitudesInverted = IsAltitudesInverted();
513   if ( anIsAltitudesInverted == theIsInverted )
514     return;
515
516   TDataStd_Integer::Set( myLab.FindChild( DataTag_AltitudesInverted ), (Standard_Integer)theIsInverted );
517
518   Changed( Geom_Z );
519
520   if ( !theIsUpdate )
521     return;
522
523   // Update altitude points
524   AltitudePoints anAltitudePoints = GetAltitudePoints();
525   if ( anAltitudePoints.IsEmpty() )
526     return;
527
528   AltitudePoints::Iterator anIter( anAltitudePoints );
529   for ( ; anIter.More(); anIter.Next() )
530   {
531     AltitudePoint& aPoint = anIter.ChangeValue();
532     aPoint.SetZ( aPoint.Z() * -1 );
533   }
534
535   SetAltitudePoints( anAltitudePoints );
536 }
537
538 bool HYDROData_Bathymetry::IsAltitudesInverted() const
539 {
540   bool aRes = false;
541
542   TDF_Label aLabel = myLab.FindChild( DataTag_AltitudesInverted, false );
543   if ( !aLabel.IsNull() )
544   {
545     Handle(TDataStd_Integer) anIntVal;
546     if ( aLabel.FindAttribute( TDataStd_Integer::GetID(), anIntVal ) )
547       aRes = (bool)anIntVal->Get();
548   }
549
550   return aRes;
551 }
552
553 bool HYDROData_Bathymetry::ImportFromFile( const TCollection_AsciiString& theFileName )
554 {
555   // Try to open the file
556   QFile aFile( theFileName.ToCString() );
557   if ( !aFile.exists() || !aFile.open( QIODevice::ReadOnly ) )
558     return false;
559
560   bool aRes = false;
561
562   QString aFileSuf = QFileInfo( aFile ).suffix().toLower();
563
564   AltitudePoints aPoints;
565
566   // Try to import the file
567   if ( aFileSuf == "xyz" )
568     aRes = importFromXYZFile( aFile, aPoints );
569   else if ( aFileSuf == "asc" )
570     aRes = importFromASCFile( aFile, aPoints );
571
572   // Close the file
573   aFile.close();
574   
575
576   // Convert from global to local CS
577   Handle_HYDROData_Document aDoc = HYDROData_Document::Document( myLab );
578   AltitudePoints::Iterator anIter( aPoints );
579   for ( ; anIter.More(); anIter.Next() )
580   {
581     AltitudePoint& aPoint = anIter.ChangeValue();
582     aDoc->Transform( aPoint, true );
583   }
584
585   if ( aRes )
586   {
587     // Update file path and altitude points of this Bathymetry
588     SetFilePath( theFileName );
589     SetAltitudePoints( aPoints );
590   }
591
592   return aRes && !aPoints.IsEmpty();
593 }
594
595 bool HYDROData_Bathymetry::importFromXYZFile( QFile&          theFile,
596                                               AltitudePoints& thePoints ) const
597 {
598   if ( !theFile.isOpen() )
599     return false;
600
601   // Strings in file is written as:
602   //  1. X(float) Y(float) Z(float)
603   //  2. X(float) Y(float) Z(float)
604   //  ...
605
606 #ifdef _TIMER
607   OSD_Timer aTimer;
608   aTimer.Start();
609 #endif
610
611   bool anIsAltitudesInverted = IsAltitudesInverted();
612   while ( !theFile.atEnd() )
613   {
614     QString aLine = theFile.readLine().simplified();
615     if ( aLine.isEmpty() )
616       continue;
617
618     QStringList aValues = aLine.split( ' ', QString::SkipEmptyParts );
619     if ( aValues.length() < 3 )
620       return false;
621
622     AltitudePoint aPoint;
623     
624     QString anX = aValues.value( 0 );
625     QString anY = aValues.value( 1 );
626     QString aZ  = aValues.value( 2 );
627
628     bool isXOk = false, isYOk = false, isZOk = false;
629
630     aPoint.SetX( anX.toDouble( &isXOk ) );
631     aPoint.SetY( anY.toDouble( &isYOk ) );
632     aPoint.SetZ( aZ.toDouble( &isZOk ) );
633
634     if ( !isXOk || !isYOk || !isZOk )
635       return false;
636
637     if ( HYDROData_Tool::IsNan( aPoint.X() ) || HYDROData_Tool::IsInf( aPoint.X() ) ||
638          HYDROData_Tool::IsNan( aPoint.Y() ) || HYDROData_Tool::IsInf( aPoint.Y() ) ||
639          HYDROData_Tool::IsNan( aPoint.Z() ) || HYDROData_Tool::IsInf( aPoint.Z() ) )
640       return false;
641
642     // Invert the z value if requested
643     if ( anIsAltitudesInverted )
644       aPoint.SetZ( -aPoint.Z() );
645
646     thePoints.Append( aPoint );
647   }
648
649 #ifdef _TIMER
650   aTimer.Stop();
651   std::ofstream stream( "W:/HYDRO/WORK/log.txt", std::ofstream::out );
652   aTimer.Show( stream );
653 #endif
654
655   return true;
656 }
657
658 bool HYDROData_Bathymetry::importFromASCFile( QFile&          theFile,
659                                               AltitudePoints& thePoints ) const
660 {
661   if ( !theFile.isOpen() )
662     return false;
663
664   QString aLine;
665   QStringList aStrList;
666
667   int aNCols;
668   int aNRows;
669   double anXllCorner; 
670   double anYllCorner; 
671   double aCellSize; 
672   double aNoDataValue;
673
674   aLine = theFile.readLine().simplified();
675   aStrList = aLine.split( ' ', QString::SkipEmptyParts );
676   if ( aStrList.length() != 2 && aStrList[0].toLower() != "ncols" )
677     return false;
678   aNCols = aStrList[1].toInt();
679
680   aLine = theFile.readLine().simplified();
681   aStrList = aLine.split( ' ', QString::SkipEmptyParts );
682   if ( aStrList.length() != 2 && aStrList[0].toLower() != "nrows" )
683     return false;
684   aNRows = aStrList[1].toInt();
685
686   aLine = theFile.readLine().simplified();
687   aStrList = aLine.split( ' ', QString::SkipEmptyParts );
688   if ( aStrList.length() != 2 && aStrList[0].toLower() != "xllcorner" )
689     return false;
690   anXllCorner = aStrList[1].toDouble();
691
692   aLine = theFile.readLine().simplified();
693   aStrList = aLine.split( ' ', QString::SkipEmptyParts );
694   if ( aStrList.length() != 2 && aStrList[0].toLower() != "yllcorner" )
695     return false;
696   anYllCorner = aStrList[1].toDouble();
697
698   aLine = theFile.readLine().simplified();
699   aStrList = aLine.split( ' ', QString::SkipEmptyParts );
700   if ( aStrList.length() != 2 && aStrList[0].toLower() != "cellsize" )
701     return false;
702   aCellSize = aStrList[1].toDouble();
703
704   aLine = theFile.readLine().simplified();
705   aStrList = aLine.split( ' ', QString::SkipEmptyParts );
706   if ( aStrList.length() != 2 && aStrList[0].toLower() != "nodata_value" )
707     return false;
708   aNoDataValue = aStrList[1].toDouble();
709
710   bool anIsAltitudesInverted = IsAltitudesInverted();
711
712   int i = 0;
713   int aStrLength = 0;
714   while ( !theFile.atEnd() )
715   {
716     aLine = theFile.readLine().simplified();
717     aStrList = aLine.split( ' ', QString::SkipEmptyParts );
718
719     aStrLength =  aStrList.length();
720     if ( aStrLength == 0 )
721       continue;
722
723     if ( aStrLength != aNRows )
724       return false;
725
726     for (int j = 0; j < aNCols; j++)
727     {
728       if (aStrList[j].toDouble() != aNoDataValue)
729       {
730         AltitudePoint aPoint;
731         aPoint.SetX(anXllCorner + aCellSize*(j + 0.5));
732         aPoint.SetY(anYllCorner + aCellSize*(aNRows - i + 0.5));
733         aPoint.SetZ(aStrList[j].toDouble());
734
735         if ( anIsAltitudesInverted )
736          aPoint.SetZ( -aPoint.Z() );
737
738         thePoints.Append(aPoint);
739       }
740     }
741     i++;
742
743   }
744
745   return true;
746
747 }
748
749
750 Handle_HYDROData_PolylineXY HYDROData_Bathymetry::CreateBoundaryPolyline() const
751 {
752   Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
753   Handle_HYDROData_PolylineXY aResult = 
754     Handle_HYDROData_PolylineXY::DownCast( aDocument->CreateObject( KIND_POLYLINEXY ) );
755
756   if( aResult.IsNull() )
757     return aResult;
758
759   //search free name
760   QString aPolylinePref = GetName() + "_Boundary";
761   QString aPolylineName = HYDROData_Tool::GenerateObjectName( aDocument, aPolylinePref );
762   aResult->SetName( aPolylineName );
763
764   double Xmin = 0.0, Xmax = 0.0, Ymin = 0.0, Ymax = 0.0;
765   bool isFirst = true;
766   AltitudePoints aPoints = GetAltitudePoints();
767
768   AltitudePoints::Iterator anIter( aPoints );
769   for ( ; anIter.More(); anIter.Next() )
770   {
771     const AltitudePoint& aPoint = anIter.Value();
772
773     double x = aPoint.X(), y = aPoint.Y();
774     if( isFirst || x<Xmin )
775       Xmin = x;
776     if( isFirst || x>Xmax )
777       Xmax = x;
778     if( isFirst || y<Ymin )
779       Ymin = y;
780     if( isFirst || y>Ymax )
781       Ymax = y;
782     isFirst = false;
783   }
784
785   aResult->AddSection( "bound", HYDROData_IPolyline::SECTION_POLYLINE, true );
786   aResult->AddPoint( 0, HYDROData_IPolyline::Point( Xmin, Ymin ) );
787   aResult->AddPoint( 0, HYDROData_IPolyline::Point( Xmin, Ymax ) );
788   aResult->AddPoint( 0, HYDROData_IPolyline::Point( Xmax, Ymax ) );
789   aResult->AddPoint( 0, HYDROData_IPolyline::Point( Xmax, Ymin ) );
790   
791   aResult->SetWireColor( HYDROData_PolylineXY::DefaultWireColor() );
792   
793   aResult->Update();
794
795   return aResult;
796 }
797
798 void HYDROData_Bathymetry::UpdateLocalCS( double theDx, double theDy )
799 {
800   gp_XYZ aDelta( theDx, theDy, 0 );
801   AltitudePoints aPoints = GetAltitudePoints();
802   AltitudePoints::Iterator anIter( aPoints );
803   for ( int i = 0 ; anIter.More(); ++i, anIter.Next() )
804   {
805     AltitudePoint& aPoint = anIter.ChangeValue();
806     aPoint += aDelta;
807   }
808   SetAltitudePoints( aPoints );
809 }
810