Salome HOME
interpolZ.py produces a 3D mesh (with z != 0) by default
[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.IsNull())
260     return;
261   if( aShape.ShapeType()==TopAbs_WIRE )
262   {
263     theWires.push_back( TopoDS::Wire( aShape ) );
264   }
265   else
266   {
267     TopExp_Explorer anExp( aShape, TopAbs_WIRE );
268     for( ; anExp.More(); anExp.Next() )
269     {
270       theWires.push_back( TopoDS::Wire( anExp.Current() ) );
271     }
272   }
273 }
274
275 void HYDROData_PolylineOperator::Split(
276   const TopoDS_Wire& theWire,
277   const gp_Pnt2d& thePoint,
278   double theTolerance,
279   std::vector<TopoDS_Shape>& theWires)
280 {
281   HYDROData_TopoCurve aCurve;
282   if (!aCurve.Initialize(theWire))
283   {
284     theWires.push_back(theWire);
285     return;
286   }
287
288   const gp_XYZ aP(thePoint.X(), thePoint.Y(), 0);
289   std::list<TopoDS_Edge>::const_iterator aEPos;
290   double aParam;
291   aCurve.Project(aP, aEPos, aParam);
292   HYDROData_TopoCurve aCurve1, aCurve2;
293   aCurve.Cut(aEPos, aParam, aCurve1, aCurve2);
294   theWires.push_back(aCurve1.Wire());
295   if (!aCurve2.IsEmpty())
296   {
297     theWires.push_back(aCurve2.Wire());
298   }
299 }
300
301 bool HYDROData_PolylineOperator::CreatePolylines( const Handle( HYDROData_Document )& theDoc,
302                                                   const Handle( HYDROData_PolylineXY )& theOldPolyline,
303                                                   const std::vector<TopoDS_Shape>& theShapes,
304                                                   bool isUseIndices )
305 {
306   if( theDoc.IsNull() )
307     return false;
308
309   if ( theOldPolyline.IsNull() )
310     return false;
311   const QString& theNamePrefix = theOldPolyline->GetName();
312   const QColor& theColor = theOldPolyline->GetWireColor();
313
314   int n = theShapes.size();
315   DEBTRACE("theShapes.size() "<< n);
316   int anIndex = 1;
317   for( int i=0; i<n; i++ )
318   {
319     Handle( HYDROData_PolylineXY ) aPolyline = 
320       Handle( HYDROData_PolylineXY )::DownCast( theDoc->CreateObject( KIND_POLYLINEXY ) );
321     if( aPolyline.IsNull() )
322       return false;
323
324     aPolyline->ImportShape(theShapes[i], false, theOldPolyline, false);
325
326     if( isUseIndices )
327     {
328       QString aNewName = theNamePrefix + "_" + QString::number( anIndex );
329       while( !theDoc->FindObjectByName( aNewName ).IsNull() )  // the object with such a name is not found
330       {
331         anIndex++;
332         aNewName = theNamePrefix + "_" + QString::number( anIndex );
333       }
334       aPolyline->SetName( aNewName );
335     }
336     else
337     {
338       aPolyline->SetName( theNamePrefix );
339     }
340
341     if( theColor.isValid() )
342       aPolyline->SetWireColor( theColor );
343   }
344   return true;
345 }
346
347 double HYDROData_PolylineOperator::ReduceDeflection(
348   const double theDeflection,
349   HYDROData_TopoCurve& theCurve,
350   int& thePieceCount)
351 {
352   // Construct the approximating B-spline.
353   std::list<gp_XYZ> aPs;
354   if (!theCurve.ValuesInKnots(aPs))
355   {
356     return -1;
357   }
358
359   Handle(TColgp_HArray1OfPnt) aPs2 = new TColgp_HArray1OfPnt(1, aPs.size());
360   {
361     std::list<gp_XYZ>::const_iterator aLastPIt = aPs.end();
362     std::list<gp_XYZ>::const_iterator aPIt = aPs.begin();
363     for (int aPN = 1; aPIt != aLastPIt; ++aPN, ++aPIt)
364     {
365       aPs2->SetValue(aPN, *aPIt);
366     }
367   }
368   Handle(Geom_BSplineCurve) aBSpline2;
369   const bool isClosed = theCurve.IsClosed();
370 #ifndef LIGHT_MODE
371   if (!CurveCreator_Utils::constructBSpline(aPs2, isClosed, aBSpline2))
372 #endif
373   {
374     return -1;
375   }
376
377   // Calculate the piece deflections.
378   std::deque<double> aSqDefls;
379   double aMaxSqDefl = 0;
380   std::list<TopoDS_Edge>& aEdges = theCurve.Edges();
381   std::list<TopoDS_Edge>::const_iterator aLastEIt = aEdges.end();
382   {
383     std::list<TopoDS_Edge>::const_iterator aEIt = aEdges.begin();
384     for (int aPrevKCount = 0; aEIt != aLastEIt; ++aEIt)
385     {
386       TopLoc_Location aLoc;
387       double aParams[2];
388       Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
389         BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
390       const int aKCount = aBSpline->NbKnots();
391       for (int aKN = 1; aKN < aKCount; ++aKN)
392       {
393         const double aParam =
394           (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5;
395         const double aParam2 = (aBSpline2->Knot(aPrevKCount + aKN) +
396           aBSpline2->Knot(aPrevKCount + aKN + 1)) * 0.5;
397         const double aSqDefl = Abs(aBSpline->Value(aParam).
398           SquareDistance(aBSpline2->Value(aParam2)));
399         aSqDefls.push_back(aSqDefl);
400         if (aMaxSqDefl < aSqDefl)
401         {
402           aMaxSqDefl = aSqDefl;
403         }
404       }
405       aPrevKCount += aKCount - 1;
406     }
407   }
408
409   // Check whether the reducing is necessary.
410   const double aMaxDefl = Sqrt(aMaxSqDefl);
411   if (aMaxDefl <= theDeflection)
412   {
413     return aMaxDefl;
414   }
415
416   // Reduce the deflections.
417   const double aThresSqDefl =
418     Max(aMaxSqDefl * 0.25, theDeflection * theDeflection);
419   std::list<TopoDS_Edge>::iterator aEIt = aEdges.begin();
420   std::deque<double>::const_iterator aSqDIt = aSqDefls.begin();
421   thePieceCount = 0;
422   for (; aEIt != aLastEIt; ++aEIt)
423   {
424     TopLoc_Location aLoc;
425     double aParams[2];
426     Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
427       BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
428     Handle(Geom_BSplineCurve) aBSpline2 =
429       Handle(Geom_BSplineCurve)::DownCast(aBSpline->Copy());
430     const int aKCount = aBSpline->NbKnots();
431     for (int aKN = 1; aKN < aKCount; ++aSqDIt, ++aKN)
432     {
433       if (*aSqDIt > aThresSqDefl)
434       {
435         aBSpline2->InsertKnot(
436           (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5);
437       }
438     }
439     TopoDS_Edge aEdge;
440     BRep_Builder().MakeEdge(aEdge, aBSpline2, Precision::Confusion());
441     BRep_Builder().Add(aEdge, TopExp::FirstVertex(*aEIt));
442     BRep_Builder().Add(aEdge, TopExp::LastVertex(*aEIt));
443     thePieceCount += aBSpline2->NbKnots() - 1;
444     *aEIt = aEdge;
445   }
446   return aMaxDefl;
447 }
448
449 bool HYDROData_PolylineOperator::Extract( const Handle(HYDROData_Document)& theDocument,
450                                           const Handle(HYDROData_Object)& theObject )
451 {
452   if( theObject.IsNull() || theDocument.IsNull() )
453     return false;
454
455   QList<TopoDS_Shape> aBoundShapes;
456   QStringList aBoundNames;
457   QMap<QString, TopTools_IndexedMapOfShape> aNameToShMap;
458
459   theObject->GetBoundaries( aBoundShapes, aBoundNames );
460
461   for( int i=0, n=aBoundShapes.size(); i<n; i++ )
462   {
463     TopoDS_Shape aShape = aBoundShapes[i];
464     if( aShape.IsNull() )
465       continue;
466
467     QString aBoundName = i<aBoundNames.size() ? aBoundNames[i] : "";
468     
469     if (!aNameToShMap.contains(aBoundName))
470     {
471       TopTools_IndexedMapOfShape IM;
472       IM.Add(aShape);
473       aNameToShMap[aBoundName] = IM;
474     }
475     else
476       aNameToShMap[aBoundName].Add(aShape);
477      
478   }
479
480   foreach( QString K, aNameToShMap.keys() )
481   {
482     const TopTools_IndexedMapOfShape& IM = aNameToShMap.value(K);
483     TopTools_ListOfShape LSE;
484     for (int i = 1; i <= IM.Extent(); i++)
485     {
486       const TopoDS_Edge& E = TopoDS::Edge(IM(i));
487       if (E.IsNull())
488         continue;
489       LSE.Append(E);
490     }
491
492
493     TopoDS_Shape aShapeOut;
494     if (LSE.Extent() == 1)
495     {
496       aShapeOut = LSE.First();
497     }
498     else if (LSE.Extent() > 1)
499     {
500       BRepLib_MakeWire WM;
501       WM.Add(LSE);
502       if (WM.IsDone())
503         aShapeOut = WM.Wire();
504       else
505         continue;
506     }
507     else continue;
508
509     Handle( HYDROData_PolylineXY ) aPolyline = 
510       Handle( HYDROData_PolylineXY )::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
511
512     if( aPolyline.IsNull() )
513       return false;
514
515     aPolyline->SetShape( aShapeOut );
516
517     int anIndex = 0;
518     QString aName = K;
519     while( !theDocument->FindObjectByName( aName ).IsNull() )
520     {
521       anIndex++;
522       aName = K + "_" + QString::number( anIndex );
523     }
524     aPolyline->SetName( aName );
525   }
526
527   return true;
528 }