Salome HOME
Merge branch 'BR_LAND_COVER_MAP' of ssh://git.salome-platform.org/modules/hydro into...
[modules/hydro.git] / src / HYDROData / HYDROData_ShapeFile.cxx
index b8b3effd5bf74d6a2af4ed318e95c6400d448e3b..93a75c2a4c212add5c924eefde6668f961afcd02 100644 (file)
@@ -33,6 +33,7 @@
 #include <TopoDS_Edge.hxx>
 #include <TopoDS_Face.hxx>
 #include <BRep_Tool.hxx>
+#include <BRepTools.hxx>
 #include <Precision.hxx>
 #include <Handle_Geom_Curve.hxx>
 #include <Handle_Geom_Line.hxx>
 #include <TopTools_SequenceOfShape.hxx>
 #include <QColor>
 #include <BRepTopAdaptor_FClass2d.hxx>
+#include <TopExp.hxx>
+#include <OSD_Timer.hxx>
+#include <BRepLib_MakeVertex.hxx>
+#include <NCollection_List.hxx>
+#include <GC_MakeSegment.hxx>
+#include <BRep_Builder.hxx>
+#include <BRepAdaptor_Curve.hxx>
+#include <GCPnts_QuasiUniformDeflection.hxx>
+#include <TopLoc_Location.hxx>
+#include <Geom_Plane.hxx>
+#include <NCollection_Array1.hxx>
+#include <BRepBndLib.hxx>
+#include <Bnd_Box.hxx>
 
 #ifdef WIN32
   #pragma warning( disable: 4996 )
 #endif
 
+//SHP->TFaces (Import) 
+#define OSD_TIMER
+
 HYDROData_ShapeFile::HYDROData_ShapeFile() : myHSHP(NULL)
 { 
 }
@@ -88,33 +105,36 @@ void HYDROData_ShapeFile::Export(const QString& aFileName,
     SHPClose( hSHPHandle );
     QString aFN = aFileName.simplified();
     remove (aFN.toStdString().c_str());
-    remove (aFN.replace( ".shp", ".shx", Qt::CaseInsensitive).toStdString().c_str());
+    remove ((aFN.simplified().replace( aFN.simplified().size() - 4, 4, ".shx")).toStdString().c_str());
   }
 }
 
-void HYDROData_ShapeFile::Export(const QString& aFileName,
-  const Handle_HYDROData_LandCoverMap& aLCM, QStringList& aNonExpList)
+void HYDROData_ShapeFile::Export(const QString& aFileName, const Handle_HYDROData_LandCoverMap& aLCM, 
+                                 QStringList& aNonExpList, bool bCheckLinear, bool bUseDiscr, double theDefl)
 {
-  SHPHandle hSHPHandle;
+  if (bCheckLinear && !aLCM->CheckLinear())
+    return;
+  //
+  SHPHandle hSHPHandle = NULL;
   if ( !aLCM.IsNull() && !aLCM->IsEmpty())
   {
     hSHPHandle = SHPCreate( aFileName.toAscii().data(), SHPT_POLYGON );
-    HYDROData_LandCoverMap::Iterator It( aLCM );
-    for( ; It.More(); It.Next() )
+    HYDROData_LandCoverMap::Explorer It( aLCM );
+    for( ; It.More(); It.Next())
     {
       TopoDS_Face aFace = It.Face();
-      if (WriteObjectPolygon(hSHPHandle, aFace) != 1)
+      if (WriteObjectPolygon(hSHPHandle, aFace, bUseDiscr, theDefl) != 1)
         aNonExpList.append(aLCM->GetName() + "_" +  QString::number(It.Index()));
     }
   }
-  if (hSHPHandle->nRecords > 0)
+  if (hSHPHandle && hSHPHandle->nRecords > 0)
     SHPClose( hSHPHandle );
   else
   {
     SHPClose( hSHPHandle );
     QString aFN = aFileName.simplified();
     remove (aFN.toStdString().c_str());
-    remove (aFN.replace( ".shp", ".shx", Qt::CaseInsensitive).toStdString().c_str());
+    remove ((aFN.simplified().replace( aFN.simplified().size() - 4, 4, ".shx")).toStdString().c_str());
   }
 }
 
@@ -186,34 +206,15 @@ int HYDROData_ShapeFile::WriteObjectPoly3D(SHPHandle theShpHandle, Handle_HYDROD
   return 1;
 }
 
