Salome HOME
Merge branch 'BR_LAND_COVER_MAP' of ssh://git.salome-platform.org/modules/hydro into...
[modules/hydro.git] / src / HYDROData / HYDROData_ShapeFile.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_ShapeFile.h>
20 #include <HYDROData_PolylineXY.h>
21 #include <HYDROData_Polyline3D.h>
22 #include <HYDROData_Bathymetry.h>
23 #include <HYDROData_Profile.h>
24 #include <HYDROData_Iterator.h>
25 #include <HYDROData_LandCoverMap.h>
26
27 #include <QFile>
28 #include <QFileInfo>
29 #include <TopoDS.hxx>
30 #include <TopExp_Explorer.hxx>
31 #include <TopoDS_Wire.hxx>
32 #include <TopoDS_Vertex.hxx>
33 #include <TopoDS_Edge.hxx>
34 #include <TopoDS_Face.hxx>
35 #include <BRep_Tool.hxx>
36 #include <BRepTools.hxx>
37 #include <Precision.hxx>
38 #include <Handle_Geom_Curve.hxx>
39 #include <Handle_Geom_Line.hxx>
40 #include <Handle_Geom_TrimmedCurve.hxx>
41 #include <Geom_TrimmedCurve.hxx>
42 #include <BRepBuilderAPI_MakeEdge.hxx>
43 #include <BRepBuilderAPI_MakeWire.hxx>
44 #include <BRepBuilderAPI_MakeFace.hxx>
45 #include <gp_Pln.hxx>
46 #include <BRepLib.hxx>
47 #include <ShapeFix_Shape.hxx>
48 #include <TopTools_SequenceOfShape.hxx>
49 #include <QColor>
50 #include <BRepTopAdaptor_FClass2d.hxx>
51 #include <TopExp.hxx>
52
53 #ifdef WIN32
54   #pragma warning( disable: 4996 )
55 #endif
56
57 HYDROData_ShapeFile::HYDROData_ShapeFile() : myHSHP(NULL)
58
59 }
60
61 HYDROData_ShapeFile::~HYDROData_ShapeFile()
62 {
63   Free();
64 }
65
66 void HYDROData_ShapeFile::Export(const QString& aFileName, 
67   NCollection_Sequence<Handle_HYDROData_PolylineXY> aPolyXYSeq,
68   NCollection_Sequence<Handle_HYDROData_Polyline3D> aPoly3DSeq,
69   QStringList& aNonExpList)
70 {
71   SHPHandle hSHPHandle;
72   if (!aPolyXYSeq.IsEmpty() && aPoly3DSeq.IsEmpty())
73   {
74     hSHPHandle = SHPCreate( aFileName.toAscii().data(), SHPT_ARC );        
75     for (int i = 1; i <= aPolyXYSeq.Size(); i++)
76       if (WriteObjectPolyXY(hSHPHandle, aPolyXYSeq(i)) != 1)
77         aNonExpList.append(aPolyXYSeq(i)->GetName());
78   }
79   else if (aPolyXYSeq.IsEmpty() && !aPoly3DSeq.IsEmpty())
80   {
81     hSHPHandle = SHPCreate( aFileName.toAscii().data(), SHPT_ARCZ );
82     for (int i = 1; i <= aPoly3DSeq.Size(); i++)
83       if (WriteObjectPoly3D(hSHPHandle, aPoly3DSeq(i)) != 1)
84         aNonExpList.append(aPoly3DSeq(i)->GetName());
85   }
86   if (hSHPHandle->nRecords > 0)
87     SHPClose( hSHPHandle );
88   else
89   {
90     SHPClose( hSHPHandle );
91     QString aFN = aFileName.simplified();
92     remove (aFN.toStdString().c_str());
93     remove (aFN.replace( ".shp", ".shx", Qt::CaseInsensitive).toStdString().c_str());
94   }
95 }
96
97 void HYDROData_ShapeFile::Export(const QString& aFileName,
98   const Handle_HYDROData_LandCoverMap& aLCM, QStringList& aNonExpList)
99 {
100   SHPHandle hSHPHandle;
101   if ( !aLCM.IsNull() && !aLCM->IsEmpty())
102   {
103     hSHPHandle = SHPCreate( aFileName.toAscii().data(), SHPT_POLYGON );
104     HYDROData_LandCoverMap::Iterator It( aLCM );
105     for( ; It.More(); It.Next() )
106     {
107       TopoDS_Face aFace = It.Face();
108       if (WriteObjectPolygon(hSHPHandle, aFace) != 1)
109         aNonExpList.append(aLCM->GetName() + "_" +  QString::number(It.Index()));
110     }
111   }
112   if (hSHPHandle->nRecords > 0)
113     SHPClose( hSHPHandle );
114   else
115   {
116     SHPClose( hSHPHandle );
117     QString aFN = aFileName.simplified();
118     remove (aFN.toStdString().c_str());
119     remove (aFN.replace( ".shp", ".shx", Qt::CaseInsensitive).toStdString().c_str());
120   }
121 }
122
123
124 int HYDROData_ShapeFile::WriteObjectPolyXY(SHPHandle theShpHandle, Handle_HYDROData_PolylineXY thePoly )
125 {
126   SHPObject     *aSHPObj;
127   std::vector<double> x, y;
128   std::vector<int> anPartStart;
129   
130   for (int i = 0; i < thePoly->NbSections(); i++)    
131     if (thePoly->GetSectionType(i) == HYDROData_IPolyline::SECTION_SPLINE)
132       return -1;
133
134   for (int i = 0; i < thePoly->NbSections(); i++)
135   {
136     anPartStart.push_back(x.size());
137     HYDROData_PolylineXY::PointsList aPointList = thePoly->GetPoints(i);
138     for (int j = 1; j <= aPointList.Size(); j++)
139     {
140       x.push_back( aPointList(j).X());
141       y.push_back( aPointList(j).Y()); 
142     }
143     if (thePoly->IsClosedSection(i))
144     {
145       x.push_back( aPointList(1).X());
146       y.push_back( aPointList(1).Y()); 
147     }
148   }
149     
150   aSHPObj = SHPCreateObject( SHPT_ARC, -1, thePoly->NbSections(), &anPartStart[0], NULL, x.size(), &x[0], &y[0], NULL, NULL );
151   SHPWriteObject( theShpHandle, -1, aSHPObj );
152   SHPDestroyObject( aSHPObj );
153   return 1;
154 }
155
156 int HYDROData_ShapeFile::WriteObjectPoly3D(SHPHandle theShpHandle, Handle_HYDROData_Polyline3D thePoly )
157 {
158   SHPObject     *aSHPObj;
159   std::vector<double> x, y, z;
160   std::vector<int> anPartStart;
161
162   for (int i = 0; i < thePoly->GetPolylineXY()->NbSections(); i++)    
163     if (thePoly->GetPolylineXY()->GetSectionType(i) == HYDROData_IPolyline::SECTION_SPLINE)
164       return -1;
165   
166   for (int i = 0; i < thePoly->GetPolylineXY()->NbSections(); i++)
167   {
168     anPartStart.push_back(x.size());
169     HYDROData_PolylineXY::PointsList aPointList = thePoly->GetPolylineXY()->GetPoints(i);
170     for (int j = 1; j <= aPointList.Size(); j++)
171     {
172       x.push_back( aPointList(j).X());
173       y.push_back( aPointList(j).Y()); 
174       z.push_back(thePoly->GetAltitudeObject()->GetAltitudeForPoint(gp_XY (aPointList(j).X(), aPointList(j).Y())));
175     }
176     if ( thePoly->GetPolylineXY()->IsClosedSection(i))
177     {
178       x.push_back( aPointList(1).X());
179       y.push_back( aPointList(1).Y()); 
180       z.push_back(thePoly->GetAltitudeObject()->GetAltitudeForPoint(gp_XY (aPointList(1).X(), aPointList(1).Y())));
181
182     }
183   }
184   
185   aSHPObj = SHPCreateObject( SHPT_ARCZ, -1, thePoly->GetPolylineXY()->NbSections(), &anPartStart[0], NULL, x.size(), &x[0], &y[0], &z[0], NULL );
186   SHPWriteObject( theShpHandle, -1, aSHPObj );
187   SHPDestroyObject( aSHPObj );
188   return 1;
189 }
190
191 int HYDROData_ShapeFile::WriteObjectPolygon(SHPHandle theShpHandle, const TopoDS_Shape& theInputShape )
192 {
193   if (theInputShape.IsNull())
194     return 0;
195   TopExp_Explorer anEdgeEx(theInputShape, TopAbs_EDGE);
196   for (; anEdgeEx.More(); anEdgeEx.Next()) 
197   {
198     TopoDS_Edge E = TopoDS::Edge(anEdgeEx.Current());
199     double aFP, aLP;
200     Handle_Geom_Curve aCur = BRep_Tool::Curve(E, aFP, aLP);
201     Handle(Geom_Line) aLine = Handle(Geom_Line)::DownCast(aCur);
202     if (aLine.IsNull())
203     {
204       Handle(Geom_TrimmedCurve) aTC = Handle(Geom_TrimmedCurve)::DownCast(aCur);
205       if (!aTC.IsNull())
206       {
207         Handle(Geom_Line) aLine = Handle(Geom_Line)::DownCast(aTC->BasisCurve());
208         if (aLine.IsNull())
209           return -1;
210       }
211       else
212         return -1;
213     }
214
215   }
216   if (theInputShape.ShapeType() == TopAbs_FACE)
217   {
218     ProcessFace(TopoDS::Face(theInputShape), theShpHandle);
219   }
220   else if (theInputShape.ShapeType() == TopAbs_COMPOUND)
221   {
222     TopExp_Explorer Ex(theInputShape, TopAbs_FACE);
223     for (; Ex.More(); Ex.Next()) 
224     {
225       TopoDS_Face aF = TopoDS::Face(Ex.Current());   
226       if (aF.IsNull())
227         continue;
228       ProcessFace(aF, theShpHandle);
229     }
230   }
231   else
232     return 0;
233
234   return 1;
235  
236 }
237
238 void HYDROData_ShapeFile::ProcessFace(TopoDS_Face theFace, SHPHandle theShpHandle)
239 {
240   if (theFace.ShapeType() != TopAbs_FACE)
241      return;
242   SHPObject     *aSHPObj;
243   std::vector<double> x, y;
244   std::vector<int> anPartStart;
245   TopoDS_Wire OuterW = BRepTools::OuterWire(theFace);
246   NCollection_Sequence<TopoDS_Wire> aWires;
247
248   //write an outer wire first
249   aWires.Append(OuterW); 
250   TopExp_Explorer Ex(theFace, TopAbs_WIRE);  
251   for (; Ex.More(); Ex.Next()) 
252   {
253     TopoDS_Wire aW = TopoDS::Wire(Ex.Current());
254     if (aW.IsEqual(OuterW))
255       continue;
256     aWires.Append(aW); 
257   }
258
259   //TopExp_Explorer Ex(theFace, TopAbs_WIRE);
260   int NbWires = 0;
261   for (int k = 1; k <= aWires.Length(); k++) 
262   {
263     TopoDS_Wire aW = aWires(k);   
264     if (aW.IsNull())
265       continue;
266     NbWires++;
267     // Try to reorder edges
268     Handle(ShapeFix_Wire) aSFW = new ShapeFix_Wire( aW, theFace, Precision::Confusion() );
269     aSFW->FixReorder();
270     Handle(ShapeExtend_WireData) aSEWD = aSFW->WireData();
271     Standard_Integer nbE = aSEWD->NbEdges();
272     //
273     anPartStart.push_back(x.size());
274     NCollection_Sequence<gp_Pnt2d> aPnts;
275     for (Standard_Integer i = 1; i <= nbE; i++)
276     {
277       TopoDS_Edge E = aSEWD->Edge(i);
278       TopoDS_Vertex aV = TopExp::LastVertex(E, 1);
279       if (aV.IsNull())
280         continue;
281       gp_Pnt P = BRep_Tool::Pnt(aV);
282       aPnts.Append(gp_Pnt2d(P.X(), P.Y()));
283     }
284     NCollection_Sequence<gp_Pnt2d> aNPnts;
285     aNPnts.Append(aPnts.First());
286     for (int j = 1; j <= aPnts.Size() - 1; j++)
287     {
288       if (!aPnts(j).IsEqual(aPnts(j + 1), Precision::Confusion())) 
289         aNPnts.Append(aPnts(j + 1));
290     }
291
292     if (k == 1)
293     {
294       //an outer wire
295       //clockwise direction
296       for (int j = 1; j <= aNPnts.Size(); j++)
297       { 
298         x.push_back( aNPnts(j).X());
299         y.push_back( aNPnts(j).Y()); 
300       }
301       x.push_back( aNPnts(1).X());
302       y.push_back( aNPnts(1).Y()); 
303     }
304     else
305     {
306       //holes
307       //counter-clockwise direction
308       for (int j = aNPnts.Size(); j > 0; j--)
309       { 
310         x.push_back( aNPnts(j).X());
311         y.push_back( aNPnts(j).Y()); 
312       }
313       x.push_back( aNPnts(aNPnts.Size()).X());
314       y.push_back( aNPnts(aNPnts.Size()).Y()); 
315     }
316   }
317   
318   aSHPObj = SHPCreateObject( SHPT_POLYGON, -1, NbWires, &anPartStart[0], NULL, x.size(), &x[0], &y[0], NULL, NULL );
319   SHPWriteObject( theShpHandle, -1, aSHPObj );
320   SHPDestroyObject( aSHPObj );
321
322 }
323
324 bool HYDROData_ShapeFile::Parse(SHPHandle theHandle, ShapeType theType, int& theShapeTypeOfFile)
325 {
326   int aShapeType;
327   mySHPObjects.clear();
328   SHPGetInfo( theHandle, NULL, &aShapeType, NULL, NULL );
329   theShapeTypeOfFile = aShapeType;
330   bool ToRead = (theType == ShapeType_Polyline && (aShapeType == 3 || aShapeType == 13 || aShapeType == 23)) ||
331    (theType == ShapeType_Polygon && aShapeType == 5);
332   if (ToRead) 
333   {
334     for (int i = 0; i < theHandle->nRecords; i++) 
335       mySHPObjects.push_back(SHPReadObject(theHandle, i));
336     return true;
337   }
338   else
339     return false;
340 }
341
342 void HYDROData_ShapeFile::ReadSHPPolygon(SHPObject* anObj, int i, TopoDS_Face& F)
343 {
344   TopoDS_Wire W;
345   TopoDS_Edge E; 
346   int nParts = anObj->nParts;
347   gp_Pln pln(gp_Pnt(0,0,0), gp_Dir(0,0,1));
348
349   //Handle(ShapeFix_Shape) sfs = new ShapeFix_Shape;
350   //sfs->FixFaceTool()->FixOrientationMode() = 1;
351   TopTools_SequenceOfShape aWires;
352   for ( int i = 0 ; i < nParts ; i++ )
353   { 
354     BRepBuilderAPI_MakeWire aBuilder;
355     int StartIndex = anObj->panPartStart[i];
356     int EndIndex;
357     if (i != nParts - 1)
358       EndIndex = anObj->panPartStart[i + 1];
359     else
360       EndIndex = anObj->nVertices;
361
362     for ( int k = StartIndex; k < EndIndex - 1  ; k++ )
363     {
364       gp_Pnt P1 (anObj->padfX[k], anObj->padfY[k], 0);
365       gp_Pnt P2 (anObj->padfX[k+1], anObj->padfY[k+1], 0);
366       if (P1.Distance(P2) < Precision::Confusion())
367         continue;
368       BRepBuilderAPI_MakeEdge aMakeEdge(P1, P2);
369       aBuilder.Add(TopoDS::Edge(aMakeEdge.Shape()));
370     }
371     
372     aBuilder.Build();
373     W = TopoDS::Wire(aBuilder.Shape());
374     W.Orientation(TopAbs_FORWARD);
375     BRepBuilderAPI_MakeFace aDB(pln, W);
376     TopoDS_Face aDummyFace = TopoDS::Face(aDB.Shape());
377     BRepTopAdaptor_FClass2d FClass(aDummyFace, Precision::PConfusion());
378     if ( i == 0 && FClass.PerformInfinitePoint() == TopAbs_OUT) 
379       W.Reverse();
380     if ( i > 0 && FClass.PerformInfinitePoint() != TopAbs_IN) 
381       W.Reverse();
382    
383     aWires.Append(W);
384   }
385   
386   BRepBuilderAPI_MakeFace aFBuilder(pln, TopoDS::Wire(aWires(1)));
387   for (int i = 2; i <= aWires.Length(); i++)
388     aFBuilder.Add(TopoDS::Wire(aWires(i)));
389   F = TopoDS::Face(aFBuilder.Shape());
390
391   BRepLib::BuildCurves3d(F);  
392 }
393
394 int HYDROData_ShapeFile::ImportPolygons(const QString theFileName, QStringList& thePolygonsList, TopTools_SequenceOfShape& theFaces, int& theShapeTypeOfFile)
395 {
396   Free();
397   int Stat = TryOpenShapeFile(theFileName);
398   if (Stat != 0)
399     return Stat;
400   myHSHP = SHPOpen( theFileName.toAscii().data(), "rb" );
401   if (!Parse(myHSHP, HYDROData_ShapeFile::ShapeType_Polygon, theShapeTypeOfFile))
402     return 0;
403   for (size_t i = 0; i < mySHPObjects.size(); i++)
404     thePolygonsList.append("polygon_" + QString::number(i + 1));
405    
406   TopoDS_Face aF;
407   if (myHSHP->nShapeType == 5)
408   {
409     for (size_t i = 0; i < mySHPObjects.size(); i++) 
410     {
411        ReadSHPPolygon(mySHPObjects[i], i, aF);
412        theFaces.Append(aF);
413     }
414     return 1;
415   }
416   else
417     return 0;
418 }
419
420 void HYDROData_ShapeFile::Free()
421 {  
422   for (size_t i = 0; i < mySHPObjects.size(); i++ )
423     free (mySHPObjects[i]);
424
425   mySHPObjects.clear();
426   if (myHSHP != NULL)
427   {
428     SHPClose(myHSHP);
429     myHSHP = NULL; 
430   }
431 }
432
433
434 void HYDROData_ShapeFile::ReadSHPPolyXY(Handle(HYDROData_Document) theDocument, SHPObject* anObj, QString theFileName, 
435   int theInd, NCollection_Sequence<Handle_HYDROData_Entity>& theEntities)
436 {
437
438   Handle(HYDROData_PolylineXY) aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
439   
440   int nParts = anObj->nParts;
441   for ( int i = 0 ; i < nParts ; i++ )
442   {
443     int StartIndex = anObj->panPartStart[i];
444     int EndIndex;
445     if (i != nParts - 1)
446       EndIndex = anObj->panPartStart[i + 1];
447     else
448       EndIndex = anObj->nVertices;
449
450     bool IsClosed = false;
451     HYDROData_PolylineXY::SectionType aSectType = HYDROData_PolylineXY::SECTION_POLYLINE; 
452     if (anObj->padfX[StartIndex] == anObj->padfX[EndIndex - 1] &&
453         anObj->padfY[StartIndex] == anObj->padfY[EndIndex - 1] )
454     {
455       IsClosed = true;
456       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, true);
457     }
458     else
459       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, false);
460     
461     if (IsClosed)
462       EndIndex--;
463     for ( int k = StartIndex; k < EndIndex ; k++ )
464     {
465       HYDROData_PolylineXY::Point aSectPoint;
466       aSectPoint.SetX( anObj->padfX[k] );
467       aSectPoint.SetY( anObj->padfY[k] );
468       aPolylineXY->AddPoint( i, aSectPoint );
469     }
470
471   }
472   
473   aPolylineXY->SetWireColor( HYDROData_PolylineXY::DefaultWireColor() );
474   aPolylineXY->SetName( theFileName + "_PolyXY_" + QString::number(theInd) );
475   
476   aPolylineXY->Update();
477   theEntities.Append(aPolylineXY);
478
479 }
480
481 void HYDROData_ShapeFile::ReadSHPPoly3D(Handle(HYDROData_Document) theDocument, SHPObject* anObj, QString theFileName, 
482   int theInd, NCollection_Sequence<Handle_HYDROData_Entity>& theEntities)
483 {
484   Handle(HYDROData_PolylineXY) aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
485
486   Handle(HYDROData_Polyline3D) aPolylineObj = Handle(HYDROData_Polyline3D)::DownCast( theDocument->CreateObject( KIND_POLYLINE ) );
487
488   Handle(HYDROData_Bathymetry) aBath = Handle(HYDROData_Bathymetry)::DownCast( theDocument->CreateObject( KIND_BATHYMETRY ) );
489   HYDROData_Bathymetry::AltitudePoints aAPoints;
490
491   int nParts = anObj->nParts;
492   for ( int i = 0 ; i < nParts ; i++ )
493   {
494     //bool aSectClosure = true;
495     int StartIndex = anObj->panPartStart[i];
496     int EndIndex;
497     if (i != nParts - 1)
498       EndIndex = anObj->panPartStart[i + 1];
499     else
500       EndIndex = anObj->nVertices;
501
502     bool IsClosed = false;
503     HYDROData_PolylineXY::SectionType aSectType = HYDROData_PolylineXY::SECTION_POLYLINE; 
504     if (anObj->padfX[StartIndex] == anObj->padfX[EndIndex - 1] &&
505         anObj->padfY[StartIndex] == anObj->padfY[EndIndex - 1] &&
506         anObj->padfZ[StartIndex] == anObj->padfZ[EndIndex - 1])
507     {
508       IsClosed = true;
509       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, true );
510     }
511     else
512       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, false  );
513     
514     if (IsClosed)
515       EndIndex--;
516     for ( int k = StartIndex ; k < EndIndex ; k++ )
517     {
518       HYDROData_PolylineXY::Point aSectPoint;
519       aSectPoint.SetX( anObj->padfX[k] );
520       aSectPoint.SetY( anObj->padfY[k] );
521       aPolylineXY->AddPoint( i, aSectPoint );
522       aAPoints.Append(gp_XYZ (anObj->padfX[k], anObj->padfY[k], anObj->padfZ[k]));
523     }
524   }
525
526
527   QString aBathName = theFileName + "_bath_" + QString::number(theInd);
528   QString aPolyXYName = theFileName + "_polyXY_" + QString::number(theInd);
529   QString aPoly3DName = theFileName + "_poly3D_" + QString::number(theInd);
530
531   aPolylineXY->SetName( aPolyXYName );
532   aPolylineXY->SetWireColor(HYDROData_PolylineXY::DefaultWireColor());
533   aPolylineXY->Update();
534   
535   aBath->SetAltitudePoints(aAPoints);
536   aBath->SetName( aBathName );
537
538   aPolylineObj->SetPolylineXY (aPolylineXY, false);
539   aPolylineObj->SetAltitudeObject(aBath);
540
541   aPolylineObj->SetBorderColor( aPolylineObj->DefaultBorderColor() );
542   aPolylineObj->SetName( aPoly3DName );
543   
544   aPolylineObj->Update();
545   theEntities.Append(aPolylineXY);
546   theEntities.Append(aPolylineObj);
547
548 }
549
550
551
552 int HYDROData_ShapeFile::ImportPolylines(Handle(HYDROData_Document) theDocument, const QString& theFileName, 
553   NCollection_Sequence<Handle_HYDROData_Entity>& theEntities, int& theShapeTypeOfFile)
554 {
555   //Free();
556   int aStat = TryOpenShapeFile(theFileName);
557   if (aStat != 0)
558     return aStat;
559
560   HYDROData_Iterator anIter( theDocument );
561   int anInd = 0;
562   QStringList anExistingNames;
563   std::vector<int> anAllowedIndexes;
564   for( ; anIter.More(); anIter.Next() )
565     anExistingNames.push_back(anIter.Current()->GetName());
566
567   SHPHandle aHSHP;
568   aHSHP = SHPOpen( theFileName.toAscii().data(), "rb" );
569   
570   QFileInfo aFileInfo(theFileName);
571   QString aBaseFileName = aFileInfo.baseName();
572
573   if (!Parse(aHSHP, HYDROData_ShapeFile::ShapeType_Polyline, theShapeTypeOfFile))
574     return 0;
575   if (aHSHP->nShapeType == 3 || aHSHP->nShapeType == 23)
576   {
577     anInd = 0;
578     for (;anAllowedIndexes.size() < mySHPObjects.size();)
579     {
580       if (!anExistingNames.contains(aBaseFileName + "_PolyXY_" + QString::number(anInd)))
581       {
582         anAllowedIndexes.push_back(anInd);
583         anInd++;
584       }
585       else
586         anInd++;
587     }
588     
589     for (size_t i = 0; i < mySHPObjects.size(); i++ )
590     {
591       ReadSHPPolyXY(theDocument, mySHPObjects[i], aBaseFileName, anAllowedIndexes[i], theEntities);
592     }
593     aStat = 1;
594   }
595   else if (aHSHP->nShapeType == 13)
596   {
597     anInd = 0;
598     for (;anAllowedIndexes.size() < mySHPObjects.size();)
599     {
600       if (!anExistingNames.contains(aBaseFileName + "_PolyXY_" + QString::number(anInd)) &&
601           !anExistingNames.contains(aBaseFileName + "_Poly3D_" + QString::number(anInd)) &&
602           !anExistingNames.contains(aBaseFileName + "_Bath_" + QString::number(anInd)))
603       {
604         anAllowedIndexes.push_back(anInd);
605         anInd++;
606       }
607       else
608         anInd++;
609     }
610     for (size_t i = 0; i < mySHPObjects.size(); i++ )
611       ReadSHPPoly3D(theDocument, mySHPObjects[i], aBaseFileName, anAllowedIndexes[i], theEntities);
612     aStat = 1;
613   }
614   else  
615   {
616     aStat = 0;
617   }
618   
619   for (size_t i = 0; i < mySHPObjects.size(); i++ )
620     free (mySHPObjects[i]);
621
622   mySHPObjects.clear();
623   SHPClose(aHSHP);
624   return aStat;
625 }
626
627 QString HYDROData_ShapeFile::GetShapeTypeName(int theType)
628 {
629   switch (theType)
630   {
631     case 0:
632       return "null shape";
633     case 1:
634       return "point (unsupported by HYDRO)";
635     case 3:
636       return "arc/polyline (supported by HYDRO)";
637     case 5:
638       return "polygon (supported by HYDRO)";
639     case 8:
640       return "multipoint (unsupported by HYDRO)";
641     case 11:
642       return "pointZ (unsupported by HYDRO)";
643     case 13:
644       return "arcZ/polyline (supported by HYDRO)";
645     case 15:
646       return "polygonZ (unsupported by HYDRO)";
647     case 18:
648       return "multipointZ (unsupported by HYDRO)";
649     case 21:
650       return "pointM (unsupported by HYDRO)";
651     case 23:
652       return "arcM/polyline (supported by HYDRO)";
653     case 25:
654       return "polygonM (unsupported by HYDRO)";
655     case 28:
656       return "multipointM (unsupported by HYDRO)";
657     case 31:
658       return "multipatch (unsupported by HYDRO)";
659     default:
660       return "unknown";
661   }
662 }
663
664 int HYDROData_ShapeFile::TryOpenShapeFile(QString theFileName)
665 {
666   QString aSHPfile = theFileName.simplified();
667   QString aSHXfile = theFileName.simplified().replace( ".shp", ".shx", Qt::CaseInsensitive);
668   FILE* pFileSHP = NULL;
669   pFileSHP = fopen (aSHPfile.toAscii().data(), "r");
670   FILE* pFileSHX = NULL;
671   pFileSHX = fopen (aSHXfile.toAscii().data(), "r");
672
673   if (pFileSHP == NULL || pFileSHX == NULL)
674   {
675     if (pFileSHP == NULL)
676       return -1;
677     if (pFileSHX == NULL)
678       return -2;
679   }
680   
681   fclose (pFileSHP);
682   fclose (pFileSHX);
683   return 0;
684 }
685
686
687 bool HYDROData_ShapeFile::CheckDBFFileExisting(const QString& theSHPFilePath, QString& thePathToDBFFile)
688 {
689   QString aSHPfile = theSHPFilePath.simplified();
690   QString aDBFfile = theSHPFilePath.simplified().replace( ".shp", ".dbf", Qt::CaseInsensitive);
691   FILE* pFileDBF = NULL;
692   pFileDBF = fopen (aDBFfile.toAscii().data(), "r");
693
694   if (pFileDBF == NULL)
695   {
696     return false;
697   }
698   
699   fclose (pFileDBF);
700   thePathToDBFFile = aDBFfile;
701   return true;
702 }
703
704
705 bool HYDROData_ShapeFile::DBF_OpenDBF(const QString& thePathToDBFFile)
706 {
707   myHDBF = DBFOpen( thePathToDBFFile.toAscii().data(), "r" );
708   if(myHDBF != NULL)
709     return true;
710   else
711     return false;
712 }
713
714 int HYDROData_ShapeFile::DBF_GetNbFields()
715 {
716   if(myHDBF == NULL)
717     return 0;
718   return DBFGetFieldCount(myHDBF);
719 }
720
721 void HYDROData_ShapeFile::DBF_CloseDBF()
722 {
723   if(myHDBF != NULL)
724      DBFClose( myHDBF );
725 }
726
727 QStringList HYDROData_ShapeFile::DBF_GetFieldList()
728 {
729   QStringList FieldList;
730   int   nWidth, nDecimals;
731   char chField[12];
732
733   for( int i = 0; i < DBFGetFieldCount(myHDBF); i++ )
734   {
735       DBFFieldType eType;
736       eType = DBFGetFieldInfo( myHDBF, i, chField, &nWidth, &nDecimals );
737       FieldList.append(QString(chField));
738   }
739
740   return FieldList;
741 }
742
743 void HYDROData_ShapeFile::DBF_GetFieldTypeList(std::vector<DBF_FieldType>& FTVect)
744 {
745   int   nWidth, nDecimals;
746   char chField[12];
747   DBF_FieldType FT;
748   for( int i = 0; i < DBFGetFieldCount(myHDBF); i++ )
749   {
750     DBFFieldType eType;
751     eType = DBFGetFieldInfo( myHDBF, i, chField, &nWidth, &nDecimals );
752     if( eType == FTString )
753       FT = DBF_FieldType_String;
754     else if( eType == FTInteger )
755       FT = DBF_FieldType_Integer;
756     else if( eType == FTDouble )
757       FT = DBF_FieldType_Double;
758     else if( eType == FTInvalid )
759       FT = DBF_FieldType_Invalid;
760
761     FTVect.push_back(FT);
762   }
763
764 }
765
766 int HYDROData_ShapeFile::DBF_GetNbRecords()
767 {
768   if(myHDBF == NULL)
769     return 0;
770   return DBFGetRecordCount(myHDBF);
771 }
772
773 void HYDROData_ShapeFile::DBF_GetAttributeList(int theIndexOfField, std::vector<DBF_AttrValue>& theAttrV)
774 {
775   int nWidth, nDecimals;
776   char chField[12];
777   
778   for( int i = 0; i < DBFGetRecordCount(myHDBF); i++ )
779   {      
780     DBFFieldType eType;
781     DBF_AttrValue anAttr;
782     eType = DBFGetFieldInfo( myHDBF, theIndexOfField, chField, &nWidth, &nDecimals );
783
784     if( DBFIsAttributeNULL( myHDBF, i, theIndexOfField ) )
785     {
786       anAttr.myIsNull = true;
787       DBF_FieldType FT = DBF_FieldType_None;
788       if( eType == FTString )
789         FT = DBF_FieldType_String;
790       else if( eType == FTInteger )
791         FT = DBF_FieldType_Integer;
792       else if( eType == FTDouble )
793         FT = DBF_FieldType_Double;
794       else if( eType == FTInvalid )
795         FT = DBF_FieldType_Invalid;
796       anAttr.myFieldType = FT;
797     }
798     else
799     {
800       switch( eType )
801       {
802         case FTString:
803         {
804           const char* chAttr = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
805           anAttr.myIsNull = false;
806           anAttr.myFieldType = DBF_FieldType_String;
807           anAttr.myRawValue = chAttr;
808           anAttr.myStrVal = QString(chAttr);
809           break;
810         }
811        
812         case FTInteger:
813         {
814           int iAttr = DBFReadIntegerAttribute( myHDBF, i, theIndexOfField );
815           anAttr.myIsNull = false;
816           anAttr.myFieldType = DBF_FieldType_Integer;
817           anAttr.myRawValue = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
818           anAttr.myIntVal = iAttr;
819           break;
820         }
821           
822         case FTDouble:
823         {
824           double dAttr = DBFReadDoubleAttribute( myHDBF, i, theIndexOfField );
825           anAttr.myIsNull = false;
826           anAttr.myFieldType = DBF_FieldType_Double;
827           anAttr.myRawValue = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
828           anAttr.myDoubleVal = dAttr;
829           break;
830         }
831         default:
832           break;
833       }
834     }
835     theAttrV.push_back(anAttr);
836   }
837
838 }
839
840 bool HYDROData_ShapeFile::DBF_WriteFieldAndValues(const QString& theFileName, const QString& theFieldName, DBF_FieldType theType, const std::vector<DBF_AttrValue>& theAttrV, bool bUseRawValue)
841 {
842   // Check that given field type is equal to field types of attributes values
843   for (size_t i = 0; i < theAttrV.size(); i++)
844   {
845     if (theAttrV[i].myFieldType != theType)
846       return false;
847   }
848
849   DBFHandle     hDBF;
850   hDBF = DBFCreate( theFileName.toStdString().c_str() );
851   if( hDBF == NULL )
852           return false;
853   
854   if (theType != DBF_FieldType_String && theType != DBF_FieldType_Integer && theType != DBF_FieldType_Double) 
855   {
856     DBFClose( hDBF );
857     return false; //cant handle any other cases
858   }
859
860   int nWidth = 20;
861   switch( theType )
862   {
863     case DBF_FieldType_String:
864     {
865       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTString, nWidth, 0);
866       break;
867     }
868    
869     case DBF_FieldType_Integer:
870     {
871       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTInteger, nWidth, 0);
872       break;
873     }
874       
875     case DBF_FieldType_Double:
876     {
877       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTDouble, nWidth, 0);
878       break;
879     }
880     default:
881       break;
882   }
883
884   if (DBFGetFieldCount( hDBF ) != 1) 
885   {
886     DBFClose( hDBF );
887     return false;
888   }
889   if (DBFGetRecordCount( hDBF ) != 0)
890   {
891     DBFClose( hDBF );
892     return false;
893   }
894   int stat = -1;
895
896   if (bUseRawValue)
897   {
898     for (size_t i = 0; i < theAttrV.size(); i++)
899     {
900       if (!theAttrV[i].myIsNull)
901         stat = DBFWriteStringAttribute(hDBF, (int)i, 0, theAttrV[i].myRawValue.c_str());
902       else
903         stat = DBFWriteNULLAttribute(hDBF, (int)i, 0 );
904
905       if (stat != 1)
906       {
907         DBFClose( hDBF );
908         return false;
909       }
910     }
911   }
912   else
913   {
914     for (size_t i = 0; i < theAttrV.size(); i++)
915     {
916       if (!theAttrV[i].myIsNull)
917         switch( theType )
918         {
919           case DBF_FieldType_String:
920           {
921             stat = DBFWriteStringAttribute(hDBF, (int)i, 0, theAttrV[i].myStrVal.toStdString().c_str());
922             break;
923           }
924          
925           case DBF_FieldType_Integer:
926           {
927             stat = DBFWriteIntegerAttribute(hDBF, (int)i, 0, theAttrV[i].myIntVal);
928             break;
929           }
930             
931           case DBF_FieldType_Double:
932           {
933             stat = DBFWriteDoubleAttribute(hDBF, (int)i, 0, theAttrV[i].myDoubleVal);
934             break;
935           }
936           default:
937             break;
938         }
939       else
940         stat = DBFWriteNULLAttribute(hDBF, (int)i, 0 );
941
942       if (stat != 1)
943       {
944         DBFClose( hDBF );
945         return false;
946       }
947     }
948   }
949
950   DBFClose( hDBF );
951   return true;
952
953 }