Salome HOME
#18963 Minimize compiler warnings
[modules/geom.git] / src / GEOMImpl / GEOMImpl_HealingDriver.cxx
1 // Copyright (C) 2007-2020  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, or (at your option) any later version.
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
23 #include <GEOMImpl_HealingDriver.hxx>
24 #include <GEOMImpl_Types.hxx>
25 #include <GEOMImpl_IHealing.hxx>
26 #include <GEOM_Function.hxx>
27
28 #include <GEOMImpl_GlueDriver.hxx>
29 #include <GEOMImpl_ShapeDriver.hxx>
30
31 #include <GEOMUtils.hxx>
32 #include <GEOMAlgo_RemoverWebs.hxx>
33
34 #include <ShHealOper_ShapeProcess.hxx>
35 #include <ShHealOper_RemoveFace.hxx>
36 #include <ShHealOper_CloseContour.hxx>
37 #include <ShHealOper_RemoveInternalWires.hxx>
38 #include <ShHealOper_FillHoles.hxx>
39 #include <ShHealOper_Sewing.hxx>
40 #include <ShHealOper_EdgeDivide.hxx>
41 #include <ShHealOper_ChangeOrientation.hxx>
42
43 #include <TNaming_CopyShape.hxx>
44
45 #include <BRep_Builder.hxx>
46 #include <BRepAdaptor_Curve.hxx>
47 #include <BRepTools_WireExplorer.hxx>
48
49 #include <TopExp.hxx>
50 #include <TopExp_Explorer.hxx>
51 #include <TopoDS.hxx>
52 #include <TopoDS_Iterator.hxx>
53 #include <TopTools_IndexedMapOfShape.hxx>
54 #include <TopTools_ListOfShape.hxx>
55 #include <TopTools_ListIteratorOfListOfShape.hxx>
56
57 #include <TColStd_IndexedDataMapOfTransientTransient.hxx>
58
59 #include <Precision.hxx>
60
61 #include <StdFail_NotDone.hxx>
62 #include <Standard_NullObject.hxx>
63
64 //=======================================================================
65 //function :  raiseNotDoneExeption
66 //purpose  :  global function: forms error message and raises exception
67 //=======================================================================
68 void raiseNotDoneExeption( const int theErrorStatus )
69 {
70   switch ( theErrorStatus )
71   {
72   case ShHealOper_NotError:           StdFail_NotDone::Raise( "ShHealOper_NotError_msg" ); break;
73   case ShHealOper_InvalidParameters:  StdFail_NotDone::Raise( "ShHealOper_InvalidParameters_msg" ); break;
74   case ShHealOper_ErrorExecution:
75   default:                            StdFail_NotDone::Raise( "ShHealOper_ErrorExecution_msg" ); break;
76   }
77 }
78
79 //=======================================================================
80 //function : GetID
81 //purpose  :
82 //=======================================================================
83 const Standard_GUID& GEOMImpl_HealingDriver::GetID()
84 {
85   static Standard_GUID aHealingDriver("FF1BBB61-5D14-4df2-980B-3A668264EA16");
86   return aHealingDriver;
87 }
88
89 //=======================================================================
90 //function : GEOMImpl_HealingDriver
91 //purpose  :
92 //=======================================================================
93 GEOMImpl_HealingDriver::GEOMImpl_HealingDriver()
94 {
95 }
96
97 //=======================================================================
98 //function : Execute
99 //purpose  :
100 //=======================================================================
101 Standard_Integer GEOMImpl_HealingDriver::Execute(Handle(TFunction_Logbook)& log) const
102 {
103   if (Label().IsNull()) return 0;
104   Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
105
106   if (aFunction.IsNull()) return 0;
107
108   GEOMImpl_IHealing HI (aFunction);
109   Standard_Integer aType = aFunction->GetType();
110   Handle(GEOM_Function) anOriginalFunction = HI.GetOriginal();
111   if (anOriginalFunction.IsNull()) return 0;
112   TopoDS_Shape aShape, anOriginalShape = anOriginalFunction->GetValue();
113   if (anOriginalShape.IsNull()) return 0;
114
115   switch (aType)
116   {
117   case SHAPE_PROCESS:
118     ShapeProcess(&HI, anOriginalShape, aShape);
119     break;
120   case SUPPRESS_FACES:
121     SuppressFaces(&HI, anOriginalShape, aShape);
122     break;
123   case CLOSE_CONTOUR:
124     CloseContour(&HI, anOriginalShape, aShape);
125     break;
126   case REMOVE_INT_WIRES:
127     RemoveIntWires(&HI, anOriginalShape, aShape);
128     break;
129   case FILL_HOLES:
130     RemoveHoles(&HI, anOriginalShape, aShape);
131     break;
132   case SEWING:
133     Sew(&HI, anOriginalShape, aShape, false);
134     break;
135   case SEWING_NON_MANIFOLD:
136     Sew(&HI, anOriginalShape, aShape, true);
137     break;
138   case REMOVE_INTERNAL_FACES:
139     RemoveInternalFaces(&HI, anOriginalShape, aShape);
140     break;
141   case DIVIDE_EDGE:
142   case DIVIDE_EDGE_BY_POINT:
143     AddPointOnEdge(&HI, anOriginalShape, aShape);
144     break;
145   case CHANGE_ORIENTATION:
146     ChangeOrientation(&HI, anOriginalShape, aShape);
147     break;
148   case LIMIT_TOLERANCE:
149     LimitTolerance(&HI, anOriginalShape, aShape);
150     break;
151   case FUSE_COLLINEAR_EDGES:
152     {
153       Handle(TColStd_HSequenceOfTransient) aVerts = HI.GetShapes();
154       FuseCollinearEdges(anOriginalShape, aVerts, aShape);
155     }
156     break;
157   default:
158     return 0;
159   }
160
161   if (aShape.IsNull())
162     raiseNotDoneExeption( ShHealOper_ErrorExecution );
163
164   aFunction->SetValue(aShape);
165
166   log->SetTouched(Label());
167   return 1;
168 }
169
170 //=======================================================================
171 //function :  ShapeProcess
172 //purpose  :
173 //=======================================================================
174 Standard_Boolean GEOMImpl_HealingDriver::ShapeProcess (GEOMImpl_IHealing* theHI,
175                                                        const TopoDS_Shape& theOriginalShape,
176                                                        TopoDS_Shape& theOutShape) const
177 {
178   Handle(TColStd_HArray1OfExtendedString) anOperators = theHI->GetOperators();
179   Handle(TColStd_HArray1OfExtendedString) aParams = theHI->GetParameters();
180   Handle(TColStd_HArray1OfExtendedString) aValues = theHI->GetValues();
181
182   if (anOperators.IsNull() || anOperators->Length() <= 0)
183     return Standard_False;
184
185   Standard_Integer nbParams = 0, nbValues = 0;
186   if (!aParams.IsNull()) {
187     nbParams = aParams->Length();
188   }
189   if (!aValues.IsNull()) {
190     nbValues = aValues->Length();
191   }
192   if (nbParams != nbValues)
193     return Standard_False;
194
195   ShHealOper_ShapeProcess aHealer;
196   TColStd_SequenceOfAsciiString anOperatorsAS, aParamsAS, aValuesAS;
197   int i;
198   for (i = 1; i <= anOperators->Length(); i++)
199     anOperatorsAS.Append(TCollection_AsciiString(anOperators->Value(i)));
200
201   aHealer.SetOperators(anOperatorsAS);
202
203   for (i = 1; i <= nbParams; i++) {
204     aHealer.SetParameter(TCollection_AsciiString(aParams->Value(i)),
205                          TCollection_AsciiString(aValues->Value(i)));
206   }
207
208   aHealer.Perform(theOriginalShape, theOutShape);
209
210   if (!aHealer.isDone())
211     raiseNotDoneExeption( ShHealOper_NotError );
212
213   SaveStatistics( aHealer );
214
215   return Standard_True;
216 }
217
218 //=======================================================================
219 //function :  SupressFaces
220 //purpose  :
221 //=======================================================================
222 void GEOMImpl_HealingDriver::SuppressFacesRec (const TopTools_SequenceOfShape& theShapesFaces,
223                                                const TopoDS_Shape&             theOriginalShape,
224                                                TopoDS_Shape&                   theOutShape) const
225 {
226   if ((theOriginalShape.ShapeType() != TopAbs_COMPOUND &&
227        theOriginalShape.ShapeType() != TopAbs_COMPSOLID))
228   {
229     ShHealOper_RemoveFace aHealer (theOriginalShape);
230     Standard_Boolean aResult = aHealer.Perform(theShapesFaces);
231
232     if (aResult)
233       theOutShape = aHealer.GetResultShape();
234     else
235       raiseNotDoneExeption(aHealer.GetErrorStatus());
236   }
237   else
238   {
239     BRep_Builder BB;
240     TopoDS_Compound CC;
241     BB.MakeCompound(CC);
242
243     TopTools_MapOfShape mapShape;
244     TopoDS_Iterator It (theOriginalShape, Standard_True, Standard_True);
245
246     for (; It.More(); It.Next()) {
247       TopoDS_Shape aShape_i = It.Value();
248       if (mapShape.Add(aShape_i)) {
249         // check, if current shape contains at least one of faces to be removed
250         bool isFound = false;
251         TopTools_IndexedMapOfShape aShapes_i;
252         TopExp::MapShapes(aShape_i, aShapes_i);
253         for (int i = 1; i <= theShapesFaces.Length() && !isFound; i++) {
254           const TopoDS_Shape& aFace_i = theShapesFaces.Value(i);
255           if (aShapes_i.Contains(aFace_i)) isFound = true;
256         }
257         if (isFound) {
258           TopoDS_Shape anOutSh_i;
259           SuppressFacesRec(theShapesFaces, aShape_i, anOutSh_i);
260           if ( !anOutSh_i.IsNull() )
261             BB.Add(CC, anOutSh_i);
262         }
263         else {
264           // nothing to do
265           BB.Add(CC, aShape_i);
266         }
267       }
268     }
269     theOutShape = CC;
270   }
271 }
272
273 Standard_Boolean GEOMImpl_HealingDriver::SuppressFaces (GEOMImpl_IHealing* theHI,
274                                                         const TopoDS_Shape& theOriginalShape,
275                                                         TopoDS_Shape& theOutShape) const
276 {
277   Handle(TColStd_HArray1OfInteger) aFaces = theHI->GetFaces();
278
279   Standard_Boolean aResult = Standard_False;
280
281   if (aFaces.IsNull()) {
282     ShHealOper_RemoveFace aHealer (theOriginalShape);
283     aResult = aHealer.Perform();
284
285     if (aResult)
286       theOutShape = aHealer.GetResultShape();
287     else
288       raiseNotDoneExeption(aHealer.GetErrorStatus());
289   }
290   else {
291     TopTools_SequenceOfShape aShapesFaces;
292     TopTools_IndexedMapOfShape aShapes;
293     TopExp::MapShapes(theOriginalShape, aShapes);
294     for (int i = 1; i <= aFaces->Length(); i++) {
295       int indexOfFace = aFaces->Value(i);
296       TopoDS_Shape aFace = aShapes.FindKey(indexOfFace);
297       aShapesFaces.Append(aFace);
298     }
299     SuppressFacesRec(aShapesFaces, theOriginalShape, theOutShape);
300     if ((theOriginalShape.ShapeType() == TopAbs_COMPOUND ||
301          theOriginalShape.ShapeType() == TopAbs_COMPSOLID)) {
302       TopoDS_Shape aSh = theOutShape;
303       theOutShape = GEOMImpl_GlueDriver::GlueFaces(aSh, Precision::Confusion(), Standard_True);
304     }
305   }
306   // count removed faces
307   TopTools_IndexedMapOfShape faces;
308   TopExp::MapShapes(theOriginalShape, TopAbs_FACE, faces);
309   int nbBefore = faces.Extent();
310   faces.Clear();
311   TopExp::MapShapes(theOutShape, TopAbs_FACE, faces);
312   int nbAfter = faces.Extent();
313
314   if ( nbAfter < nbBefore )
315   {
316     ShHealOper_Tool tool;
317     ShHealOper_ModifStats& stats = tool.GetStatistics();
318     stats.AddModif( "Face removed", nbBefore - nbAfter );
319     SaveStatistics( tool );
320   }
321
322   return Standard_True;
323 }
324
325 //=======================================================================
326 //function :  CloseContour
327 //purpose  :
328 //=======================================================================
329 Standard_Boolean GEOMImpl_HealingDriver::CloseContour (GEOMImpl_IHealing* theHI,
330                                                        const TopoDS_Shape& theOriginalShape,
331                                                        TopoDS_Shape& theOutShape) const
332 {
333   Standard_Boolean isByVertex = theHI->GetIsCommonVertex();
334   Handle(TColStd_HArray1OfInteger) aWires = theHI->GetWires();
335
336   ShHealOper_CloseContour aHealer (theOriginalShape);
337
338   Standard_Boolean aResult = Standard_False;
339   if ( aWires.IsNull() ) {
340     if ( theOriginalShape.ShapeType() == TopAbs_WIRE )
341       aResult = aHealer.Perform(TopoDS::Wire(theOriginalShape), isByVertex, !isByVertex);
342   }
343   else {
344     TopTools_SequenceOfShape aShapesWires;
345     TopTools_IndexedMapOfShape aShapes;
346     TopExp::MapShapes(theOriginalShape, aShapes);
347     for (int i = 1; i <= aWires->Length(); i++) {
348       int indexOfWire = aWires->Value(i);
349       TopoDS_Shape aWire = aShapes.FindKey(indexOfWire);
350       aShapesWires.Append(aWire);
351     }
352
353     aResult = aHealer.Perform( aShapesWires, isByVertex, !isByVertex );
354   }
355
356   if (aResult)
357     theOutShape = aHealer.GetResultShape();
358   else
359     raiseNotDoneExeption( aHealer.GetErrorStatus() );
360
361   SaveStatistics( aHealer );
362
363   return aResult;
364 }
365
366 //=======================================================================
367 //function :  RemoveIntWires
368 //purpose  :
369 //=======================================================================
370 Standard_Boolean GEOMImpl_HealingDriver::RemoveIntWires (GEOMImpl_IHealing* theHI,
371                                                          const TopoDS_Shape& theOriginalShape,
372                                                          TopoDS_Shape& theOutShape) const
373 {
374   Handle(TColStd_HArray1OfInteger) aWires = theHI->GetWires();
375
376   ShHealOper_RemoveInternalWires aHealer(theOriginalShape);
377
378   Standard_Boolean aResult = Standard_False;
379   if (aWires.IsNull()) { // remove all faces
380     aResult = aHealer.Remove();
381   } else {
382     TopTools_SequenceOfShape aShapesWires;
383     TopTools_IndexedMapOfShape aShapes;
384     TopExp::MapShapes(theOriginalShape, aShapes);
385     for (int i = 1; i <= aWires->Length(); i++) {
386       int indexOfWire = aWires->Value(i);
387       TopoDS_Shape aWire = aShapes.FindKey(indexOfWire);
388       aShapesWires.Append(aWire);
389     }
390
391     aResult = aHealer.Remove(aShapesWires);
392   }
393
394   if (aResult)
395     theOutShape = aHealer.GetResultShape();
396   else
397     raiseNotDoneExeption( aHealer.GetErrorStatus() );
398
399   SaveStatistics( aHealer );
400
401   return aResult;
402 }
403
404 //=======================================================================
405 //function :  RemoveHoles
406 //purpose  :
407 //=======================================================================
408 Standard_Boolean GEOMImpl_HealingDriver::RemoveHoles (GEOMImpl_IHealing* theHI,
409                                                       const TopoDS_Shape& theOriginalShape,
410                                                       TopoDS_Shape& theOutShape) const
411 {
412   Handle(TColStd_HArray1OfInteger) aWires = theHI->GetWires();
413
414   ShHealOper_FillHoles aHealer (theOriginalShape);
415
416   Standard_Boolean aResult = Standard_False;
417   if (aWires.IsNull()) { // remove all faces
418     aResult = aHealer.Fill();
419   } else {
420     TopTools_SequenceOfShape aShapesWires;
421     TopTools_IndexedMapOfShape aShapes;
422     TopExp::MapShapes(theOriginalShape, aShapes);
423     for (int i = 1; i <= aWires->Length(); i++) {
424       int indexOfWire = aWires->Value(i);
425       TopoDS_Shape aWire = aShapes.FindKey(indexOfWire);
426       aShapesWires.Append(aWire);
427     }
428
429     aResult = aHealer.Fill(aShapesWires);
430   }
431
432   if (aResult)
433     theOutShape = aHealer.GetResultShape();
434   else
435     raiseNotDoneExeption( aHealer.GetErrorStatus() );
436
437   SaveStatistics( aHealer );
438
439   return aResult;
440 }
441
442 //=======================================================================
443 //function :  Sew
444 //purpose  :
445 //=======================================================================
446 Standard_Boolean GEOMImpl_HealingDriver::Sew (GEOMImpl_IHealing*  theHI,
447                                               const TopoDS_Shape& theOriginalShape,
448                                               TopoDS_Shape&       theOutShape,
449                                               Standard_Boolean    isAllowNonManifold) const
450 {
451   Standard_Real aTol = theHI->GetTolerance();
452
453   TopoDS_Compound aCompound;
454   BRep_Builder builder;
455   builder.MakeCompound( aCompound );
456
457   builder.Add( aCompound, theOriginalShape );
458   Handle(TColStd_HSequenceOfTransient) otherObjs = theHI->GetShapes();
459   for ( int ind = 1; ind <= otherObjs->Length(); ind++)
460   {
461     Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(otherObjs->Value(ind));
462     builder.Add( aCompound, aRefShape->GetValue() );
463   }
464
465   ShHealOper_Sewing aHealer (aCompound, aTol);
466
467   // Set non-manifold mode.
468   aHealer.SetNonManifoldMode(isAllowNonManifold);
469
470   Standard_Boolean aResult = aHealer.Perform();
471
472   if (aResult)
473     theOutShape = aHealer.GetResultShape();
474   else
475     raiseNotDoneExeption( aHealer.GetErrorStatus() );
476
477   SaveStatistics( aHealer );
478
479   return aResult;
480 }
481
482 //=======================================================================
483 //function : RemoveInternalFaces
484 //purpose  :
485 //=======================================================================
486 Standard_Boolean
487 GEOMImpl_HealingDriver::RemoveInternalFaces (GEOMImpl_IHealing*  theHI,
488                                              const TopoDS_Shape& theOriginalShape,
489                                              TopoDS_Shape&       theOutShape) const
490 {
491   // get all input shapes
492   TopTools_SequenceOfShape shapeSeq;
493   shapeSeq.Append( theOriginalShape );
494   Handle(TColStd_HSequenceOfTransient) otherObjs = theHI->GetShapes();
495   if ( !otherObjs.IsNull() )
496     for ( int ind = 1; ind <= otherObjs->Length(); ind++)
497     {
498       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(otherObjs->Value(ind));
499       TopoDS_Shape aShape = aRefShape->GetValue();
500       if (aShape.IsNull())
501         Standard_NullObject::Raise("Null object given");
502       shapeSeq.Append( aShape );
503     }
504
505   // pass input shapes to the algorithm
506   GEOMAlgo_RemoverWebs aTool;
507   if ( shapeSeq.Length() == 1 )
508   {
509     aTool.SetShape( shapeSeq.First() );
510   }
511   else
512   {
513     TopoDS_Compound solidCompound;
514     BRep_Builder builder;
515     builder.MakeCompound( solidCompound );
516     for ( int ind = 1; ind <= shapeSeq.Length(); ++ind )
517       for ( TopExp_Explorer so( shapeSeq( ind ), TopAbs_SOLID ); so.More(); so.Next() )
518         builder.Add( solidCompound, so.Current() );
519
520     aTool.SetShape( solidCompound );
521   }
522
523   // run the algorithm
524   aTool.Perform();
525
526   if (aTool.ErrorStatus() == 0) { // OK
527     theOutShape = aTool.Result();
528
529     // as GEOMAlgo_RemoverWebs always produces compound, lets simplify it
530     // for the case, if it contains only one sub-shape
531     TopTools_ListOfShape listShapeRes;
532     GEOMUtils::AddSimpleShapes(theOutShape, listShapeRes);
533     if (listShapeRes.Extent() == 1) {
534       theOutShape = listShapeRes.First();
535     }
536   }
537   else if (aTool.ErrorStatus() == 11) // invalid argument (contains non-solids), do nothing
538     theOutShape = theOriginalShape;
539   else // error
540     StdFail_NotDone::Raise("GEOMAlgo_RemoverWebs failed!");
541
542   return Standard_True;
543 }
544
545 //=======================================================================
546 //function :  AddPointOnEdge
547 //purpose  :
548 //=======================================================================
549 Standard_Boolean GEOMImpl_HealingDriver::AddPointOnEdge (GEOMImpl_IHealing*  theHI,
550                                                          const TopoDS_Shape& theOriginalShape,
551                                                          TopoDS_Shape&       theOutShape) const
552 {
553   Standard_Boolean isByParameter = theHI->GetIsByParameter();
554   Standard_Integer       anIndex = theHI->GetIndex();
555   Standard_Real           aValue = theHI->GetDevideEdgeValue();
556
557   TopoDS_Shape pointToProject;
558   {
559     Handle(TColStd_HSequenceOfTransient) funs = theHI->GetShapes();
560     if ( !funs.IsNull() && funs->Length() > 0 ) {
561       TopoDS_Compound vCompound;
562       BRep_Builder builder;
563       builder.MakeCompound( vCompound );
564       pointToProject = vCompound;
565       for ( int ind = 1; ind <= funs->Length(); ind++)
566       {
567         Handle(GEOM_Function) vFun = Handle(GEOM_Function)::DownCast(funs->Value(ind));
568         TopoDS_Shape vertex = vFun->GetValue();
569         if ( vertex.IsNull() )
570           Standard_NullObject::Raise("Null vertex given");
571         builder.Add( vCompound, vertex );
572       }
573     }
574   }
575
576   ShHealOper_EdgeDivide aHealer (theOriginalShape);
577
578   Standard_Boolean aResult = Standard_False;
579   if (anIndex == -1) { // apply algorithm for the whole shape which is EDGE
580     if (theOriginalShape.ShapeType() == TopAbs_EDGE) {
581       if ( pointToProject.IsNull() )
582         aResult = aHealer.Perform(TopoDS::Edge(theOriginalShape), aValue, isByParameter);
583       else
584         aResult = aHealer.Perform(TopoDS::Edge(theOriginalShape), pointToProject);
585     }
586   } else {
587     TopTools_IndexedMapOfShape aShapes;
588     TopExp::MapShapes(theOriginalShape, aShapes);
589     TopoDS_Shape aEdgeShape = aShapes.FindKey(anIndex);
590     if (aEdgeShape.ShapeType() == TopAbs_EDGE) {
591       if ( pointToProject.IsNull() )
592         aResult = aHealer.Perform(TopoDS::Edge(aEdgeShape), aValue, isByParameter);
593       else
594         aResult = aHealer.Perform(TopoDS::Edge(aEdgeShape), pointToProject);
595     }
596   }
597
598   if (aResult)
599     theOutShape = aHealer.GetResultShape();
600   else
601     raiseNotDoneExeption( aHealer.GetErrorStatus() );
602
603   SaveStatistics( aHealer );
604
605   return aResult;
606 }
607
608
609 //=======================================================================
610 //function :  ChangeOrientation
611 //purpose  :
612 //=======================================================================
613 Standard_Boolean GEOMImpl_HealingDriver::ChangeOrientation (GEOMImpl_IHealing* /*theHI*/,
614                                                             const TopoDS_Shape& theOriginalShape,
615                                                             TopoDS_Shape& theOutShape) const
616 {
617   ShHealOper_ChangeOrientation aHealer (theOriginalShape);
618
619   Standard_Boolean aResult = aHealer.Perform();
620
621   if (aResult)
622     theOutShape = aHealer.GetResultShape();
623   else
624     raiseNotDoneExeption( aHealer.GetErrorStatus() );
625
626   SaveStatistics( aHealer );
627
628   return aResult;
629 }
630
631 //=======================================================================
632 //function : LimitTolerance
633 //purpose  :
634 //=======================================================================
635 void GEOMImpl_HealingDriver::LimitTolerance (GEOMImpl_IHealing* theHI,
636                                              const TopoDS_Shape& theOriginalShape,
637                                              TopoDS_Shape& theOutShape) const
638 {
639   Standard_Real aTol = theHI->GetTolerance();
640   TopAbs_ShapeEnum aType = theHI->GetType();
641
642   if (aTol < Precision::Confusion())
643     aTol = Precision::Confusion();
644
645   // 1. Make a copy to prevent the original shape changes.
646   TopoDS_Shape aShapeCopy;
647   {
648     TColStd_IndexedDataMapOfTransientTransient aMapTShapes;
649     TNaming_CopyShape::CopyTool(theOriginalShape, aMapTShapes, aShapeCopy);
650   }
651
652   // 2. Limit tolerance.
653   if (!GEOMUtils::FixShapeTolerance(aShapeCopy, aType, aTol))
654     StdFail_NotDone::Raise("Non valid shape result");
655
656   // 3. Set the result
657   theOutShape = aShapeCopy;
658
659   // 4. Collect statistics
660   {
661     ShHealOper_Tool tool;
662     ShHealOper_ModifStats& stats = tool.GetStatistics();
663
664     int nb[3] = { 0,0,0 };
665     TopTools_IndexedMapOfShape aShapes;
666     TopExp::MapShapes( theOutShape, TopAbs_VERTEX, aShapes);
667     for ( int i = 1; i <= aShapes.Extent(); ++i )
668     {
669       const TopoDS_Vertex& v = TopoDS::Vertex( aShapes( i ));
670       double tol = BRep_Tool::Tolerance( v );
671       if      ( tol < aTol ) nb[0]++;
672       else if ( tol > aTol ) nb[2]++;
673       else                   nb[1]++;
674     }
675     if ( nb[0] > 0 )
676       stats.AddModif( "Tolerance of vertex decreased for shape validity", nb[0] );
677     if ( nb[1] > 0 )
678       stats.AddModif( "Tolerance of vertex limited as requested", nb[1] );
679     if ( nb[2] > 0 )
680       stats.AddModif( "Tolerance of vertex increased for shape validity", nb[2] );
681
682     nb[0] = nb[1] = nb[2] = 0;
683     aShapes.Clear();
684     TopExp::MapShapes( theOutShape, TopAbs_EDGE, aShapes);
685     for ( int i = 1; i <= aShapes.Extent(); ++i )
686     {
687       const TopoDS_Edge& e = TopoDS::Edge( aShapes( i ));
688       double tol = BRep_Tool::Tolerance( e );
689       if      ( tol < aTol ) nb[0]++;
690       else if ( tol > aTol ) nb[2]++;
691       else                   nb[1]++;
692     }
693     if ( nb[0] > 0 )
694       stats.AddModif( "Tolerance of edge decreased for shape validity", nb[0] );
695     if ( nb[1] > 0 )
696       stats.AddModif( "Tolerance of edge limited as requested", nb[1] );
697     if ( nb[2] > 0 )
698       stats.AddModif( "Tolerance of edge increased for shape validity", nb[2] );
699
700     nb[0] = nb[1] = nb[2] = 0;
701     aShapes.Clear();
702     TopExp::MapShapes( theOutShape, TopAbs_FACE, aShapes);
703     for ( int i = 1; i <= aShapes.Extent(); ++i )
704     {
705       const TopoDS_Face& f = TopoDS::Face( aShapes( i ));
706       double tol = BRep_Tool::Tolerance( f );
707       if      ( tol < aTol ) nb[0]++;
708       else if ( tol > aTol ) nb[2]++;
709       else                   nb[1]++;
710     }
711     if ( nb[0] > 0 )
712       stats.AddModif( "Tolerance of face decreased for shape validity", nb[0] );
713     if ( nb[1] > 0 )
714       stats.AddModif( "Tolerance of face limited as requested", nb[1] );
715     if ( nb[2] > 0 )
716       stats.AddModif( "Tolerance of face increased for shape validity", nb[2] );
717
718     SaveStatistics( tool );
719   }
720 }
721
722 //=======================================================================
723 //function : FuseCollinearEdges
724 //purpose  :
725 //=======================================================================
726 void GEOMImpl_HealingDriver::FuseCollinearEdges (const TopoDS_Shape& theOriginalShape,
727                                                  const Handle(TColStd_HSequenceOfTransient)& aVerts,
728                                                  TopoDS_Shape& theOutShape)
729 {
730   if (theOriginalShape.ShapeType() != TopAbs_WIRE)
731     Standard_TypeMismatch::Raise("Not a wire is given");
732
733   // Tolerances
734   Standard_Real AngTol = Precision::Angular();
735   Standard_Real LinTol = Precision::Confusion();
736   Standard_Real tol;
737   for (TopExp_Explorer ExV (theOriginalShape, TopAbs_VERTEX); ExV.More(); ExV.Next()) {
738     TopoDS_Vertex Vertex = TopoDS::Vertex(ExV.Current());
739     tol = BRep_Tool::Tolerance(Vertex);
740     if (tol > LinTol)
741       LinTol = tol;
742   }
743
744   // 1. Make a copy to prevent the original shape changes.
745   TopoDS_Shape aWire;
746   TColStd_IndexedDataMapOfTransientTransient aMapTShapes;
747   TNaming_CopyShape::CopyTool(theOriginalShape, aMapTShapes, aWire);
748   TopoDS_Wire theWire = TopoDS::Wire(aWire);
749
750   // 2. Sub-shapes of the wire
751   TopTools_MapOfShape aMapToRemove;
752
753   TopTools_IndexedMapOfShape anOldIndices;
754   TopExp::MapShapes(theOriginalShape, anOldIndices);
755
756   TopTools_IndexedMapOfShape aNewIndices;
757   TopExp::MapShapes(theWire, aNewIndices);
758
759   // 3. Collect vertices of the wire, same or equal to the given vertices
760   bool removeAll = false;
761   if (aVerts.IsNull() || aVerts->Length() < 1)
762     removeAll = true;
763
764   if (!removeAll) {
765     for ( int ind = 1; ind <= aVerts->Length(); ind++) {
766       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aVerts->Value(ind));
767       TopoDS_Shape aShape_i = aRefShape->GetValue();
768       if (aShape_i.IsNull())
769         Standard_NullObject::Raise("Null vertex given");
770       if (aShape_i.ShapeType() != TopAbs_VERTEX)
771         Standard_TypeMismatch::Raise("Shape to suppress is not a vertex");
772
773       // find vertices shared with the initial wire
774       if (anOldIndices.Contains(aShape_i)) {
775         aMapToRemove.Add(aNewIndices.FindKey(anOldIndices.FindIndex(aShape_i)));
776       } else {
777         // try to find by coords in the new wire
778         TopoDS_Vertex aVert = TopoDS::Vertex(aShape_i);
779         gp_Pnt aP = BRep_Tool::Pnt(aVert);
780
781         bool isFound = false;
782         TopTools_MapOfShape mapShape;
783         TopExp_Explorer exp (theWire, TopAbs_VERTEX);
784         for (; exp.More() && !isFound; exp.Next()) {
785           if (mapShape.Add(exp.Current())) {
786             TopoDS_Vertex aVi = TopoDS::Vertex(exp.Current());
787             gp_Pnt aPi = BRep_Tool::Pnt(aVi);
788             if (aPi.Distance(aP) < LinTol) {
789               aMapToRemove.Add(aVi);
790               isFound = true;
791             }
792           }
793         }
794       }
795     }
796   }
797
798   /*
799   BRepLib::BuildCurves3d(theWire);
800   Handle(ShapeFix_Shape) Fixer = new ShapeFix_Shape(theWire);
801   Fixer->SetPrecision(LinTol);
802   Fixer->SetMaxTolerance(LinTol);
803   Fixer->Perform();
804   theWire = TopoDS::Wire(Fixer->Shape());
805   */
806
807   // Get the ordered list of edges.
808   TopTools_ListOfShape   anEdges;
809   TopTools_ListOfShape   aCurVertices;
810   BRepTools_WireExplorer aWExp (theWire);
811
812   for (; aWExp.More(); aWExp.Next()) {
813     anEdges.Append(aWExp.Current());
814     aCurVertices.Append(aWExp.CurrentVertex());
815   }
816
817   if (anEdges.IsEmpty()) {
818     Standard_NullObject::Raise("Empty wire given");
819   }
820
821   // Treat the case if the wire is closed and first and last edges are C1.
822   Standard_Boolean isShift = Standard_False;
823
824   if (BRep_Tool::IsClosed(theWire)) {
825     // Wire is closed. Check if there are more than 2 edges in the wire.
826     if (!anEdges.First().IsSame(anEdges.Last())) {
827       isShift = Standard_True;
828     }
829   }
830
831   if (isShift) {
832     // Put first edge to the end of the list while the chain break is reached.
833     TopoDS_Shape aFirstEdge = anEdges.First();
834
835     while (isShift) {
836       isShift = Standard_False;
837
838       // Check if the first vertex should be kept
839       if (aMapToRemove.Contains(aCurVertices.First()) || removeAll) {
840         // Check if first and last edges are C1.
841         TopoDS_Edge anEdge1 = TopoDS::Edge(anEdges.Last());
842         TopoDS_Edge anEdge2 = TopoDS::Edge(anEdges.First());
843
844         if (AreEdgesC1(anEdge1, anEdge2)) {
845           // Make the first edge last.
846           anEdges.Append(anEdge2);
847           anEdges.RemoveFirst();
848           aCurVertices.Append(aCurVertices.First());
849           aCurVertices.RemoveFirst();
850
851           // Check if we reached the first edge again.
852           // Break the loop in this case.
853           isShift = !aFirstEdge.IsSame(anEdges.First());
854         }
855       }
856     }
857   }
858
859   TopTools_ListOfShape finalList, currChain;
860   TopTools_ListIteratorOfListOfShape anEIter(anEdges);
861   TopTools_ListIteratorOfListOfShape aVIter(aCurVertices);
862   TopoDS_Edge                        prevEdge = TopoDS::Edge(anEIter.Value());
863
864   currChain.Append(prevEdge);
865   anEIter.Next();
866   aVIter.Next();
867
868   for (; anEIter.More(); anEIter.Next(), aVIter.Next()) {
869     TopoDS_Edge         anEdge     = TopoDS::Edge(anEIter.Value());
870     const TopoDS_Shape &aCurVertex = aVIter.Value();
871
872     bool continueChain = false;
873     if (aMapToRemove.Contains(aCurVertex) || removeAll) {
874       // if C1 -> continue chain
875       if (AreEdgesC1(prevEdge, anEdge)) {
876         continueChain = true;
877       }
878     }
879
880     if (!continueChain) {
881       if (currChain.Extent() == 1) {
882         // add one edge to the final list
883         finalList.Append(currChain.First());
884       }
885       else {
886         // make wire from the list of edges
887         BRep_Builder B;
888         TopoDS_Wire aCurrWire;
889         B.MakeWire(aCurrWire);
890         TopTools_ListIteratorOfListOfShape itEdges (currChain);
891         for (; itEdges.More(); itEdges.Next()) {
892           TopoDS_Shape aValue = itEdges.Value();
893           B.Add(aCurrWire, TopoDS::Edge(aValue));
894         }
895
896         // make edge from the wire
897         TopoDS_Edge anEdge = GEOMImpl_ShapeDriver::MakeEdgeFromWire(aCurrWire, LinTol, AngTol);
898
899         // add this new edge to the final list
900         finalList.Append(anEdge);
901       }
902       currChain.Clear();
903     }
904
905     // add one edge to the chain
906     currChain.Append(anEdge);
907     prevEdge = anEdge;
908   }
909
910   if (currChain.Extent() == 1) {
911     // add one edge to the final list
912     finalList.Append(currChain.First());
913   }
914   else {
915     // make wire from the list of edges
916     BRep_Builder B;
917     TopoDS_Wire aCurrWire;
918     B.MakeWire(aCurrWire);
919     TopTools_ListIteratorOfListOfShape itEdges (currChain);
920     for (; itEdges.More(); itEdges.Next()) {
921       TopoDS_Shape aValue = itEdges.Value();
922       B.Add(aCurrWire, TopoDS::Edge(aValue));
923     }
924
925     // make edge from the wire
926     TopoDS_Edge anEdge = GEOMImpl_ShapeDriver::MakeEdgeFromWire(aCurrWire, LinTol, AngTol);
927
928     // add this new edge to the final list
929     finalList.Append(anEdge);
930   }
931
932   BRep_Builder B;
933   TopoDS_Wire aFinalWire;
934   B.MakeWire(aFinalWire);
935   TopTools_ListIteratorOfListOfShape itEdges (finalList);
936   for (; itEdges.More(); itEdges.Next()) {
937     TopoDS_Shape aValue = itEdges.Value();
938     B.Add(aFinalWire, TopoDS::Edge(aValue));
939   }
940   theOutShape = aFinalWire;
941
942   if (!GEOMUtils::CheckShape(theOutShape, true))
943     StdFail_NotDone::Raise("Non valid shape result");
944 }
945
946 //=======================================================================
947 //function : AreEdgesC1
948 //purpose  :
949 //=======================================================================
950 Standard_Boolean GEOMImpl_HealingDriver::AreEdgesC1 (const TopoDS_Edge& E1, const TopoDS_Edge& E2)
951 {
952   BRepAdaptor_Curve aCurve1 (E1);
953   BRepAdaptor_Curve aCurve2 (E2);
954
955   if (aCurve1.Continuity() == GeomAbs_C0 || aCurve2.Continuity() == GeomAbs_C0)
956     return Standard_False;
957
958   Standard_Real tol, tolMax = Precision::Confusion();
959   for (TopExp_Explorer ExV1 (E1, TopAbs_VERTEX); ExV1.More(); ExV1.Next()) {
960     TopoDS_Vertex Vertex = TopoDS::Vertex(ExV1.Current());
961     tol = BRep_Tool::Tolerance(Vertex);
962       if (tol > tolMax)
963         tolMax = tol;
964   }
965   for (TopExp_Explorer ExV2 (E2, TopAbs_VERTEX); ExV2.More(); ExV2.Next()) {
966     TopoDS_Vertex Vertex = TopoDS::Vertex(ExV2.Current());
967     tol = BRep_Tool::Tolerance(Vertex);
968       if (tol > tolMax)
969         tolMax = tol;
970   }
971
972   Standard_Real f1, l1, f2, l2;
973   f1 = aCurve1.FirstParameter();
974   l1 = aCurve1.LastParameter();
975   f2 = aCurve2.FirstParameter();
976   l2 = aCurve2.LastParameter();
977
978   if (f1 > l1) {
979     Standard_Real tmp = f1;
980     f1 = l1;
981     l1 = tmp;
982   }
983
984   if (f2 > l2) {
985     Standard_Real tmp = f2;
986     f2 = l2;
987     l2 = tmp;
988   }
989
990   gp_Pnt pf1, pl1, pf2, pl2;
991   gp_Vec vf1, vl1, vf2, vl2;
992   aCurve1.D1(f1, pf1, vf1);
993   aCurve1.D1(l1, pl1, vl1);
994   aCurve2.D1(f2, pf2, vf2);
995   aCurve2.D1(l2, pl2, vl2);
996
997   // pf1--->---pl1.pf2--->---pl2
998   if (pl1.SquareDistance(pf2) < tolMax*tolMax) {
999     if (vl1.Angle(vf2) < Precision::Angular())
1000       return Standard_True;
1001   }
1002   // pl1---<---pf1.pf2--->---pl2
1003   else if (pf1.SquareDistance(pf2) < tolMax*tolMax) {
1004     if (vf1.Angle(-vf2) < Precision::Angular())
1005       return Standard_True;
1006   }
1007   // pf1--->---pl1.pl2---<---pf2
1008   else if (pl1.SquareDistance(pl2) < tolMax*tolMax) {
1009     if (vl1.Angle(-vl2) < Precision::Angular())
1010       return Standard_True;
1011   }
1012   // pl1---<---pf1.pl2---<---pf2
1013   else {
1014     if (vf1.Angle(vl2) < Precision::Angular())
1015       return Standard_True;
1016   }
1017
1018   return Standard_False;
1019 }
1020
1021 //================================================================================
1022 /*!
1023  * \brief Returns a name of creation operation and names and values of creation parameters
1024  */
1025 //================================================================================
1026
1027 bool GEOMImpl_HealingDriver::
1028 GetCreationInformation(std::string&             theOperationName,
1029                        std::vector<GEOM_Param>& theParams)
1030 {
1031   if (Label().IsNull()) return 0;
1032   Handle(GEOM_Function) function = GEOM_Function::GetFunction(Label());
1033
1034   GEOMImpl_IHealing aCI( function );
1035   Standard_Integer aType = function->GetType();
1036
1037   switch ( aType ) {
1038   case SHAPE_PROCESS:
1039   {
1040     theOperationName = "SHAPE_PROCESS";
1041     AddParam( theParams, "Object", aCI.GetOriginal() );
1042     Handle(TColStd_HArray1OfExtendedString) anOperators = aCI.GetOperators();
1043     Handle(TColStd_HArray1OfExtendedString) aParams     = aCI.GetParameters();
1044     Handle(TColStd_HArray1OfExtendedString) aValues     = aCI.GetValues();
1045     for ( int i = anOperators->Lower(), nb = anOperators->Upper(); i <= nb; ++i )
1046     {
1047       const TCollection_ExtendedString& op = anOperators->Value(i);
1048       AddParam( theParams, "Operation", op );
1049       for ( int iP = aParams->Lower(), nbP = aParams->Upper(); iP <= nbP; ++iP )
1050       {
1051         const TCollection_ExtendedString& par = aParams->Value(iP);
1052         TCollection_AsciiString parAscii( par );
1053         if ( par.Search( op ) == 1 && parAscii.Value( op.Length() + 1 ) == '.' )
1054         {
1055           GEOM_Param& p = AddParam( theParams, parAscii.ToCString() );
1056           if ( iP <= aValues->Upper() )
1057             p << aValues->Value( iP );
1058         }
1059       }
1060     }
1061     break;
1062   }
1063   case SUPPRESS_FACES:
1064     theOperationName = "SUPPRESS_FACES";
1065     AddParam( theParams, "Selected Shape", aCI.GetOriginal() );
1066     AddParam( theParams, "Faces to remove", aCI.GetFaces() );
1067     break;
1068   case CLOSE_CONTOUR:
1069     theOperationName = "CLOSE_CONTOUR";
1070     AddParam( theParams, "Selected Shape", aCI.GetOriginal() );
1071     AddParam( theParams, "Contour to close", aCI.GetWires() );
1072     AddParam( theParams, "Close by common vertex", aCI.GetIsCommonVertex() );
1073     break;
1074   case REMOVE_INT_WIRES:
1075     theOperationName = "SUPPRESS_INT_WIRES";
1076     AddParam( theParams, "Selected face", aCI.GetOriginal() );
1077     AddParam( theParams, "Wires to remove", aCI.GetWires(), "all" );
1078     break;
1079   case FILL_HOLES:
1080     theOperationName = "SUPPERSS_HOLES";
1081     AddParam( theParams, "Selected shape", aCI.GetOriginal() );
1082     AddParam( theParams, "Wires to remove", aCI.GetWires(), "all" );
1083     break;
1084   case SEWING:
1085   case SEWING_NON_MANIFOLD:
1086     theOperationName = "SEWING";
1087     AddParam( theParams, "Selected shapes", aCI.GetOriginalAndShapes() );
1088     AddParam( theParams, "Allow Non Manifold", ( aType == SEWING_NON_MANIFOLD ));
1089     AddParam( theParams, "Tolerance", aCI.GetTolerance() );
1090     break;
1091   case DIVIDE_EDGE:
1092     theOperationName = "POINT_ON_EDGE";
1093     if ( aCI.GetIndex() > 0 )
1094       AddParam( theParams, "Edge", "#" ) << aCI.GetIndex() << " of " << aCI.GetOriginal();
1095     else
1096       AddParam( theParams, "Edge", aCI.GetOriginal() );
1097     AddParam( theParams, "By parameter", aCI.GetIsByParameter() );
1098     AddParam( theParams, "Value", aCI.GetDevideEdgeValue() );
1099     break;
1100   case DIVIDE_EDGE_BY_POINT:
1101     theOperationName = "POINT_ON_EDGE";
1102     if ( aCI.GetIndex() > 0 )
1103       AddParam( theParams, "Edge", "#" ) << aCI.GetIndex() << " of " << aCI.GetOriginal();
1104     else
1105       AddParam( theParams, "Edge", aCI.GetOriginal() );
1106     AddParam( theParams, "Points", aCI.GetShapes() );
1107     break;
1108   case CHANGE_ORIENTATION:
1109     theOperationName = "CHANGE_ORIENTATION";
1110     AddParam( theParams, "Selected shape", aCI.GetOriginal() );
1111     break;
1112   case LIMIT_TOLERANCE:
1113     theOperationName = "LIMIT_TOLERANCE";
1114     AddParam( theParams, "Selected shape", aCI.GetOriginal() );
1115     AddParam( theParams, "Tolerance", aCI.GetTolerance() );
1116     AddParam( theParams, "Type", aCI.GetType() );
1117     break;
1118   case FUSE_COLLINEAR_EDGES:
1119     theOperationName = "FUSE_EDGES";
1120     AddParam( theParams, "Wire", aCI.GetOriginal() );
1121     AddParam( theParams, "Vertexes", aCI.GetShapes() );
1122     break;
1123   case REMOVE_INTERNAL_FACES:
1124     theOperationName = "REMOVE_WEBS";
1125     AddParam( theParams, "Selected shapes", aCI.GetOriginalAndShapes() );
1126     break;
1127   default:
1128     return false;
1129   }
1130   
1131   return true;
1132 }
1133
1134 //================================================================================
1135 /*!
1136  * \brief Pass a record of what is done to the operation
1137  */
1138 //================================================================================
1139
1140 void GEOMImpl_HealingDriver::SaveStatistics( const ShHealOper_Tool& healer, bool add ) const
1141 {
1142   if ( healer.GetStatistics().GetData().empty() )
1143     return;
1144
1145   if (Label().IsNull()) return;
1146
1147   Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
1148   if (aFunction.IsNull()) return;
1149
1150   GEOMImpl_IHealing HI (aFunction);
1151   ShHealOper_ModifStats * stats = HI.GetStatistics();
1152   if ( !stats ) return;
1153
1154   if ( add )
1155     stats->Add( healer.GetStatistics() );
1156   else
1157     *stats = healer.GetStatistics();
1158 }
1159
1160 IMPLEMENT_STANDARD_RTTIEXT (GEOMImpl_HealingDriver,GEOM_BaseDriver)