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