Salome HOME
Update from BR_V5_DEV 13Feb2009
[modules/geom.git] / src / ShHealOper / ShHealOper_CloseContour.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 // File:      ShHealOper_CloseContour.cxx
23 // Created:   20.04.04 11:36:01
24 // Author:    Galina KULIKOVA
25 //
26 #include <ShHealOper_CloseContour.hxx>
27 #include <ShapeExtend_WireData.hxx>
28 #include <ShapeFix_Wire.hxx>
29 #include <TopoDS_Face.hxx>
30 #include <ShapeFix_Edge.hxx>
31 #include <TopoDS_Iterator.hxx>
32 #include <ShapeAnalysis_Wire.hxx>
33 #include <TColStd_SequenceOfInteger.hxx>
34 #include <TopTools_IndexedMapOfShape.hxx>
35 #include <TopoDS_Edge.hxx>
36 #include <TopTools_ListOfShape.hxx>
37 #include <TopTools_ListIteratorOfListOfShape.hxx>
38 #include <TColStd_MapOfInteger.hxx>
39 #include <TopExp.hxx>
40 #include <TopoDS.hxx>
41 #include <TColStd_MapIteratorOfMapOfInteger.hxx>
42 #include <ShapeAnalysis_Edge.hxx>
43 #include <BRep_Builder.hxx>
44 #include <TopoDS_Edge.hxx>
45 #include <TopoDS_Vertex.hxx>
46 #include <BRepBuilderAPI_MakeVertex.hxx>
47 #include <ShapeAnalysis_Edge.hxx>
48 #include <gp_Pnt.hxx>
49 #include <gp_Vec2d.hxx>
50 #include <gp_Vec.hxx>
51 #include <Geom_Line.hxx>
52 #include <Geom2d_Line.hxx>
53 #include <TopoDS_Compound.hxx>
54 #include <BRep_Tool.hxx>
55 #include <ShapeBuild_Edge.hxx>
56 #include <TopExp_Explorer.hxx>
57
58 //=======================================================================
59 //function : ShHealOper_CloseContour()
60 //purpose  : Constructor
61 //=======================================================================
62 ShHealOper_CloseContour::ShHealOper_CloseContour (const TopoDS_Shape& theShape  ) 
63 {
64   Init(theShape);
65 }
66
67 //=======================================================================
68 //function : Init
69 //purpose  : 
70 //=======================================================================
71 void ShHealOper_CloseContour::Init(const TopoDS_Shape& theShape)
72 {
73   ShHealOper_Tool::Init(theShape);
74   myTolerance = Precision::Confusion();
75   myMaxTolerance = 1.0;
76   TopExp::MapShapesAndAncestors(theShape,TopAbs_EDGE,TopAbs_FACE,myMapEdgesFace);
77 }
78
79 //=======================================================================
80 //function : Perform
81 //purpose  : 
82 //=======================================================================
83 Standard_Boolean ShHealOper_CloseContour::Perform(const TopTools_SequenceOfShape& theSeqEdges,
84                                                   const Standard_Boolean theModeVertex,
85                                                   const Standard_Boolean theModeFixGapsCurves)
86 {
87   myFreeEdges.Clear();
88   myDone = Standard_False;
89   myErrorStatus =ShHealOper_NotError;
90   if(myInitShape.IsNull()) {
91     myErrorStatus = ShHealOper_InvalidParameters;
92     return myDone;
93   }
94   Handle(ShapeExtend_WireData) asewd = new ShapeExtend_WireData;
95   Standard_Integer i =1;
96   for ( ; i <= theSeqEdges.Length(); i++)
97     asewd->Add(theSeqEdges.Value(i));
98
99   myModeVertex = theModeVertex;
100   myModeFixGapsCurves = theModeFixGapsCurves;
101
102   build(asewd);
103   
104   return myDone;
105 }
106
107 //=======================================================================
108 //function : Perform
109 //purpose  : 
110 //=======================================================================
111 Standard_Boolean ShHealOper_CloseContour::Perform(const TopoDS_Wire& theWire,
112                                                   const Standard_Boolean theModeVertex,
113                                                   const Standard_Boolean theModeFixGapsCurves)
114 {
115   myFreeEdges.Clear();
116   myDone = Standard_False;
117   if(myInitShape.IsNull()) {
118     myErrorStatus = ShHealOper_InvalidParameters;
119     return myDone;
120   }
121   Handle(ShapeExtend_WireData) asewd = new ShapeExtend_WireData(theWire);
122   myModeVertex = theModeVertex;
123   myModeFixGapsCurves = theModeFixGapsCurves;
124   build(asewd);
125   return myDone;
126 }
127
128 //=======================================================================
129 //function : Build
130 //purpose  : 
131 //=======================================================================
132 void ShHealOper_CloseContour::build(Handle(ShapeExtend_WireData)& theSewd)
133 {
134   TopTools_SequenceOfShape aCommonFaces;
135   //checks that all specified edges belong the one face or not.
136   Standard_Boolean isOneFace = checkOneFace(theSewd,aCommonFaces);
137
138   //add edge or increase max tolerance in dependance on specified VertexMode.
139   //if all edges belong the one face that gap will be closed in the 2D by line
140   //else gap will be closed in the 3D by line.
141   myDone = fixGaps(theSewd,aCommonFaces);
142   updateWire(theSewd);
143   Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
144   sfw->SetContext(myContext);
145   sfw->Load(theSewd);
146
147   sfw->ClosedWireMode() = Standard_True;
148   sfw->SetPrecision(myTolerance);
149   sfw->SetMaxTolerance(myMaxTolerance);
150   
151   if(isOneFace) {
152     Standard_Integer ii =1;
153     for( ; ii <= aCommonFaces.Length(); ii++) {
154       TopoDS_Face aFace = TopoDS::Face(aCommonFaces.Value(ii));
155       sfw->SetFace(aFace);
156       myDone = (sfw->Perform() || myDone);
157       //if Mode for fix gaps is equal to true that
158       //curve 3D and curve 2D will be pull to each other.
159       if(myModeFixGapsCurves) {
160         Standard_Boolean isFixgaps = Standard_False;
161         if(ii ==1) {
162           sfw->FixGaps3d();
163           isFixgaps = sfw->StatusGaps3d(ShapeExtend_DONE);
164           if(!isFixgaps && sfw->StatusGaps3d(ShapeExtend_FAIL))
165              myErrorStatus = ShHealOper_ErrorExecution;
166         }
167         if(sfw->FixGaps2d())
168           sfw->FixSelfIntersection();
169         else if(sfw->StatusGaps2d(ShapeExtend_FAIL))
170           myErrorStatus = ShHealOper_ErrorExecution;
171
172         isFixgaps = (isFixgaps || sfw->StatusGaps2d(ShapeExtend_DONE));
173         myDone = (myDone || isFixgaps);
174         if(isFixgaps) {
175           Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
176           Handle(ShapeFix_Edge) sfe = new ShapeFix_Edge;
177           for (Standard_Integer iedge = 1; iedge <= sbwd->NbEdges(); iedge++) {
178             TopoDS_Edge aEdge = TopoDS::Edge(sbwd->Edge(iedge));
179             sfe->FixVertexTolerance(aEdge,aFace);
180             sfe->FixSameParameter(aEdge);
181           }
182         }
183       }
184     }
185   }
186   else {
187     myDone = (sfw->Perform() || myDone);
188     if(myModeFixGapsCurves) {
189       //if Mode for fix gaps is equal to true that
190       //curve 3D will be pull to each other.
191       if(sfw->FixGaps3d()) {
192         Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
193         Handle(ShapeFix_Edge) sfe = new ShapeFix_Edge;
194         for (Standard_Integer iedge = 1; iedge <= sbwd->NbEdges(); iedge++) {
195           TopoDS_Edge aEdge = TopoDS::Edge(sbwd->Edge(iedge));
196           sfe->FixVertexTolerance(aEdge);
197           sfe->FixSameParameter(aEdge);
198         }
199       }
200       else if(sfw->StatusGaps3d(ShapeExtend_FAIL))
201         myErrorStatus = ShHealOper_ErrorExecution;
202       myDone = (sfw->StatusGaps3d(ShapeExtend_DONE) || myDone);
203     }
204   }
205
206   if(myDone) {
207     TopoDS_Shape aoldShape = myInitShape;
208     //if free edges were added they will be added to the result shape
209     //and type of result shape should be change if initial shape is not COMPOUND.
210     if( myFreeEdges.Length()) {
211       BRep_Builder aB;
212       TopoDS_Compound aComp;
213       aB.MakeCompound(aComp);
214       if(aoldShape.ShapeType() == TopAbs_COMPOUND) {
215         TopoDS_Iterator aIt(aoldShape);
216         for( ;aIt.More();aIt.Next() )
217            aB.Add(aComp,aIt.Value());
218       }
219       else
220         aB.Add(aComp,aoldShape);
221
222       Standard_Integer i=1;
223       for ( ; i <= myFreeEdges.Length(); i++ ) 
224         aB.Add(aComp,myFreeEdges.Value(i));
225       aoldShape = aComp;
226       
227     }
228     myResultShape = myContext->Apply(aoldShape);
229   }
230   return;
231 }
232
233 //=======================================================================
234 //function : checkGaps
235 //purpose  : 
236 //=======================================================================
237 Standard_Boolean ShHealOper_CloseContour::fixGaps(const Handle(ShapeExtend_WireData)& theWire,
238                                                   const TopTools_SequenceOfShape& theCommonFaces) 
239 {
240   Handle(ShapeAnalysis_Wire) asaw = new ShapeAnalysis_Wire;
241   asaw->Load(theWire);
242   
243   Standard_Integer i =1;
244   Standard_Boolean hasGaps = Standard_False;
245   for ( ; i <= asaw->NbEdges(); i++) {
246     if(asaw->CheckGap3d(i)) {
247       Standard_Real dist = asaw->MinDistance3d();
248       if(dist > myMaxTolerance) {
249         hasGaps = Standard_True;
250         Standard_Integer ind2 = (i ==0 ? theWire->NbEdges() :i);
251         Standard_Integer ind1 = (ind2 >1 ? ind2 -1 : theWire->NbEdges());
252         TopoDS_Edge aE1= theWire->Edge(ind1);
253         TopoDS_Edge aE2= theWire->Edge(ind2);
254         if(!myModeVertex)
255           buildEdge(aE1,aE2,theCommonFaces);
256         else
257           myMaxTolerance = RealLast();
258         if(ind2 == ind1) break;
259       }
260     }
261     
262   }
263   return  hasGaps;
264 }
265
266 //=======================================================================
267 //function : checkOneFace
268 //purpose  : 
269 //=======================================================================
270 Standard_Boolean ShHealOper_CloseContour::checkOneFace(const Handle(ShapeExtend_WireData)& theSewd,
271                                                        TopTools_SequenceOfShape& theCommonFaces) const
272 {
273   TopTools_IndexedMapOfShape amapfaces;
274   TopoDS_Edge aEdge1 = theSewd->Edge(1);
275   Standard_Boolean isOneFace = myMapEdgesFace.Contains(aEdge1 );
276   if(!isOneFace)
277     return isOneFace;
278
279   //check that all specified edges belong to one face. 
280   const TopTools_ListOfShape& alfaces = myMapEdgesFace.FindFromKey(aEdge1);
281   isOneFace = isOneFace && (!alfaces.IsEmpty());
282   if(!isOneFace)
283     return Standard_False;
284
285   TopTools_ListIteratorOfListOfShape litr(alfaces);
286   for( ; litr.More();litr.Next() ) 
287     amapfaces.Add(litr.Value());
288   
289   TColStd_MapOfInteger amapIndex;
290   Standard_Integer ind  =0;
291   Standard_Integer i =2;
292   for( ; i <= theSewd->NbEdges() && isOneFace; i++) {
293     isOneFace = myMapEdgesFace.Contains(theSewd->Edge(i));
294     if(isOneFace) {
295       const TopTools_ListOfShape& alfaces1 = myMapEdgesFace.FindFromKey(theSewd->Edge(i));
296       
297         TColStd_MapOfInteger aTmpInd;
298         for(litr.Initialize(alfaces1) ; litr.More() ;litr.Next() ) {
299           if(amapfaces.Contains(litr.Value())) {
300             ind = amapfaces.FindIndex(litr.Value());
301             if( i == 2) 
302               amapIndex.Add(ind);
303             else 
304               aTmpInd.Add(ind);
305           }
306         }
307       if(i ==2) {
308         isOneFace = (amapIndex.Extent());
309         continue;
310       }
311       else {
312         TColStd_MapIteratorOfMapOfInteger aMi(amapIndex);
313         for( ;  aMi.More();aMi.Next()) {
314           if(!aTmpInd.Contains(aMi.Key()))
315             amapIndex.Remove(aMi.Key());
316         }
317         isOneFace = (amapIndex.Extent()); 
318         
319       }
320     }
321   }
322   if(theSewd->NbEdges() >1) {
323     Standard_Integer j =1;
324     for( ; j <= amapfaces.Extent(); j++) {
325       if(!amapIndex.Contains(j)) continue;
326       TopoDS_Shape aF = amapfaces.FindKey(j);
327       theCommonFaces.Append(aF);
328     }
329   }
330   return isOneFace;
331 }
332
333 //=======================================================================
334 //function : buildEdge
335 //purpose  : 
336 //=======================================================================
337 void ShHealOper_CloseContour::buildEdge(const TopoDS_Edge& aE1, 
338                                         const TopoDS_Edge& aE2,
339                                         const TopTools_SequenceOfShape& theCommonFaces) 
340 {
341   ShapeAnalysis_Edge asae;
342   TopoDS_Vertex aV1 = asae.LastVertex(aE1);
343   TopoDS_Vertex aV2 = asae.FirstVertex(aE2);
344   gp_Pnt p1 = BRep_Tool::Pnt(aV1);
345   gp_Pnt p2 = BRep_Tool::Pnt(aV2);
346   BRepBuilderAPI_MakeVertex mkver1( p1 );
347   TopoDS_Vertex newV1 = mkver1.Vertex();
348   
349   BRepBuilderAPI_MakeVertex mkver2( p2 );
350   TopoDS_Vertex newV2 = mkver2.Vertex();
351   BRep_Builder B;
352   B.UpdateVertex ( newV1,Precision::Confusion());
353   B.UpdateVertex ( newV2, Precision::Confusion());
354   Standard_Boolean isBuild = Standard_False;
355   TopoDS_Edge edge;
356   B.MakeEdge ( edge );
357   ShapeBuild_Edge sbe;
358   //if all edges belong to one face that gap will be closed in the 2D by line
359   //than 3D curve will be built by 2D curve
360   if(theCommonFaces.Length()) {
361     
362     TopoDS_Face aF1 = TopoDS::Face(theCommonFaces.Value(1));
363     Handle(Geom2d_Curve) c2d1,c2d2;
364     gp_Pnt2d p2d1,p2d2;
365     Standard_Real a1, b1,a2, b2;
366     if (  asae.PCurve ( aE1, aF1, c2d1, a1, b1, Standard_True )  && 
367         asae.PCurve ( aE2, aF1, c2d2, a2, b2, Standard_True )) {
368       
369       c2d1->D0 ( b1, p2d1);
370       c2d2->D0 ( a2, p2d2);
371       gp_Vec2d v12 ( p2d1, p2d2 );
372       
373       Handle(Geom2d_Line) aLine2d = new Geom2d_Line ( p2d1, gp_Dir2d ( v12 ) );
374       B.UpdateEdge ( edge, aLine2d, aF1, ::Precision::Confusion() );
375       B.Range ( edge, aF1, 0.0, v12.Magnitude() );
376       
377       isBuild = sbe.BuildCurve3d ( edge );
378     }
379   }
380   //else gap will be closed in the 3D by line.
381   if(!isBuild) {
382     gp_Vec v1 ( p1, p2 );
383     Handle(Geom_Line) aLine = new Geom_Line ( p1, gp_Dir ( v1 ) );
384     B.UpdateEdge ( edge, aLine, ::Precision::Confusion() );
385     B.Range ( edge,0.0, v1.Magnitude());
386   }
387   B.Add ( edge, newV1.Oriented ( TopAbs_FORWARD ) );
388   B.Add ( edge, newV2.Oriented ( TopAbs_REVERSED ) );
389   myContext->Replace(aV1, newV1.Oriented (aV1.Orientation()));
390   myContext->Replace(aV2, newV2.Oriented (aV2.Orientation()));
391   if(isBuild) {
392     newV1.Orientation(aV1.Orientation());
393     TopoDS_Edge newEdge = sbe.CopyReplaceVertices ( aE1,TopoDS_Vertex(), newV1);
394     TopoDS_Wire aw;
395     B.MakeWire(aw);
396     B.Add(aw,newEdge);
397     B.Add(aw,edge);
398     TopoDS_Shape anE1 = myContext->Apply(aE1);
399     myContext->Replace(anE1,aw);
400   }
401   else {
402     myFreeEdges.Append(edge);
403   }
404 }
405
406 //=======================================================================
407 //function : UpdateWire
408 //purpose  : 
409 //=======================================================================
410 void ShHealOper_CloseContour::updateWire (Handle(ShapeExtend_WireData)& sbwd) 
411 {
412   Standard_Integer i=1;
413   for ( ; i <= sbwd->NbEdges(); i++ ) {
414     TopoDS_Edge E = sbwd->Edge(i);
415     TopoDS_Shape S = myContext->Apply ( E );
416     if ( S == E ) continue;
417     for ( TopExp_Explorer exp(S,TopAbs_EDGE); exp.More(); exp.Next() )
418       sbwd->Add ( exp.Current(), i++ );
419     sbwd->Remove ( i-- );
420   }
421   for ( i =1; i <= myFreeEdges.Length(); i++ ) {
422     sbwd->Add(TopoDS::Edge(myFreeEdges.Value(i)));
423   }
424 }