Salome HOME
Merge branch 'BR_HYDRO_IMPS_2016' of ssh://gitolite3@git.salome-platform.org/modules...
[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   for( int i=0, n=aCurves.size(); i<n; i++ )
90   {
91     std::vector<TopoDS_Shape> aCurvesList;
92     Split( aCurves[i], thePoint, theTolerance, aCurvesList );
93     bool isLocalOK = CreatePolylines( theDoc, thePolyline, aCurvesList, true );
94     isOK = isOK && isLocalOK;
95   }
96   return isOK;
97 }
98
99 bool HYDROData_PolylineOperator::Split( const Handle( HYDROData_Document )& theDoc,
100               const Handle( HYDROData_PolylineXY )& thePolyline,
101               const Handle( HYDROData_PolylineXY )& theTool,
102               double theTolerance,
103               bool& theIsIntersected) const
104 {
105   if (thePolyline.IsNull() || theTool.IsNull())
106   {
107     return false;
108   }
109
110   HYDROData_SequenceOfObjects aSeq;
111   aSeq.Append( theTool );
112   return split( theDoc, thePolyline, aSeq, theTolerance, -1, theIsIntersected);
113 }
114
115 bool HYDROData_PolylineOperator::Split( const Handle( HYDROData_Document )& theDoc,
116                                         const HYDROData_SequenceOfObjects& thePolylines,
117                                         double theTolerance )
118 {
119   int f = thePolylines.Lower(), l = thePolylines.Upper();
120   for( int i=f; i<=l; i++ )
121   {
122     Handle( HYDROData_PolylineXY ) aPolyline = Handle( HYDROData_PolylineXY )::DownCast( thePolylines.Value( i ) );
123     bool isIntersected;
124     if( !split( theDoc, aPolyline, thePolylines, theTolerance, i, isIntersected) )
125       return false;
126   }
127   return true;
128 }
129
130 bool HYDROData_PolylineOperator::Merge( const Handle( HYDROData_Document )& theDoc,
131                                         const QString& theName,
132                                         const HYDROData_SequenceOfObjects& thePolylines,
133                                         bool isConnectByNewSegment,
134                                         double theTolerance )
135 {
136   Handle( HYDROData_PolylineXY ) aNewPolyline =
137     Handle( HYDROData_PolylineXY )::DownCast( theDoc->CreateObject( KIND_POLYLINEXY ) );
138   int ins =0;
139
140   HYDROData_SequenceOfObjects::Iterator aPIt(thePolylines);
141
142   for (int ip=1; aPIt.More(); aPIt.Next(), ip++)
143   {
144     Handle(HYDROData_PolylineXY) aPolyline =
145       Handle(HYDROData_PolylineXY)::DownCast(aPIt.Value());
146     NCollection_Sequence<TCollection_AsciiString>           aSectNames;
147     NCollection_Sequence<HYDROData_PolylineXY::SectionType> aSectTypes;
148     NCollection_Sequence<bool>                              aSectClosures;
149     aPolyline->GetSections( aSectNames, aSectTypes, aSectClosures );
150
151     for ( int i = 1, n = aSectNames.Size(); i <= n; ++i )
152     {
153       const TCollection_AsciiString& aSectName = aSectNames.Value( i ) + "_" + ip;
154       const HYDROData_PolylineXY::SectionType& aSectType = aSectTypes.Value( i );
155       bool aSectClosure = aSectClosures.Value( i );
156       aNewPolyline->AddSection(aSectName, aSectType, aSectClosure);
157       HYDROData_PolylineXY::PointsList aPointsList = aPolyline->GetPoints(i-1, false);
158       aNewPolyline->SetPoints(ins++, aPointsList);
159     }
160   }
161   QString aName = theName;
162   if( aName.isEmpty() )
163     {
164       aName = "merged";
165       int anIndex = 1;
166       QString aNewName = aName + "_" + QString::number(anIndex);
167       while (!theDoc->FindObjectByName(aNewName).IsNull())  // the object with such a name is not found
168         {
169           anIndex++;
170           aNewName = aName + "_" + QString::number(anIndex);
171         }
172       aName = aNewName;
173     }
174
175   aNewPolyline->SetName(aName);
176   aNewPolyline->Update();
177   return true;
178 }
179
180 bool HYDROData_PolylineOperator::split( const Handle( HYDROData_Document )& theDoc,
181                                         const Handle( HYDROData_PolylineXY )& thePolyline,
182                                         const HYDROData_SequenceOfObjects& theTools,
183                                         double theTolerance,
184                                         int theIgnoreIndex,
185                                         bool& theIsIntersected) const
186 {
187   theIsIntersected = false;
188
189   if (thePolyline.IsNull())
190   {
191     return false;
192   }
193
194   std::vector<TopoDS_Wire> aCurves;
195   GetWires(thePolyline, aCurves);
196   std::vector<TopoDS_Wire> aToolCurves;
197   for( int i=theTools.Lower(), n=theTools.Upper(); i<=n; i++ )
198     if( i!=theIgnoreIndex )
199     {
200       Handle( HYDROData_PolylineXY ) aToolPolyline = 
201         Handle( HYDROData_PolylineXY )::DownCast( theTools.Value( i ) );
202       if (!aToolPolyline.IsNull())
203       {
204         std::vector<TopoDS_Wire> aTCurves;
205         GetWires(aToolPolyline, aTCurves);
206         append( aToolCurves, aTCurves);
207       }
208     }
209
210   if (aToolCurves.empty())
211   {
212     return false;
213   }
214
215   const int aPSCount = aCurves.size();
216   const int aTSCount = aToolCurves.size();
217   std::vector<TopoDS_Shape> aResult;
218   for (int aPSI = 0; aPSI < aPSCount; ++aPSI)
219   {
220     HYDROData_TopoCurve aCurve;
221     //DEBTRACE("Initialize curve " << aPSI);
222     if (!aCurve.Initialize(aCurves[aPSI]))
223     {
224       continue;
225     }
226
227     std::deque<std::list<double> > aParams;
228     for (int aTSI = 0; aTSI < aTSCount; ++aTSI)
229     {
230       aCurve.Intersect(aToolCurves[aTSI], aParams);
231     }
232
233     std::deque<HYDROData_TopoCurve> aSplitCurves;
234     theIsIntersected |= aCurve.Cut(aParams, aSplitCurves);
235     std::deque<HYDROData_TopoCurve>::const_iterator aCIt =
236       aSplitCurves.begin();
237     std::deque<HYDROData_TopoCurve>::const_iterator aLastCIt =
238       aSplitCurves.end();
239     for (int iw=0; aCIt != aLastCIt; ++aCIt, iw++)
240     {
241       /*std::stringstream brepName;
242       brepName << "theSplitWire_";
243       brepName << iw;
244       brepName << ".brep";
245       BRepTools::Write(aCIt->Wire() , brepName.str().c_str() );*/
246       aResult.push_back(aCIt->Wire());
247     }
248   }
249
250   CreatePolylines( theDoc, thePolyline, aResult, true );
251   return true;
252 }
253
254 void HYDROData_PolylineOperator::GetWires(
255   const Handle( HYDROData_PolylineXY )& thePolyline,
256   std::vector<TopoDS_Wire>& theWires)
257 {
258   TopoDS_Shape aShape = thePolyline->GetShape();
259   if( aShape.ShapeType()==TopAbs_WIRE )
260   {
261     theWires.push_back( TopoDS::Wire( aShape ) );
262   }
263   else
264   {
265     TopExp_Explorer anExp( aShape, TopAbs_WIRE );
266     for( ; anExp.More(); anExp.Next() )
267     {
268       theWires.push_back( TopoDS::Wire( anExp.Current() ) );
269     }
270   }
271 }
272
273 void HYDROData_PolylineOperator::Split(
274   const TopoDS_Wire& theWire,
275   const gp_Pnt2d& thePoint,
276   double theTolerance,
277   std::vector<TopoDS_Shape>& theWires)
278 {
279   HYDROData_TopoCurve aCurve;
280   if (!aCurve.Initialize(theWire))
281   {
282     theWires.push_back(theWire);
283     return;
284   }
285
286   const gp_XYZ aP(thePoint.X(), thePoint.Y(), 0);
287   std::list<TopoDS_Edge>::const_iterator aEPos;
288   double aParam;
289   aCurve.Project(aP, aEPos, aParam);
290   HYDROData_TopoCurve aCurve1, aCurve2;
291   aCurve.Cut(aEPos, aParam, aCurve1, aCurve2);
292   theWires.push_back(aCurve1.Wire());
293   if (!aCurve2.IsEmpty())
294   {
295     theWires.push_back(aCurve2.Wire());
296   }
297 }
298
299 bool HYDROData_PolylineOperator::CreatePolylines( const Handle( HYDROData_Document )& theDoc,
300                                                   const Handle( HYDROData_PolylineXY )& theOldPolyline,
301                                                   const std::vector<TopoDS_Shape>& theShapes,
302                                                   bool isUseIndices )
303 {
304   if( theDoc.IsNull() )
305     return false;
306
307   if ( theOldPolyline.IsNull() )
308     return false;
309   const QString& theNamePrefix = theOldPolyline->GetName();
310   const QColor& theColor = theOldPolyline->GetWireColor();
311
312   int n = theShapes.size();
313   //DEBTRACE("theShapes.size() "<< n);
314   int anIndex = 1;
315   for( int i=0; i<n; i++ )
316   {
317     Handle( HYDROData_PolylineXY ) aPolyline = 
318       Handle( HYDROData_PolylineXY )::DownCast( theDoc->CreateObject( KIND_POLYLINEXY ) );
319     if( aPolyline.IsNull() )
320       return false;
321
322     aPolyline->ImportShape(theShapes[i], false, theOldPolyline, false);
323
324     if( isUseIndices )
325     {
326       QString aNewName = theNamePrefix + "_" + QString::number( anIndex );
327       while( !theDoc->FindObjectByName( aNewName ).IsNull() )  // the object with such a name is not found
328       {
329         anIndex++;
330         aNewName = theNamePrefix + "_" + QString::number( anIndex );
331       }
332       aPolyline->SetName( aNewName );
333     }
334     else
335     {
336       aPolyline->SetName( theNamePrefix );
337     }
338
339     if( theColor.isValid() )
340       aPolyline->SetWireColor( theColor );
341   }
342   return true;
343 }
344
345 double HYDROData_PolylineOperator::ReduceDeflection(
346   const double theDeflection,
347   HYDROData_TopoCurve& theCurve,
348   int& thePieceCount)
349 {
350   // Construct the approximating B-spline.
351   std::list<gp_XYZ> aPs;
352   if (!theCurve.ValuesInKnots(aPs))
353   {
354     return -1;
355   }
356
357   Handle(TColgp_HArray1OfPnt) aPs2 = new TColgp_HArray1OfPnt(1, aPs.size());
358   {
359     std::list<gp_XYZ>::const_iterator aLastPIt = aPs.end();
360     std::list<gp_XYZ>::const_iterator aPIt = aPs.begin();
361     for (int aPN = 1; aPIt != aLastPIt; ++aPN, ++aPIt)
362     {
363       aPs2->SetValue(aPN, *aPIt);
364     }
365   }
366   Handle(Geom_BSplineCurve) aBSpline2;
367   const bool isClosed = theCurve.IsClosed();
368 #ifndef LIGHT_MODE
369   if (!CurveCreator_Utils::constructBSpline(aPs2, isClosed, aBSpline2))
370 #endif
371   {
372     return -1;
373   }
374
375   // Calculate the piece deflections.
376   std::deque<double> aSqDefls;
377   double aMaxSqDefl = 0;
378   std::list<TopoDS_Edge>& aEdges = theCurve.Edges();
379   std::list<TopoDS_Edge>::const_iterator aLastEIt = aEdges.end();
380   {
381     std::list<TopoDS_Edge>::const_iterator aEIt = aEdges.begin();
382     for (int aPrevKCount = 0; aEIt != aLastEIt; ++aEIt)
383     {
384       TopLoc_Location aLoc;
385       double aParams[2];
386       Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
387         BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
388       const int aKCount = aBSpline->NbKnots();
389       for (int aKN = 1; aKN < aKCount; ++aKN)
390       {
391         const double aParam =
392           (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5;
393         const double aParam2 = (aBSpline2->Knot(aPrevKCount + aKN) +
394           aBSpline2->Knot(aPrevKCount + aKN + 1)) * 0.5;
395         const double aSqDefl = Abs(aBSpline->Value(aParam).
396           SquareDistance(aBSpline2->Value(aParam2)));
397         aSqDefls.push_back(aSqDefl);
398         if (aMaxSqDefl < aSqDefl)
399         {
400           aMaxSqDefl = aSqDefl;
401         }
402       }
403       aPrevKCount += aKCount - 1;
404     }
405   }
406
407   // Check whether the reducing is necessary.
408   const double aMaxDefl = Sqrt(aMaxSqDefl);
409   if (aMaxDefl <= theDeflection)
410   {
411     return aMaxDefl;
412   }
413
414   // Reduce the deflections.
415   const double aThresSqDefl =
416     Max(aMaxSqDefl * 0.25, theDeflection * theDeflection);
417   std::list<TopoDS_Edge>::iterator aEIt = aEdges.begin();
418   std::deque<double>::const_iterator aSqDIt = aSqDefls.begin();
419   thePieceCount = 0;
420   for (; aEIt != aLastEIt; ++aEIt)
421   {
422     TopLoc_Location aLoc;
423     double aParams[2];
424     Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
425       BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
426     Handle(Geom_BSplineCurve) aBSpline2 =
427       Handle(Geom_BSplineCurve)::DownCast(aBSpline->Copy());
428     const int aKCount = aBSpline->NbKnots();
429     for (int aKN = 1; aKN < aKCount; ++aSqDIt, ++aKN)
430     {
431       if (*aSqDIt > aThresSqDefl)
432       {
433         aBSpline2->InsertKnot(
434           (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5);
435       }
436     }
437     TopoDS_Edge aEdge;
438     BRep_Builder().MakeEdge(aEdge, aBSpline2, Precision::Confusion());
439     BRep_Builder().Add(aEdge, TopExp::FirstVertex(*aEIt));
440     BRep_Builder().Add(aEdge, TopExp::LastVertex(*aEIt));
441     thePieceCount += aBSpline2->NbKnots() - 1;
442     *aEIt = aEdge;
443   }
444   return aMaxDefl;
445 }
446
447 bool HYDROData_PolylineOperator::Extract( const Handle(HYDROData_Document)& theDocument,
448                                           const Handle(HYDROData_Object)& theObject )
449 {
450   if( theObject.IsNull() || theDocument.IsNull() )
451     return false;
452
453   QList<TopoDS_Shape> aBoundShapes;
454   QStringList aBoundNames;
455   QMap<QString, TopTools_IndexedMapOfShape> aNameToShMap;
456
457   theObject->GetBoundaries( aBoundShapes, aBoundNames );
458
459   for( int i=0, n=aBoundShapes.size(); i<n; i++ )
460   {
461     TopoDS_Shape aShape = aBoundShapes[i];
462     if( aShape.IsNull() )
463       continue;
464
465     QString aBoundName = i<aBoundNames.size() ? aBoundNames[i] : "";
466     
467     if (!aNameToShMap.contains(aBoundName))
468     {
469       TopTools_IndexedMapOfShape IM;
470       IM.Add(aShape);
471       aNameToShMap[aBoundName] = IM;
472     }
473     else
474       aNameToShMap[aBoundName].Add(aShape);
475      
476   }
477
478   foreach( QString K, aNameToShMap.keys() )
479   {
480     const TopTools_IndexedMapOfShape& IM = aNameToShMap.value(K);
481     TopTools_ListOfShape LSE;
482     for (int i = 1; i <= IM.Extent(); i++)
483     {
484       const TopoDS_Edge& E = TopoDS::Edge(IM(i));
485       if (E.IsNull())
486         continue;
487       LSE.Append(E);
488     }
489
490     BRepLib_MakeWire WM;
491     WM.Add(LSE);
492     TopoDS_Shape aShapeW;
493     if (WM.IsDone())
494       aShapeW = WM.Wire();
495     else
496       continue;
497
498     Handle( HYDROData_PolylineXY ) aPolyline = 
499       Handle( HYDROData_PolylineXY )::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
500
501     if( aPolyline.IsNull() )
502       return false;
503
504     aPolyline->SetShape( aShapeW );
505
506     int anIndex = 0;
507     QString aName = K;
508     while( !theDocument->FindObjectByName( aName ).IsNull() )
509     {
510       anIndex++;
511       aName = K + "_" + QString::number( anIndex );
512     }
513     aPolyline->SetName( aName );
514   }
515
516   return true;
517 }