Salome HOME
Merge branch 'BR_quadtree' into V7_dev
[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(Handle(HYDROData_Document) theDocument, 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       theDocument->Transform(P, true);
405       VPoints.ChangeValue(j) = BRepLib_MakeVertex(P).Vertex();
406       j--;
407     }
408       
409     for ( int k = 0; k < VPoints.Size() - 1; k++ )
410     {
411       gp_Pnt P1 = BRep_Tool::Pnt(VPoints(k));
412       gp_Pnt P2 = BRep_Tool::Pnt(VPoints(k + 1));
413       if (P1.Distance(P2) < Precision::Confusion())
414         continue;
415       Handle_Geom_TrimmedCurve aTC = GC_MakeSegment(P1, P2).Value();
416       TopoDS_Edge E;
417       if ( k != VPoints.Size() - 2)
418         E = BRepLib_MakeEdge(aTC, VPoints(k), VPoints(k + 1)).Edge();
419       else
420         //the last edge => use first and last vertices
421         E = BRepLib_MakeEdge(aTC, VPoints.First(), VPoints.Value(VPoints.Upper() - 1)).Edge();
422       //Add edge to wire
423       //If SHP file is correct then the outer wire and the holes will have the correct orientations
424       W.Closed (Standard_True);
425       W.Orientation(TopAbs_FORWARD);
426       BB.Add(W, E);
427     }
428     allWires.Append(W);
429   }
430
431   int OutWIndex = -1;
432   if (allWires.Size() > 1)
433   {
434     NCollection_Sequence<Bnd_Box> BBs;
435     //try to find the largest bbox
436     for (int i = 1; i <= allWires.Size(); i++)
437     {
438       TopoDS_Wire W = allWires(i);
439       Bnd_Box BB;
440       BRepBndLib::AddClose(W, BB);
441       BBs.Append(BB);
442     }
443     for (int i = 1; i <= BBs.Size(); i++)
444     {
445       bool IsIn = false;
446       for (int j = 1; j <= BBs.Size(); j++)
447       {
448         if (i == j)
449           continue;
450         Standard_Real iXmax, iXmin, iYmax, iYmin, z0, z1;
451         Standard_Real jXmax, jXmin, jYmax, jYmin;
452         BBs(i).Get(iXmin, iYmin, z0, iXmax, iYmax, z1);
453         BBs(j).Get(jXmin, jYmin, z0, jXmax, jYmax, z1);
454         if (!(iXmin > jXmin && 
455             iYmin > jYmin &&
456             iXmax < jXmax &&
457             iYmax < jYmax))
458           IsIn = true;
459       }
460       if (IsIn)
461       {
462         OutWIndex = i;
463         break;
464       }
465     }
466   }
467   else
468     OutWIndex = 1; //one wire => no need to check
469
470   for (int i = 1; i <= allWires.Size(); i++)
471   {
472     TopoDS_Face DF;
473     BB.MakeFace(DF);
474     TopoDS_Wire W = allWires(i);
475     BB.Add(DF, W);
476     BB.UpdateFace(DF, aPlaneSur, TopLoc_Location(), Precision::Confusion());
477     //
478     BRepTopAdaptor_FClass2d FClass(DF, Precision::PConfusion());
479     if ( i == OutWIndex && FClass.PerformInfinitePoint() == TopAbs_IN) 
480       W.Reverse();
481     if ( i != OutWIndex && FClass.PerformInfinitePoint() == TopAbs_OUT) 
482       W.Reverse();
483     //
484     BB.Add(F, W);
485   }
486   
487   //Add surface to the face
488   BB.UpdateFace(F, aPlaneSur, TopLoc_Location(), Precision::Confusion());
489   F.Closed(Standard_True);
490 }
491
492 int HYDROData_ShapeFile::ImportPolygons(Handle(HYDROData_Document) theDocument, const QString theFileName, QStringList& thePolygonsList, TopTools_SequenceOfShape& theFaces, int& theShapeTypeOfFile)
493 {
494   Free();
495   int Stat = TryOpenShapeFile(theFileName);
496   if (Stat != 0)
497     return Stat;
498   myHSHP = SHPOpen( theFileName.toAscii().data(), "rb" );
499   if (!Parse(myHSHP, HYDROData_ShapeFile::ShapeType_Polygon, theShapeTypeOfFile))
500     return 0;
501   for (size_t i = 0; i < mySHPObjects.size(); i++)
502     thePolygonsList.append("polygon_" + QString::number(i + 1));
503    
504   TopoDS_Face aF;
505   if (myHSHP->nShapeType == 5)
506   {
507 #ifdef OSD_TIMER
508     OSD_Timer timer;
509     timer.Start();
510 #endif
511     for (size_t i = 0; i < mySHPObjects.size(); i++) 
512     {
513        ReadSHPPolygon(theDocument, mySHPObjects[i], i, aF);
514        theFaces.Append(aF);
515     }
516 #ifdef OSD_TIMER
517     timer.Stop();
518     timer.Show();
519 #endif
520     return 1;
521   }
522   else
523     return 0;
524 }
525
526 void HYDROData_ShapeFile::Free()
527 {  
528   for (size_t i = 0; i < mySHPObjects.size(); i++ )
529     free (mySHPObjects[i]);
530
531   mySHPObjects.clear();
532   if (myHSHP != NULL)
533   {
534     SHPClose(myHSHP);
535     myHSHP = NULL; 
536   }
537 }
538
539
540 void HYDROData_ShapeFile::ReadSHPPolyXY(Handle(HYDROData_Document) theDocument, SHPObject* anObj, QString theFileName, 
541   int theInd, NCollection_Sequence<Handle_HYDROData_Entity>& theEntities)
542 {
543
544   Handle(HYDROData_PolylineXY) aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
545   
546   int nParts = anObj->nParts;
547   for ( int i = 0 ; i < nParts ; i++ )
548   {
549     int StartIndex = anObj->panPartStart[i];
550     int EndIndex;
551     if (i != nParts - 1)
552       EndIndex = anObj->panPartStart[i + 1];
553     else
554       EndIndex = anObj->nVertices;
555
556     bool IsClosed = false;
557     HYDROData_PolylineXY::SectionType aSectType = HYDROData_PolylineXY::SECTION_POLYLINE; 
558     if (anObj->padfX[StartIndex] == anObj->padfX[EndIndex - 1] &&
559         anObj->padfY[StartIndex] == anObj->padfY[EndIndex - 1] )
560     {
561       IsClosed = true;
562       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, true);
563     }
564     else
565       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, false);
566     
567     if (IsClosed)
568       EndIndex--;
569     for ( int k = StartIndex; k < EndIndex ; k++ )
570     {
571       HYDROData_PolylineXY::Point aSectPoint = gp_XY(anObj->padfX[k], anObj->padfY[k]);
572       theDocument->Transform(aSectPoint, true);
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 = gp_XY(anObj->padfX[k], anObj->padfY[k]);
624       theDocument->Transform(aSectPoint, true);
625       aPolylineXY->AddPoint( i, aSectPoint );
626       aAPoints.Append(gp_XYZ (aSectPoint.X(), aSectPoint.Y(), anObj->padfZ[k]));
627     }
628   }
629
630
631   QString aBathName = theFileName + "_bath_" + QString::number(theInd);
632   QString aPolyXYName = theFileName + "_polyXY_" + QString::number(theInd);
633   QString aPoly3DName = theFileName + "_poly3D_" + QString::number(theInd);
634
635   aPolylineXY->SetName( aPolyXYName );
636   aPolylineXY->SetWireColor(HYDROData_PolylineXY::DefaultWireColor());
637   aPolylineXY->Update();
638   
639   aBath->SetAltitudePoints(aAPoints);
640   aBath->SetName( aBathName );
641
642   aPolylineObj->SetPolylineXY (aPolylineXY, false);
643   aPolylineObj->SetAltitudeObject(aBath);
644
645   aPolylineObj->SetBorderColor( aPolylineObj->DefaultBorderColor() );
646   aPolylineObj->SetName( aPoly3DName );
647   
648   aPolylineObj->Update();
649   theEntities.Append(aPolylineXY);
650   theEntities.Append(aPolylineObj);
651
652 }
653
654
655
656 int HYDROData_ShapeFile::ImportPolylines(Handle(HYDROData_Document) theDocument, const QString& theFileName, 
657   NCollection_Sequence<Handle_HYDROData_Entity>& theEntities, int& theShapeTypeOfFile)
658 {
659   //Free();
660   int aStat = TryOpenShapeFile(theFileName);
661   if (aStat != 0)
662     return aStat;
663
664   HYDROData_Iterator anIter( theDocument );
665   int anInd = 0;
666   QStringList anExistingNames;
667   std::vector<int> anAllowedIndexes;
668   for( ; anIter.More(); anIter.Next() )
669     anExistingNames.push_back(anIter.Current()->GetName());
670
671   SHPHandle aHSHP;
672   aHSHP = SHPOpen( theFileName.toAscii().data(), "rb" );
673   
674   QFileInfo aFileInfo(theFileName);
675   QString aBaseFileName = aFileInfo.baseName();
676
677   if (!Parse(aHSHP, HYDROData_ShapeFile::ShapeType_Polyline, theShapeTypeOfFile))
678     return 0;
679   if (aHSHP->nShapeType == 3 || aHSHP->nShapeType == 23)
680   {
681     anInd = 0;
682     for (;anAllowedIndexes.size() < mySHPObjects.size();)
683     {
684       if (!anExistingNames.contains(aBaseFileName + "_PolyXY_" + QString::number(anInd)))
685       {
686         anAllowedIndexes.push_back(anInd);
687         anInd++;
688       }
689       else
690         anInd++;
691     }
692     
693     for (size_t i = 0; i < mySHPObjects.size(); i++ )
694     {
695       ReadSHPPolyXY(theDocument, mySHPObjects[i], aBaseFileName, anAllowedIndexes[i], theEntities);
696     }
697     aStat = 1;
698   }
699   else if (aHSHP->nShapeType == 13)
700   {
701     anInd = 0;
702     for (;anAllowedIndexes.size() < mySHPObjects.size();)
703     {
704       if (!anExistingNames.contains(aBaseFileName + "_PolyXY_" + QString::number(anInd)) &&
705           !anExistingNames.contains(aBaseFileName + "_Poly3D_" + QString::number(anInd)) &&
706           !anExistingNames.contains(aBaseFileName + "_Bath_" + QString::number(anInd)))
707       {
708         anAllowedIndexes.push_back(anInd);
709         anInd++;
710       }
711       else
712         anInd++;
713     }
714     for (size_t i = 0; i < mySHPObjects.size(); i++ )
715       ReadSHPPoly3D(theDocument, mySHPObjects[i], aBaseFileName, anAllowedIndexes[i], theEntities);
716     aStat = 1;
717   }
718   else  
719   {
720     aStat = 0;
721   }
722   
723   for (size_t i = 0; i < mySHPObjects.size(); i++ )
724     free (mySHPObjects[i]);
725
726   mySHPObjects.clear();
727   SHPClose(aHSHP);
728   return aStat;
729 }
730
731 QString HYDROData_ShapeFile::GetShapeTypeName(int theType)
732 {
733   switch (theType)
734   {
735     case 0:
736       return "null shape";
737     case 1:
738       return "point (unsupported by HYDRO)";
739     case 3:
740       return "arc/polyline (supported by HYDRO)";
741     case 5:
742       return "polygon (supported by HYDRO)";
743     case 8:
744       return "multipoint (unsupported by HYDRO)";
745     case 11:
746       return "pointZ (unsupported by HYDRO)";
747     case 13:
748       return "arcZ/polyline (supported by HYDRO)";
749     case 15:
750       return "polygonZ (unsupported by HYDRO)";
751     case 18:
752       return "multipointZ (unsupported by HYDRO)";
753     case 21:
754       return "pointM (unsupported by HYDRO)";
755     case 23:
756       return "arcM/polyline (supported by HYDRO)";
757     case 25:
758       return "polygonM (unsupported by HYDRO)";
759     case 28:
760       return "multipointM (unsupported by HYDRO)";
761     case 31:
762       return "multipatch (unsupported by HYDRO)";
763     default:
764       return "unknown";
765   }
766 }
767
768 int HYDROData_ShapeFile::TryOpenShapeFile(QString theFileName)
769 {
770   QString aSHPfile = theFileName.simplified();
771   QString aSHXfile = theFileName.simplified().replace( theFileName.simplified().size() - 4, 4, ".shx");
772
773   QString anExt = theFileName.split('.', QString::SkipEmptyParts).back();
774   if (anExt.toLower() != "shp")
775     return -3;
776
777   FILE* pFileSHP = NULL;
778   pFileSHP = fopen (aSHPfile.toAscii().data(), "r");
779   FILE* pFileSHX = NULL;
780   pFileSHX = fopen (aSHXfile.toAscii().data(), "r");
781
782   if (pFileSHP == NULL || pFileSHX == NULL)
783   {
784     if (pFileSHP == NULL)
785       return -1;
786     if (pFileSHX == NULL)
787       return -2;
788   }
789   
790   fclose (pFileSHP);
791   fclose (pFileSHX);
792   return 0;
793 }
794
795
796 bool HYDROData_ShapeFile::CheckDBFFileExisting(const QString& theSHPFilePath, QString& thePathToDBFFile)
797 {
798   QString aSHPfile = theSHPFilePath.simplified();
799   QString aDBFfile = theSHPFilePath.simplified().replace( theSHPFilePath.simplified().size() - 4, 4, ".dbf");
800   FILE* pFileDBF = NULL;
801   pFileDBF = fopen (aDBFfile.toAscii().data(), "r");
802
803   if (pFileDBF == NULL)
804   {
805     return false;
806   }
807   
808   fclose (pFileDBF);
809   thePathToDBFFile = aDBFfile;
810   return true;
811 }
812
813
814 bool HYDROData_ShapeFile::DBF_OpenDBF(const QString& thePathToDBFFile)
815 {
816   myHDBF = DBFOpen( thePathToDBFFile.toAscii().data(), "r" );
817   if(myHDBF != NULL)
818     return true;
819   else
820     return false;
821 }
822
823 int HYDROData_ShapeFile::DBF_GetNbFields()
824 {
825   if(myHDBF == NULL)
826     return 0;
827   return DBFGetFieldCount(myHDBF);
828 }
829
830 void HYDROData_ShapeFile::DBF_CloseDBF()
831 {
832   if(myHDBF != NULL)
833      DBFClose( myHDBF );
834 }
835
836 QStringList HYDROData_ShapeFile::DBF_GetFieldList()
837 {
838   QStringList FieldList;
839   int   nWidth, nDecimals;
840   char chField[12];
841
842   for( int i = 0; i < DBFGetFieldCount(myHDBF); i++ )
843   {
844       DBFFieldType eType;
845       eType = DBFGetFieldInfo( myHDBF, i, chField, &nWidth, &nDecimals );
846       FieldList.append(QString(chField));
847   }
848
849   return FieldList;
850 }
851
852 void HYDROData_ShapeFile::DBF_GetFieldTypeList(std::vector<DBF_FieldType>& FTVect)
853 {
854   int   nWidth, nDecimals;
855   char chField[12];
856   DBF_FieldType FT;
857   for( int i = 0; i < DBFGetFieldCount(myHDBF); i++ )
858   {
859     DBFFieldType eType;
860     eType = DBFGetFieldInfo( myHDBF, i, chField, &nWidth, &nDecimals );
861     if( eType == FTString )
862       FT = DBF_FieldType_String;
863     else if( eType == FTInteger )
864       FT = DBF_FieldType_Integer;
865     else if( eType == FTDouble )
866       FT = DBF_FieldType_Double;
867     else if( eType == FTInvalid )
868       FT = DBF_FieldType_Invalid;
869
870     FTVect.push_back(FT);
871   }
872
873 }
874
875 int HYDROData_ShapeFile::DBF_GetNbRecords()
876 {
877   if(myHDBF == NULL)
878     return 0;
879   return DBFGetRecordCount(myHDBF);
880 }
881
882 void HYDROData_ShapeFile::DBF_GetAttributeList(int theIndexOfField, std::vector<DBF_AttrValue>& theAttrV)
883 {
884   int nWidth, nDecimals;
885   char chField[12];
886   
887   for( int i = 0; i < DBFGetRecordCount(myHDBF); i++ )
888   {      
889     DBFFieldType eType;
890     DBF_AttrValue anAttr;
891     eType = DBFGetFieldInfo( myHDBF, theIndexOfField, chField, &nWidth, &nDecimals );
892
893     if( DBFIsAttributeNULL( myHDBF, i, theIndexOfField ) )
894     {
895       anAttr.myIsNull = true;
896       DBF_FieldType FT = DBF_FieldType_None;
897       if( eType == FTString )
898         FT = DBF_FieldType_String;
899       else if( eType == FTInteger )
900         FT = DBF_FieldType_Integer;
901       else if( eType == FTDouble )
902         FT = DBF_FieldType_Double;
903       else if( eType == FTInvalid )
904         FT = DBF_FieldType_Invalid;
905       anAttr.myFieldType = FT;
906     }
907     else
908     {
909       switch( eType )
910       {
911         case FTString:
912         {
913           const char* chAttr = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
914           anAttr.myIsNull = false;
915           anAttr.myFieldType = DBF_FieldType_String;
916           anAttr.myRawValue = chAttr;
917           anAttr.myStrVal = QString(chAttr);
918           break;
919         }
920        
921         case FTInteger:
922         {
923           int iAttr = DBFReadIntegerAttribute( myHDBF, i, theIndexOfField );
924           anAttr.myIsNull = false;
925           anAttr.myFieldType = DBF_FieldType_Integer;
926           anAttr.myRawValue = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
927           anAttr.myIntVal = iAttr;
928           break;
929         }
930           
931         case FTDouble:
932         {
933           double dAttr = DBFReadDoubleAttribute( myHDBF, i, theIndexOfField );
934           anAttr.myIsNull = false;
935           anAttr.myFieldType = DBF_FieldType_Double;
936           anAttr.myRawValue = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
937           anAttr.myDoubleVal = dAttr;
938           break;
939         }
940         default:
941           break;
942       }
943     }
944     theAttrV.push_back(anAttr);
945   }
946
947 }
948
949 bool HYDROData_ShapeFile::DBF_WriteFieldAndValues(const QString& theFileName, const QString& theFieldName, DBF_FieldType theType, const std::vector<DBF_AttrValue>& theAttrV, bool bUseRawValue)
950 {
951   // Check that given field type is equal to field types of attributes values
952   for (size_t i = 0; i < theAttrV.size(); i++)
953   {
954     if (theAttrV[i].myFieldType != theType)
955       return false;
956   }
957
958   DBFHandle     hDBF;
959   hDBF = DBFCreate( theFileName.toStdString().c_str() );
960   if( hDBF == NULL )
961           return false;
962   
963   if (theType != DBF_FieldType_String && theType != DBF_FieldType_Integer && theType != DBF_FieldType_Double) 
964   {
965     DBFClose( hDBF );
966     return false; //cant handle any other cases
967   }
968
969   int nWidth = 20;
970   switch( theType )
971   {
972     case DBF_FieldType_String:
973     {
974       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTString, nWidth, 0);
975       break;
976     }
977    
978     case DBF_FieldType_Integer:
979     {
980       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTInteger, nWidth, 0);
981       break;
982     }
983       
984     case DBF_FieldType_Double:
985     {
986       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTDouble, nWidth, 0);
987       break;
988     }
989     default:
990       break;
991   }
992
993   if (DBFGetFieldCount( hDBF ) != 1) 
994   {
995     DBFClose( hDBF );
996     return false;
997   }
998   if (DBFGetRecordCount( hDBF ) != 0)
999   {
1000     DBFClose( hDBF );
1001     return false;
1002   }
1003   int stat = -1;
1004
1005   if (bUseRawValue)
1006   {
1007     for (size_t i = 0; i < theAttrV.size(); i++)
1008     {
1009       if (!theAttrV[i].myIsNull)
1010         stat = DBFWriteStringAttribute(hDBF, (int)i, 0, theAttrV[i].myRawValue.c_str());
1011       else
1012         stat = DBFWriteNULLAttribute(hDBF, (int)i, 0 );
1013
1014       if (stat != 1)
1015       {
1016         DBFClose( hDBF );
1017         return false;
1018       }
1019     }
1020   }
1021   else
1022   {
1023     for (size_t i = 0; i < theAttrV.size(); i++)
1024     {
1025       if (!theAttrV[i].myIsNull)
1026         switch( theType )
1027         {
1028           case DBF_FieldType_String:
1029           {
1030             stat = DBFWriteStringAttribute(hDBF, (int)i, 0, theAttrV[i].myStrVal.toStdString().c_str());
1031             break;
1032           }
1033          
1034           case DBF_FieldType_Integer:
1035           {
1036             stat = DBFWriteIntegerAttribute(hDBF, (int)i, 0, theAttrV[i].myIntVal);
1037             break;
1038           }
1039             
1040           case DBF_FieldType_Double:
1041           {
1042             stat = DBFWriteDoubleAttribute(hDBF, (int)i, 0, theAttrV[i].myDoubleVal);
1043             break;
1044           }
1045           default:
1046             break;
1047         }
1048       else
1049         stat = DBFWriteNULLAttribute(hDBF, (int)i, 0 );
1050
1051       if (stat != 1)
1052       {
1053         DBFClose( hDBF );
1054         return false;
1055       }
1056     }
1057   }
1058
1059   DBFClose( hDBF );
1060   return true;
1061
1062 }
1063