-int HYDROData_ShapeFile::WriteObjectPolygon(SHPHandle theShpHandle, const TopoDS_Shape& theInputShape )
+int HYDROData_ShapeFile::WriteObjectPolygon(SHPHandle theShpHandle, const TopoDS_Shape& theInputShape,
+                                            bool bUseDiscr, double theDefl)
 {
   if (theInputShape.IsNull())
     return 0;
-  TopExp_Explorer anEdgeEx(theInputShape, TopAbs_EDGE);
-  for (; anEdgeEx.More(); anEdgeEx.Next()) 
-  {
-    TopoDS_Edge E = TopoDS::Edge(anEdgeEx.Current());
-    double aFP, aLP;
-    Handle_Geom_Curve aCur = BRep_Tool::Curve(E, aFP, aLP);
-    Handle(Geom_Line) aLine = Handle(Geom_Line)::DownCast(aCur);
-    if (aLine.IsNull())
-    {
-      Handle(Geom_TrimmedCurve) aTC = Handle(Geom_TrimmedCurve)::DownCast(aCur);
-      if (!aTC.IsNull())
-      {
-        Handle(Geom_Line) aLine = Handle(Geom_Line)::DownCast(aTC->BasisCurve());
-        if (aLine.IsNull())
-          return -1;
-      }
-      else
-        return -1;
-    }
 
-  }
   if (theInputShape.ShapeType() == TopAbs_FACE)
   {
-    ProcessFace(TopoDS::Face(theInputShape), theShpHandle);
+    ProcessFace(TopoDS::Face(theInputShape), theShpHandle, bUseDiscr, theDefl);
   }
   else if (theInputShape.ShapeType() == TopAbs_COMPOUND)
   {
@@ -223,7 +224,7 @@ int HYDROData_ShapeFile::WriteObjectPolygon(SHPHandle theShpHandle, const TopoDS
       TopoDS_Face aF = TopoDS::Face(Ex.Current());   
       if (aF.IsNull())
         continue;
-      ProcessFace(aF, theShpHandle);
+      ProcessFace(aF, theShpHandle, bUseDiscr, theDefl);
     }
   }
   else
@@ -233,55 +234,119 @@ int HYDROData_ShapeFile::WriteObjectPolygon(SHPHandle theShpHandle, const TopoDS
  
 }
 
-void HYDROData_ShapeFile::ProcessFace(TopoDS_Face theFace, SHPHandle theShpHandle)
+void HYDROData_ShapeFile::ProcessFace(const TopoDS_Face& theFace, SHPHandle theShpHandle,
+                                      bool bUseDiscr, double theDefl )
 {
+  if (theFace.ShapeType() != TopAbs_FACE)
+     return;
   SHPObject    *aSHPObj;
   std::vector<double> x, y;
   std::vector<int> anPartStart;
-  if (theFace.ShapeType() == TopAbs_FACE)
+  TopoDS_Wire OuterW = BRepTools::OuterWire(theFace);
+  NCollection_Sequence<TopoDS_Wire> aWires;
+
+  //write an outer wire first
+  aWires.Append(OuterW); 
+  TopExp_Explorer Ex(theFace, TopAbs_WIRE);  
+  for (; Ex.More(); Ex.Next()) 
   {
-    TopExp_Explorer Ex(theFace, TopAbs_WIRE);
-    int NbWires = 0;
-    for (; Ex.More(); Ex.Next()) 
+    TopoDS_Wire aW = TopoDS::Wire(Ex.Current());
+    if (aW.IsEqual(OuterW))
+      continue;
+    aWires.Append(aW); 
+  }
+
+  int NbWires = 0;
+  for (int k = 1; k <= aWires.Length(); k++) 
+  {
+    TopoDS_Wire aW = aWires(k);   
+    if (aW.IsNull())
+      continue;
+    NbWires++;
+    if (aW.Orientation() == TopAbs_INTERNAL)
+      //cant write internal wires/edges
+      continue; 
+    // Try to reorder edges
+    Handle(ShapeFix_Wire) aSFW = new ShapeFix_Wire( aW, theFace, Precision::Confusion() );
+    aSFW->ModifyTopologyMode() = Standard_False;
+    aSFW->ModifyGeometryMode() = Standard_False;
+    aSFW->FixReorder();
+    Handle(ShapeExtend_WireData) aSEWD = aSFW->WireData();
+    Standard_Integer nbE = aSEWD->NbEdges();
+    if (nbE == 0)
+      continue;
+    //
+    anPartStart.push_back(x.size());
+    NCollection_Sequence<gp_Pnt2d> aPnts;
+    for (Standard_Integer i = 1; i <= nbE; i++)
     {
-      TopoDS_Wire aW = TopoDS::Wire(Ex.Current());   
-      if (aW.IsNull())
-        continue;
-      NbWires++;
-      anPartStart.push_back(x.size());
-      TopExp_Explorer aVEx(aW, TopAbs_VERTEX);
-      NCollection_Sequence<gp_Pnt2d> aPnts;
-      for (; aVEx.More(); aVEx.Next())
+      TopoDS_Edge E = aSEWD->Edge(i);
+      if (!bUseDiscr)
       {
-        TopoDS_Vertex aV = TopoDS::Vertex(aVEx.Current()); 
+        TopoDS_Vertex aV = TopExp::LastVertex(E, 1);
         if (aV.IsNull())
           continue;
         gp_Pnt P = BRep_Tool::Pnt(aV);
         aPnts.Append(gp_Pnt2d(P.X(), P.Y()));
       }
-      NCollection_Sequence<gp_Pnt2d> aNPnts;
-      aNPnts.Append(aPnts.First());
-      for (int j = 1; j <= aPnts.Size() - 1; j++)
+      else
       {
-        if (!aPnts(j).IsEqual(aPnts(j + 1), Precision::Confusion())) 
-          aNPnts.Append(aPnts(j + 1));
+        BRepAdaptor_Curve Cur( E );
+        GCPnts_QuasiUniformDeflection Discr( Cur, theDefl );
+        if( !Discr.IsDone() )
+          continue; //skip edge?
+        double NewDefl = theDefl/2.0;
+        while (Discr.NbPoints() < 2)
+        {
+          Discr.Initialize(Cur, NewDefl);
+          NewDefl = NewDefl/2.0;
+        }
+        //
+        if (E.Orientation() == TopAbs_FORWARD)
+        {
+          for( int i = 1; i <= Discr.NbPoints(); i++ )
+          {
+            gp_Pnt P = Discr.Value( i );
+            aPnts.Append(gp_Pnt2d(P.X(), P.Y()));
+          }
+        }
+        else
+        {
+          for( int i = Discr.NbPoints(); i > 0; i-- )
+          {
+            gp_Pnt P = Discr.Value( i );
+            aPnts.Append(gp_Pnt2d(P.X(), P.Y()));
+          }
+        }
       }
+    }
+    NCollection_Sequence<gp_Pnt2d> aNPnts;
+    aNPnts.Append(aPnts.First());
+    for (int j = 1; j <= aPnts.Size() - 1; j++)
+    {
+      if (!aPnts(j).IsEqual(aPnts(j + 1), Precision::Confusion())) 
+        aNPnts.Append(aPnts(j + 1));
+    }
 
-      for (int j = 1; j <= aNPnts.Size(); j++)
-      { 
-        x.push_back( aNPnts(j).X());
-        y.push_back( aNPnts(j).Y()); 
-      }
-      //x.push_back( aNPnts(1).X());
-      //y.push_back( aNPnts(1).Y()); 
+    //assume that the orientation of external wire & internal wires is correct
+    //so just write all points "as-is"
+    //External wire will be written in clockwise direction
+    //any other wires (holes) - in anticlockwise direction
+    for (int j = aNPnts.Size(); j >= 1; j--)
+    { 
+      x.push_back( aNPnts(j).X());
+      y.push_back( aNPnts(j).Y()); 
     }
-    
-    aSHPObj = SHPCreateObject( SHPT_POLYGON, -1, NbWires, &anPartStart[0], NULL, x.size(), &x[0], &y[0], NULL, NULL );
-    SHPWriteObject( theShpHandle, -1, aSHPObj );
-    SHPDestroyObject( aSHPObj );
+    //first point is same as the last one => closed polygon
+    x.push_back( aNPnts.Last().X());
+    y.push_back( aNPnts.Last().Y()); 
+
   }
-  else
-    return;
+  
+  aSHPObj = SHPCreateObject( SHPT_POLYGON, -1, NbWires, &anPartStart[0], NULL, x.size(), &x[0], &y[0], NULL, NULL );
+  SHPWriteObject( theShpHandle, -1, aSHPObj );
+  SHPDestroyObject( aSHPObj );
+
 }
 
 bool HYDROData_ShapeFile::Parse(SHPHandle theHandle, ShapeType theType, int& theShapeTypeOfFile)
@@ -304,13 +369,17 @@ bool HYDROData_ShapeFile::Parse(SHPHandle theHandle, ShapeType theType, int& the
 
 void HYDROData_ShapeFile::ReadSHPPolygon(SHPObject* anObj, int i, TopoDS_Face& F)
 {
-  TopoDS_Wire W;
+  if (!anObj)
+    return;
   TopoDS_Edge E; 
   int nParts = anObj->nParts;
-  gp_Pln pln(gp_Pnt(0,0,0), gp_Dir(0,0,1));
+  Handle_Geom_Plane aPlaneSur = new Geom_Plane(gp_Pnt(0,0,0), gp_Dir(0,0,1));
+
+  BRep_Builder BB;
+  BB.MakeFace(F);
+
+  NCollection_Sequence<TopoDS_Wire> allWires;
 
-  //Handle(ShapeFix_Shape) sfs = new ShapeFix_Shape;
-  //sfs->FixFaceTool()->FixOrientationMode() = 1;
   TopTools_SequenceOfShape aWires;
   for ( int i = 0 ; i < nParts ; i++ )
   { 
@@ -322,36 +391,101 @@ void HYDROData_ShapeFile::ReadSHPPolygon(SHPObject* anObj, int i, TopoDS_Face& F
     else
       EndIndex = anObj->nVertices;
 
-    for ( int k = StartIndex; k < EndIndex - 1  ; k++ )
+    TopoDS_Wire W;
+    BB.MakeWire(W);
+
+    //First point is same as the last point 
+    int NbPnts = EndIndex - StartIndex - 1;
+    NCollection_Array1<TopoDS_Vertex> VPoints(0, NbPnts);
+    int j = NbPnts;
+    for ( int k = StartIndex; k < EndIndex; k++ )
+    {
+      gp_Pnt P (anObj->padfX[k], anObj->padfY[k], 0);
+      VPoints.ChangeValue(j) = BRepLib_MakeVertex(P).Vertex();
+      j--;
+    }
+      
+    for ( int k = 0; k < VPoints.Size() - 1; k++ )
     {
-      gp_Pnt P1 (anObj->padfX[k], anObj->padfY[k], 0);
-      gp_Pnt P2 (anObj->padfX[k+1], anObj->padfY[k+1], 0);
+      gp_Pnt P1 = BRep_Tool::Pnt(VPoints(k));
+      gp_Pnt P2 = BRep_Tool::Pnt(VPoints(k + 1));
       if (P1.Distance(P2) < Precision::Confusion())
         continue;
-      BRepBuilderAPI_MakeEdge aMakeEdge(P1, P2);
-      aBuilder.Add(TopoDS::Edge(aMakeEdge.Shape()));
+      Handle_Geom_TrimmedCurve aTC = GC_MakeSegment(P1, P2).Value();
+      TopoDS_Edge E;
+      if ( k != VPoints.Size() - 2)
+        E = BRepLib_MakeEdge(aTC, VPoints(k), VPoints(k + 1)).Edge();
+      else
+        //the last edge => use first and last vertices
+        E = BRepLib_MakeEdge(aTC, VPoints.First(), VPoints.Value(VPoints.Upper() - 1)).Edge();
+      //Add edge to wire
+      //If SHP file is correct then the outer wire and the holes will have the correct orientations
+      W.Closed (Standard_True);
+      W.Orientation(TopAbs_FORWARD);
+      BB.Add(W, E);
     }
-    
-    aBuilder.Build();
-    W = TopoDS::Wire(aBuilder.Shape());
-    W.Orientation(TopAbs_FORWARD);
-    BRepBuilderAPI_MakeFace aDB(pln, W);
-    TopoDS_Face aDummyFace = TopoDS::Face(aDB.Shape());
-    BRepTopAdaptor_FClass2d FClass(aDummyFace, Precision::PConfusion());
-    if ( i == 0 && FClass.PerformInfinitePoint() == TopAbs_OUT) 
+    allWires.Append(W);
+  }
+
+  int OutWIndex = -1;
+  if (allWires.Size() > 1)
+  {
+    NCollection_Sequence<Bnd_Box> BBs;
+    //try to find the largest bbox
+    for (int i = 1; i <= allWires.Size(); i++)
+    {
+      TopoDS_Wire W = allWires(i);
+      Bnd_Box BB;
+      BRepBndLib::AddClose(W, BB);
+      BBs.Append(BB);
+    }
+    for (int i = 1; i <= BBs.Size(); i++)
+    {
+      bool IsIn = false;
+      for (int j = 1; j <= BBs.Size(); j++)
+      {
+        if (i == j)
+          continue;
+        Standard_Real iXmax, iXmin, iYmax, iYmin, z0, z1;
+        Standard_Real jXmax, jXmin, jYmax, jYmin;
+        BBs(i).Get(iXmin, iYmin, z0, iXmax, iYmax, z1);
+        BBs(j).Get(jXmin, jYmin, z0, jXmax, jYmax, z1);
+        if (!(iXmin > jXmin && 
+            iYmin > jYmin &&
+            iXmax < jXmax &&
+            iYmax < jYmax))
+          IsIn = true;
+      }
+      if (IsIn)
+      {
+        OutWIndex = i;
+        break;
+      }
+    }
+  }
+  else
+    OutWIndex = 1; //one wire => no need to check
+
+  for (int i = 1; i <= allWires.Size(); i++)
+  {
+    TopoDS_Face DF;
+    BB.MakeFace(DF);
+    TopoDS_Wire W = allWires(i);
+    BB.Add(DF, W);
+    BB.UpdateFace(DF, aPlaneSur, TopLoc_Location(), Precision::Confusion());
+    //
+    BRepTopAdaptor_FClass2d FClass(DF, Precision::PConfusion());
+    if ( i == OutWIndex && FClass.PerformInfinitePoint() == TopAbs_IN) 
       W.Reverse();
-    if ( i > 0 && FClass.PerformInfinitePoint() != TopAbs_IN
+    if ( i != OutWIndex && FClass.PerformInfinitePoint() == TopAbs_OUT
       W.Reverse();
-   
-    aWires.Append(W);
+    //
+    BB.Add(F, W);
   }
   
-  BRepBuilderAPI_MakeFace aFBuilder(pln, TopoDS::Wire(aWires(1)));
-  for (int i = 2; i <= aWires.Length(); i++)
-    aFBuilder.Add(TopoDS::Wire(aWires(i)));
-  F = TopoDS::Face(aFBuilder.Shape());
-
-  BRepLib::BuildCurves3d(F);  
+  //Add surface to the face
+  BB.UpdateFace(F, aPlaneSur, TopLoc_Location(), Precision::Confusion());
+  F.Closed(Standard_True);
 }
 
 int HYDROData_ShapeFile::ImportPolygons(const QString theFileName, QStringList& thePolygonsList, TopTools_SequenceOfShape& theFaces, int& theShapeTypeOfFile)
@@ -369,11 +503,19 @@ int HYDROData_ShapeFile::ImportPolygons(const QString theFileName, QStringList&
   TopoDS_Face aF;
   if (myHSHP->nShapeType == 5)
   {
+#ifdef OSD_TIMER
+    OSD_Timer timer;
+    timer.Start();
+#endif
     for (size_t i = 0; i < mySHPObjects.size(); i++) 
     {
        ReadSHPPolygon(mySHPObjects[i], i, aF);
        theFaces.Append(aF);
     }
+#ifdef OSD_TIMER
+    timer.Stop();
+    timer.Show();
+#endif
     return 1;
   }
   else
@@ -627,7 +769,12 @@ QString HYDROData_ShapeFile::GetShapeTypeName(int theType)
 int HYDROData_ShapeFile::TryOpenShapeFile(QString theFileName)
 {
   QString aSHPfile = theFileName.simplified();
-  QString aSHXfile = theFileName.simplified().replace( ".shp", ".shx", Qt::CaseInsensitive);
+  QString aSHXfile = theFileName.simplified().replace( theFileName.simplified().size() - 4, 4, ".shx");
+
+  QString anExt = theFileName.split('.', QString::SkipEmptyParts).back();
+  if (anExt.toLower() != "shp")
+    return -3;
+
   FILE* pFileSHP = NULL;
   pFileSHP = fopen (aSHPfile.toAscii().data(), "r");
   FILE* pFileSHX = NULL;
@@ -650,7 +797,7 @@ int HYDROData_ShapeFile::TryOpenShapeFile(QString theFileName)
 bool HYDROData_ShapeFile::CheckDBFFileExisting(const QString& theSHPFilePath, QString& thePathToDBFFile)
 {
   QString aSHPfile = theSHPFilePath.simplified();
-  QString aDBFfile = theSHPFilePath.simplified().replace( ".shp", ".dbf", Qt::CaseInsensitive);
+  QString aDBFfile = theSHPFilePath.simplified().replace( theSHPFilePath.simplified().size() - 4, 4, ".dbf");
   FILE* pFileDBF = NULL;
   pFileDBF = fopen (aDBFfile.toAscii().data(), "r");
 
@@ -913,4 +1060,5 @@ bool HYDROData_ShapeFile::DBF_WriteFieldAndValues(const QString& theFileName, co
   DBFClose( hDBF );
   return true;
 
-}
\ No newline at end of file
+}
+