Salome HOME
comments and debug traces on split polylines
[modules/hydro.git] / src / HYDROData / HYDROData_PolylineOperator.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_PolylineOperator.h>
20 #include <HYDROData_Document.h>
21 #include <HYDROData_TopoCurve.h>
22 #include <HYDROData_Object.h>
23
24 #ifndef LIGHT_MODE
25 #include <CurveCreator_Utils.hxx>
26 #endif
27
28 #include <BRepAdaptor_Curve.hxx>
29 #include <BRep_Builder.hxx>
30 #include <BRep_Tool.hxx>
31 #include <BRepBuilderAPI_MakeEdge2d.hxx>
32 #include <BRepBuilderAPI_MakeEdge.hxx>
33 #include <BRepBuilderAPI_MakeWire.hxx>
34 #include <Extrema_ExtCC.hxx>
35 #include <Extrema_ExtPC.hxx>
36 #include <GeomAPI_Interpolate.hxx>
37 #include <NCollection_Vector.hxx>
38 #include <Precision.hxx>
39 #include <ShapeAnalysis_TransferParametersProj.hxx>
40 #include <ShapeBuild_Edge.hxx>
41 #include <TColgp_Array1OfVec.hxx>
42 #include <TColgp_HArray1OfPnt.hxx>
43 #include <TColStd_HArray1OfBoolean.hxx>
44 #include <TopoDS.hxx>
45 #include <TopoDS_Edge.hxx>
46 #include <TopoDS_Wire.hxx>
47 #include <TopExp.hxx>
48 #include <TopExp_Explorer.hxx>
49 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
50 #include <QStringList>
51 #include <QColor>
52 #include <Geom_BSplineCurve.hxx>
53 #include <TopTools_IndexedMapOfShape.hxx>
54 #include <BRepLib_MakeWire.hxx>
55
56 #define _DEVDEBUG_
57 #include "HYDRO_trace.hxx"
58 #include <BRepTools.hxx>
59 #include <sstream>
60
61 template<class T> void append( std::vector<T>& theList, const std::vector<T>& theList2 )
62 {
63   int aSize = theList.size();
64   int aNewSize = aSize + theList2.size();
65
66   if( aSize==aNewSize )
67     return;
68
69   theList.resize( aNewSize );
70   for( int i=aSize, j=0; i<aNewSize; i++, j++ )
71     theList[i] = theList2[j];
72 }
73
74 bool HYDROData_PolylineOperator::Split( const Handle( HYDROData_Document )& theDoc,
75                                         const Handle( HYDROData_PolylineXY )& thePolyline,
76                                         const gp_Pnt2d& thePoint,
77                                         double theTolerance ) const
78 {
79   if (thePolyline.IsNull())
80   {
81     return false;
82   }
83
84   std::vector<gp_Pnt2d> aPointsList( 1 );
85   aPointsList[0] = thePoint;
86   std::vector<TopoDS_Wire> aCurves;
87   GetWires(thePolyline, aCurves);
88   bool isOK = true;
89
90   std::vector<QColor> aSectColors;
91   int nbSec = thePolyline->NbSections();
92   for (int i = 0; i < nbSec; i++)
93   {
94     QColor aColor;
95     thePolyline->GetSectionColor(i, aColor);
96     aSectColors.push_back(aColor);
97   }
98
99   bool bsetColor = aCurves.size() == aSectColors.size();
100   for( int i=0, n=aCurves.size(); i<n; i++ )
101   {
102     std::vector<TopoDS_Shape> aCurvesList;
103     Split( aCurves[i], thePoint, theTolerance, aCurvesList );
104     NCollection_IndexedDataMap<Handle(HYDROData_PolylineXY), TopoDS_Shape> outPoly2Sh;
105     bool isLocalOK = CreatePolylines( theDoc, thePolyline, aCurvesList, true, outPoly2Sh );
106     isOK = isOK && isLocalOK;
107     if (bsetColor)
108     {
109       QColor aColor = aSectColors[i];
110       if( aColor.isValid() )
111       {
112         for (int j=1;j<=outPoly2Sh.Extent();j++)
113         {
114           const Handle(HYDROData_PolylineXY)& Poly = outPoly2Sh.FindKey(j); 
115           int nbSec = Poly->NbSections();
116           for (int k = 0; k < nbSec; k++)
117             Poly->SetSectionColor(k, aColor);
118         }
119       }
120     }
121   }
122
123   return isOK;
124 }
125
126 bool HYDROData_PolylineOperator::Split( const Handle( HYDROData_Document )& theDoc,
127               const Handle( HYDROData_PolylineXY )& thePolyline,
128               const Handle( HYDROData_PolylineXY )& theTool,
129               double theTolerance,
130               bool& theIsIntersected) const
131 {
132   if (thePolyline.IsNull() || theTool.IsNull())
133   {
134     return false;
135   }
136
137   HYDROData_SequenceOfObjects aSeq;
138   aSeq.Append( theTool );
139   return split( theDoc, thePolyline, aSeq, theTolerance, -1, theIsIntersected);
140 }
141
142 bool HYDROData_PolylineOperator::Split( const Handle( HYDROData_Document )& theDoc,
143                                         const HYDROData_SequenceOfObjects& thePolylines,
144                                         double theTolerance )
145 {
146   int f = thePolylines.Lower(), l = thePolylines.Upper();
147   for( int i=f; i<=l; i++ )
148   {
149     Handle( HYDROData_PolylineXY ) aPolyline = Handle( HYDROData_PolylineXY )::DownCast( thePolylines.Value( i ) );
150     bool isIntersected;
151     if( !split( theDoc, aPolyline, thePolylines, theTolerance, i, isIntersected) )
152       return false;
153   }
154   return true;
155 }
156
157 bool HYDROData_PolylineOperator::Merge( const Handle( HYDROData_Document )& theDoc,
158                                         const QString& theName,
159                                         const HYDROData_SequenceOfObjects& thePolylines,
160                                         bool isConnectByNewSegment,
161                                         double theTolerance )
162 {
163   Handle( HYDROData_PolylineXY ) aNewPolyline =
164     Handle( HYDROData_PolylineXY )::DownCast( theDoc->CreateObject( KIND_POLYLINEXY ) );
165   int ins =0;
166
167   HYDROData_SequenceOfObjects::Iterator aPIt(thePolylines);
168
169   for (int ip=1; aPIt.More(); aPIt.Next(), ip++)
170   {
171     Handle(HYDROData_PolylineXY) aPolyline =
172       Handle(HYDROData_PolylineXY)::DownCast(aPIt.Value());
173     NCollection_Sequence<TCollection_AsciiString>           aSectNames;
174     NCollection_Sequence<HYDROData_PolylineXY::SectionType> aSectTypes;
175     NCollection_Sequence<bool>                              aSectClosures;
176     aPolyline->GetSections( aSectNames, aSectTypes, aSectClosures );    
177
178     for ( int i = 1, n = aSectNames.Size(); i <= n; ++i )
179     {
180       const TCollection_AsciiString& aSectName = aSectNames.Value( i ) + "_" + ip;
181       const HYDROData_PolylineXY::SectionType& aSectType = aSectTypes.Value( i );
182       bool aSectClosure = aSectClosures.Value( i );
183       aNewPolyline->AddSection(aSectName, aSectType, aSectClosure);
184       HYDROData_PolylineXY::PointsList aPointsList = aPolyline->GetPoints(i-1, false);
185       QColor sectColor; 
186       aPolyline->GetSectionColor(i-1, sectColor);
187       aNewPolyline->SetPoints(ins, aPointsList);
188       if (sectColor.isValid())
189         aNewPolyline->SetSectionColor(ins, sectColor);
190       ins++;
191     }
192   }
193   QString aName = theName;
194   if( aName.isEmpty() )
195     {
196       aName = "merged";
197       int anIndex = 1;
198       QString aNewName = aName + "_" + QString::number(anIndex);
199       while (!theDoc->FindObjectByName(aNewName).IsNull())  // the object with such a name is not found
200         {
201           anIndex++;
202           aNewName = aName + "_" + QString::number(anIndex);
203         }
204       aName = aNewName;
205     }
206
207   aNewPolyline->SetName(aName);
208   aNewPolyline->Update();
209   return true;
210 }
211
212 bool HYDROData_PolylineOperator::split( const Handle( HYDROData_Document )& theDoc,
213                                         const Handle( HYDROData_PolylineXY )& thePolyline,
214                                         const HYDROData_SequenceOfObjects& theTools,
215                                         double theTolerance,
216                                         int theIgnoreIndex,
217                                         bool& theIsIntersected) const
218 {
219   theIsIntersected = false;
220
221   if (thePolyline.IsNull())
222   {
223     return false;
224   }
225
226   std::vector<TopoDS_Wire> aCurves;
227   GetWires(thePolyline, aCurves);
228   std::vector<TopoDS_Wire> aToolCurves;
229   for( int i=theTools.Lower(), n=theTools.Upper(); i<=n; i++ )
230     if( i!=theIgnoreIndex )
231     {
232       Handle( HYDROData_PolylineXY ) aToolPolyline = 
233         Handle( HYDROData_PolylineXY )::DownCast( theTools.Value( i ) );
234       if (!aToolPolyline.IsNull())
235       {
236         std::vector<TopoDS_Wire> aTCurves;
237         GetWires(aToolPolyline, aTCurves);
238         append( aToolCurves, aTCurves);
239       }
240     }
241
242   if (aToolCurves.empty())
243   {
244     return false;
245   }
246
247   std::vector<QColor> aSectColors;
248   int nbSec = thePolyline->NbSections();
249
250   const int aPSCount = aCurves.size();
251   const int aTSCount = aToolCurves.size();
252   std::vector<TopoDS_Shape> aResult;
253
254   bool bSetColor = aPSCount == nbSec;
255   if (bSetColor)
256   {
257     for (int i = 0; i < nbSec; i++)
258     {
259       QColor aColor;
260       thePolyline->GetSectionColor(i, aColor);
261       aSectColors.push_back(aColor);
262     }
263   }
264   NCollection_DataMap <TopoDS_Shape, QColor, TopTools_ShapeMapHasher> W2Color;
265
266   for (int aPSI = 0; aPSI < aPSCount; ++aPSI)
267   {
268     HYDROData_TopoCurve aCurve;
269     DEBTRACE("Initialize curve " << aPSI);
270     if (!aCurve.Initialize(aCurves[aPSI]))    // empty, non manifold (or internal bug!)
271     {
272       DEBTRACE("discarded curve (empty or non manifold)!");
273       continue;
274     }
275
276     std::deque<std::list<double> > aParams;
277     for (int aTSI = 0; aTSI < aTSCount; ++aTSI)
278     {
279       aCurve.Intersect(aToolCurves[aTSI], aParams);
280     }
281
282     std::deque<HYDROData_TopoCurve> aSplitCurves;
283     theIsIntersected |= aCurve.Cut(aParams, aSplitCurves);
284     std::deque<HYDROData_TopoCurve>::const_iterator aCIt =
285       aSplitCurves.begin();
286     std::deque<HYDROData_TopoCurve>::const_iterator aLastCIt =
287       aSplitCurves.end();
288     for (int iw=0; aCIt != aLastCIt; ++aCIt, iw++)
289     {
290       //std::stringstream brepName;
291       //brepName << "theSplitWire_";
292       //brepName << iw;
293       //brepName << ".brep";
294       //BRepTools::Write(aCIt->Wire() , brepName.str().c_str() );
295       const TopoDS_Wire& aW = aCIt->Wire();
296       if (bSetColor)
297         W2Color.Bind(aW, aSectColors[aPSI]);
298       aResult.push_back(aW);
299     }
300   }
301
302   NCollection_IndexedDataMap<Handle(HYDROData_PolylineXY), TopoDS_Shape> outPoly2Sh;
303   CreatePolylines( theDoc, thePolyline, aResult, true, outPoly2Sh );
304   
305   for (int j=1;j<=outPoly2Sh.Extent();j++)
306   {
307     const Handle(HYDROData_PolylineXY)& Poly = outPoly2Sh.FindKey(j); 
308     const TopoDS_Shape& Sh = outPoly2Sh.FindFromIndex(j); 
309
310     int nbSec = Poly->NbSections();
311     for (int k = 0; k < nbSec; k++)
312     {
313       const QColor* color = W2Color.Seek(Sh);
314       if (color)
315         Poly->SetSectionColor(k, *color);
316     }
317   }
318   
319   return true;
320 }
321
322 void HYDROData_PolylineOperator::GetWires(
323   const Handle( HYDROData_PolylineXY )& thePolyline,
324   std::vector<TopoDS_Wire>& theWires)
325 {
326   TopoDS_Shape aShape = thePolyline->GetShape();
327   if (aShape.IsNull())
328     return;
329   if( aShape.ShapeType()==TopAbs_WIRE )
330   {
331     theWires.push_back( TopoDS::Wire( aShape ) );
332   }
333   else
334   {
335     TopExp_Explorer anExp( aShape, TopAbs_WIRE );
336     for( ; anExp.More(); anExp.Next() )
337     {
338       theWires.push_back( TopoDS::Wire( anExp.Current() ) );
339     }
340   }
341 }
342
343 void HYDROData_PolylineOperator::Split(
344   const TopoDS_Wire& theWire,
345   const gp_Pnt2d& thePoint,
346   double theTolerance,
347   std::vector<TopoDS_Shape>& theWires)
348 {
349   HYDROData_TopoCurve aCurve;
350   if (!aCurve.Initialize(theWire))
351   {
352     theWires.push_back(theWire);
353     return;
354   }
355
356   const gp_XYZ aP(thePoint.X(), thePoint.Y(), 0);
357   std::list<TopoDS_Edge>::const_iterator aEPos;
358   double aParam;
359   aCurve.Project(aP, aEPos, aParam);
360   HYDROData_TopoCurve aCurve1, aCurve2;
361   aCurve.Cut(aEPos, aParam, aCurve1, aCurve2);
362   theWires.push_back(aCurve1.Wire());
363   if (!aCurve2.IsEmpty())
364   {
365     theWires.push_back(aCurve2.Wire());
366   }
367 }
368
369 bool HYDROData_PolylineOperator::CreatePolylines( const Handle( HYDROData_Document )& theDoc,
370                                                   const Handle( HYDROData_PolylineXY )& theOldPolyline,
371                                                   const std::vector<TopoDS_Shape>& theShapes,
372                                                   bool isUseIndices,
373                                                   NCollection_IndexedDataMap<Handle(HYDROData_PolylineXY), TopoDS_Shape>& outPoly2Sh)
374 {
375   if( theDoc.IsNull() )
376     return false;
377
378   if ( theOldPolyline.IsNull() )
379     return false;
380   const QString& theNamePrefix = theOldPolyline->GetName();
381
382   int n = theShapes.size();
383   DEBTRACE("theShapes.size() "<< n);
384   int anIndex = 1;
385   for( int i=0; i<n; i++ )
386   {
387     Handle( HYDROData_PolylineXY ) aPolyline = 
388       Handle( HYDROData_PolylineXY )::DownCast( theDoc->CreateObject( KIND_POLYLINEXY ) );
389     if( aPolyline.IsNull() )
390       return false;
391
392     aPolyline->ImportShape(theShapes[i], false, theOldPolyline, false);
393
394     if( isUseIndices )
395     {
396       QString aNewName = theNamePrefix + "_" + QString::number( anIndex );
397       while( !theDoc->FindObjectByName( aNewName ).IsNull() )  // the object with such a name is not found
398       {
399         anIndex++;
400         aNewName = theNamePrefix + "_" + QString::number( anIndex );
401       }
402       aPolyline->SetName( aNewName );
403     }
404     else
405     {
406       aPolyline->SetName( theNamePrefix );
407     }
408
409     outPoly2Sh.Add(aPolyline, theShapes[i]);
410   }
411   return true;
412 }
413
414 double HYDROData_PolylineOperator::ReduceDeflection(
415   const double theDeflection,
416   HYDROData_TopoCurve& theCurve,
417   int& thePieceCount)
418 {
419   // Construct the approximating B-spline.
420   std::list<gp_XYZ> aPs;
421   if (!theCurve.ValuesInKnots(aPs))
422   {
423     return -1;
424   }
425
426   Handle(TColgp_HArray1OfPnt) aPs2 = new TColgp_HArray1OfPnt(1, aPs.size());
427   {
428     std::list<gp_XYZ>::const_iterator aLastPIt = aPs.end();
429     std::list<gp_XYZ>::const_iterator aPIt = aPs.begin();
430     for (int aPN = 1; aPIt != aLastPIt; ++aPN, ++aPIt)
431     {
432       aPs2->SetValue(aPN, *aPIt);
433     }
434   }
435   Handle(Geom_BSplineCurve) aBSpline2;
436   const bool isClosed = theCurve.IsClosed();
437 #ifndef LIGHT_MODE
438   if (!CurveCreator_Utils::constructBSpline(aPs2, isClosed, aBSpline2))
439 #endif
440   {
441     return -1;
442   }
443
444   // Calculate the piece deflections.
445   std::deque<double> aSqDefls;
446   double aMaxSqDefl = 0;
447   std::list<TopoDS_Edge>& aEdges = theCurve.Edges();
448   std::list<TopoDS_Edge>::const_iterator aLastEIt = aEdges.end();
449   {
450     std::list<TopoDS_Edge>::const_iterator aEIt = aEdges.begin();
451     for (int aPrevKCount = 0; aEIt != aLastEIt; ++aEIt)
452     {
453       TopLoc_Location aLoc;
454       double aParams[2];
455       Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
456         BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
457       const int aKCount = aBSpline->NbKnots();
458       for (int aKN = 1; aKN < aKCount; ++aKN)
459       {
460         const double aParam =
461           (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5;
462         const double aParam2 = (aBSpline2->Knot(aPrevKCount + aKN) +
463           aBSpline2->Knot(aPrevKCount + aKN + 1)) * 0.5;
464         const double aSqDefl = Abs(aBSpline->Value(aParam).
465           SquareDistance(aBSpline2->Value(aParam2)));
466         aSqDefls.push_back(aSqDefl);
467         if (aMaxSqDefl < aSqDefl)
468         {
469           aMaxSqDefl = aSqDefl;
470         }
471       }
472       aPrevKCount += aKCount - 1;
473     }
474   }
475
476   // Check whether the reducing is necessary.
477   const double aMaxDefl = Sqrt(aMaxSqDefl);
478   if (aMaxDefl <= theDeflection)
479   {
480     return aMaxDefl;
481   }
482
483   // Reduce the deflections.
484   const double aThresSqDefl =
485     Max(aMaxSqDefl * 0.25, theDeflection * theDeflection);
486   std::list<TopoDS_Edge>::iterator aEIt = aEdges.begin();
487   std::deque<double>::const_iterator aSqDIt = aSqDefls.begin();
488   thePieceCount = 0;
489   for (; aEIt != aLastEIt; ++aEIt)
490   {
491     TopLoc_Location aLoc;
492     double aParams[2];
493     Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
494       BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
495     Handle(Geom_BSplineCurve) aBSpline2 =
496       Handle(Geom_BSplineCurve)::DownCast(aBSpline->Copy());
497     const int aKCount = aBSpline->NbKnots();
498     for (int aKN = 1; aKN < aKCount; ++aSqDIt, ++aKN)
499     {
500       if (*aSqDIt > aThresSqDefl)
501       {
502         aBSpline2->InsertKnot(
503           (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5);
504       }
505     }
506     TopoDS_Edge aEdge;
507     BRep_Builder().MakeEdge(aEdge, aBSpline2, Precision::Confusion());
508     BRep_Builder().Add(aEdge, TopExp::FirstVertex(*aEIt));
509     BRep_Builder().Add(aEdge, TopExp::LastVertex(*aEIt));
510     thePieceCount += aBSpline2->NbKnots() - 1;
511     *aEIt = aEdge;
512   }
513   return aMaxDefl;
514 }
515
516 bool HYDROData_PolylineOperator::Extract( const Handle(HYDROData_Document)& theDocument,
517                                           const Handle(HYDROData_Object)& theObject )
518 {
519   if( theObject.IsNull() || theDocument.IsNull() )
520     return false;
521
522   QList<TopoDS_Shape> aBoundShapes;
523   QStringList aBoundNames;
524   QMap<QString, TopTools_IndexedMapOfShape> aNameToShMap;
525
526   theObject->GetBoundaries( aBoundShapes, aBoundNames );
527
528   for( int i=0, n=aBoundShapes.size(); i<n; i++ )
529   {
530     TopoDS_Shape aShape = aBoundShapes[i];
531     if( aShape.IsNull() )
532       continue;
533
534     QString aBoundName = i<aBoundNames.size() ? aBoundNames[i] : "";
535     
536     if (!aNameToShMap.contains(aBoundName))
537     {
538       TopTools_IndexedMapOfShape IM;
539       IM.Add(aShape);
540       aNameToShMap[aBoundName] = IM;
541     }
542     else
543       aNameToShMap[aBoundName].Add(aShape);
544      
545   }
546
547   foreach( QString K, aNameToShMap.keys() )
548   {
549     const TopTools_IndexedMapOfShape& IM = aNameToShMap.value(K);
550     TopTools_ListOfShape LSE;
551     for (int i = 1; i <= IM.Extent(); i++)
552     {
553       const TopoDS_Edge& E = TopoDS::Edge(IM(i));
554       if (E.IsNull())
555         continue;
556       LSE.Append(E);
557     }
558
559
560     TopoDS_Shape aShapeOut;
561     if (LSE.Extent() == 1)
562     {
563       aShapeOut = LSE.First();
564     }
565     else if (LSE.Extent() > 1)
566     {
567       BRepLib_MakeWire WM;
568       WM.Add(LSE);
569       if (WM.IsDone())
570         aShapeOut = WM.Wire();
571       else
572         continue;
573     }
574     else continue;
575
576     Handle( HYDROData_PolylineXY ) aPolyline = 
577       Handle( HYDROData_PolylineXY )::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
578
579     if( aPolyline.IsNull() )
580       return false;
581
582     aPolyline->SetShape( aShapeOut );
583
584     int anIndex = 0;
585     QString aName = K;
586     while( !theDocument->FindObjectByName( aName ).IsNull() )
587     {
588       anIndex++;
589       aName = K + "_" + QString::number( anIndex );
590     }
591     aPolyline->SetName( aName );
592   }
593
594   return true;
595 }