Salome HOME
796c50b55d3d87d3445b770927bc7432dcf85da8
[modules/shaper.git] / src / GeomAlgoAPI / GeomAlgoAPI_Pipe.cpp
1 // Copyright (C) 2014-2022  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "GeomAlgoAPI_Pipe.h"
21
22 #include "GeomAlgoAPI_DFLoader.h"
23
24 #include <GeomAPI_Dir.h>
25 #include <GeomAPI_Edge.h>
26 #include <GeomAPI_Lin.h>
27 #include <GeomAPI_ShapeExplorer.h>
28
29 #include <BRep_Tool.hxx>
30 #include <BRepExtrema_DistShapeShape.hxx>
31 #include <BRepOffsetAPI_MakePipe.hxx>
32 #include <BRepOffsetAPI_MakePipeShell.hxx>
33 #include <BRepBuilderAPI_MakeWire.hxx>
34 #include <BOPAlgo_ArgumentAnalyzer.hxx>
35 #include <Geom_Curve.hxx>
36 #include <Geom_Line.hxx>
37 #include <gp_Lin.hxx>
38 #include <NCollection_List.hxx>
39 #include <TopExp.hxx>
40 #include <TopExp_Explorer.hxx>
41 #include <TopoDS.hxx>
42 #include <TopoDS_Shape.hxx>
43 #include <Precision.hxx>
44
45 static bool getBase(TopoDS_Shape& theBaseOut,
46                     TopAbs_ShapeEnum& theBaseTypeOut,
47                     const GeomShapePtr theBaseShape);
48 static bool getPath(TopoDS_Wire& thePathOut,
49                     const GeomShapePtr thePathShape);
50 static gp_Trsf getPathToBaseTranslation(const TopoDS_Shape& theBase,
51                                         const TopoDS_Shape& thePath);
52 static bool buildPipe(BRepOffsetAPI_MakePipeShell* thePipeBuilder);
53 static ListOfShape getListFromShape(const TopoDS_Shape& theShape);
54
55 //==================================================================================================
56 GeomAlgoAPI_Pipe::GeomAlgoAPI_Pipe(const GeomShapePtr theBaseShape,
57                                    const GeomShapePtr thePathShape)
58 {
59   build(theBaseShape, thePathShape);
60 }
61
62 //==================================================================================================
63 GeomAlgoAPI_Pipe::GeomAlgoAPI_Pipe(const GeomShapePtr theBaseShape,
64                                    const GeomShapePtr thePathShape,
65                                    const GeomShapePtr theBiNormal)
66 {
67   build(theBaseShape, thePathShape, theBiNormal);
68 }
69
70 //==================================================================================================
71 GeomAlgoAPI_Pipe::GeomAlgoAPI_Pipe(const ListOfShape& theBaseShapes,
72                                    const ListOfShape& theLocations,
73                                    const GeomShapePtr thePathShape)
74 {
75   build(theBaseShapes, theLocations, thePathShape);
76 }
77
78 //==================================================================================================
79 void GeomAlgoAPI_Pipe::build(const GeomShapePtr theBaseShape,
80                              const GeomShapePtr thePathShape)
81 {
82   // Getting base shape.
83   if(!theBaseShape.get()) {
84     return;
85   }
86   TopoDS_Shape aBaseShape = theBaseShape->impl<TopoDS_Shape>();
87   if(aBaseShape.IsNull()) {
88     return;
89   }
90   TopAbs_ShapeEnum aBaseShapeType = aBaseShape.ShapeType();
91   if(aBaseShapeType != TopAbs_VERTEX && aBaseShapeType != TopAbs_EDGE &&
92      aBaseShapeType != TopAbs_WIRE && aBaseShapeType != TopAbs_FACE &&
93      aBaseShapeType != TopAbs_SHELL && aBaseShapeType != TopAbs_COMPOUND) {
94     return;
95   }
96
97   // Getting path.
98   TopoDS_Wire aPathWire;
99   if(!getPath(aPathWire, thePathShape)) {
100     return;
101   }
102   GeomShapePtr anOldPath(new GeomAPI_Shape), aNewPath(new GeomAPI_Shape);
103   anOldPath->setImpl(new TopoDS_Shape(aPathWire));
104   aPathWire.Move(getPathToBaseTranslation(aBaseShape, aPathWire));
105   aNewPath->setImpl(new TopoDS_Shape(aPathWire));
106   if (!anOldPath->isSame(aNewPath))
107     addMovedPath(anOldPath, aNewPath);
108
109   // Making pipe.
110   BRepOffsetAPI_MakePipe* aPipeBuilder = NULL;
111   try {
112     aPipeBuilder = new BRepOffsetAPI_MakePipe(aPathWire, aBaseShape);
113   }
114   catch (...) {
115   }
116
117   // Checking result.
118   bool isDone = false;
119   static const Standard_Real TolPipeSurf = 5.e-4;
120   if (aPipeBuilder &&
121       aPipeBuilder->IsDone() &&
122       !aPipeBuilder->Shape().IsNull() &&
123       aPipeBuilder->ErrorOnSurface() <= TolPipeSurf) {
124     // check result
125     BOPAlgo_ArgumentAnalyzer aChecker;
126     aChecker.SetShape1(aPipeBuilder->Shape());
127     aChecker.SelfInterMode() = Standard_True;
128     aChecker.StopOnFirstFaulty() = Standard_True;
129     aChecker.Perform();
130     if (!aChecker.HasFaulty())
131       isDone = true;
132   }
133
134   if (!isDone) {
135     if (aPipeBuilder)
136       delete aPipeBuilder;
137
138     // Try to use Descrete Trihedron mode.
139     aPipeBuilder = new BRepOffsetAPI_MakePipe
140       (aPathWire, aBaseShape, GeomFill_IsDiscreteTrihedron, Standard_True);
141     if (!aPipeBuilder->IsDone() || aPipeBuilder->Shape().IsNull()) {
142       myError = "Pipe algorithm has failed.";
143       delete aPipeBuilder;
144       return;
145     }
146
147     // Check for self-interfering result
148     BOPAlgo_ArgumentAnalyzer aChecker;
149     aChecker.SetShape1(aPipeBuilder->Shape());
150     aChecker.SelfInterMode() = Standard_True;
151     aChecker.StopOnFirstFaulty() = Standard_True;
152     aChecker.Perform();
153     if (aChecker.HasFaulty()) {
154       myError = "Self-interfering result.";
155       delete aPipeBuilder;
156       return;
157     }
158   }
159
160   this->initialize(aPipeBuilder);
161
162   // Setting naming.
163   this->setToShapes(getListFromShape(aPipeBuilder->LastShape()));
164   this->setFromShapes(getListFromShape(aPipeBuilder->FirstShape()));
165
166   // Setting result.
167   TopoDS_Shape aResult = aPipeBuilder->Shape();
168   aResult = GeomAlgoAPI_DFLoader::refineResult(aResult);
169   GeomShapePtr aGeomSh(new GeomAPI_Shape());
170   aGeomSh->setImpl(new TopoDS_Shape(aResult));
171   this->setShape(aGeomSh);
172   this->setDone(true);
173 }
174
175 //==================================================================================================
176 void GeomAlgoAPI_Pipe::build(const GeomShapePtr theBaseShape,
177                              const GeomShapePtr thePathShape,
178                              const GeomShapePtr theBiNormal)
179 {
180   // Getting base shape and path.
181   TopoDS_Shape aBaseShape;
182   TopAbs_ShapeEnum aBaseShapeType;
183   TopoDS_Wire aPathWire;
184   if (!getBase(aBaseShape, aBaseShapeType, theBaseShape) ||
185       !getPath(aPathWire, thePathShape) ||
186       !theBiNormal.get()) {
187     return;
188   }
189
190   GeomShapePtr anOldPath(new GeomAPI_Shape), aNewPath(new GeomAPI_Shape);
191   anOldPath->setImpl(new TopoDS_Shape(aPathWire));
192   aPathWire.Move(getPathToBaseTranslation(theBaseShape->impl<TopoDS_Shape>(), aPathWire));
193   aNewPath->setImpl(new TopoDS_Shape(aPathWire));
194   if (!anOldPath->isSame(aNewPath))
195     addMovedPath(anOldPath, aNewPath);
196
197   // Getting Bi-Normal.
198   TopoDS_Shape aBiNormalShape = theBiNormal->impl<TopoDS_Shape>();
199   if(aBiNormalShape.IsNull() || aBiNormalShape.ShapeType() != TopAbs_EDGE) {
200     return;
201   }
202   TopoDS_Edge aBiNormalEdge = TopoDS::Edge(aBiNormalShape);
203   Standard_Real aFirst, aLast;
204   Handle(Geom_Curve) aBiNormalCurve = BRep_Tool::Curve(aBiNormalEdge, aFirst, aLast);
205   Handle(Geom_Line) aBiNormalLine = Handle(Geom_Line)::DownCast(aBiNormalCurve);
206   if(aBiNormalLine.IsNull()) {
207     return;
208   }
209   gp_Dir aBiNormalDir = aBiNormalLine->Lin().Direction();
210
211   // Making pipe.
212   BRepOffsetAPI_MakePipeShell* aPipeBuilder = new BRepOffsetAPI_MakePipeShell(aPathWire);
213   if(!aPipeBuilder) {
214     return;
215   }
216   aPipeBuilder->Add(aBaseShape);
217   aPipeBuilder->SetMode(aBiNormalDir);
218   if(!buildPipe(aPipeBuilder)) {
219     delete aPipeBuilder;
220     return;
221   }
222   this->initialize(aPipeBuilder);
223
224   // Checking result.
225   if(aBaseShapeType == TopAbs_FACE && !aPipeBuilder->MakeSolid()) {
226     return;
227   }
228   TopoDS_Shape aResult = aPipeBuilder->Shape();
229   if(aResult.IsNull()) {
230     return;
231   }
232
233   // Setting naming.
234   this->setToShapes(getListFromShape(aPipeBuilder->LastShape()));
235   this->setFromShapes(getListFromShape(aPipeBuilder->FirstShape()));
236
237   // Setting result.
238   aResult = GeomAlgoAPI_DFLoader::refineResult(aResult);
239   GeomShapePtr aGeomSh(new GeomAPI_Shape());
240   aGeomSh->setImpl(new TopoDS_Shape(aResult));
241   this->setShape(aGeomSh);
242   this->setDone(true);
243 }
244
245 //==================================================================================================
246 void GeomAlgoAPI_Pipe::build(const ListOfShape& theBaseShapes,
247                              const ListOfShape& theLocations,
248                              const GeomShapePtr thePathShape)
249 {
250   if(theBaseShapes.empty() ||
251      (!theLocations.empty() && theLocations.size() != theBaseShapes.size())) {
252     return;
253   }
254
255   // Getting base shape and path.
256   TopoDS_Shape aBaseShape;
257   TopAbs_ShapeEnum aBaseShapeType;
258   TopoDS_Wire aPathWire;
259   if (!getBase(aBaseShape, aBaseShapeType, theBaseShapes.front()) ||
260       !getPath(aPathWire, thePathShape)) {
261     return;
262   }
263
264   TopoDS_Shape aReallyBase = theBaseShapes.front()->impl<TopoDS_Shape>();
265   gp_Trsf aTrsf = getPathToBaseTranslation(aReallyBase, aPathWire);
266
267   GeomShapePtr anOldPath(new GeomAPI_Shape), aNewPath(new GeomAPI_Shape);
268   anOldPath->setImpl(new TopoDS_Shape(aPathWire));
269   aPathWire.Move(aTrsf);
270   aNewPath->setImpl(new TopoDS_Shape(aPathWire));
271   if (!anOldPath->isSame(aNewPath))
272     addMovedPath(anOldPath, aNewPath);
273
274   // Get locations after moving path shape.
275   std::list<TopoDS_Vertex> aLocations;
276   for (ListOfShape::const_iterator aLocIt = theLocations.cbegin();
277        aLocIt != theLocations.cend();
278        ++aLocIt)
279   {
280     GeomShapePtr aLocation = *aLocIt;
281     if (!aLocation.get() || aLocation->shapeType() != GeomAPI_Shape::VERTEX) {
282       return;
283     }
284
285     TopoDS_Vertex aLocationVertex = aLocation->impl<TopoDS_Vertex>();
286     TopoDS_Vertex aMovedVertex;
287     for (TopExp_Explorer anExp(aPathWire, TopAbs_VERTEX); anExp.More(); anExp.Next()) {
288       if (anExp.Current().IsPartner(aLocationVertex)) {
289         aMovedVertex = TopoDS::Vertex(anExp.Current());
290         aLocations.push_back(aMovedVertex);
291         break;
292       }
293     }
294     if (aMovedVertex.IsNull()) {
295       return;
296     }
297   }
298
299   if (theLocations.size() != aLocations.size()) {
300     return;
301   }
302
303   bool aHasLocations = !aLocations.empty();
304
305   // Making pipe.
306   Standard_Boolean isDone = Standard_False;
307   bool anIsSolidNeeded = false;
308   BRepOffsetAPI_MakePipeShell* aPipeBuilder;
309   for(int i = 0; i < 2; ++i) {
310     aPipeBuilder = new BRepOffsetAPI_MakePipeShell(aPathWire);
311     if(!aPipeBuilder) {
312       return;
313     }
314     ListOfShape::const_iterator aBaseIt = theBaseShapes.cbegin();
315     std::list<TopoDS_Vertex>::const_iterator aLocationsIt = aLocations.cbegin();
316     while(aBaseIt != theBaseShapes.cend()) {
317       GeomShapePtr aBase = *aBaseIt;
318       if(!getBase(aBaseShape, aBaseShapeType, aBase)) {
319         delete aPipeBuilder;
320         return;
321       }
322       ++aBaseIt;
323       if(aBaseShapeType == TopAbs_FACE) {
324         anIsSolidNeeded = true;
325       }
326
327       if(aHasLocations) {
328         aPipeBuilder->Add(aBaseShape, *aLocationsIt);
329         ++aLocationsIt;
330       } else {
331         aPipeBuilder->Add(aBaseShape);
332       }
333     }
334
335     if(aPipeBuilder->IsReady() == Standard_False) {
336       delete aPipeBuilder;
337       return;
338     }
339
340     if (i == 1) {
341        // Try to use Descrete Trihedron mode.
342       aPipeBuilder->SetDiscreteMode();
343     }
344     aPipeBuilder->Build();
345     isDone = aPipeBuilder->IsDone();
346
347     if (isDone) {
348       break;
349     }
350
351     delete aPipeBuilder;
352   }
353
354   if (!isDone) {
355     return;
356   }
357
358   this->initialize(aPipeBuilder);
359
360   // Checking result.
361   if(anIsSolidNeeded && !aPipeBuilder->MakeSolid()) {
362     return;
363   }
364   TopoDS_Shape aResult = aPipeBuilder->Shape();
365
366   // Setting naming.
367   GeomShapePtr aFromShape(new GeomAPI_Shape), aToShape(new GeomAPI_Shape);
368   aFromShape->setImpl(new TopoDS_Shape(aPipeBuilder->FirstShape()));
369   aToShape->setImpl(new TopoDS_Shape(aPipeBuilder->LastShape()));
370   fixOrientation(aFromShape);
371   fixOrientation(aToShape);
372   this->addFromShape(aFromShape);
373   this->addToShape(aToShape);
374
375   // Setting result.
376   if(aResult.IsNull()) {
377     return;
378   }
379   aResult = GeomAlgoAPI_DFLoader::refineResult(aResult);
380   GeomShapePtr aGeomSh(new GeomAPI_Shape());
381   aGeomSh->setImpl(new TopoDS_Shape(aResult));
382   this->setShape(aGeomSh);
383   this->setDone(true);
384 }
385
386 //==================================================================================================
387 void GeomAlgoAPI_Pipe::generated(const GeomShapePtr theShape,
388                                  ListOfShape& theHistory)
389 {
390   if (myMovedPath.isBound(theShape))
391     GeomAlgoAPI_MakeShape::generated(myMovedPath.find(theShape), theHistory);
392   else
393     GeomAlgoAPI_MakeShape::generated(theShape, theHistory);
394 }
395
396 // Auxilary functions:
397 //==================================================================================================
398 bool getBase(TopoDS_Shape& theBaseOut,
399              TopAbs_ShapeEnum& theBaseTypeOut,
400              const GeomShapePtr theBaseShape)
401 {
402   if(!theBaseShape.get()) {
403     return false;
404   }
405
406   theBaseOut = theBaseShape->impl<TopoDS_Shape>();
407   if(theBaseOut.IsNull()) {
408     return false;
409   }
410   theBaseTypeOut = theBaseOut.ShapeType();
411   if(theBaseTypeOut == TopAbs_VERTEX) {
412     // Do nothing.
413   } else if(theBaseTypeOut == TopAbs_EDGE) {
414     theBaseOut = BRepBuilderAPI_MakeWire(TopoDS::Edge(theBaseOut)).Shape();
415   } else if(theBaseTypeOut == TopAbs_WIRE) {
416     // Do nothing.
417   } else if(theBaseTypeOut == TopAbs_FACE) {
418     TopExp_Explorer anExp(theBaseOut, TopAbs_WIRE);
419     theBaseOut = anExp.Current();
420   } else {
421     return false;
422   }
423
424   return true;
425 }
426
427 //==================================================================================================
428 bool getPath(TopoDS_Wire& thePathOut, const GeomShapePtr thePathShape)
429 {
430   if(!thePathShape.get()) {
431     return false;
432   }
433
434   TopoDS_Shape aPathShape = thePathShape->impl<TopoDS_Shape>();
435   if(aPathShape.IsNull()) {
436     return false;
437   }
438   TopAbs_ShapeEnum aPathShapeType = aPathShape.ShapeType();
439   if(aPathShapeType == TopAbs_EDGE) {
440     TopoDS_Edge aPathEdge = TopoDS::Edge(aPathShape);
441     thePathOut = BRepBuilderAPI_MakeWire(aPathEdge).Wire();
442   } else if(aPathShapeType == TopAbs_WIRE) {
443     thePathOut = TopoDS::Wire(aPathShape);
444   } else {
445     return false;
446   }
447
448   return true;
449 }
450
451 //==================================================================================================
452 gp_Trsf getPathToBaseTranslation(const TopoDS_Shape& theBase, const TopoDS_Shape& thePath)
453 {
454   gp_Trsf aTranslation;
455
456   BRepExtrema_DistShapeShape aDist(theBase, thePath);
457   aDist.Perform();
458   if (aDist.IsDone() && aDist.Value() > Precision::Confusion()) {
459     gp_Pnt aPntBase = aDist.PointOnShape1(1);
460     gp_Pnt aPntPath = aDist.PointOnShape2(1);
461     // get the end point on the path nearest to the found point,
462     // because the path is almost usually started from the one of the sections
463     if (!BRep_Tool::IsClosed(thePath)) {
464       TopoDS_Wire aPathWire = TopoDS::Wire(thePath);
465       if (!aPathWire.IsNull()) {
466         TopoDS_Vertex aV1, aV2;
467         TopExp::Vertices(aPathWire, aV1, aV2);
468
469         gp_Pnt aStart = BRep_Tool::Pnt(aV1);
470         gp_Pnt anEnd = BRep_Tool::Pnt(aV2);
471
472         // compare 3 distances
473         double aDistToStart = aPntBase.Distance(aStart);
474         double aDistToEnd = aPntBase.Distance(anEnd);
475         double aMinDist = aPntBase.Distance(aPntPath);
476
477         static const double THE_THRESHOLD = 0.01; // threshold for distance ratio
478         double aDeltaStart = Abs(aDistToStart - aMinDist);
479         double aDeltaEnd = Abs(aDistToEnd - aMinDist);
480         if (aDeltaStart < THE_THRESHOLD * aDeltaEnd)
481           aPntPath = aStart;
482         else if (aDeltaEnd < THE_THRESHOLD * aDeltaStart)
483           aPntPath = anEnd;
484         else
485           aPntPath = aPntBase; // no translation
486       }
487     }
488     aTranslation.SetTranslation(aPntPath, aPntBase);
489   }
490
491   return aTranslation;
492 }
493
494 //==================================================================================================
495 bool buildPipe(BRepOffsetAPI_MakePipeShell* thePipeBuilder)
496 {
497   thePipeBuilder->Build();
498
499   Standard_Boolean isDone = thePipeBuilder->IsDone();
500
501   if (!isDone) {
502     // Try to use Descrete Trihedron mode.
503     thePipeBuilder->SetDiscreteMode();
504     thePipeBuilder->Build();
505     isDone = thePipeBuilder->IsDone();
506   }
507
508   return isDone == Standard_True;
509 }
510
511 //==================================================================================================
512 ListOfShape getListFromShape(const TopoDS_Shape& theShape)
513 {
514   ListOfShape aList;
515
516   TopAbs_ShapeEnum aType = theShape.ShapeType();
517   if(aType == TopAbs_WIRE || aType == TopAbs_SHELL || aType == TopAbs_COMPOUND) {
518     for(TopoDS_Iterator anIt(theShape); anIt.More(); anIt.Next()) {
519       GeomShapePtr aGeomShape(new GeomAPI_Shape());
520       aGeomShape->setImpl(new TopoDS_Shape(anIt.Value()));
521       aList.push_back(aGeomShape);
522     }
523   } else {
524     GeomShapePtr aGeomShape(new GeomAPI_Shape());
525     aGeomShape->setImpl(new TopoDS_Shape(theShape));
526     aList.push_back(aGeomShape);
527   }
528
529   return aList;
530 }
531
532 //==================================================================================================
533 void GeomAlgoAPI_Pipe::addMovedPath(GeomShapePtr thePath, GeomShapePtr theMoved)
534 {
535   myMovedPath.clear();
536   GeomAPI_ShapeExplorer anOldExp(thePath, GeomAPI_Shape::EDGE);
537   GeomAPI_ShapeExplorer aNewExp(theMoved, GeomAPI_Shape::EDGE);
538   for(; anOldExp.more(); anOldExp.next(), aNewExp.next()) {
539     myMovedPath.bind(anOldExp.current(), aNewExp.current());
540   }
541 }