Salome HOME
34efa40cd333fa70e69f8e0078f8f6895d41b492
[modules/geom.git] / src / GEOMImpl / GEOMImpl_Fillet1dDriver.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
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 <Standard_Stream.hxx>
21
22 #include <GEOMImpl_Fillet1dDriver.hxx>
23
24 #include <GEOMImpl_Fillet1d.hxx>
25 #include <GEOMImpl_IFillet1d.hxx>
26 #include <GEOMImpl_Types.hxx>
27 #include <GEOMImpl_HealingDriver.hxx>
28
29 #include <GEOM_Function.hxx>
30
31 #include <GEOMUtils.hxx>
32
33 #include <ShapeFix_Wire.hxx>
34 #include <StdFail_NotDone.hxx>
35 #include <Standard_ConstructionError.hxx>
36
37 #include <TopAbs.hxx>
38 #include <TopoDS.hxx>
39 #include <TopoDS_Edge.hxx>
40 #include <TopoDS_Wire.hxx>
41 #include <TopoDS_Shape.hxx>
42 #include <TopExp.hxx>
43 #include <TopExp_Explorer.hxx>
44 #include <TopTools_DataMapOfShapeShape.hxx>
45 #include <TopTools_ListOfShape.hxx>
46 #include <TopTools_ListIteratorOfListOfShape.hxx>
47 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
48 #include <TopTools_IndexedMapOfShape.hxx>
49
50 #include <BRep_Tool.hxx>
51 #include <BRepTools.hxx>
52 #include <BRepBuilderAPI_MakeWire.hxx>
53 #include <BRepCheck_Analyzer.hxx>
54
55 #include <gp_Pln.hxx>
56 #include <gp_Dir.hxx>
57 #include <gp_XYZ.hxx>
58
59 #include <Precision.hxx>
60
61 //=======================================================================
62 //function : GetID
63 //purpose  :
64 //=======================================================================
65 const Standard_GUID& GEOMImpl_Fillet1dDriver::GetID()
66 {
67   static Standard_GUID aFillet1dDriver("FF60908B-AB2E-4b71-B098-5C256C37D961");
68   return aFillet1dDriver;
69 }
70
71 //=======================================================================
72 //function : GEOMImpl_Fillet1dDriver
73 //purpose  :
74 //=======================================================================
75 GEOMImpl_Fillet1dDriver::GEOMImpl_Fillet1dDriver()
76 {
77 }
78
79 //=======================================================================
80 //function : anotherVertex
81 //purpose  : local function to get vertex from edge
82 //=======================================================================
83 static TopoDS_Vertex anotherVertex( const TopoDS_Edge& theE,
84                                     const TopoDS_Vertex& theV )
85 {
86   // here is an assumption that edge has different vertices
87   TopoDS_Vertex aV;
88   TopExp_Explorer anExp( theE, TopAbs_VERTEX );
89   for ( ; anExp.More(); anExp.Next() )
90   {
91     if ( BRepTools::Compare(theV,TopoDS::Vertex(anExp.Current())) /*theV.IsSame(anExp.Current())*/ )
92       continue;
93     aV = TopoDS::Vertex( anExp.Current() );
94     break;
95   }
96   return aV;
97 }
98
99 //=======================================================================
100 //function : takePlane
101 //purpose  : local function returns plane of given edges
102 //=======================================================================
103 static Standard_Boolean takePlane( const TopoDS_Edge& theE1,
104                                    const TopoDS_Edge& theE2,
105                                    const TopoDS_Vertex& theV,
106                                    gp_Pln& thePlane )
107 {
108   TopoDS_Vertex aV12 = anotherVertex( theE1, theV );
109   TopoDS_Vertex aV22 = anotherVertex( theE2, theV );
110   // check can closed wire be created by two initial edges
111   if ( aV12.IsNull()  || aV22.IsNull() || aV12.IsSame( aV22 ) )
112     return false;
113
114   // create plane by 3 points
115   gp_XYZ aXYZ = BRep_Tool::Pnt( theV ).XYZ();
116   gp_XYZ aXYZ1 = BRep_Tool::Pnt( aV12 ).XYZ();
117   gp_XYZ aXYZ2 = BRep_Tool::Pnt( aV22 ).XYZ();
118   try {
119     gp_Dir aDir1( aXYZ - aXYZ1 );
120     gp_Dir aDir2( aXYZ2 - aXYZ );
121     Standard_Real anAngle = aDir1.Angle(aDir2);
122     if ( fabs(anAngle) <= gp::Resolution() ||
123          fabs(anAngle - M_PI) <= gp::Resolution() )
124       return false;
125     thePlane = gp_Pln( gp_Pnt(aXYZ), aDir1^ aDir2);
126   }
127   catch (Standard_Failure) {
128     return false;
129   }
130   return true;
131 }
132
133 //=======================================================================
134 //function : addEdgeRelation
135 //purpose  : local function to remember relation between initial and modified edge
136 //=======================================================================
137 static void addEdgeRelation(TopTools_DataMapOfShapeShape& theMap,
138                             const TopoDS_Edge& theInitE,
139                             const TopoDS_Edge& theResE)
140 {
141   if ( theMap.IsBound( theInitE ) )
142     theMap.ChangeFind( theInitE ) = theResE;
143   else
144     theMap.Bind( theInitE, theResE );
145 }
146
147 //=======================================================================
148 //function : Execute
149 //purpose  :
150 //=======================================================================
151 Standard_Integer GEOMImpl_Fillet1dDriver::Execute(LOGBOOK& log) const
152 {
153   if (Label().IsNull()) return 0;
154   Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
155
156   GEOMImpl_IFillet1d aCI (aFunction);
157
158   Handle(GEOM_Function) aRefShape = aCI.GetShape();
159   TopoDS_Shape aShape = aRefShape->GetValue();
160   if (aShape.IsNull())
161     return 0;
162   if (aShape.ShapeType() != TopAbs_WIRE)
163     Standard_ConstructionError::Raise("Wrong arguments: polyline as wire must be given");
164
165   TopoDS_Wire aWire = TopoDS::Wire(aShape);
166
167   bool doIgnoreSecantPoints = aCI.GetFlag();
168
169   double rad = aCI.GetR();
170   if (rad < Precision::Confusion())
171     return 0;
172
173   // collect vertices for make fillet
174   TopTools_ListOfShape aVertexList;
175   TopTools_IndexedMapOfShape anIndices;
176   TopExp::MapShapes(aWire, anIndices);
177   int aLen = aCI.GetLength();
178   if (aLen > 0) {
179     for (int ii = 1; ii <= aLen; ii++) {
180       int ind = aCI.GetVertex(ii);
181       if (1 <= ind && ind <= anIndices.Extent()) {
182         TopoDS_Shape aShapeVertex = anIndices.FindKey(ind);
183         if (aShapeVertex.ShapeType() == TopAbs_VERTEX)
184           aVertexList.Append(aShapeVertex);
185       }
186     }
187   }
188   else { // get all vertices from wire
189     TopTools_MapOfShape mapShape;
190     TopExp_Explorer anExp (aWire, TopAbs_VERTEX);
191     for (; anExp.More(); anExp.Next()) {
192       if (mapShape.Add(anExp.Current()))
193         aVertexList.Append(anExp.Current());
194     }
195   }
196   if (aVertexList.IsEmpty())
197     Standard_ConstructionError::Raise("Invalid input: no vertices to make fillet");
198
199   // at first we try to make fillet on the initial wire (without edges fusing)
200   bool isFinalPass = !doIgnoreSecantPoints;
201   TopoDS_Wire aResult;
202   bool isAllStepsOk = MakeFillet(aWire, aVertexList, rad, isFinalPass, aResult);
203
204   // try to fuse collinear edges to allow bigger radius
205   if (!isFinalPass && !isAllStepsOk) {
206     // 1. Fuse
207     TopoDS_Shape aShapeNew;
208     Handle(TColStd_HSequenceOfTransient) aVerts;
209     GEOMImpl_HealingDriver::FuseCollinearEdges(aWire, aVerts, aShapeNew);
210     TopoDS_Wire aWireNew = TopoDS::Wire(aShapeNew);
211
212     // 2. Rebuild the list of vertices (by coincidence)
213     Standard_Real tol, tolMax = Precision::Confusion();
214     for (TopExp_Explorer ExV (aWireNew, TopAbs_VERTEX); ExV.More(); ExV.Next()) {
215       TopoDS_Vertex Vertex = TopoDS::Vertex(ExV.Current());
216       tol = BRep_Tool::Tolerance(Vertex);
217       if (tol > tolMax)
218         tolMax = tol;
219     }
220
221     TopTools_ListOfShape aVertexListNew;
222     TopTools_IndexedMapOfShape anIndicesNew;
223     TopExp::MapShapes(aWireNew, anIndicesNew);
224     TopTools_ListIteratorOfListOfShape anIt (aVertexList);
225     for (; anIt.More(); anIt.Next()) {
226       TopoDS_Vertex aV = TopoDS::Vertex(anIt.Value());
227       if (anIndicesNew.Contains(aV))
228         aVertexListNew.Append(aV);
229       else {
230         // try to find by coords in the new wire
231         gp_Pnt aP = BRep_Tool::Pnt(aV);
232
233         bool isFound = false;
234         TopTools_MapOfShape mapShape;
235         TopExp_Explorer exp (aWireNew, TopAbs_VERTEX);
236         for (; exp.More() && !isFound; exp.Next()) {
237           if (mapShape.Add(exp.Current())) {
238             TopoDS_Vertex aVi = TopoDS::Vertex(exp.Current());
239             gp_Pnt aPi = BRep_Tool::Pnt(aVi);
240             if (aPi.Distance(aP) < tolMax) {
241               aVertexListNew.Append(aVi);
242               isFound = true;
243             }
244           }
245         }
246       }
247     }
248
249     // 3. Repeat the fillet algorithm
250     isFinalPass = true;
251     MakeFillet(aWireNew, aVertexListNew, rad, isFinalPass, aResult);
252   }
253
254   if (!GEOMUtils::CheckShape(aResult, true) &&
255       !GEOMUtils::FixShapeTolerance(aResult)) {
256     Standard_ConstructionError::Raise("Non valid shape result");
257   }
258
259   aFunction->SetValue(aResult);
260 #if OCC_VERSION_MAJOR < 7
261   log.SetTouched(Label());
262 #else
263   log->SetTouched(Label());
264 #endif
265
266   return 1;
267 }
268
269 //=======================================================================
270 //function : MakeFillet
271 //purpose  :
272 //=======================================================================
273 bool GEOMImpl_Fillet1dDriver::MakeFillet(const TopoDS_Wire& aWire,
274                                          const TopTools_ListOfShape& aVertexList,
275                                          const Standard_Real rad,
276                                          bool isFinalPass,
277                                          TopoDS_Wire& aResult) const
278 {
279   // this variable is needed to break execution
280   // in case of fillet failure and try to fuse edges
281   bool isAllStepsOk = true;
282
283   //INFO: this algorithm implemented in assumption that user can select both
284   //  vertices of some edges to make fillet. In this case we should remember
285   //  already modified initial edges to take care in next fillet step
286   TopTools_DataMapOfShapeShape anEdgeToEdgeMap;
287
288   //iterates on vertices, and make fillet on each couple of edges
289   //collect result fillet edges in list
290   TopTools_ListOfShape aListOfNewEdge;
291   // remember relation between initial and modified map
292   TopTools_IndexedDataMapOfShapeListOfShape aMapVToEdges;
293   TopExp::MapShapesAndAncestors( aWire, TopAbs_VERTEX, TopAbs_EDGE, aMapVToEdges );
294   TopTools_ListIteratorOfListOfShape anIt( aVertexList );
295   for ( ; anIt.More(); anIt.Next() ) {
296     TopoDS_Vertex aV = TopoDS::Vertex( anIt.Value() );
297     if ( aV.IsNull() || !aMapVToEdges.Contains( aV ) )
298       continue;
299     const TopTools_ListOfShape& aVertexEdges = aMapVToEdges.FindFromKey( aV );
300     if ( aVertexEdges.Extent() != 2 )
301       continue; // no input data to make fillet
302     TopoDS_Edge anEdge1 = TopoDS::Edge( aVertexEdges.First() );
303     TopoDS_Edge anEdge2 = TopoDS::Edge( aVertexEdges.Last() );
304     // check if initial edges already modified in previous fillet operation
305     if ( anEdgeToEdgeMap.IsBound( anEdge1 ) ) anEdge1 = TopoDS::Edge(anEdgeToEdgeMap.Find( anEdge1 ));
306     if ( anEdgeToEdgeMap.IsBound( anEdge2 ) ) anEdge2 = TopoDS::Edge(anEdgeToEdgeMap.Find( anEdge2 ));
307     if ( anEdge1.IsNull() || anEdge2.IsNull() || anEdge1.IsSame( anEdge2 ) )
308       continue; //no input data to make fillet
309
310     // create plane on 2 edges
311     gp_Pln aPlane;
312     if ( !takePlane(anEdge1, anEdge2, aV, aPlane) )
313       continue; // seems edges does not belong to same plane or parallel (fillet can not be build)
314
315     GEOMImpl_Fillet1d aFilletAlgo (anEdge1, anEdge2, aPlane);
316     if (!aFilletAlgo.Perform(rad)) {
317       if (isFinalPass)
318         continue; // can not create fillet with given radius
319       else {
320         isAllStepsOk = false;
321         break; // can not create fillet with given radius
322       }
323     }
324
325     // take fillet result in given vertex
326     TopoDS_Edge aModifE1, aModifE2;
327     TopoDS_Edge aNewE = aFilletAlgo.Result(BRep_Tool::Pnt(aV), aModifE1, aModifE2);
328     if (aNewE.IsNull()) {
329       if (isFinalPass)
330         continue; // no result found
331       else {
332         isAllStepsOk = false;
333         break; // no result found
334       }
335     }
336
337     // add  new created edges and take modified edges
338     aListOfNewEdge.Append(aNewE);
339
340     // check if wire edges modified,
341     // if yes, then map to original edges (from vertex-edges list), because edges can be modified before
342     if (aModifE1.IsNull() || !anEdge1.IsSame( aModifE1 ))
343       addEdgeRelation( anEdgeToEdgeMap, TopoDS::Edge(aVertexEdges.First()), aModifE1 );
344     if (aModifE2.IsNull() || !anEdge2.IsSame( aModifE2 ))
345       addEdgeRelation( anEdgeToEdgeMap, TopoDS::Edge(aVertexEdges.Last()), aModifE2 );
346   }
347
348   if (anEdgeToEdgeMap.IsEmpty() && aListOfNewEdge.IsEmpty()) {
349     if (isFinalPass)
350       StdFail_NotDone::Raise("1D Fillet can't be computed on the given shape with the given radius");
351     else
352       isAllStepsOk = false;
353   }
354
355   if (!isAllStepsOk)
356     return false;
357
358   // create new wire instead of original
359   for (TopExp_Explorer anExp (aWire, TopAbs_EDGE); anExp.More(); anExp.Next()) {
360     TopoDS_Shape anEdge = anExp.Current();
361     if (!anEdgeToEdgeMap.IsBound(anEdge))
362       aListOfNewEdge.Append(anEdge);
363     else if (!anEdgeToEdgeMap.Find(anEdge).IsNull())
364       aListOfNewEdge.Append(anEdgeToEdgeMap.Find(anEdge));
365   }
366
367   GEOMUtils::SortShapes(aListOfNewEdge);
368
369   BRepBuilderAPI_MakeWire aWireTool;
370   aWireTool.Add(aListOfNewEdge);
371   aWireTool.Build();
372   if (!aWireTool.IsDone())
373     return 0;
374
375   aResult = aWireTool.Wire();
376
377   return isAllStepsOk;
378 }
379 //================================================================================
380 /*!
381  * \brief Returns a name of creation operation and names and values of creation parameters
382  */
383 //================================================================================
384
385 bool GEOMImpl_Fillet1dDriver::
386 GetCreationInformation(std::string&             theOperationName,
387                        std::vector<GEOM_Param>& theParams)
388 {
389   if (Label().IsNull()) return 0;
390   Handle(GEOM_Function) function = GEOM_Function::GetFunction(Label());
391
392   GEOMImpl_IFillet1d aCI( function );
393   Standard_Integer aType = function->GetType();
394
395   theOperationName = "FILLET_1D";
396
397   switch ( aType ) {
398   case GEOM_FILLET_1D:
399     AddParam( theParams, "Wire", aCI.GetShape() );
400     AddParam( theParams, "Vertexes");
401     if ( aCI.GetLength() > 1 )
402       theParams[1] << aCI.GetLength() << " vertexes: ";
403     for (int i = 1; i <= aCI.GetLength(); ++i )
404       theParams[1] << aCI.GetVertex( i ) << " ";
405     AddParam( theParams, "Radius", aCI.GetR() );
406     AddParam( theParams, "Fuse collinear edges", aCI.GetFlag() );
407     break;
408   default:
409     return false;
410   }
411   
412   return true;
413 }
414
415 OCCT_IMPLEMENT_STANDARD_RTTIEXT (GEOMImpl_Fillet1dDriver,GEOM_BaseDriver);