Salome HOME
refs #762
[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 #include <OSD_Timer.hxx>
53 #include <BRepLib_MakeVertex.hxx>
54 #include <NCollection_List.hxx>
55 #include <GC_MakeSegment.hxx>
56 #include <BRep_Builder.hxx>
57 #include <BRepAdaptor_Curve.hxx>
58 #include <GCPnts_QuasiUniformDeflection.hxx>
59 #include <TopLoc_Location.hxx>
60 #include <Geom_Plane.hxx>
61 #include <NCollection_Array1.hxx>
62 #include <BRepBndLib.hxx>
63 #include <Bnd_Box.hxx>
64
65 #ifdef WIN32
66   #pragma warning( disable: 4996 )
67 #endif
68
69 //SHP->TFaces (Import) 
70 #define OSD_TIMER
71
72 HYDROData_ShapeFile::HYDROData_ShapeFile() : myHSHP(NULL)
73
74 }
75
76 HYDROData_ShapeFile::~HYDROData_ShapeFile()
77 {
78   Free();
79 }
80
81 void HYDROData_ShapeFile::Export(const QString& aFileName, 
82   NCollection_Sequence<Handle_HYDROData_PolylineXY> aPolyXYSeq,
83   NCollection_Sequence<Handle_HYDROData_Polyline3D> aPoly3DSeq,
84   QStringList& aNonExpList)
85 {
86   SHPHandle hSHPHandle;
87   if (!aPolyXYSeq.IsEmpty() && aPoly3DSeq.IsEmpty())
88   {
89     hSHPHandle = SHPCreate( aFileName.toAscii().data(), SHPT_ARC );        
90     for (int i = 1; i <= aPolyXYSeq.Size(); i++)
91       if (WriteObjectPolyXY(hSHPHandle, aPolyXYSeq(i)) != 1)
92         aNonExpList.append(aPolyXYSeq(i)->GetName());
93   }
94   else if (aPolyXYSeq.IsEmpty() && !aPoly3DSeq.IsEmpty())
95   {
96     hSHPHandle = SHPCreate( aFileName.toAscii().data(), SHPT_ARCZ );
97     for (int i = 1; i <= aPoly3DSeq.Size(); i++)
98       if (WriteObjectPoly3D(hSHPHandle, aPoly3DSeq(i)) != 1)
99         aNonExpList.append(aPoly3DSeq(i)->GetName());
100   }
101   if (hSHPHandle->nRecords > 0)
102     SHPClose( hSHPHandle );
103   else
104   {
105     SHPClose( hSHPHandle );
106     QString aFN = aFileName.simplified();
107     remove (aFN.toStdString().c_str());
108     remove ((aFN.simplified().replace( aFN.simplified().size() - 4, 4, ".shx")).toStdString().c_str());
109   }
110 }
111
112 void HYDROData_ShapeFile::Export(const QString& aFileName, const Handle_HYDROData_LandCoverMap& aLCM, 
113                                  QStringList& aNonExpList, bool bCheckLinear, bool bUseDiscr, double theDefl)
114 {
115   if (bCheckLinear && !aLCM->CheckLinear())
116     return;
117   //
118   SHPHandle hSHPHandle = NULL;
119   if ( !aLCM.IsNull() && !aLCM->IsEmpty())
120   {
121     hSHPHandle = SHPCreate( aFileName.toAscii().data(), SHPT_POLYGON );
122     HYDROData_LandCoverMap::Explorer It( aLCM );
123     for( ; It.More(); It.Next())
124     {
125       TopoDS_Face aFace = It.Face();
126       if (WriteObjectPolygon(hSHPHandle, aFace, bUseDiscr, theDefl) != 1)
127         aNonExpList.append(aLCM->GetName() + "_" +  QString::number(It.Index()));
128     }
129   }
130   if (hSHPHandle && hSHPHandle->nRecords > 0)
131     SHPClose( hSHPHandle );
132   else
133   {
134     SHPClose( hSHPHandle );
135     QString aFN = aFileName.simplified();
136     remove (aFN.toStdString().c_str());
137     remove ((aFN.simplified().replace( aFN.simplified().size() - 4, 4, ".shx")).toStdString().c_str());
138   }
139 }
140
141
142 int HYDROData_ShapeFile::WriteObjectPolyXY(SHPHandle theShpHandle, Handle_HYDROData_PolylineXY thePoly )
143 {
144   SHPObject     *aSHPObj;
145   std::vector<double> x, y;
146   std::vector<int> anPartStart;
147   
148   for (int i = 0; i < thePoly->NbSections(); i++)    
149     if (thePoly->GetSectionType(i) == HYDROData_IPolyline::SECTION_SPLINE)
150       return -1;
151
152   for (int i = 0; i < thePoly->NbSections(); i++)
153   {
154     anPartStart.push_back(x.size());
155     HYDROData_PolylineXY::PointsList aPointList = thePoly->GetPoints(i);
156     for (int j = 1; j <= aPointList.Size(); j++)
157     {
158       x.push_back( aPointList(j).X());
159       y.push_back( aPointList(j).Y()); 
160     }
161     if (thePoly->IsClosedSection(i))
162     {
163       x.push_back( aPointList(1).X());
164       y.push_back( aPointList(1).Y()); 
165     }
166   }
167     
168   aSHPObj = SHPCreateObject( SHPT_ARC, -1, thePoly->NbSections(), &anPartStart[0], NULL, x.size(), &x[0], &y[0], NULL, NULL );
169   SHPWriteObject( theShpHandle, -1, aSHPObj );
170   SHPDestroyObject( aSHPObj );
171   return 1;
172 }
173
174 int HYDROData_ShapeFile::WriteObjectPoly3D(SHPHandle theShpHandle, Handle_HYDROData_Polyline3D thePoly )
175 {
176   SHPObject     *aSHPObj;
177   std::vector<double> x, y, z;
178   std::vector<int> anPartStart;
179
180   for (int i = 0; i < thePoly->GetPolylineXY()->NbSections(); i++)    
181     if (thePoly->GetPolylineXY()->GetSectionType(i) == HYDROData_IPolyline::SECTION_SPLINE)
182       return -1;
183   
184   for (int i = 0; i < thePoly->GetPolylineXY()->NbSections(); i++)
185   {
186     anPartStart.push_back(x.size());
187     HYDROData_PolylineXY::PointsList aPointList = thePoly->GetPolylineXY()->GetPoints(i);
188     for (int j = 1; j <= aPointList.Size(); j++)
189     {
190       x.push_back( aPointList(j).X());
191       y.push_back( aPointList(j).Y()); 
192       z.push_back(thePoly->GetAltitudeObject()->GetAltitudeForPoint(gp_XY (aPointList(j).X(), aPointList(j).Y())));
193     }
194     if ( thePoly->GetPolylineXY()->IsClosedSection(i))
195     {
196       x.push_back( aPointList(1).X());
197       y.push_back( aPointList(1).Y()); 
198       z.push_back(thePoly->GetAltitudeObject()->GetAltitudeForPoint(gp_XY (aPointList(1).X(), aPointList(1).Y())));
199
200     }
201   }
202   
203   aSHPObj = SHPCreateObject( SHPT_ARCZ, -1, thePoly->GetPolylineXY()->NbSections(), &anPartStart[0], NULL, x.size(), &x[0], &y[0], &z[0], NULL );
204   SHPWriteObject( theShpHandle, -1, aSHPObj );
205   SHPDestroyObject( aSHPObj );
206   return 1;
207 }
208
209 int HYDROData_ShapeFile::WriteObjectPolygon(SHPHandle theShpHandle, const TopoDS_Shape& theInputShape,
210                                             bool bUseDiscr, double theDefl)
211 {
212   if (theInputShape.IsNull())
213     return 0;
214
215   if (theInputShape.ShapeType() == TopAbs_FACE)
216   {
217     ProcessFace(TopoDS::Face(theInputShape), theShpHandle, bUseDiscr, theDefl);
218   }
219   else if (theInputShape.ShapeType() == TopAbs_COMPOUND)
220   {
221     TopExp_Explorer Ex(theInputShape, TopAbs_FACE);
222     for (; Ex.More(); Ex.Next()) 
223     {
224       TopoDS_Face aF = TopoDS::Face(Ex.Current());   
225       if (aF.IsNull())
226         continue;
227       ProcessFace(aF, theShpHandle, bUseDiscr, theDefl);
228     }
229   }
230   else
231     return 0;
232
233   return 1;
234  
235 }
236
237 void HYDROData_ShapeFile::ProcessFace(const TopoDS_Face& theFace, SHPHandle theShpHandle,
238                                       bool bUseDiscr, double theDefl )
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   int NbWires = 0;
260   for (int k = 1; k <= aWires.Length(); k++) 
261   {
262     TopoDS_Wire aW = aWires(k);   
263     if (aW.IsNull())
264       continue;
265     NbWires++;
266     if (aW.Orientation() == TopAbs_INTERNAL)
267       //cant write internal wires/edges
268       continue; 
269     // Try to reorder edges
270     Handle(ShapeFix_Wire) aSFW = new ShapeFix_Wire( aW, theFace, Precision::Confusion() );
271     aSFW->ModifyTopologyMode() = Standard_False;
272     aSFW->ModifyGeometryMode() = Standard_False;
273     aSFW->FixReorder();
274     Handle(ShapeExtend_WireData) aSEWD = aSFW->WireData();
275     Standard_Integer nbE = aSEWD->NbEdges();
276     if (nbE == 0)
277       continue;
278     //
279     anPartStart.push_back(x.size());
280     NCollection_Sequence<gp_Pnt2d> aPnts;
281     for (Standard_Integer i = 1; i <= nbE; i++)
282     {
283       TopoDS_Edge E = aSEWD->Edge(i);
284       if (!bUseDiscr)
285       {
286         TopoDS_Vertex aV = TopExp::LastVertex(E, 1);
287         if (aV.IsNull())
288           continue;
289         gp_Pnt P = BRep_Tool::Pnt(aV);
290         aPnts.Append(gp_Pnt2d(P.X(), P.Y()));
291       }
292       else
293       {
294         BRepAdaptor_Curve Cur( E );
295         GCPnts_QuasiUniformDeflection Discr( Cur, theDefl );
296         if( !Discr.IsDone() )
297           continue; //skip edge?
298         double NewDefl = theDefl/2.0;
299         while (Discr.NbPoints() < 2)
300         {
301           Discr.Initialize(Cur, NewDefl);
302           NewDefl = NewDefl/2.0;
303         }
304         //
305         if (E.Orientation() == TopAbs_FORWARD)
306         {
307           for( int i = 1; i <= Discr.NbPoints(); i++ )
308           {
309             gp_Pnt P = Discr.Value( i );
310             aPnts.Append(gp_Pnt2d(P.X(), P.Y()));
311           }
312         }
313         else
314         {
315           for( int i = Discr.NbPoints(); i > 0; i-- )
316           {
317             gp_Pnt P = Discr.Value( i );
318             aPnts.Append(gp_Pnt2d(P.X(), P.Y()));
319           }
320         }
321       }
322     }
323     NCollection_Sequence<gp_Pnt2d> aNPnts;
324     aNPnts.Append(aPnts.First());
325     for (int j = 1; j <= aPnts.Size() - 1; j++)
326     {
327       if (!aPnts(j).IsEqual(aPnts(j + 1), Precision::Confusion())) 
328         aNPnts.Append(aPnts(j + 1));
329     }
330
331     //assume that the orientation of external wire & internal wires is correct
332     //so just write all points "as-is"
333     //External wire will be written in clockwise direction
334     //any other wires (holes) - in anticlockwise direction
335     for (int j = aNPnts.Size(); j >= 1; j--)
336     { 
337       x.push_back( aNPnts(j).X());
338       y.push_back( aNPnts(j).Y()); 
339     }
340     //first point is same as the last one => closed polygon
341     x.push_back( aNPnts.Last().X());
342     y.push_back( aNPnts.Last().Y()); 
343
344   }
345   
346   aSHPObj = SHPCreateObject( SHPT_POLYGON, -1, NbWires, &anPartStart[0], NULL, x.size(), &x[0], &y[0], NULL, NULL );
347   SHPWriteObject( theShpHandle, -1, aSHPObj );
348   SHPDestroyObject( aSHPObj );
349
350 }
351
352 bool HYDROData_ShapeFile::Parse(SHPHandle theHandle, ShapeType theType, int& theShapeTypeOfFile)
353 {
354   int aShapeType;
355   mySHPObjects.clear();
356   SHPGetInfo( theHandle, NULL, &aShapeType, NULL, NULL );
357   theShapeTypeOfFile = aShapeType;
358   bool ToRead = (theType == ShapeType_Polyline && (aShapeType == 3 || aShapeType == 13 || aShapeType == 23)) ||
359    (theType == ShapeType_Polygon && aShapeType == 5);
360   if (ToRead) 
361   {
362     for (int i = 0; i < theHandle->nRecords; i++) 
363       mySHPObjects.push_back(SHPReadObject(theHandle, i));
364     return true;
365   }
366   else
367     return false;
368 }
369
370 void HYDROData_ShapeFile::ReadSHPPolygon(SHPObject* anObj, int i, TopoDS_Face& F)
371 {
372   if (!anObj)
373     return;
374   TopoDS_Edge E; 
375   int nParts = anObj->nParts;
376   Handle_Geom_Plane aPlaneSur = new Geom_Plane(gp_Pnt(0,0,0), gp_Dir(0,0,1));
377
378   BRep_Builder BB;
379   BB.MakeFace(F);
380
381   NCollection_Sequence<TopoDS_Wire> allWires;
382
383   TopTools_SequenceOfShape aWires;
384   for ( int i = 0 ; i < nParts ; i++ )
385   { 
386     BRepBuilderAPI_MakeWire aBuilder;
387     int StartIndex = anObj->panPartStart[i];
388     int EndIndex;
389     if (i != nParts - 1)
390       EndIndex = anObj->panPartStart[i + 1];
391     else
392       EndIndex = anObj->nVertices;
393
394     TopoDS_Wire W;
395     BB.MakeWire(W);
396
397     //First point is same as the last point 
398     int NbPnts = EndIndex - StartIndex - 1;
399     NCollection_Array1<TopoDS_Vertex> VPoints(0, NbPnts);
400     int j = NbPnts;
401     for ( int k = StartIndex; k < EndIndex; k++ )
402     {
403       gp_Pnt P (anObj->padfX[k], anObj->padfY[k], 0);
404       VPoints.ChangeValue(j) = BRepLib_MakeVertex(P).Vertex();
405       j--;
406     }
407       
408     for ( int k = 0; k < VPoints.Size() - 1; k++ )
409     {
410       gp_Pnt P1 = BRep_Tool::Pnt(VPoints(k));
411       gp_Pnt P2 = BRep_Tool::Pnt(VPoints(k + 1));
412       if (P1.Distance(P2) < Precision::Confusion())
413         continue;
414       Handle_Geom_TrimmedCurve aTC = GC_MakeSegment(P1, P2).Value();
415       TopoDS_Edge E;
416       if ( k != VPoints.Size() - 2)
417         E = BRepLib_MakeEdge(aTC, VPoints(k), VPoints(k + 1)).Edge();
418       else
419         //the last edge => use first and last vertices
420         E = BRepLib_MakeEdge(aTC, VPoints.First(), VPoints.Value(VPoints.Upper() - 1)).Edge();
421       //Add edge to wire
422       //If SHP file is correct then the outer wire and the holes will have the correct orientations
423       W.Closed (Standard_True);
424       W.Orientation(TopAbs_FORWARD);
425       BB.Add(W, E);
426     }
427     allWires.Append(W);
428   }
429
430   int OutWIndex = -1;
431   if (allWires.Size() > 1)
432   {
433     NCollection_Sequence<Bnd_Box> BBs;
434     //try to find the largest bbox
435     for (int i = 1; i <= allWires.Size(); i++)
436     {
437       TopoDS_Wire W = allWires(i);
438       Bnd_Box BB;
439       BRepBndLib::AddClose(W, BB);
440       BBs.Append(BB);
441     }
442     for (int i = 1; i <= BBs.Size(); i++)
443     {
444       bool IsIn = false;
445       for (int j = 1; j <= BBs.Size(); j++)
446       {
447         if (i == j)
448           continue;
449         Standard_Real iXmax, iXmin, iYmax, iYmin, z0, z1;
450         Standard_Real jXmax, jXmin, jYmax, jYmin;
451         BBs(i).Get(iXmin, iYmin, z0, iXmax, iYmax, z1);
452         BBs(j).Get(jXmin, jYmin, z0, jXmax, jYmax, z1);
453         if (!(iXmin > jXmin && 
454             iYmin > jYmin &&
455             iXmax < jXmax &&
456             iYmax < jYmax))
457           IsIn = true;
458       }
459       if (IsIn)
460       {
461         OutWIndex = i;
462         break;
463       }
464     }
465   }
466   else
467     OutWIndex = 1; //one wire => no need to check
468
469   for (int i = 1; i <= allWires.Size(); i++)
470   {
471     TopoDS_Face DF;
472     BB.MakeFace(DF);
473     TopoDS_Wire W = allWires(i);
474     BB.Add(DF, W);
475     BB.UpdateFace(DF, aPlaneSur, TopLoc_Location(), Precision::Confusion());
476     //
477     BRepTopAdaptor_FClass2d FClass(DF, Precision::PConfusion());
478     if ( i == OutWIndex && FClass.PerformInfinitePoint() == TopAbs_IN) 
479       W.Reverse();
480     if ( i != OutWIndex && FClass.PerformInfinitePoint() == TopAbs_OUT) 
481       W.Reverse();
482     //
483     BB.Add(F, W);
484   }
485   
486   //Add surface to the face
487   BB.UpdateFace(F, aPlaneSur, TopLoc_Location(), Precision::Confusion());
488   F.Closed(Standard_True);
489 }
490
491 int HYDROData_ShapeFile::ImportPolygons(const QString theFileName, QStringList& thePolygonsList, TopTools_SequenceOfShape& theFaces, int& theShapeTypeOfFile)
492 {
493   Free();
494   int Stat = TryOpenShapeFile(theFileName);
495   if (Stat != 0)
496     return Stat;
497   myHSHP = SHPOpen( theFileName.toAscii().data(), "rb" );
498   if (!Parse(myHSHP, HYDROData_ShapeFile::ShapeType_Polygon, theShapeTypeOfFile))
499     return 0;
500   for (size_t i = 0; i < mySHPObjects.size(); i++)
501     thePolygonsList.append("polygon_" + QString::number(i + 1));
502    
503   TopoDS_Face aF;
504   if (myHSHP->nShapeType == 5)
505   {
506 #ifdef OSD_TIMER
507     OSD_Timer timer;
508     timer.Start();
509 #endif
510     for (size_t i = 0; i < mySHPObjects.size(); i++) 
511     {
512        ReadSHPPolygon(mySHPObjects[i], i, aF);
513        theFaces.Append(aF);
514     }
515 #ifdef OSD_TIMER
516     timer.Stop();
517     timer.Show();
518 #endif
519     return 1;
520   }
521   else
522     return 0;
523 }
524
525 void HYDROData_ShapeFile::Free()
526 {  
527   for (size_t i = 0; i < mySHPObjects.size(); i++ )
528     free (mySHPObjects[i]);
529
530   mySHPObjects.clear();
531   if (myHSHP != NULL)
532   {
533     SHPClose(myHSHP);
534     myHSHP = NULL; 
535   }
536 }
537
538
539 void HYDROData_ShapeFile::ReadSHPPolyXY(Handle(HYDROData_Document) theDocument, SHPObject* anObj, QString theFileName, 
540   int theInd, NCollection_Sequence<Handle_HYDROData_Entity>& theEntities)
541 {
542
543   Handle(HYDROData_PolylineXY) aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
544   
545   int nParts = anObj->nParts;
546   for ( int i = 0 ; i < nParts ; i++ )
547   {
548     int StartIndex = anObj->panPartStart[i];
549     int EndIndex;
550     if (i != nParts - 1)
551       EndIndex = anObj->panPartStart[i + 1];
552     else
553       EndIndex = anObj->nVertices;
554
555     bool IsClosed = false;
556     HYDROData_PolylineXY::SectionType aSectType = HYDROData_PolylineXY::SECTION_POLYLINE; 
557     if (anObj->padfX[StartIndex] == anObj->padfX[EndIndex - 1] &&
558         anObj->padfY[StartIndex] == anObj->padfY[EndIndex - 1] )
559     {
560       IsClosed = true;
561       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, true);
562     }
563     else
564       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, false);
565     
566     if (IsClosed)
567       EndIndex--;
568     for ( int k = StartIndex; k < EndIndex ; k++ )
569     {
570       HYDROData_PolylineXY::Point aSectPoint;
571       aSectPoint.SetX( anObj->padfX[k] );
572       aSectPoint.SetY( anObj->padfY[k] );
573       aPolylineXY->AddPoint( i, aSectPoint );
574     }
575
576   }
577   
578   aPolylineXY->SetWireColor( HYDROData_PolylineXY::DefaultWireColor() );
579   aPolylineXY->SetName( theFileName + "_PolyXY_" + QString::number(theInd) );
580   
581   aPolylineXY->Update();
582   theEntities.Append(aPolylineXY);
583
584 }
585
586 void HYDROData_ShapeFile::ReadSHPPoly3D(Handle(HYDROData_Document) theDocument, SHPObject* anObj, QString theFileName, 
587   int theInd, NCollection_Sequence<Handle_HYDROData_Entity>& theEntities)
588 {
589   Handle(HYDROData_PolylineXY) aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
590
591   Handle(HYDROData_Polyline3D) aPolylineObj = Handle(HYDROData_Polyline3D)::DownCast( theDocument->CreateObject( KIND_POLYLINE ) );
592
593   Handle(HYDROData_Bathymetry) aBath = Handle(HYDROData_Bathymetry)::DownCast( theDocument->CreateObject( KIND_BATHYMETRY ) );
594   HYDROData_Bathymetry::AltitudePoints aAPoints;
595
596   int nParts = anObj->nParts;
597   for ( int i = 0 ; i < nParts ; i++ )
598   {
599     //bool aSectClosure = true;
600     int StartIndex = anObj->panPartStart[i];
601     int EndIndex;
602     if (i != nParts - 1)
603       EndIndex = anObj->panPartStart[i + 1];
604     else
605       EndIndex = anObj->nVertices;
606
607     bool IsClosed = false;
608     HYDROData_PolylineXY::SectionType aSectType = HYDROData_PolylineXY::SECTION_POLYLINE; 
609     if (anObj->padfX[StartIndex] == anObj->padfX[EndIndex - 1] &&
610         anObj->padfY[StartIndex] == anObj->padfY[EndIndex - 1] &&
611         anObj->padfZ[StartIndex] == anObj->padfZ[EndIndex - 1])
612     {
613       IsClosed = true;
614       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, true );
615     }
616     else
617       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, false  );
618     
619     if (IsClosed)
620       EndIndex--;
621     for ( int k = StartIndex ; k < EndIndex ; k++ )
622     {
623       HYDROData_PolylineXY::Point aSectPoint;
624       aSectPoint.SetX( anObj->padfX[k] );
625       aSectPoint.SetY( anObj->padfY[k] );
626       aPolylineXY->AddPoint( i, aSectPoint );
627       aAPoints.Append(gp_XYZ (anObj->padfX[k], anObj->padfY[k], anObj->padfZ[k]));
628     }
629   }
630
631
632   QString aBathName = theFileName + "_bath_" + QString::number(theInd);
633   QString aPolyXYName = theFileName + "_polyXY_" + QString::number(theInd);
634   QString aPoly3DName = theFileName + "_poly3D_" + QString::number(theInd);
635
636   aPolylineXY->SetName( aPolyXYName );
637   aPolylineXY->SetWireColor(HYDROData_PolylineXY::DefaultWireColor());
638   aPolylineXY->Update();
639   
640   aBath->SetAltitudePoints(aAPoints);
641   aBath->SetName( aBathName );
642
643   aPolylineObj->SetPolylineXY (aPolylineXY, false);
644   aPolylineObj->SetAltitudeObject(aBath);
645
646   aPolylineObj->SetBorderColor( aPolylineObj->DefaultBorderColor() );
647   aPolylineObj->SetName( aPoly3DName );
648   
649   aPolylineObj->Update();
650   theEntities.Append(aPolylineXY);
651   theEntities.Append(aPolylineObj);
652
653 }
654
655
656
657 int HYDROData_ShapeFile::ImportPolylines(Handle(HYDROData_Document) theDocument, const QString& theFileName, 
658   NCollection_Sequence<Handle_HYDROData_Entity>& theEntities, int& theShapeTypeOfFile)
659 {
660   //Free();
661   int aStat = TryOpenShapeFile(theFileName);
662   if (aStat != 0)
663     return aStat;
664
665   HYDROData_Iterator anIter( theDocument );
666   int anInd = 0;
667   QStringList anExistingNames;
668   std::vector<int> anAllowedIndexes;
669   for( ; anIter.More(); anIter.Next() )
670     anExistingNames.push_back(anIter.Current()->GetName());
671
672   SHPHandle aHSHP;
673   aHSHP = SHPOpen( theFileName.toAscii().data(), "rb" );
674   
675   QFileInfo aFileInfo(theFileName);
676   QString aBaseFileName = aFileInfo.baseName();
677
678   if (!Parse(aHSHP, HYDROData_ShapeFile::ShapeType_Polyline, theShapeTypeOfFile))
679     return 0;
680   if (aHSHP->nShapeType == 3 || aHSHP->nShapeType == 23)
681   {
682     anInd = 0;
683     for (;anAllowedIndexes.size() < mySHPObjects.size();)
684     {
685       if (!anExistingNames.contains(aBaseFileName + "_PolyXY_" + QString::number(anInd)))
686       {
687         anAllowedIndexes.push_back(anInd);
688         anInd++;
689       }
690       else
691         anInd++;
692     }
693     
694     for (size_t i = 0; i < mySHPObjects.size(); i++ )
695     {
696       ReadSHPPolyXY(theDocument, mySHPObjects[i], aBaseFileName, anAllowedIndexes[i], theEntities);
697     }
698     aStat = 1;
699   }
700   else if (aHSHP->nShapeType == 13)
701   {
702     anInd = 0;
703     for (;anAllowedIndexes.size() < mySHPObjects.size();)
704     {
705       if (!anExistingNames.contains(aBaseFileName + "_PolyXY_" + QString::number(anInd)) &&
706           !anExistingNames.contains(aBaseFileName + "_Poly3D_" + QString::number(anInd)) &&
707           !anExistingNames.contains(aBaseFileName + "_Bath_" + QString::number(anInd)))
708       {
709         anAllowedIndexes.push_back(anInd);
710         anInd++;
711       }
712       else
713         anInd++;
714     }
715     for (size_t i = 0; i < mySHPObjects.size(); i++ )
716       ReadSHPPoly3D(theDocument, mySHPObjects[i], aBaseFileName, anAllowedIndexes[i], theEntities);
717     aStat = 1;
718   }
719   else  
720   {
721     aStat = 0;
722   }
723   
724   for (size_t i = 0; i < mySHPObjects.size(); i++ )
725     free (mySHPObjects[i]);
726
727   mySHPObjects.clear();
728   SHPClose(aHSHP);
729   return aStat;
730 }
731
732 QString HYDROData_ShapeFile::GetShapeTypeName(int theType)
733 {
734   switch (theType)
735   {
736     case 0:
737       return "null shape";
738     case 1:
739       return "point (unsupported by HYDRO)";
740     case 3:
741       return "arc/polyline (supported by HYDRO)";
742     case 5:
743       return "polygon (supported by HYDRO)";
744     case 8:
745       return "multipoint (unsupported by HYDRO)";
746     case 11:
747       return "pointZ (unsupported by HYDRO)";
748     case 13:
749       return "arcZ/polyline (supported by HYDRO)";
750     case 15:
751       return "polygonZ (unsupported by HYDRO)";
752     case 18:
753       return "multipointZ (unsupported by HYDRO)";
754     case 21:
755       return "pointM (unsupported by HYDRO)";
756     case 23:
757       return "arcM/polyline (supported by HYDRO)";
758     case 25:
759       return "polygonM (unsupported by HYDRO)";
760     case 28:
761       return "multipointM (unsupported by HYDRO)";
762     case 31:
763       return "multipatch (unsupported by HYDRO)";
764     default:
765       return "unknown";
766   }
767 }
768
769 int HYDROData_ShapeFile::TryOpenShapeFile(QString theFileName)
770 {
771   QString aSHPfile = theFileName.simplified();
772   QString aSHXfile = theFileName.simplified().replace( theFileName.simplified().size() - 4, 4, ".shx");
773
774   QString anExt = theFileName.split('.', QString::SkipEmptyParts).back();
775   if (anExt.toLower() != "shp")
776     return -3;
777
778   FILE* pFileSHP = NULL;
779   pFileSHP = fopen (aSHPfile.toAscii().data(), "r");
780   FILE* pFileSHX = NULL;
781   pFileSHX = fopen (aSHXfile.toAscii().data(), "r");
782
783   if (pFileSHP == NULL || pFileSHX == NULL)
784   {
785     if (pFileSHP == NULL)
786       return -1;
787     if (pFileSHX == NULL)
788       return -2;
789   }
790   
791   fclose (pFileSHP);
792   fclose (pFileSHX);
793   return 0;
794 }
795
796
797 bool HYDROData_ShapeFile::CheckDBFFileExisting(const QString& theSHPFilePath, QString& thePathToDBFFile)
798 {
799   QString aSHPfile = theSHPFilePath.simplified();
800   QString aDBFfile = theSHPFilePath.simplified().replace( theSHPFilePath.simplified().size() - 4, 4, ".dbf");
801   FILE* pFileDBF = NULL;
802   pFileDBF = fopen (aDBFfile.toAscii().data(), "r");
803
804   if (pFileDBF == NULL)
805   {
806     return false;
807   }
808   
809   fclose (pFileDBF);
810   thePathToDBFFile = aDBFfile;
811   return true;
812 }
813
814
815 bool HYDROData_ShapeFile::DBF_OpenDBF(const QString& thePathToDBFFile)
816 {
817   myHDBF = DBFOpen( thePathToDBFFile.toAscii().data(), "r" );
818   if(myHDBF != NULL)
819     return true;
820   else
821     return false;
822 }
823
824 int HYDROData_ShapeFile::DBF_GetNbFields()
825 {
826   if(myHDBF == NULL)
827     return 0;
828   return DBFGetFieldCount(myHDBF);
829 }
830
831 void HYDROData_ShapeFile::DBF_CloseDBF()
832 {
833   if(myHDBF != NULL)
834      DBFClose( myHDBF );
835 }
836
837 QStringList HYDROData_ShapeFile::DBF_GetFieldList()
838 {
839   QStringList FieldList;
840   int   nWidth, nDecimals;
841   char chField[12];
842
843   for( int i = 0; i < DBFGetFieldCount(myHDBF); i++ )
844   {
845       DBFFieldType eType;
846       eType = DBFGetFieldInfo( myHDBF, i, chField, &nWidth, &nDecimals );
847       FieldList.append(QString(chField));
848   }
849
850   return FieldList;
851 }
852
853 void HYDROData_ShapeFile::DBF_GetFieldTypeList(std::vector<DBF_FieldType>& FTVect)
854 {
855   int   nWidth, nDecimals;
856   char chField[12];
857   DBF_FieldType FT;
858   for( int i = 0; i < DBFGetFieldCount(myHDBF); i++ )
859   {
860     DBFFieldType eType;
861     eType = DBFGetFieldInfo( myHDBF, i, chField, &nWidth, &nDecimals );
862     if( eType == FTString )
863       FT = DBF_FieldType_String;
864     else if( eType == FTInteger )
865       FT = DBF_FieldType_Integer;
866     else if( eType == FTDouble )
867       FT = DBF_FieldType_Double;
868     else if( eType == FTInvalid )
869       FT = DBF_FieldType_Invalid;
870
871     FTVect.push_back(FT);
872   }
873
874 }
875
876 int HYDROData_ShapeFile::DBF_GetNbRecords()
877 {
878   if(myHDBF == NULL)
879     return 0;
880   return DBFGetRecordCount(myHDBF);
881 }
882
883 void HYDROData_ShapeFile::DBF_GetAttributeList(int theIndexOfField, std::vector<DBF_AttrValue>& theAttrV)
884 {
885   int nWidth, nDecimals;
886   char chField[12];
887   
888   for( int i = 0; i < DBFGetRecordCount(myHDBF); i++ )
889   {      
890     DBFFieldType eType;
891     DBF_AttrValue anAttr;
892     eType = DBFGetFieldInfo( myHDBF, theIndexOfField, chField, &nWidth, &nDecimals );
893
894     if( DBFIsAttributeNULL( myHDBF, i, theIndexOfField ) )
895     {
896       anAttr.myIsNull = true;
897       DBF_FieldType FT = DBF_FieldType_None;
898       if( eType == FTString )
899         FT = DBF_FieldType_String;
900       else if( eType == FTInteger )
901         FT = DBF_FieldType_Integer;
902       else if( eType == FTDouble )
903         FT = DBF_FieldType_Double;
904       else if( eType == FTInvalid )
905         FT = DBF_FieldType_Invalid;
906       anAttr.myFieldType = FT;
907     }
908     else
909     {
910       switch( eType )
911       {
912         case FTString:
913         {
914           const char* chAttr = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
915           anAttr.myIsNull = false;
916           anAttr.myFieldType = DBF_FieldType_String;
917           anAttr.myRawValue = chAttr;
918           anAttr.myStrVal = QString(chAttr);
919           break;
920         }
921        
922         case FTInteger:
923         {
924           int iAttr = DBFReadIntegerAttribute( myHDBF, i, theIndexOfField );
925           anAttr.myIsNull = false;
926           anAttr.myFieldType = DBF_FieldType_Integer;
927           anAttr.myRawValue = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
928           anAttr.myIntVal = iAttr;
929           break;
930         }
931           
932         case FTDouble:
933         {
934           double dAttr = DBFReadDoubleAttribute( myHDBF, i, theIndexOfField );
935           anAttr.myIsNull = false;
936           anAttr.myFieldType = DBF_FieldType_Double;
937           anAttr.myRawValue = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
938           anAttr.myDoubleVal = dAttr;
939           break;
940         }
941         default:
942           break;
943       }
944     }
945     theAttrV.push_back(anAttr);
946   }
947
948 }
949
950 bool HYDROData_ShapeFile::DBF_WriteFieldAndValues(const QString& theFileName, const QString& theFieldName, DBF_FieldType theType, const std::vector<DBF_AttrValue>& theAttrV, bool bUseRawValue)
951 {
952   // Check that given field type is equal to field types of attributes values
953   for (size_t i = 0; i < theAttrV.size(); i++)
954   {
955     if (theAttrV[i].myFieldType != theType)
956       return false;
957   }
958
959   DBFHandle     hDBF;
960   hDBF = DBFCreate( theFileName.toStdString().c_str() );
961   if( hDBF == NULL )
962           return false;
963   
964   if (theType != DBF_FieldType_String && theType != DBF_FieldType_Integer && theType != DBF_FieldType_Double) 
965   {
966     DBFClose( hDBF );
967     return false; //cant handle any other cases
968   }
969
970   int nWidth = 20;
971   switch( theType )
972   {
973     case DBF_FieldType_String:
974     {
975       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTString, nWidth, 0);
976       break;
977     }
978    
979     case DBF_FieldType_Integer:
980     {
981       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTInteger, nWidth, 0);
982       break;
983     }
984       
985     case DBF_FieldType_Double:
986     {
987       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTDouble, nWidth, 0);
988       break;
989     }
990     default:
991       break;
992   }
993
994   if (DBFGetFieldCount( hDBF ) != 1) 
995   {
996     DBFClose( hDBF );
997     return false;
998   }
999   if (DBFGetRecordCount( hDBF ) != 0)
1000   {
1001     DBFClose( hDBF );
1002     return false;
1003   }
1004   int stat = -1;
1005
1006   if (bUseRawValue)
1007   {
1008     for (size_t i = 0; i < theAttrV.size(); i++)
1009     {
1010       if (!theAttrV[i].myIsNull)
1011         stat = DBFWriteStringAttribute(hDBF, (int)i, 0, theAttrV[i].myRawValue.c_str());
1012       else
1013         stat = DBFWriteNULLAttribute(hDBF, (int)i, 0 );
1014
1015       if (stat != 1)
1016       {
1017         DBFClose( hDBF );
1018         return false;
1019       }
1020     }
1021   }
1022   else
1023   {
1024     for (size_t i = 0; i < theAttrV.size(); i++)
1025     {
1026       if (!theAttrV[i].myIsNull)
1027         switch( theType )
1028         {
1029           case DBF_FieldType_String:
1030           {
1031             stat = DBFWriteStringAttribute(hDBF, (int)i, 0, theAttrV[i].myStrVal.toStdString().c_str());
1032             break;
1033           }
1034          
1035           case DBF_FieldType_Integer:
1036           {
1037             stat = DBFWriteIntegerAttribute(hDBF, (int)i, 0, theAttrV[i].myIntVal);
1038             break;
1039           }
1040             
1041           case DBF_FieldType_Double:
1042           {
1043             stat = DBFWriteDoubleAttribute(hDBF, (int)i, 0, theAttrV[i].myDoubleVal);
1044             break;
1045           }
1046           default:
1047             break;
1048         }
1049       else
1050         stat = DBFWriteNULLAttribute(hDBF, (int)i, 0 );
1051
1052       if (stat != 1)
1053       {
1054         DBFClose( hDBF );
1055         return false;
1056       }
1057     }
1058   }
1059
1060   DBFClose( hDBF );
1061   return true;
1062
1063 }
1064