Salome HOME
export of 3D poly to SHP (lot 5)
[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
251
252   const int aPSCount = aCurves.size();
253   const int aTSCount = aToolCurves.size();
254   std::vector<TopoDS_Shape> aResult;
255
256   bool bSetColor = aPSCount == nbSec;
257   if (bSetColor)
258   {
259     for (int i = 0; i < nbSec; i++)
260     {
261       QColor aColor;
262       thePolyline->GetSectionColor(i, aColor);
263       aSectColors.push_back(aColor);
264     }
265   }
266   NCollection_DataMap <TopoDS_Shape, QColor, TopTools_ShapeMapHasher> W2Color;
267
268   for (int aPSI = 0; aPSI < aPSCount; ++aPSI)
269   {
270     HYDROData_TopoCurve aCurve;
271     DEBTRACE("Initialize curve " << aPSI);
272     if (!aCurve.Initialize(aCurves[aPSI]))
273     {
274       continue;
275     }
276
277     std::deque<std::list<double> > aParams;
278     for (int aTSI = 0; aTSI < aTSCount; ++aTSI)
279     {
280       aCurve.Intersect(aToolCurves[aTSI], aParams);
281     }
282
283     std::deque<HYDROData_TopoCurve> aSplitCurves;
284     theIsIntersected |= aCurve.Cut(aParams, aSplitCurves);
285     std::deque<HYDROData_TopoCurve>::const_iterator aCIt =
286       aSplitCurves.begin();
287     std::deque<HYDROData_TopoCurve>::const_iterator aLastCIt =
288       aSplitCurves.end();
289     for (int iw=0; aCIt != aLastCIt; ++aCIt, iw++)
290     {
291       //std::stringstream brepName;
292       //brepName << "theSplitWire_";
293       //brepName << iw;
294       //brepName << ".brep";
295       //BRepTools::Write(aCIt->Wire() , brepName.str().c_str() );
296       const TopoDS_Wire& aW = aCIt->Wire();
297       if (bSetColor)
298         W2Color.Bind(aW, aSectColors[aPSI]);
299       aResult.push_back(aW);
300     }
301   }
302
303   NCollection_IndexedDataMap<Handle(HYDROData_PolylineXY), TopoDS_Shape> outPoly2Sh;
304   CreatePolylines( theDoc, thePolyline, aResult, true, outPoly2Sh );
305   
306   for (int j=1;j<=outPoly2Sh.Extent();j++)
307   {
308     const Handle(HYDROData_PolylineXY)& Poly = outPoly2Sh.FindKey(j); 
309     const TopoDS_Shape& Sh = outPoly2Sh.FindFromIndex(j); 
310
311     int nbSec = Poly->NbSections();
312     for (int k = 0; k < nbSec; k++)
313     {
314       const QColor* color = W2Color.Seek(Sh);
315       if (color)
316         Poly->SetSectionColor(k, *color);
317     }
318   }
319   
320   return true;
321 }
322
323 void HYDROData_PolylineOperator::GetWires(
324   const Handle( HYDROData_PolylineXY )& thePolyline,
325   std::vector<TopoDS_Wire>& theWires)
326 {
327   TopoDS_Shape aShape = thePolyline->GetShape();
328   if (aShape.IsNull())
329     return;
330   if( aShape.ShapeType()==TopAbs_WIRE )
331   {
332     theWires.push_back( TopoDS::Wire( aShape ) );
333   }
334   else
335   {
336     TopExp_Explorer anExp( aShape, TopAbs_WIRE );
337     for( ; anExp.More(); anExp.Next() )
338     {
339       theWires.push_back( TopoDS::Wire( anExp.Current() ) );
340     }
341   }
342 }
343
344 void HYDROData_PolylineOperator::Split(
345   const TopoDS_Wire& theWire,
346   const gp_Pnt2d& thePoint,
347   double theTolerance,
348   std::vector<TopoDS_Shape>& theWires)
349 {
350   HYDROData_TopoCurve aCurve;
351   if (!aCurve.Initialize(theWire))
352   {
353     theWires.push_back(theWire);
354     return;
355   }
356
357   const gp_XYZ aP(thePoint.X(), thePoint.Y(), 0);
358   std::list<TopoDS_Edge>::const_iterator aEPos;
359   double aParam;
360   aCurve.Project(aP, aEPos, aParam);
361   HYDROData_TopoCurve aCurve1, aCurve2;
362   aCurve.Cut(aEPos, aParam, aCurve1, aCurve2);
363   theWires.push_back(aCurve1.Wire());
364   if (!aCurve2.IsEmpty())
365   {
366     theWires.push_back(aCurve2.Wire());
367   }
368 }
369
370 bool HYDROData_PolylineOperator::CreatePolylines( const Handle( HYDROData_Document )& theDoc,
371                                                   const Handle( HYDROData_PolylineXY )& theOldPolyline,
372                                                   const std::vector<TopoDS_Shape>& theShapes,
373                                                   bool isUseIndices,
374                                                   NCollection_IndexedDataMap<Handle(HYDROData_PolylineXY), TopoDS_Shape>& outPoly2Sh)
375 {
376   if( theDoc.IsNull() )
377     return false;
378
379   if ( theOldPolyline.IsNull() )
380     return false;
381   const QString& theNamePrefix = theOldPolyline->GetName();
382
383   int n = theShapes.size();
384   DEBTRACE("theShapes.size() "<< n);
385   int anIndex = 1;
386   for( int i=0; i<n; i++ )
387   {
388     Handle( HYDROData_PolylineXY ) aPolyline = 
389       Handle( HYDROData_PolylineXY )::DownCast( theDoc->CreateObject( KIND_POLYLINEXY ) );
390     if( aPolyline.IsNull() )
391       return false;
392
393     aPolyline->ImportShape(theShapes[i], false, theOldPolyline, false);
394
395     if( isUseIndices )
396     {
397       QString aNewName = theNamePrefix + "_" + QString::number( anIndex );
398       while( !theDoc->FindObjectByName( aNewName ).IsNull() )  // the object with such a name is not found
399       {
400         anIndex++;
401         aNewName = theNamePrefix + "_" + QString::number( anIndex );
402       }
403       aPolyline->SetName( aNewName );
404     }
405     else
406     {
407       aPolyline->SetName( theNamePrefix );
408     }
409
410     outPoly2Sh.Add(aPolyline, theShapes[i]);
411   }
412   return true;
413 }
414
415 double HYDROData_PolylineOperator::ReduceDeflection(
416   const double theDeflection,
417   HYDROData_TopoCurve& theCurve,
418   int& thePieceCount)
419 {
420   // Construct the approximating B-spline.
421   std::list<gp_XYZ> aPs;
422   if (!theCurve.ValuesInKnots(aPs))
423   {
424     return -1;
425   }
426
427   Handle(TColgp_HArray1OfPnt) aPs2 = new TColgp_HArray1OfPnt(1, aPs.size());
428   {
429     std::list<gp_XYZ>::const_iterator aLastPIt = aPs.end();
430     std::list<gp_XYZ>::const_iterator aPIt = aPs.begin();
431     for (int aPN = 1; aPIt != aLastPIt; ++aPN, ++aPIt)
432     {
433       aPs2->SetValue(aPN, *aPIt);
434     }
435   }
436   Handle(Geom_BSplineCurve) aBSpline2;
437   const bool isClosed = theCurve.IsClosed();
438 #ifndef LIGHT_MODE
439   if (!CurveCreator_Utils::constructBSpline(aPs2, isClosed, aBSpline2))
440 #endif
441   {
442     return -1;
443   }
444
445   // Calculate the piece deflections.
446   std::deque<double> aSqDefls;
447   double aMaxSqDefl = 0;
448   std::list<TopoDS_Edge>& aEdges = theCurve.Edges();
449   std::list<TopoDS_Edge>::const_iterator aLastEIt = aEdges.end();
450   {
451     std::list<TopoDS_Edge>::const_iterator aEIt = aEdges.begin();
452     for (int aPrevKCount = 0; aEIt != aLastEIt; ++aEIt)
453     {
454       TopLoc_Location aLoc;
455       double aParams[2];
456       Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
457         BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
458       const int aKCount = aBSpline->NbKnots();
459       for (int aKN = 1; aKN < aKCount; ++aKN)
460       {
461         const double aParam =
462           (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5;
463         const double aParam2 = (aBSpline2->Knot(aPrevKCount + aKN) +
464           aBSpline2->Knot(aPrevKCount + aKN + 1)) * 0.5;
465         const double aSqDefl = Abs(aBSpline->Value(aParam).
466           SquareDistance(aBSpline2->Value(aParam2)));
467         aSqDefls.push_back(aSqDefl);
468         if (aMaxSqDefl < aSqDefl)
469         {
470           aMaxSqDefl = aSqDefl;
471         }
472       }
473       aPrevKCount += aKCount - 1;
474     }
475   }
476
477   // Check whether the reducing is necessary.
478   const double aMaxDefl = Sqrt(aMaxSqDefl);
479   if (aMaxDefl <= theDeflection)
480   {
481     return aMaxDefl;
482   }
483
484   // Reduce the deflections.
485   const double aThresSqDefl =
486     Max(aMaxSqDefl * 0.25, theDeflection * theDeflection);
487   std::list<TopoDS_Edge>::iterator aEIt = aEdges.begin();
488   std::deque<double>::const_iterator aSqDIt = aSqDefls.begin();
489   thePieceCount = 0;
490   for (; aEIt != aLastEIt; ++aEIt)
491   {
492     TopLoc_Location aLoc;
493     double aParams[2];
494     Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
495       BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
496     Handle(Geom_BSplineCurve) aBSpline2 =
497       Handle(Geom_BSplineCurve)::DownCast(aBSpline->Copy());
498     const int aKCount = aBSpline->NbKnots();
499     for (int aKN = 1; aKN < aKCount; ++aSqDIt, ++aKN)
500     {
501       if (*aSqDIt > aThresSqDefl)
502       {
503         aBSpline2->InsertKnot(
504           (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5);
505       }
506     }
507     TopoDS_Edge aEdge;
508     BRep_Builder().MakeEdge(aEdge, aBSpline2, Precision::Confusion());
509     BRep_Builder().Add(aEdge, TopExp::FirstVertex(*aEIt));
510     BRep_Builder().Add(aEdge, TopExp::LastVertex(*aEIt));
511     thePieceCount += aBSpline2->NbKnots() - 1;
512     *aEIt = aEdge;
513   }
514   return aMaxDefl;
515 }
516
517 bool HYDROData_PolylineOperator::Extract( const Handle(HYDROData_Document)& theDocument,
518                                           const Handle(HYDROData_Object)& theObject )
519 {
520   if( theObject.IsNull() || theDocument.IsNull() )
521     return false;
522
523   QList<TopoDS_Shape> aBoundShapes;
524   QStringList aBoundNames;
525   QMap<QString, TopTools_IndexedMapOfShape> aNameToShMap;
526
527   theObject->GetBoundaries( aBoundShapes, aBoundNames );
528
529   for( int i=0, n=aBoundShapes.size(); i<n; i++ )
530   {
531     TopoDS_Shape aShape = aBoundShapes[i];
532     if( aShape.IsNull() )
533       continue;
534
535     QString aBoundName = i<aBoundNames.size() ? aBoundNames[i] : "";
536     
537     if (!aNameToShMap.contains(aBoundName))
538     {
539       TopTools_IndexedMapOfShape IM;
540       IM.Add(aShape);
541       aNameToShMap[aBoundName] = IM;
542     }
543     else
544       aNameToShMap[aBoundName].Add(aShape);
545      
546   }
547
548   foreach( QString K, aNameToShMap.keys() )
549   {
550     const TopTools_IndexedMapOfShape& IM = aNameToShMap.value(K);
551     TopTools_ListOfShape LSE;
552     for (int i = 1; i <= IM.Extent(); i++)
553     {
554       const TopoDS_Edge& E = TopoDS::Edge(IM(i));
555       if (E.IsNull())
556         continue;
557       LSE.Append(E);
558     }
559
560
561     TopoDS_Shape aShapeOut;
562     if (LSE.Extent() == 1)
563     {
564       aShapeOut = LSE.First();
565     }
566     else if (LSE.Extent() > 1)
567     {
568       BRepLib_MakeWire WM;
569       WM.Add(LSE);
570       if (WM.IsDone())
571         aShapeOut = WM.Wire();
572       else
573         continue;
574     }
575     else continue;
576
577     Handle( HYDROData_PolylineXY ) aPolyline = 
578       Handle( HYDROData_PolylineXY )::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
579
580     if( aPolyline.IsNull() )
581       return false;
582
583     aPolyline->SetShape( aShapeOut );
584
585     int anIndex = 0;
586     QString aName = K;
587     while( !theDocument->FindObjectByName( aName ).IsNull() )
588     {
589       anIndex++;
590       aName = K + "_" + QString::number( anIndex );
591     }
592     aPolyline->SetName( aName );
593   }
594
595   return true;
596 }