Salome HOME
bug EDF #12861: import Shapefile after Local Coordinates System change
[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 = gp_XY(anObj->padfX[k], anObj->padfY[k]);
571       theDocument->Transform(aSectPoint, true);
572       aPolylineXY->AddPoint( i, aSectPoint );
573     }
574
575   }
576   
577   aPolylineXY->SetWireColor( HYDROData_PolylineXY::DefaultWireColor() );
578   aPolylineXY->SetName( theFileName + "_PolyXY_" + QString::number(theInd) );
579   
580   aPolylineXY->Update();
581   theEntities.Append(aPolylineXY);
582
583 }
584
585 void HYDROData_ShapeFile::ReadSHPPoly3D(Handle(HYDROData_Document) theDocument, SHPObject* anObj, QString theFileName, 
586   int theInd, NCollection_Sequence<Handle_HYDROData_Entity>& theEntities)
587 {
588   Handle(HYDROData_PolylineXY) aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
589
590   Handle(HYDROData_Polyline3D) aPolylineObj = Handle(HYDROData_Polyline3D)::DownCast( theDocument->CreateObject( KIND_POLYLINE ) );
591
592   Handle(HYDROData_Bathymetry) aBath = Handle(HYDROData_Bathymetry)::DownCast( theDocument->CreateObject( KIND_BATHYMETRY ) );
593   HYDROData_Bathymetry::AltitudePoints aAPoints;
594
595   int nParts = anObj->nParts;
596   for ( int i = 0 ; i < nParts ; i++ )
597   {
598     //bool aSectClosure = true;
599     int StartIndex = anObj->panPartStart[i];
600     int EndIndex;
601     if (i != nParts - 1)
602       EndIndex = anObj->panPartStart[i + 1];
603     else
604       EndIndex = anObj->nVertices;
605
606     bool IsClosed = false;
607     HYDROData_PolylineXY::SectionType aSectType = HYDROData_PolylineXY::SECTION_POLYLINE; 
608     if (anObj->padfX[StartIndex] == anObj->padfX[EndIndex - 1] &&
609         anObj->padfY[StartIndex] == anObj->padfY[EndIndex - 1] &&
610         anObj->padfZ[StartIndex] == anObj->padfZ[EndIndex - 1])
611     {
612       IsClosed = true;
613       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, true );
614     }
615     else
616       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, false  );
617     
618     if (IsClosed)
619       EndIndex--;
620     for ( int k = StartIndex ; k < EndIndex ; k++ )
621     {
622       HYDROData_PolylineXY::Point aSectPoint = gp_XY(anObj->padfX[k], anObj->padfY[k]);
623       theDocument->Transform(aSectPoint, true);
624       aPolylineXY->AddPoint( i, aSectPoint );
625       aAPoints.Append(gp_XYZ (aSectPoint.X(), aSectPoint.Y(), anObj->padfZ[k]));
626     }
627   }
628
629
630   QString aBathName = theFileName + "_bath_" + QString::number(theInd);
631   QString aPolyXYName = theFileName + "_polyXY_" + QString::number(theInd);
632   QString aPoly3DName = theFileName + "_poly3D_" + QString::number(theInd);
633
634   aPolylineXY->SetName( aPolyXYName );
635   aPolylineXY->SetWireColor(HYDROData_PolylineXY::DefaultWireColor());
636   aPolylineXY->Update();
637   
638   aBath->SetAltitudePoints(aAPoints);
639   aBath->SetName( aBathName );
640
641   aPolylineObj->SetPolylineXY (aPolylineXY, false);
642   aPolylineObj->SetAltitudeObject(aBath);
643
644   aPolylineObj->SetBorderColor( aPolylineObj->DefaultBorderColor() );
645   aPolylineObj->SetName( aPoly3DName );
646   
647   aPolylineObj->Update();
648   theEntities.Append(aPolylineXY);
649   theEntities.Append(aPolylineObj);
650
651 }
652
653
654
655 int HYDROData_ShapeFile::ImportPolylines(Handle(HYDROData_Document) theDocument, const QString& theFileName, 
656   NCollection_Sequence<Handle_HYDROData_Entity>& theEntities, int& theShapeTypeOfFile)
657 {
658   //Free();
659   int aStat = TryOpenShapeFile(theFileName);
660   if (aStat != 0)
661     return aStat;
662
663   HYDROData_Iterator anIter( theDocument );
664   int anInd = 0;
665   QStringList anExistingNames;
666   std::vector<int> anAllowedIndexes;
667   for( ; anIter.More(); anIter.Next() )
668     anExistingNames.push_back(anIter.Current()->GetName());
669
670   SHPHandle aHSHP;
671   aHSHP = SHPOpen( theFileName.toAscii().data(), "rb" );
672   
673   QFileInfo aFileInfo(theFileName);
674   QString aBaseFileName = aFileInfo.baseName();
675
676   if (!Parse(aHSHP, HYDROData_ShapeFile::ShapeType_Polyline, theShapeTypeOfFile))
677     return 0;
678   if (aHSHP->nShapeType == 3 || aHSHP->nShapeType == 23)
679   {
680     anInd = 0;
681     for (;anAllowedIndexes.size() < mySHPObjects.size();)
682     {
683       if (!anExistingNames.contains(aBaseFileName + "_PolyXY_" + QString::number(anInd)))
684       {
685         anAllowedIndexes.push_back(anInd);
686         anInd++;
687       }
688       else
689         anInd++;
690     }
691     
692     for (size_t i = 0; i < mySHPObjects.size(); i++ )
693     {
694       ReadSHPPolyXY(theDocument, mySHPObjects[i], aBaseFileName, anAllowedIndexes[i], theEntities);
695     }
696     aStat = 1;
697   }
698   else if (aHSHP->nShapeType == 13)
699   {
700     anInd = 0;
701     for (;anAllowedIndexes.size() < mySHPObjects.size();)
702     {
703       if (!anExistingNames.contains(aBaseFileName + "_PolyXY_" + QString::number(anInd)) &&
704           !anExistingNames.contains(aBaseFileName + "_Poly3D_" + QString::number(anInd)) &&
705           !anExistingNames.contains(aBaseFileName + "_Bath_" + QString::number(anInd)))
706       {
707         anAllowedIndexes.push_back(anInd);
708         anInd++;
709       }
710       else
711         anInd++;
712     }
713     for (size_t i = 0; i < mySHPObjects.size(); i++ )
714       ReadSHPPoly3D(theDocument, mySHPObjects[i], aBaseFileName, anAllowedIndexes[i], theEntities);
715     aStat = 1;
716   }
717   else  
718   {
719     aStat = 0;
720   }
721   
722   for (size_t i = 0; i < mySHPObjects.size(); i++ )
723     free (mySHPObjects[i]);
724
725   mySHPObjects.clear();
726   SHPClose(aHSHP);
727   return aStat;
728 }
729
730 QString HYDROData_ShapeFile::GetShapeTypeName(int theType)
731 {
732   switch (theType)
733   {
734     case 0:
735       return "null shape";
736     case 1:
737       return "point (unsupported by HYDRO)";
738     case 3:
739       return "arc/polyline (supported by HYDRO)";
740     case 5:
741       return "polygon (supported by HYDRO)";
742     case 8:
743       return "multipoint (unsupported by HYDRO)";
744     case 11:
745       return "pointZ (unsupported by HYDRO)";
746     case 13:
747       return "arcZ/polyline (supported by HYDRO)";
748     case 15:
749       return "polygonZ (unsupported by HYDRO)";
750     case 18:
751       return "multipointZ (unsupported by HYDRO)";
752     case 21:
753       return "pointM (unsupported by HYDRO)";
754     case 23:
755       return "arcM/polyline (supported by HYDRO)";
756     case 25:
757       return "polygonM (unsupported by HYDRO)";
758     case 28:
759       return "multipointM (unsupported by HYDRO)";
760     case 31:
761       return "multipatch (unsupported by HYDRO)";
762     default:
763       return "unknown";
764   }
765 }
766
767 int HYDROData_ShapeFile::TryOpenShapeFile(QString theFileName)
768 {
769   QString aSHPfile = theFileName.simplified();
770   QString aSHXfile = theFileName.simplified().replace( theFileName.simplified().size() - 4, 4, ".shx");
771
772   QString anExt = theFileName.split('.', QString::SkipEmptyParts).back();
773   if (anExt.toLower() != "shp")
774     return -3;
775
776   FILE* pFileSHP = NULL;
777   pFileSHP = fopen (aSHPfile.toAscii().data(), "r");
778   FILE* pFileSHX = NULL;
779   pFileSHX = fopen (aSHXfile.toAscii().data(), "r");
780
781   if (pFileSHP == NULL || pFileSHX == NULL)
782   {
783     if (pFileSHP == NULL)
784       return -1;
785     if (pFileSHX == NULL)
786       return -2;
787   }
788   
789   fclose (pFileSHP);
790   fclose (pFileSHX);
791   return 0;
792 }
793
794
795 bool HYDROData_ShapeFile::CheckDBFFileExisting(const QString& theSHPFilePath, QString& thePathToDBFFile)
796 {
797   QString aSHPfile = theSHPFilePath.simplified();
798   QString aDBFfile = theSHPFilePath.simplified().replace( theSHPFilePath.simplified().size() - 4, 4, ".dbf");
799   FILE* pFileDBF = NULL;
800   pFileDBF = fopen (aDBFfile.toAscii().data(), "r");
801
802   if (pFileDBF == NULL)
803   {
804     return false;
805   }
806   
807   fclose (pFileDBF);
808   thePathToDBFFile = aDBFfile;
809   return true;
810 }
811
812
813 bool HYDROData_ShapeFile::DBF_OpenDBF(const QString& thePathToDBFFile)
814 {
815   myHDBF = DBFOpen( thePathToDBFFile.toAscii().data(), "r" );
816   if(myHDBF != NULL)
817     return true;
818   else
819     return false;
820 }
821
822 int HYDROData_ShapeFile::DBF_GetNbFields()
823 {
824   if(myHDBF == NULL)
825     return 0;
826   return DBFGetFieldCount(myHDBF);
827 }
828
829 void HYDROData_ShapeFile::DBF_CloseDBF()
830 {
831   if(myHDBF != NULL)
832      DBFClose( myHDBF );
833 }
834
835 QStringList HYDROData_ShapeFile::DBF_GetFieldList()
836 {
837   QStringList FieldList;
838   int   nWidth, nDecimals;
839   char chField[12];
840
841   for( int i = 0; i < DBFGetFieldCount(myHDBF); i++ )
842   {
843       DBFFieldType eType;
844       eType = DBFGetFieldInfo( myHDBF, i, chField, &nWidth, &nDecimals );
845       FieldList.append(QString(chField));
846   }
847
848   return FieldList;
849 }
850
851 void HYDROData_ShapeFile::DBF_GetFieldTypeList(std::vector<DBF_FieldType>& FTVect)
852 {
853   int   nWidth, nDecimals;
854   char chField[12];
855   DBF_FieldType FT;
856   for( int i = 0; i < DBFGetFieldCount(myHDBF); i++ )
857   {
858     DBFFieldType eType;
859     eType = DBFGetFieldInfo( myHDBF, i, chField, &nWidth, &nDecimals );
860     if( eType == FTString )
861       FT = DBF_FieldType_String;
862     else if( eType == FTInteger )
863       FT = DBF_FieldType_Integer;
864     else if( eType == FTDouble )
865       FT = DBF_FieldType_Double;
866     else if( eType == FTInvalid )
867       FT = DBF_FieldType_Invalid;
868
869     FTVect.push_back(FT);
870   }
871
872 }
873
874 int HYDROData_ShapeFile::DBF_GetNbRecords()
875 {
876   if(myHDBF == NULL)
877     return 0;
878   return DBFGetRecordCount(myHDBF);
879 }
880
881 void HYDROData_ShapeFile::DBF_GetAttributeList(int theIndexOfField, std::vector<DBF_AttrValue>& theAttrV)
882 {
883   int nWidth, nDecimals;
884   char chField[12];
885   
886   for( int i = 0; i < DBFGetRecordCount(myHDBF); i++ )
887   {      
888     DBFFieldType eType;
889     DBF_AttrValue anAttr;
890     eType = DBFGetFieldInfo( myHDBF, theIndexOfField, chField, &nWidth, &nDecimals );
891
892     if( DBFIsAttributeNULL( myHDBF, i, theIndexOfField ) )
893     {
894       anAttr.myIsNull = true;
895       DBF_FieldType FT = DBF_FieldType_None;
896       if( eType == FTString )
897         FT = DBF_FieldType_String;
898       else if( eType == FTInteger )
899         FT = DBF_FieldType_Integer;
900       else if( eType == FTDouble )
901         FT = DBF_FieldType_Double;
902       else if( eType == FTInvalid )
903         FT = DBF_FieldType_Invalid;
904       anAttr.myFieldType = FT;
905     }
906     else
907     {
908       switch( eType )
909       {
910         case FTString:
911         {
912           const char* chAttr = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
913           anAttr.myIsNull = false;
914           anAttr.myFieldType = DBF_FieldType_String;
915           anAttr.myRawValue = chAttr;
916           anAttr.myStrVal = QString(chAttr);
917           break;
918         }
919        
920         case FTInteger:
921         {
922           int iAttr = DBFReadIntegerAttribute( myHDBF, i, theIndexOfField );
923           anAttr.myIsNull = false;
924           anAttr.myFieldType = DBF_FieldType_Integer;
925           anAttr.myRawValue = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
926           anAttr.myIntVal = iAttr;
927           break;
928         }
929           
930         case FTDouble:
931         {
932           double dAttr = DBFReadDoubleAttribute( myHDBF, i, theIndexOfField );
933           anAttr.myIsNull = false;
934           anAttr.myFieldType = DBF_FieldType_Double;
935           anAttr.myRawValue = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
936           anAttr.myDoubleVal = dAttr;
937           break;
938         }
939         default:
940           break;
941       }
942     }
943     theAttrV.push_back(anAttr);
944   }
945
946 }
947
948 bool HYDROData_ShapeFile::DBF_WriteFieldAndValues(const QString& theFileName, const QString& theFieldName, DBF_FieldType theType, const std::vector<DBF_AttrValue>& theAttrV, bool bUseRawValue)
949 {
950   // Check that given field type is equal to field types of attributes values
951   for (size_t i = 0; i < theAttrV.size(); i++)
952   {
953     if (theAttrV[i].myFieldType != theType)
954       return false;
955   }
956
957   DBFHandle     hDBF;
958   hDBF = DBFCreate( theFileName.toStdString().c_str() );
959   if( hDBF == NULL )
960           return false;
961   
962   if (theType != DBF_FieldType_String && theType != DBF_FieldType_Integer && theType != DBF_FieldType_Double) 
963   {
964     DBFClose( hDBF );
965     return false; //cant handle any other cases
966   }
967
968   int nWidth = 20;
969   switch( theType )
970   {
971     case DBF_FieldType_String:
972     {
973       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTString, nWidth, 0);
974       break;
975     }
976    
977     case DBF_FieldType_Integer:
978     {
979       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTInteger, nWidth, 0);
980       break;
981     }
982       
983     case DBF_FieldType_Double:
984     {
985       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTDouble, nWidth, 0);
986       break;
987     }
988     default:
989       break;
990   }
991
992   if (DBFGetFieldCount( hDBF ) != 1) 
993   {
994     DBFClose( hDBF );
995     return false;
996   }
997   if (DBFGetRecordCount( hDBF ) != 0)
998   {
999     DBFClose( hDBF );
1000     return false;
1001   }
1002   int stat = -1;
1003
1004   if (bUseRawValue)
1005   {
1006     for (size_t i = 0; i < theAttrV.size(); i++)
1007     {
1008       if (!theAttrV[i].myIsNull)
1009         stat = DBFWriteStringAttribute(hDBF, (int)i, 0, theAttrV[i].myRawValue.c_str());
1010       else
1011         stat = DBFWriteNULLAttribute(hDBF, (int)i, 0 );
1012
1013       if (stat != 1)
1014       {
1015         DBFClose( hDBF );
1016         return false;
1017       }
1018     }
1019   }
1020   else
1021   {
1022     for (size_t i = 0; i < theAttrV.size(); i++)
1023     {
1024       if (!theAttrV[i].myIsNull)
1025         switch( theType )
1026         {
1027           case DBF_FieldType_String:
1028           {
1029             stat = DBFWriteStringAttribute(hDBF, (int)i, 0, theAttrV[i].myStrVal.toStdString().c_str());
1030             break;
1031           }
1032          
1033           case DBF_FieldType_Integer:
1034           {
1035             stat = DBFWriteIntegerAttribute(hDBF, (int)i, 0, theAttrV[i].myIntVal);
1036             break;
1037           }
1038             
1039           case DBF_FieldType_Double:
1040           {
1041             stat = DBFWriteDoubleAttribute(hDBF, (int)i, 0, theAttrV[i].myDoubleVal);
1042             break;
1043           }
1044           default:
1045             break;
1046         }
1047       else
1048         stat = DBFWriteNULLAttribute(hDBF, (int)i, 0 );
1049
1050       if (stat != 1)
1051       {
1052         DBFClose( hDBF );
1053         return false;
1054       }
1055     }
1056   }
1057
1058   DBFClose( hDBF );
1059   return true;
1060
1061 }
1062