Salome HOME
comments and debug traces on split polylines
[modules/hydro.git] / src / HYDROData / HYDROData_PolylineOperator.cxx
index 4326e5254186a3d8d7c5a9961dd638e57ede02ee..01537030037778b25b120f97755d41ffb34c6119 100644 (file)
 //
 
 #include <HYDROData_PolylineOperator.h>
-#include <HYDROData_TopoCurve.h>
 #include <HYDROData_Document.h>
+#include <HYDROData_TopoCurve.h>
+#include <HYDROData_Object.h>
+
+#ifndef LIGHT_MODE
+#include <CurveCreator_Utils.hxx>
+#endif
+
 #include <BRepAdaptor_Curve.hxx>
 #include <BRep_Builder.hxx>
 #include <BRep_Tool.hxx>
 #include <TopExp.hxx>
 #include <TopExp_Explorer.hxx>
 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
-#include <QString>
+#include <QStringList>
+#include <QColor>
+#include <Geom_BSplineCurve.hxx>
+#include <TopTools_IndexedMapOfShape.hxx>
+#include <BRepLib_MakeWire.hxx>
+
+#define _DEVDEBUG_
+#include "HYDRO_trace.hxx"
+#include <BRepTools.hxx>
+#include <sstream>
 
 template<class T> void append( std::vector<T>& theList, const std::vector<T>& theList2 )
 {
@@ -61,29 +76,67 @@ bool HYDROData_PolylineOperator::Split( const Handle( HYDROData_Document )& theD
                                         const gp_Pnt2d& thePoint,
                                         double theTolerance ) const
 {
+  if (thePolyline.IsNull())
+  {
+    return false;
+  }
+
   std::vector<gp_Pnt2d> aPointsList( 1 );
   aPointsList[0] = thePoint;
   std::vector<TopoDS_Wire> aCurves;
   GetWires(thePolyline, aCurves);
   bool isOK = true;
+
+  std::vector<QColor> aSectColors;
+  int nbSec = thePolyline->NbSections();
+  for (int i = 0; i < nbSec; i++)
+  {
+    QColor aColor;
+    thePolyline->GetSectionColor(i, aColor);
+    aSectColors.push_back(aColor);
+  }
+
+  bool bsetColor = aCurves.size() == aSectColors.size();
   for( int i=0, n=aCurves.size(); i<n; i++ )
   {
     std::vector<TopoDS_Shape> aCurvesList;
-    Split(aCurves[i], thePoint, theTolerance, aCurvesList);
-    bool isLocalOK = CreatePolylines( theDoc, thePolyline->GetName(), aCurvesList, true );
+    Split( aCurves[i], thePoint, theTolerance, aCurvesList );
+    NCollection_IndexedDataMap<Handle(HYDROData_PolylineXY), TopoDS_Shape> outPoly2Sh;
+    bool isLocalOK = CreatePolylines( theDoc, thePolyline, aCurvesList, true, outPoly2Sh );
     isOK = isOK && isLocalOK;
+    if (bsetColor)
+    {
+      QColor aColor = aSectColors[i];
+      if( aColor.isValid() )
+      {
+        for (int j=1;j<=outPoly2Sh.Extent();j++)
+        {
+          const Handle(HYDROData_PolylineXY)& Poly = outPoly2Sh.FindKey(j); 
+          int nbSec = Poly->NbSections();
+          for (int k = 0; k < nbSec; k++)
+            Poly->SetSectionColor(k, aColor);
+        }
+      }
+    }
   }
+
   return isOK;
 }
 
 bool HYDROData_PolylineOperator::Split( const Handle( HYDROData_Document )& theDoc,
               const Handle( HYDROData_PolylineXY )& thePolyline,
               const Handle( HYDROData_PolylineXY )& theTool,
-              double theTolerance ) const
+              double theTolerance,
+              bool& theIsIntersected) const
 {
+  if (thePolyline.IsNull() || theTool.IsNull())
+  {
+    return false;
+  }
+
   HYDROData_SequenceOfObjects aSeq;
   aSeq.Append( theTool );
-  return split( theDoc, thePolyline, aSeq, theTolerance, -1 );
+  return split( theDoc, thePolyline, aSeq, theTolerance, -1, theIsIntersected);
 }
 
 bool HYDROData_PolylineOperator::Split( const Handle( HYDROData_Document )& theDoc,
@@ -94,7 +147,8 @@ bool HYDROData_PolylineOperator::Split( const Handle( HYDROData_Document )& theD
   for( int i=f; i<=l; i++ )
   {
     Handle( HYDROData_PolylineXY ) aPolyline = Handle( HYDROData_PolylineXY )::DownCast( thePolylines.Value( i ) );
-    if( !split( theDoc, aPolyline, thePolylines, theTolerance, i ) )
+    bool isIntersected;
+    if( !split( theDoc, aPolyline, thePolylines, theTolerance, i, isIntersected) )
       return false;
   }
   return true;
@@ -106,43 +160,52 @@ bool HYDROData_PolylineOperator::Merge( const Handle( HYDROData_Document )& theD
                                         bool isConnectByNewSegment,
                                         double theTolerance )
 {
-  std::deque<HYDROData_TopoCurve> aMergedCurves;
+  Handle( HYDROData_PolylineXY ) aNewPolyline =
+    Handle( HYDROData_PolylineXY )::DownCast( theDoc->CreateObject( KIND_POLYLINEXY ) );
+  int ins =0;
+
   HYDROData_SequenceOfObjects::Iterator aPIt(thePolylines);
-  for (; aPIt.More(); aPIt.Next())
+
+  for (int ip=1; aPIt.More(); aPIt.Next(), ip++)
   {
     Handle(HYDROData_PolylineXY) aPolyline =
       Handle(HYDROData_PolylineXY)::DownCast(aPIt.Value());
-    std::vector<TopoDS_Wire> aWires;
-    GetWires(aPolyline, aWires);
-    for (std::vector<TopoDS_Wire>::const_iterator aWIt = aWires.begin(),
-      aLastWIt = aWires.end(); aWIt != aLastWIt; ++aWIt)
+    NCollection_Sequence<TCollection_AsciiString>           aSectNames;
+    NCollection_Sequence<HYDROData_PolylineXY::SectionType> aSectTypes;
+    NCollection_Sequence<bool>                              aSectClosures;
+    aPolyline->GetSections( aSectNames, aSectTypes, aSectClosures );    
+
+    for ( int i = 1, n = aSectNames.Size(); i <= n; ++i )
     {
-      const Standard_Boolean aResult = !isConnectByNewSegment ?
-        HYDROData_TopoCurve::Merge(theTolerance, *aWIt, aMergedCurves) :
-        HYDROData_TopoCurve::Connect(theTolerance, *aWIt, aMergedCurves);
-      if (!aResult)
-      {
-        return false;
-      }
+      const TCollection_AsciiString& aSectName = aSectNames.Value( i ) + "_" + ip;
+      const HYDROData_PolylineXY::SectionType& aSectType = aSectTypes.Value( i );
+      bool aSectClosure = aSectClosures.Value( i );
+      aNewPolyline->AddSection(aSectName, aSectType, aSectClosure);
+      HYDROData_PolylineXY::PointsList aPointsList = aPolyline->GetPoints(i-1, false);
+      QColor sectColor; 
+      aPolyline->GetSectionColor(i-1, sectColor);
+      aNewPolyline->SetPoints(ins, aPointsList);
+      if (sectColor.isValid())
+        aNewPolyline->SetSectionColor(ins, sectColor);
+      ins++;
     }
   }
-
-  TopoDS_Compound aWireSet;
-  BRep_Builder aBuilder;
-  aBuilder.MakeCompound(aWireSet);
-  std::deque<HYDROData_TopoCurve>::iterator aCIt = aMergedCurves.begin();
-  std::deque<HYDROData_TopoCurve>::iterator aLastCIt = aMergedCurves.end();
-  for (; aCIt != aLastCIt; ++aCIt)
-  {
-    if (!aCIt->IsEmpty())
+  QString aName = theName;
+  if( aName.isEmpty() )
     {
-      aBuilder.Add(aWireSet, aCIt->Wire());
+      aName = "merged";
+      int anIndex = 1;
+      QString aNewName = aName + "_" + QString::number(anIndex);
+      while (!theDoc->FindObjectByName(aNewName).IsNull())  // the object with such a name is not found
+        {
+          anIndex++;
+          aNewName = aName + "_" + QString::number(anIndex);
+        }
+      aName = aNewName;
     }
-  }
 
-  std::vector<TopoDS_Shape> aPolylines(1);
-  aPolylines[0] = aWireSet;
-  CreatePolylines(theDoc, theName, aPolylines, false);
+  aNewPolyline->SetName(aName);
+  aNewPolyline->Update();
   return true;
 }
 
@@ -150,8 +213,16 @@ bool HYDROData_PolylineOperator::split( const Handle( HYDROData_Document )& theD
                                         const Handle( HYDROData_PolylineXY )& thePolyline,
                                         const HYDROData_SequenceOfObjects& theTools,
                                         double theTolerance,
-                                        int theIgnoreIndex ) const
+                                        int theIgnoreIndex,
+                                        bool& theIsIntersected) const
 {
+  theIsIntersected = false;
+
+  if (thePolyline.IsNull())
+  {
+    return false;
+  }
+
   std::vector<TopoDS_Wire> aCurves;
   GetWires(thePolyline, aCurves);
   std::vector<TopoDS_Wire> aToolCurves;
@@ -160,19 +231,45 @@ bool HYDROData_PolylineOperator::split( const Handle( HYDROData_Document )& theD
     {
       Handle( HYDROData_PolylineXY ) aToolPolyline = 
         Handle( HYDROData_PolylineXY )::DownCast( theTools.Value( i ) );
-      std::vector<TopoDS_Wire> aTCurves;
-      GetWires(aToolPolyline, aTCurves);
-      append( aToolCurves, aTCurves);
+      if (!aToolPolyline.IsNull())
+      {
+        std::vector<TopoDS_Wire> aTCurves;
+        GetWires(aToolPolyline, aTCurves);
+        append( aToolCurves, aTCurves);
+      }
     }
 
+  if (aToolCurves.empty())
+  {
+    return false;
+  }
+
+  std::vector<QColor> aSectColors;
+  int nbSec = thePolyline->NbSections();
+
   const int aPSCount = aCurves.size();
   const int aTSCount = aToolCurves.size();
   std::vector<TopoDS_Shape> aResult;
+
+  bool bSetColor = aPSCount == nbSec;
+  if (bSetColor)
+  {
+    for (int i = 0; i < nbSec; i++)
+    {
+      QColor aColor;
+      thePolyline->GetSectionColor(i, aColor);
+      aSectColors.push_back(aColor);
+    }
+  }
+  NCollection_DataMap <TopoDS_Shape, QColor, TopTools_ShapeMapHasher> W2Color;
+
   for (int aPSI = 0; aPSI < aPSCount; ++aPSI)
   {
     HYDROData_TopoCurve aCurve;
-    if (!aCurve.Initialize(aCurves[aPSI]))
+    DEBTRACE("Initialize curve " << aPSI);
+    if (!aCurve.Initialize(aCurves[aPSI]))    // empty, non manifold (or internal bug!)
     {
+      DEBTRACE("discarded curve (empty or non manifold)!");
       continue;
     }
 
@@ -182,19 +279,43 @@ bool HYDROData_PolylineOperator::split( const Handle( HYDROData_Document )& theD
       aCurve.Intersect(aToolCurves[aTSI], aParams);
     }
 
-    std::deque<HYDROData_TopoCurve> aSplittedCurves;
-    aCurve.Cut(aParams, aSplittedCurves);
+    std::deque<HYDROData_TopoCurve> aSplitCurves;
+    theIsIntersected |= aCurve.Cut(aParams, aSplitCurves);
     std::deque<HYDROData_TopoCurve>::const_iterator aCIt =
-      aSplittedCurves.begin();
+      aSplitCurves.begin();
     std::deque<HYDROData_TopoCurve>::const_iterator aLastCIt =
-      aSplittedCurves.end();
-    for (; aCIt != aLastCIt; ++aCIt)
+      aSplitCurves.end();
+    for (int iw=0; aCIt != aLastCIt; ++aCIt, iw++)
     {
-      aResult.push_back(aCIt->Wire());
+      //std::stringstream brepName;
+      //brepName << "theSplitWire_";
+      //brepName << iw;
+      //brepName << ".brep";
+      //BRepTools::Write(aCIt->Wire() , brepName.str().c_str() );
+      const TopoDS_Wire& aW = aCIt->Wire();
+      if (bSetColor)
+        W2Color.Bind(aW, aSectColors[aPSI]);
+      aResult.push_back(aW);
     }
   }
 
-  CreatePolylines(theDoc, thePolyline->GetName(), aResult, true);
+  NCollection_IndexedDataMap<Handle(HYDROData_PolylineXY), TopoDS_Shape> outPoly2Sh;
+  CreatePolylines( theDoc, thePolyline, aResult, true, outPoly2Sh );
+  
+  for (int j=1;j<=outPoly2Sh.Extent();j++)
+  {
+    const Handle(HYDROData_PolylineXY)& Poly = outPoly2Sh.FindKey(j); 
+    const TopoDS_Shape& Sh = outPoly2Sh.FindFromIndex(j); 
+
+    int nbSec = Poly->NbSections();
+    for (int k = 0; k < nbSec; k++)
+    {
+      const QColor* color = W2Color.Seek(Sh);
+      if (color)
+        Poly->SetSectionColor(k, *color);
+    }
+  }
+  
   return true;
 }
 
@@ -203,6 +324,8 @@ void HYDROData_PolylineOperator::GetWires(
   std::vector<TopoDS_Wire>& theWires)
 {
   TopoDS_Shape aShape = thePolyline->GetShape();
+  if (aShape.IsNull())
+    return;
   if( aShape.ShapeType()==TopAbs_WIRE )
   {
     theWires.push_back( TopoDS::Wire( aShape ) );
@@ -244,14 +367,20 @@ void HYDROData_PolylineOperator::Split(
 }
 
 bool HYDROData_PolylineOperator::CreatePolylines( const Handle( HYDROData_Document )& theDoc,
-                                                  const QString& theNamePrefix,
+                                                  const Handle( HYDROData_PolylineXY )& theOldPolyline,
                                                   const std::vector<TopoDS_Shape>& theShapes,
-                                                  bool isUseIndices )
+                                                  bool isUseIndices,
+                                                  NCollection_IndexedDataMap<Handle(HYDROData_PolylineXY), TopoDS_Shape>& outPoly2Sh)
 {
   if( theDoc.IsNull() )
     return false;
 
+  if ( theOldPolyline.IsNull() )
+    return false;
+  const QString& theNamePrefix = theOldPolyline->GetName();
+
   int n = theShapes.size();
+  DEBTRACE("theShapes.size() "<< n);
   int anIndex = 1;
   for( int i=0; i<n; i++ )
   {
@@ -260,19 +389,207 @@ bool HYDROData_PolylineOperator::CreatePolylines( const Handle( HYDROData_Docume
     if( aPolyline.IsNull() )
       return false;
 
-    aPolyline->SetShape( theShapes[i] );
+    aPolyline->ImportShape(theShapes[i], false, theOldPolyline, false);
 
     if( isUseIndices )
     {
       QString aNewName = theNamePrefix + "_" + QString::number( anIndex );
-      if( theDoc->FindObjectByName( aNewName ).IsNull() )  // the object with such a name is not found
-        aPolyline->SetName( aNewName );
-      anIndex++;
+      while( !theDoc->FindObjectByName( aNewName ).IsNull() )  // the object with such a name is not found
+      {
+        anIndex++;
+        aNewName = theNamePrefix + "_" + QString::number( anIndex );
+      }
+      aPolyline->SetName( aNewName );
     }
     else
     {
       aPolyline->SetName( theNamePrefix );
     }
+
+    outPoly2Sh.Add(aPolyline, theShapes[i]);
+  }
+  return true;
+}
+
+double HYDROData_PolylineOperator::ReduceDeflection(
+  const double theDeflection,
+  HYDROData_TopoCurve& theCurve,
+  int& thePieceCount)
+{
+  // Construct the approximating B-spline.
+  std::list<gp_XYZ> aPs;
+  if (!theCurve.ValuesInKnots(aPs))
+  {
+    return -1;
+  }
+
+  Handle(TColgp_HArray1OfPnt) aPs2 = new TColgp_HArray1OfPnt(1, aPs.size());
+  {
+    std::list<gp_XYZ>::const_iterator aLastPIt = aPs.end();
+    std::list<gp_XYZ>::const_iterator aPIt = aPs.begin();
+    for (int aPN = 1; aPIt != aLastPIt; ++aPN, ++aPIt)
+    {
+      aPs2->SetValue(aPN, *aPIt);
+    }
+  }
+  Handle(Geom_BSplineCurve) aBSpline2;
+  const bool isClosed = theCurve.IsClosed();
+#ifndef LIGHT_MODE
+  if (!CurveCreator_Utils::constructBSpline(aPs2, isClosed, aBSpline2))
+#endif
+  {
+    return -1;
+  }
+
+  // Calculate the piece deflections.
+  std::deque<double> aSqDefls;
+  double aMaxSqDefl = 0;
+  std::list<TopoDS_Edge>& aEdges = theCurve.Edges();
+  std::list<TopoDS_Edge>::const_iterator aLastEIt = aEdges.end();
+  {
+    std::list<TopoDS_Edge>::const_iterator aEIt = aEdges.begin();
+    for (int aPrevKCount = 0; aEIt != aLastEIt; ++aEIt)
+    {
+      TopLoc_Location aLoc;
+      double aParams[2];
+      Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
+        BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
+      const int aKCount = aBSpline->NbKnots();
+      for (int aKN = 1; aKN < aKCount; ++aKN)
+      {
+        const double aParam =
+          (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5;
+        const double aParam2 = (aBSpline2->Knot(aPrevKCount + aKN) +
+          aBSpline2->Knot(aPrevKCount + aKN + 1)) * 0.5;
+        const double aSqDefl = Abs(aBSpline->Value(aParam).
+          SquareDistance(aBSpline2->Value(aParam2)));
+        aSqDefls.push_back(aSqDefl);
+        if (aMaxSqDefl < aSqDefl)
+        {
+          aMaxSqDefl = aSqDefl;
+        }
+      }
+      aPrevKCount += aKCount - 1;
+    }
+  }
+
+  // Check whether the reducing is necessary.
+  const double aMaxDefl = Sqrt(aMaxSqDefl);
+  if (aMaxDefl <= theDeflection)
+  {
+    return aMaxDefl;
+  }
+
+  // Reduce the deflections.
+  const double aThresSqDefl =
+    Max(aMaxSqDefl * 0.25, theDeflection * theDeflection);
+  std::list<TopoDS_Edge>::iterator aEIt = aEdges.begin();
+  std::deque<double>::const_iterator aSqDIt = aSqDefls.begin();
+  thePieceCount = 0;
+  for (; aEIt != aLastEIt; ++aEIt)
+  {
+    TopLoc_Location aLoc;
+    double aParams[2];
+    Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
+      BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
+    Handle(Geom_BSplineCurve) aBSpline2 =
+      Handle(Geom_BSplineCurve)::DownCast(aBSpline->Copy());
+    const int aKCount = aBSpline->NbKnots();
+    for (int aKN = 1; aKN < aKCount; ++aSqDIt, ++aKN)
+    {
+      if (*aSqDIt > aThresSqDefl)
+      {
+        aBSpline2->InsertKnot(
+          (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5);
+      }
+    }
+    TopoDS_Edge aEdge;
+    BRep_Builder().MakeEdge(aEdge, aBSpline2, Precision::Confusion());
+    BRep_Builder().Add(aEdge, TopExp::FirstVertex(*aEIt));
+    BRep_Builder().Add(aEdge, TopExp::LastVertex(*aEIt));
+    thePieceCount += aBSpline2->NbKnots() - 1;
+    *aEIt = aEdge;
   }
+  return aMaxDefl;
+}
+
+bool HYDROData_PolylineOperator::Extract( const Handle(HYDROData_Document)& theDocument,
+                                          const Handle(HYDROData_Object)& theObject )
+{
+  if( theObject.IsNull() || theDocument.IsNull() )
+    return false;
+
+  QList<TopoDS_Shape> aBoundShapes;
+  QStringList aBoundNames;
+  QMap<QString, TopTools_IndexedMapOfShape> aNameToShMap;
+
+  theObject->GetBoundaries( aBoundShapes, aBoundNames );
+
+  for( int i=0, n=aBoundShapes.size(); i<n; i++ )
+  {
+    TopoDS_Shape aShape = aBoundShapes[i];
+    if( aShape.IsNull() )
+      continue;
+
+    QString aBoundName = i<aBoundNames.size() ? aBoundNames[i] : "";
+    
+    if (!aNameToShMap.contains(aBoundName))
+    {
+      TopTools_IndexedMapOfShape IM;
+      IM.Add(aShape);
+      aNameToShMap[aBoundName] = IM;
+    }
+    else
+      aNameToShMap[aBoundName].Add(aShape);
+     
+  }
+
+  foreach( QString K, aNameToShMap.keys() )
+  {
+    const TopTools_IndexedMapOfShape& IM = aNameToShMap.value(K);
+    TopTools_ListOfShape LSE;
+    for (int i = 1; i <= IM.Extent(); i++)
+    {
+      const TopoDS_Edge& E = TopoDS::Edge(IM(i));
+      if (E.IsNull())
+        continue;
+      LSE.Append(E);
+    }
+
+
+    TopoDS_Shape aShapeOut;
+    if (LSE.Extent() == 1)
+    {
+      aShapeOut = LSE.First();
+    }
+    else if (LSE.Extent() > 1)
+    {
+      BRepLib_MakeWire WM;
+      WM.Add(LSE);
+      if (WM.IsDone())
+        aShapeOut = WM.Wire();
+      else
+        continue;
+    }
+    else continue;
+
+    Handle( HYDROData_PolylineXY ) aPolyline = 
+      Handle( HYDROData_PolylineXY )::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
+
+    if( aPolyline.IsNull() )
+      return false;
+
+    aPolyline->SetShape( aShapeOut );
+
+    int anIndex = 0;
+    QString aName = K;
+    while( !theDocument->FindObjectByName( aName ).IsNull() )
+    {
+      anIndex++;
+      aName = K + "_" + QString::number( anIndex );
+    }
+    aPolyline->SetName( aName );
+  }
+
   return true;
 }