]> SALOME platform Git repositories - modules/geom.git/blob - src/GEOMImpl/GEOMImpl_IShapesOperations.cxx
Salome HOME
0052829: Failed GetSubShapeID() breaks the next IsSubShapeBelongsTo()
[modules/geom.git] / src / GEOMImpl / GEOMImpl_IShapesOperations.cxx
1 // Copyright (C) 2007-2015  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 //  File      : GEOMImpl_IShapesOperations.cxx
24 //  Created   :
25 //  Author    : modified by Lioka RAZAFINDRAZAKA (CEA) 22/06/2007
26 //  Project   : SALOME
27
28 //#include <Standard_Stream.hxx>
29
30 #include "GEOMImpl_IShapesOperations.hxx"
31
32 #include "GEOMImpl_Types.hxx"
33
34 #include "GEOMImpl_VectorDriver.hxx"
35 #include "GEOMImpl_ShapeDriver.hxx"
36 #include "GEOMImpl_GlueDriver.hxx"
37 #include "GEOMImpl_FillingDriver.hxx"
38
39 #include "GEOMImpl_IVector.hxx"
40 #include "GEOMImpl_IShapes.hxx"
41 #include "GEOMImpl_IShapeExtend.hxx"
42 #include "GEOMImpl_IGlue.hxx"
43 #include "GEOMImpl_IFilling.hxx"
44
45 #include "GEOMImpl_Block6Explorer.hxx"
46 #include "GEOMImpl_IHealingOperations.hxx"
47
48 #include "GEOMImpl_Gen.hxx"
49
50 #include "GEOM_Function.hxx"
51 #include "GEOM_ISubShape.hxx"
52 #include "GEOM_PythonDump.hxx"
53
54 #include "GEOMUtils.hxx"
55
56 #include "GEOMAlgo_ClsfBox.hxx"
57 #include "GEOMAlgo_ClsfQuad.hxx"
58 #include "GEOMAlgo_ClsfSolid.hxx"
59 #include "GEOMAlgo_ClsfSurf.hxx"
60 #include "GEOMAlgo_FinderShapeOn2.hxx"
61 #include "GEOMAlgo_GetInPlace.hxx"
62 #include "GEOMAlgo_GetInPlaceAPI.hxx"
63 #include "GEOMAlgo_GlueDetector.hxx"
64
65 #include <utilities.h>
66
67 #include <BRepAdaptor_Curve.hxx>
68 #include <BRepAdaptor_Surface.hxx>
69 #include <BRepTools.hxx>
70 #include <BRep_Builder.hxx>
71 #include <BRep_Tool.hxx>
72 #include <GeomLib_Tool.hxx>
73 #include <Geom_CylindricalSurface.hxx>
74 #include <Geom_Plane.hxx>
75 #include <Geom_SphericalSurface.hxx>
76 #include <Geom_Surface.hxx>
77 #include <Precision.hxx>
78 #include <TColStd_HArray1OfInteger.hxx>
79 #include <TDF_Tool.hxx>
80 #include <TDataStd_Integer.hxx>
81 #include <TDataStd_ListIteratorOfListOfExtendedString.hxx>
82 #include <TopExp.hxx>
83 #include <TopExp_Explorer.hxx>
84 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
85 #include <TopTools_IndexedMapOfShape.hxx>
86 #include <TopTools_ListIteratorOfListOfShape.hxx>
87 #include <TopTools_MapOfOrientedShape.hxx>
88 #include <TopTools_MapOfShape.hxx>
89 #include <TopTools_SequenceOfShape.hxx>
90 #include <TopoDS.hxx>
91 #include <TopoDS_Compound.hxx>
92 #include <TopoDS_Edge.hxx>
93 #include <TopoDS_Face.hxx>
94 #include <TopoDS_Iterator.hxx>
95 #include <TopoDS_Shape.hxx>
96 #include <TopoDS_Solid.hxx>
97 #include <TopoDS_Vertex.hxx>
98 #include <gp_Cylinder.hxx>
99 #include <gp_Pnt.hxx>
100
101 #include <vector>
102
103 #include <Standard_Failure.hxx>
104 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
105
106 namespace {
107
108   void AddFlatSubShapes(const TopoDS_Shape& S, TopTools_ListOfShape& L, TopTools_MapOfShape& M)
109   {
110     if (S.ShapeType() != TopAbs_COMPOUND) {
111       L.Append(S);
112     }
113     else {
114       TopoDS_Iterator It(S, Standard_True, Standard_True);
115       for (; It.More(); It.Next()) {
116         TopoDS_Shape SS = It.Value();
117         if (M.Add(SS))
118           AddFlatSubShapes(SS, L, M);
119       }
120     }
121   }
122 }
123
124 namespace
125 {
126   const double MAX_TOLERANCE = 1.e-7;
127
128   /**
129    * \brief Returns the vertex from theWhere shape that is coincident with
130    * theVertex.
131    *
132    * \param theWhere the shape where the coinsident vertex is searched.
133    * \param theVertex the vertex to be searched.
134    * \return the coincident vertex if it is found. Otherwise null object.
135    */
136   static TopoDS_Vertex getSameVertex(const TopoDS_Shape  &theWhere,
137                                      const TopoDS_Vertex &theVertex)
138   {
139     TopoDS_Vertex       aResult;
140     gp_Pnt              aPoint = BRep_Tool::Pnt(theVertex);
141     TopExp_Explorer     anExp(theWhere, TopAbs_VERTEX);
142     TopTools_MapOfShape aMap;
143     
144     for(; anExp.More(); anExp.Next()) {
145       const TopoDS_Shape &aLocalShape = anExp.Current();
146
147       if(!aMap.Add(aLocalShape)) {
148         continue;
149       }
150
151       TopoDS_Vertex aVertex = TopoDS::Vertex(aLocalShape);
152       gp_Pnt        aPoint2 = BRep_Tool::Pnt(aVertex);
153
154       if(aPoint.Distance(aPoint2) <= MAX_TOLERANCE) {
155         aResult = aVertex;
156         break;
157       }
158     }
159
160     return aResult;
161   }
162 } // end of namespace
163
164 //=============================================================================
165 /*!
166  *   constructor:
167  */
168 //=============================================================================
169 GEOMImpl_IShapesOperations::GEOMImpl_IShapesOperations (GEOM_Engine* theEngine, int theDocID)
170 : GEOM_IOperations(theEngine, theDocID)
171 {
172   MESSAGE("GEOMImpl_IShapesOperations::GEOMImpl_IShapesOperations");
173 }
174
175 //=============================================================================
176 /*!
177  *  destructor
178  */
179 //=============================================================================
180 GEOMImpl_IShapesOperations::~GEOMImpl_IShapesOperations()
181 {
182   MESSAGE("GEOMImpl_IShapesOperations::~GEOMImpl_IShapesOperations");
183 }
184
185 //=============================================================================
186 /*!
187  *  MakeEdge
188  */
189 //=============================================================================
190 Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeEdge
191                      (Handle(GEOM_Object) thePnt1, Handle(GEOM_Object) thePnt2)
192 {
193   SetErrorCode(KO);
194
195   if (thePnt1.IsNull() || thePnt2.IsNull()) return NULL;
196
197   //Add a new Edge object
198   Handle(GEOM_Object) anEdge = GetEngine()->AddObject(GetDocID(), GEOM_EDGE);
199
200   //Add a new Vector function
201   Handle(GEOM_Function) aFunction =
202     anEdge->AddFunction(GEOMImpl_VectorDriver::GetID(), VECTOR_TWO_PNT);
203
204   //Check if the function is set correctly
205   if (aFunction->GetDriverGUID() != GEOMImpl_VectorDriver::GetID()) return NULL;
206
207   GEOMImpl_IVector aPI (aFunction);
208
209   Handle(GEOM_Function) aRef1 = thePnt1->GetLastFunction();
210   Handle(GEOM_Function) aRef2 = thePnt2->GetLastFunction();
211   if (aRef1.IsNull() || aRef2.IsNull()) return NULL;
212
213   aPI.SetPoint1(aRef1);
214   aPI.SetPoint2(aRef2);
215
216   //Compute the Edge value
217   try {
218     OCC_CATCH_SIGNALS;
219     if (!GetSolver()->ComputeFunction(aFunction)) {
220       SetErrorCode("Vector driver failed");
221       return NULL;
222     }
223   }
224   catch (Standard_Failure) {
225     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
226     SetErrorCode(aFail->GetMessageString());
227     return NULL;
228   }
229
230   //Make a Python command
231   GEOM::TPythonDump(aFunction) << anEdge << " = geompy.MakeEdge("
232                                << thePnt1 << ", " << thePnt2 << ")";
233
234   SetErrorCode(OK);
235   return anEdge;
236 }
237
238 //=============================================================================
239 /*!
240  *  MakeEdgeOnCurveByLength
241  */
242 //=============================================================================
243 Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeEdgeOnCurveByLength
244                      (Handle(GEOM_Object) theRefCurve,
245                       const Standard_Real theLength,
246                       Handle(GEOM_Object) theStartPoint)
247 {
248   SetErrorCode(KO);
249
250   if (theRefCurve.IsNull()) return NULL;
251
252   //Add a new Edge object
253   Handle(GEOM_Object) anEdge = GetEngine()->AddObject(GetDocID(), GEOM_EDGE);
254
255   //Add a new Vector function
256   Handle(GEOM_Function) aFunction =
257     anEdge->AddFunction(GEOMImpl_ShapeDriver::GetID(), EDGE_CURVE_LENGTH);
258
259   //Check if the function is set correctly
260   if (aFunction->GetDriverGUID() != GEOMImpl_ShapeDriver::GetID()) return NULL;
261
262   GEOMImpl_IVector aPI (aFunction);
263
264   Handle(GEOM_Function) aRef1 = theRefCurve->GetLastFunction();
265   if (aRef1.IsNull()) return NULL;
266   aPI.SetPoint1(aRef1);
267
268   if (!theStartPoint.IsNull()) {
269     Handle(GEOM_Function) aRef2 = theStartPoint->GetLastFunction();
270     aPI.SetPoint2(aRef2);
271   }
272
273   aPI.SetParameter(theLength);
274
275   //Compute the Edge value
276   try {
277     OCC_CATCH_SIGNALS;
278     if (!GetSolver()->ComputeFunction(aFunction)) {
279       SetErrorCode("Vector driver failed");
280       return NULL;
281     }
282   }
283   catch (Standard_Failure) {
284     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
285     SetErrorCode(aFail->GetMessageString());
286     return NULL;
287   }
288
289   //Make a Python command
290   GEOM::TPythonDump(aFunction) << anEdge << " = geompy.MakeEdgeOnCurveByLength("
291                                << theRefCurve << ", " << theLength << ", " << theStartPoint << ")";
292
293   SetErrorCode(OK);
294   return anEdge;
295 }
296
297 //=============================================================================
298 /*!
299  *  MakeEdgeWire
300  */
301 //=============================================================================
302 Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeEdgeWire
303                     (Handle(GEOM_Object) theWire,
304                      const Standard_Real theLinearTolerance,
305                      const Standard_Real theAngularTolerance)
306 {
307   SetErrorCode(KO);
308
309   if (theWire.IsNull()) return NULL;
310
311   //Add a new Edge object
312   Handle(GEOM_Object) anEdge = GetEngine()->AddObject(GetDocID(), GEOM_EDGE);
313
314   //Add a new Vector function
315   Handle(GEOM_Function) aFunction =
316     anEdge->AddFunction(GEOMImpl_ShapeDriver::GetID(), EDGE_WIRE);
317
318   //Check if the function is set correctly
319   if (aFunction->GetDriverGUID() != GEOMImpl_ShapeDriver::GetID()) return NULL;
320
321   GEOMImpl_IShapes aCI (aFunction);
322
323   Handle(GEOM_Function) aWire = theWire->GetLastFunction();
324
325   if (aWire.IsNull()) return NULL;
326
327   aCI.SetBase(aWire);
328   aCI.SetTolerance(theLinearTolerance);
329   aCI.SetAngularTolerance(theAngularTolerance);
330
331   //Compute the Edge value
332   try {
333     OCC_CATCH_SIGNALS;
334     if (!GetSolver()->ComputeFunction(aFunction)) {
335       SetErrorCode("Shape driver failed");
336       return NULL;
337     }
338   }
339   catch (Standard_Failure) {
340     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
341     SetErrorCode(aFail->GetMessageString());
342     return NULL;
343   }
344
345   const double DEF_LIN_TOL = Precision::Confusion();
346   const double DEF_ANG_TOL = Precision::Angular();
347   //Make a Python command
348   if ( theAngularTolerance == DEF_ANG_TOL ) {
349     if ( theLinearTolerance == DEF_LIN_TOL )
350       GEOM::TPythonDump(aFunction) << anEdge  << " = geompy.MakeEdgeWire("
351                                    << theWire << ")";
352     else
353       GEOM::TPythonDump(aFunction) << anEdge  << " = geompy.MakeEdgeWire("
354                                    << theWire << ", " << theLinearTolerance << ")";
355   }
356   else {
357     GEOM::TPythonDump(aFunction) << anEdge  << " = geompy.MakeEdgeWire("
358                                  << theWire << ", " << theLinearTolerance << ", "
359                                  << theAngularTolerance << ")";
360   }
361
362   SetErrorCode(OK);
363   return anEdge;
364 }
365
366 //=============================================================================
367 /*!
368  *  MakeWire
369  */
370 //=============================================================================
371 Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeWire
372                              (std::list<Handle(GEOM_Object)> theShapes,
373                               const Standard_Real            theTolerance)
374 {
375   SetErrorCode(KO);
376
377   //Add a new object
378   Handle(GEOM_Object) aWire = GetEngine()->AddObject(GetDocID(), GEOM_WIRE);
379
380   //Add a new function
381   Handle(GEOM_Function) aFunction =
382     aWire->AddFunction(GEOMImpl_ShapeDriver::GetID(), WIRE_EDGES);
383   if (aFunction.IsNull()) return NULL;
384
385   //Check if the function is set correctly
386   if (aFunction->GetDriverGUID() != GEOMImpl_ShapeDriver::GetID()) return NULL;
387
388   GEOMImpl_IShapes aCI (aFunction);
389   aCI.SetTolerance(theTolerance);
390
391   Handle(TColStd_HSequenceOfTransient) aShapesSeq = new TColStd_HSequenceOfTransient;
392
393   // Shapes
394   std::list<Handle(GEOM_Object)>::iterator it = theShapes.begin();
395   for (; it != theShapes.end(); it++) {
396     Handle(GEOM_Function) aRefSh = (*it)->GetLastFunction();
397     if (aRefSh.IsNull()) {
398       SetErrorCode("NULL argument shape for the shape construction");
399       return NULL;
400     }
401     aShapesSeq->Append(aRefSh);
402   }
403   aCI.SetShapes(aShapesSeq);
404
405   //Compute the shape
406   try {
407     OCC_CATCH_SIGNALS;
408     if (!GetSolver()->ComputeFunction(aFunction)) {
409       SetErrorCode("Shape driver failed");
410       return NULL;
411     }
412   }
413   catch (Standard_Failure) {
414     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
415     SetErrorCode(aFail->GetMessageString());
416     return NULL;
417   }
418
419   //Make a Python command
420   GEOM::TPythonDump pd (aFunction);
421   pd << aWire << " = geompy.MakeWire([";
422
423   // Shapes
424   it = theShapes.begin();
425   if (it != theShapes.end()) {
426     pd << (*it++);
427     while (it != theShapes.end()) {
428       pd << ", " << (*it++);
429     }
430   }
431   pd << "], " << theTolerance << ")";
432
433   SetErrorCode(OK);
434   return aWire;
435 }
436
437 //=============================================================================
438 /*!
439  *  MakeFace
440  */
441 //=============================================================================
442 Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeFace (Handle(GEOM_Object) theWire,
443                                                           const bool isPlanarWanted)
444 {
445   SetErrorCode(KO);
446
447   if (theWire.IsNull()) return NULL;
448
449   //Add a new Face object
450   Handle(GEOM_Object) aFace = GetEngine()->AddObject(GetDocID(), GEOM_FACE);
451
452   //Add a new Shape function for creation of a face from a wire
453   Handle(GEOM_Function) aFunction =
454     aFace->AddFunction(GEOMImpl_ShapeDriver::GetID(), FACE_WIRE);
455   if (aFunction.IsNull()) return NULL;
456
457   //Check if the function is set correctly
458   if (aFunction->GetDriverGUID() != GEOMImpl_ShapeDriver::GetID()) return NULL;
459
460   GEOMImpl_IShapes aCI (aFunction);
461
462   Handle(GEOM_Function) aRefWire = theWire->GetLastFunction();
463
464   if (aRefWire.IsNull()) return NULL;
465
466   aCI.SetBase(aRefWire);
467   aCI.SetIsPlanar(isPlanarWanted);
468
469   //Compute the Face value
470   Standard_Boolean isWarning = Standard_False;
471   try {
472     OCC_CATCH_SIGNALS;
473     if (!GetSolver()->ComputeFunction(aFunction)) {
474       SetErrorCode("Shape driver failed to compute a face");
475       return NULL;
476     }
477   }
478   catch (Standard_Failure) {
479     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
480     SetErrorCode(aFail->GetMessageString());
481     // to provide warning
482     if (!aFunction->GetValue().IsNull()) {
483       isWarning = Standard_True;
484     } else {
485       return NULL;
486     }
487   }
488
489   //Make a Python command
490   GEOM::TPythonDump(aFunction) << aFace << " = geompy.MakeFace("
491     << theWire << ", " << (int)isPlanarWanted << ")";
492
493   // to provide warning
494   if (!isWarning) SetErrorCode(OK);
495   return aFace;
496 }
497
498 //=============================================================================
499 /*!
500  *  MakeFaceWires
501  */
502 //=============================================================================
503 Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeFaceWires
504                              (std::list<Handle(GEOM_Object)> theShapes,
505                               const bool isPlanarWanted)
506 {
507   SetErrorCode(KO);
508
509   //Add a new object
510   Handle(GEOM_Object) aShape = GetEngine()->AddObject(GetDocID(), GEOM_FACE);
511
512   //Add a new function
513   Handle(GEOM_Function) aFunction =
514     aShape->AddFunction(GEOMImpl_ShapeDriver::GetID(), FACE_WIRES);
515   if (aFunction.IsNull()) return NULL;
516
517   //Check if the function is set correctly
518   if (aFunction->GetDriverGUID() != GEOMImpl_ShapeDriver::GetID()) return NULL;
519
520   GEOMImpl_IShapes aCI (aFunction);
521
522   Handle(TColStd_HSequenceOfTransient) aShapesSeq = new TColStd_HSequenceOfTransient;
523
524   // Shapes
525   std::list<Handle(GEOM_Object)>::iterator it = theShapes.begin();
526   for (; it != theShapes.end(); it++) {
527     Handle(GEOM_Function) aRefSh = (*it)->GetLastFunction();
528     if (aRefSh.IsNull()) {
529       SetErrorCode("NULL argument shape for the face construction");
530       return NULL;
531     }
532     aShapesSeq->Append(aRefSh);
533   }
534   aCI.SetShapes(aShapesSeq);
535
536   aCI.SetIsPlanar(isPlanarWanted);
537
538   //Compute the shape
539   Standard_Boolean isWarning = Standard_False;
540   try {
541     OCC_CATCH_SIGNALS;
542     if (!GetSolver()->ComputeFunction(aFunction)) {
543       SetErrorCode("Shape driver failed");
544       return NULL;
545     }
546   }
547   catch (Standard_Failure) {
548     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
549     SetErrorCode(aFail->GetMessageString());
550     // to provide warning
551     if (!aFunction->GetValue().IsNull()) {
552       isWarning = Standard_True;
553     } else {
554       return NULL;
555     }
556   }
557
558   //Make a Python command
559   GEOM::TPythonDump pd (aFunction);
560   pd << aShape << " = geompy.MakeFaceWires([";
561
562   // Shapes
563   it = theShapes.begin();
564   if (it != theShapes.end()) {
565     pd << (*it++);
566     while (it != theShapes.end()) {
567       pd << ", " << (*it++);
568     }
569   }
570   pd << "], " << (int)isPlanarWanted << ")";
571
572   // to provide warning
573   if (!isWarning) SetErrorCode(OK);
574   return aShape;
575 }
576
577 //=============================================================================
578 /*!
579  *  MakeFaceFromSurface
580  */
581 //=============================================================================
582 Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeFaceFromSurface
583                                               (Handle(GEOM_Object) theFace,
584                                                Handle(GEOM_Object) theWire)
585 {
586   SetErrorCode(KO);
587
588   //Add a new object
589   Handle(GEOM_Object) aShape = GetEngine()->AddObject(GetDocID(), GEOM_FACE);
590
591   //Add a new function
592   Handle(GEOM_Function) aFunction =
593     aShape->AddFunction(GEOMImpl_ShapeDriver::GetID(), FACE_FROM_SURFACE);
594
595   if (aFunction.IsNull()) {
596     return NULL;
597   }
598
599   //Check if the function is set correctly
600   if (aFunction->GetDriverGUID() != GEOMImpl_ShapeDriver::GetID()) {
601     return NULL;
602   }
603
604   GEOMImpl_IShapes aCI (aFunction);
605   Handle(TColStd_HSequenceOfTransient) aShapesSeq =
606     new TColStd_HSequenceOfTransient;
607   Handle(GEOM_Function) aRefFace = theFace->GetLastFunction();
608   Handle(GEOM_Function) aRefWire = theWire->GetLastFunction();
609
610   if (aRefFace.IsNull()) {
611     SetErrorCode("NULL argument face for the face construction");
612     return NULL;
613   }
614
615   if (aRefWire.IsNull()) {
616     SetErrorCode("NULL argument wire for the face construction");
617     return NULL;
618   }
619
620   aShapesSeq->Append(aRefFace);
621   aShapesSeq->Append(aRefWire);
622
623   aCI.SetShapes(aShapesSeq);
624
625   //Compute the face
626   try {
627     OCC_CATCH_SIGNALS;
628     if (!GetSolver()->ComputeFunction(aFunction)) {
629       SetErrorCode("Shape driver failed");
630       return NULL;
631     }
632   }
633   catch (Standard_Failure) {
634     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
635     SetErrorCode(aFail->GetMessageString());
636     return NULL;
637   }
638
639   //Make a Python command
640   GEOM::TPythonDump (aFunction) << aShape
641     << " = geompy.MakeFaceFromSurface(" << theFace << ", " << theWire << ")";
642
643   SetErrorCode(OK);
644
645   return aShape;
646 }
647
648 //=============================================================================
649 /*!
650  *  MakeFaceWithConstraints
651  */
652 //=============================================================================
653 Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeFaceWithConstraints
654                              (std::list<Handle(GEOM_Object)> theConstraints)
655 {
656   SetErrorCode(KO);
657
658   //Add a new object
659   Handle(GEOM_Object) aShape = GetEngine()->AddObject(GetDocID(), GEOM_FILLING);
660
661   //Add a new function
662   Handle(GEOM_Function) aFunction =
663     aShape->AddFunction(GEOMImpl_FillingDriver::GetID(), FILLING_ON_CONSTRAINTS);
664   if (aFunction.IsNull()) return NULL;
665
666   //Check if the function is set correctly
667   if (aFunction->GetDriverGUID() != GEOMImpl_FillingDriver::GetID()) return NULL;
668
669   GEOMImpl_IFilling aCI (aFunction);
670   Handle(TColStd_HSequenceOfTransient) aConstraints = new TColStd_HSequenceOfTransient;
671
672   // Shapes
673   std::list<Handle(GEOM_Object)>::iterator it = theConstraints.begin();
674   while (it != theConstraints.end()) {
675     Handle(GEOM_Object) anObject = (*it);
676     if ( anObject.IsNull() || anObject->GetValue().ShapeType() != TopAbs_EDGE ) {
677       SetErrorCode("NULL argument edge for the face construction");
678       return NULL;
679     }
680     Handle(GEOM_Function) aRefSh = anObject->GetLastFunction();
681     aConstraints->Append(aRefSh);
682     it++;
683     if ( it != theConstraints.end() ) {
684       Handle(GEOM_Object) aFace = (*it);
685       if ( aFace.IsNull() ) {
686         // null constraint face - it is a valid case
687         it++;
688         continue;
689       }
690       if ( aFace->GetValue().ShapeType() != TopAbs_FACE )
691         // constraint face can be omitted - it is a valid case
692         continue;
693       // Keep the old error code as IsSubShapeBelongsTo changes it.
694       TCollection_AsciiString anOldCode = GetErrorCode();
695
696       if ( IsSubShapeBelongsTo( anObject, 0, aFace, 0 ) ) {
697         // valid constraint
698         SetErrorCode(anOldCode);
699         aRefSh = aFace->GetLastFunction();
700         aConstraints->Append(aRefSh);
701         it++;
702       }
703       else {
704         // bad constraint
705         SetErrorCode("Face is NULL or not connected to the Edge");
706         return NULL;
707       }
708     }
709   }
710   aCI.SetShapes( aConstraints );
711
712   //Compute the shape
713   Standard_Boolean isWarning = Standard_False;
714   try {
715     OCC_CATCH_SIGNALS;
716     if (!GetSolver()->ComputeFunction(aFunction)) {
717       SetErrorCode("Shape driver failed");
718       return NULL;
719     }
720   }
721   catch (Standard_Failure) {
722     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
723     SetErrorCode(aFail->GetMessageString());
724     // to provide warning
725     if (!aFunction->GetValue().IsNull()) {
726       isWarning = Standard_True;
727     } else {
728       return NULL;
729     }
730   }
731
732   //Make a Python command
733   GEOM::TPythonDump pd (aFunction);
734   pd << aShape << " = geompy.MakeFaceWithConstraints([";
735
736   // Constraints
737   it = theConstraints.begin();
738   if (it != theConstraints.end() ) {
739     pd << (*it++);
740     while (it != theConstraints.end()) {
741       Handle(GEOM_Object) anObject = (*it++);
742       if( !anObject.IsNull() )
743         pd << ", " << anObject;
744     }
745   }
746   pd << "])";
747
748   // to provide warning
749   if (!isWarning) SetErrorCode(OK);
750   return aShape;
751 }
752
753 //=============================================================================
754 /*!
755  *  MakeShell
756  */
757 //=============================================================================
758 Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeShell
759                              (std::list<Handle(GEOM_Object)> theShapes)
760 {
761   return MakeShape(theShapes, GEOM_SHELL, SHELL_FACES, "MakeShell");
762 }
763
764 //=============================================================================
765 /*!
766  *  MakeSolidShells
767  */
768 //=============================================================================
769 Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeSolidShells
770                              (std::list<Handle(GEOM_Object)> theShapes)
771 {
772   return MakeShape(theShapes, GEOM_SOLID, SOLID_SHELLS, "MakeSolid");
773 }
774
775 //=============================================================================
776 /*!
777  *  MakeCompound
778  */
779 //=============================================================================
780 Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeCompound
781                              (std::list<Handle(GEOM_Object)> theShapes)
782 {
783   return MakeShape(theShapes, GEOM_COMPOUND, COMPOUND_SHAPES, "MakeCompound");
784 }
785
786 //=============================================================================
787 /*!
788  *  MakeShape
789  */
790 //=============================================================================
791 Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeShape
792                              (std::list<Handle(GEOM_Object)> theShapes,
793                               const Standard_Integer         theObjectType,
794                               const Standard_Integer         theFunctionType,
795                               const TCollection_AsciiString& theMethodName)
796 {
797   SetErrorCode(KO);
798
799   //Add a new object
800   Handle(GEOM_Object) aShape = GetEngine()->AddObject(GetDocID(), theObjectType);
801
802   //Add a new function
803   Handle(GEOM_Function) aFunction =
804     aShape->AddFunction(GEOMImpl_ShapeDriver::GetID(), theFunctionType);
805   if (aFunction.IsNull()) return NULL;
806
807   //Check if the function is set correctly
808   if (aFunction->GetDriverGUID() != GEOMImpl_ShapeDriver::GetID()) return NULL;
809
810   GEOMImpl_IShapes aCI (aFunction);
811
812   Handle(TColStd_HSequenceOfTransient) aShapesSeq = new TColStd_HSequenceOfTransient;
813
814   // Shapes
815   std::list<Handle(GEOM_Object)>::iterator it = theShapes.begin();
816   for (; it != theShapes.end(); it++) {
817     Handle(GEOM_Function) aRefSh = (*it)->GetLastFunction();
818     if (aRefSh.IsNull()) {
819       SetErrorCode("NULL argument shape for the shape construction");
820       return NULL;
821     }
822     aShapesSeq->Append(aRefSh);
823   }
824   aCI.SetShapes(aShapesSeq);
825
826   //Compute the shape
827   try {
828     OCC_CATCH_SIGNALS;
829     if (!GetSolver()->ComputeFunction(aFunction)) {
830       SetErrorCode("Shape driver failed");
831       return NULL;
832     }
833   }
834   catch (Standard_Failure) {
835     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
836     SetErrorCode(aFail->GetMessageString());
837     return NULL;
838   }
839
840   //Make a Python command
841   GEOM::TPythonDump pd (aFunction);
842   pd << aShape << " = geompy." << theMethodName.ToCString() << "([";
843
844   // Shapes
845   it = theShapes.begin();
846   if (it != theShapes.end()) {
847     pd << (*it++);
848     while (it != theShapes.end()) {
849       pd << ", " << (*it++);
850     }
851   }
852   pd << "])";
853
854   SetErrorCode(OK);
855   return aShape;
856 }
857
858 //=============================================================================
859 /*!
860  *  MakeSolidFromConnectedFaces
861  */
862 //=============================================================================
863 Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeSolidFromConnectedFaces
864                              (std::list<Handle(GEOM_Object)> theFacesOrShells,
865                               const Standard_Boolean isIntersect)
866 {
867   SetErrorCode(KO);
868
869   //Add a new object
870   Handle(GEOM_Object) aSolid = GetEngine()->AddObject(GetDocID(), GEOM_SOLID);
871
872   //Add a new function
873   Handle(GEOM_Function) aFunction =
874     aSolid->AddFunction(GEOMImpl_ShapeDriver::GetID(), SOLID_FACES);
875   if (aFunction.IsNull()) return NULL;
876
877   //Check if the function is set correctly
878   if (aFunction->GetDriverGUID() != GEOMImpl_ShapeDriver::GetID()) return NULL;
879
880   GEOMImpl_IShapes aCI (aFunction);
881
882   Handle(TColStd_HSequenceOfTransient) aShapesSeq = new TColStd_HSequenceOfTransient;
883
884   // Shapes
885   std::list<Handle(GEOM_Object)>::iterator it = theFacesOrShells.begin();
886   for (; it != theFacesOrShells.end(); it++) {
887     Handle(GEOM_Function) aRefSh = (*it)->GetLastFunction();
888     if (aRefSh.IsNull()) {
889       SetErrorCode("NULL argument shape for the shape construction");
890       return NULL;
891     }
892     aShapesSeq->Append(aRefSh);
893   }
894   aCI.SetShapes(aShapesSeq);
895   aCI.SetIsIntersect(isIntersect);
896
897   //Compute the shape
898   try {
899     OCC_CATCH_SIGNALS;
900     if (!GetSolver()->ComputeFunction(aFunction)) {
901       SetErrorCode("Shape driver failed");
902       return NULL;
903     }
904   }
905   catch (Standard_Failure) {
906     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
907     SetErrorCode(aFail->GetMessageString());
908     return NULL;
909   }
910
911   //Make a Python command
912   GEOM::TPythonDump pd (aFunction);
913   pd << aSolid << " = geompy.MakeSolidFromConnectedFaces([";
914
915   // Shapes
916   it = theFacesOrShells.begin();
917   if (it != theFacesOrShells.end()) {
918     pd << (*it++);
919     while (it != theFacesOrShells.end()) {
920       pd << ", " << (*it++);
921     }
922   }
923   pd << "]," << (isIntersect ? "True" : "False") << ")";
924
925   SetErrorCode(OK);
926   return aSolid;
927 }
928
929 //=============================================================================
930 /*!
931  *  MakeGlueFaces
932  */
933 //=============================================================================
934 Handle(GEOM_Object)
935 GEOMImpl_IShapesOperations::MakeGlueFaces (std::list< Handle(GEOM_Object) >& theShapes,
936                                            const Standard_Real               theTolerance,
937                                            const Standard_Boolean            doKeepNonSolids)
938 {
939   SetErrorCode(KO);
940
941   Handle(TColStd_HSequenceOfTransient) objects = GEOM_Object::GetLastFunctions( theShapes );
942   if ( objects.IsNull() || objects->IsEmpty() ) {
943     SetErrorCode("NULL argument shape");
944     return NULL;
945   }
946
947   //Add a new Glued object
948   Handle(GEOM_Object) aGlued = GetEngine()->AddObject(GetDocID(), GEOM_GLUED);
949
950   //Add a new Glue function
951   Handle(GEOM_Function) aFunction;
952   aFunction = aGlued->AddFunction(GEOMImpl_GlueDriver::GetID(), GLUE_FACES);
953   if (aFunction.IsNull()) return NULL;
954
955   //Check if the function is set correctly
956   if (aFunction->GetDriverGUID() != GEOMImpl_GlueDriver::GetID()) return NULL;
957
958   GEOMImpl_IGlue aCI (aFunction);
959
960   aCI.SetBase( objects );
961   aCI.SetTolerance(theTolerance);
962   aCI.SetKeepNonSolids(doKeepNonSolids);
963
964   //Compute the sub-shape value
965   Standard_Boolean isWarning = Standard_False;
966   try {
967     OCC_CATCH_SIGNALS;
968     if (!GetSolver()->ComputeFunction(aFunction)) {
969       SetErrorCode("Shape driver failed to glue faces");
970       return NULL;
971     }
972   }
973   catch (Standard_Failure) {
974     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
975     SetErrorCode(aFail->GetMessageString());
976     // to provide warning
977     if (!aFunction->GetValue().IsNull()) {
978       isWarning = Standard_True;
979     } else {
980       return NULL;
981     }
982   }
983
984   //Make a Python command
985   GEOM::TPythonDump(aFunction) << aGlued << " = geompy.MakeGlueFaces("
986     << theShapes << ", " << theTolerance << ")";
987
988   // to provide warning
989   if (!isWarning) SetErrorCode(OK);
990   return aGlued;
991 }
992
993 //=============================================================================
994 /*!
995  *  GetGlueFaces
996  */
997 //=============================================================================
998 /*
999 Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::GetGlueFaces
1000                                                 (Handle(GEOM_Object) theShape,
1001                                                  const Standard_Real theTolerance)
1002 {
1003   SetErrorCode(KO);
1004
1005   if (theShape.IsNull()) return NULL;
1006   TopoDS_Shape aShape = theShape->GetValue();
1007   if (aShape.IsNull()) return NULL;
1008
1009   Handle(TColStd_HSequenceOfTransient) aSeq = new TColStd_HSequenceOfTransient;
1010
1011   Standard_Integer iErr;
1012   TopoDS_Shape aS;
1013   GEOMAlgo_Gluer1 aGluer;
1014   GEOMAlgo_ListIteratorOfListOfCoupleOfShapes aItCS;
1015   GEOMAlgo_CoupleOfShapes aCS;
1016   GEOMAlgo_ListOfCoupleOfShapes aLCS;
1017
1018   //aGluer = new GEOMAlgo_Gluer1;
1019   aGluer.SetShape(aShape);
1020   aGluer.SetTolerance(theTolerance);
1021   aGluer.Perform();
1022   iErr = aGluer.ErrorStatus();
1023   if (iErr) return NULL;
1024
1025   TopTools_ListOfShape listShape;
1026   const GEOMAlgo_ListOfCoupleOfShapes& aLCSG = aGluer.GluedFaces();
1027   // Access to faces
1028   aItCS.Initialize(aLCSG);
1029   for (; aItCS.More(); aItCS.Next()) {
1030     const GEOMAlgo_CoupleOfShapes& aCSG = aItCS.Value();
1031     listShape.Append(aCSG.Shape1());
1032   }
1033
1034   TopTools_ListIteratorOfListOfShape itSub (listShape);
1035   TCollection_AsciiString anAsciiList, anEntry;
1036   TopTools_IndexedMapOfShape anIndices;
1037   TopExp::MapShapes(aShape, anIndices);
1038   Handle(TColStd_HArray1OfInteger) anArray;
1039   Handle(GEOM_Object) anObj;
1040   for (int index = 1; itSub.More(); itSub.Next(), ++index) {
1041     TopoDS_Shape aValue = itSub.Value();
1042     anArray = new TColStd_HArray1OfInteger(1,1);
1043     anArray->SetValue(1, anIndices.FindIndex(aValue));
1044     anObj = GetEngine()->AddSubShape(theShape, anArray);
1045     if (!anObj.IsNull()) {
1046       aSeq->Append(anObj);
1047
1048       // for python command
1049       TDF_Tool::Entry(anObj->GetEntry(), anEntry);
1050       anAsciiList += anEntry;
1051       anAsciiList += ",";
1052     }
1053   }
1054
1055   //Make a Python command
1056   if( anAsciiList.Length() > 0 ) {
1057     anAsciiList.Trunc(anAsciiList.Length() - 1);
1058     Handle(GEOM_Function) aFunction = theShape->GetLastFunction();
1059     GEOM::TPythonDump pd (aFunction, true);
1060     pd << "[" << anAsciiList.ToCString();
1061     pd << "] = geompy.GetGlueFaces(" << theShape << ", " << theTolerance << ")";
1062   }
1063
1064   SetErrorCode(OK);
1065
1066   return aSeq;
1067 }
1068 */
1069
1070 //=============================================================================
1071 /*!
1072  *  MakeGlueFacesByList
1073  */
1074 //=============================================================================
1075 Handle(GEOM_Object)
1076 GEOMImpl_IShapesOperations::MakeGlueFacesByList(std::list< Handle(GEOM_Object) >& theShapes,
1077                                                 const Standard_Real               theTolerance,
1078                                                 std::list<Handle(GEOM_Object)> &  theFaces,
1079                                                 const Standard_Boolean            doKeepNonSolids,
1080                                                 const Standard_Boolean            doGlueAllEdges)
1081 {
1082   SetErrorCode(KO);
1083
1084   Handle(TColStd_HSequenceOfTransient) objects = GEOM_Object::GetLastFunctions( theShapes );
1085   if ( objects.IsNull() || objects->IsEmpty() ) {
1086     SetErrorCode("NULL argument shape");
1087     return NULL;
1088   }
1089   Handle(TColStd_HSequenceOfTransient) aFaces = GEOM_Object::GetLastFunctions( theFaces );
1090   if ( aFaces.IsNull() ) {
1091     SetErrorCode("NULL argument shape for the shape construction");
1092     return NULL;
1093   }
1094
1095   //Add a new Glued object
1096   Handle(GEOM_Object) aGlued = GetEngine()->AddObject(GetDocID(), GEOM_GLUED);
1097
1098   //Add a new Glue function
1099   Handle(GEOM_Function) aFunction;
1100   aFunction = aGlued->AddFunction(GEOMImpl_GlueDriver::GetID(), GLUE_FACES_BY_LIST);
1101   if (aFunction.IsNull()) return NULL;
1102
1103   //Check if the function is set correctly
1104   if (aFunction->GetDriverGUID() != GEOMImpl_GlueDriver::GetID()) return NULL;
1105
1106   GEOMImpl_IGlue aCI (aFunction);
1107
1108   aCI.SetBase( objects );
1109   aCI.SetTolerance(theTolerance);
1110   aCI.SetKeepNonSolids(doKeepNonSolids);
1111   aCI.SetGlueAllEdges(doGlueAllEdges);
1112   aCI.SetFaces(aFaces);
1113
1114   //Compute the sub-shape value
1115   Standard_Boolean isWarning = Standard_False;
1116   try {
1117     OCC_CATCH_SIGNALS;
1118     if (!GetSolver()->ComputeFunction(aFunction)) {
1119       SetErrorCode("Shape driver failed to glue faces");
1120       return NULL;
1121     }
1122   }
1123   catch (Standard_Failure) {
1124     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
1125     SetErrorCode(aFail->GetMessageString());
1126     // to provide warning
1127     if (!aFunction->GetValue().IsNull()) {
1128       isWarning = Standard_True;
1129     } else {
1130       return NULL;
1131     }
1132   }
1133
1134   //Make a Python command
1135
1136   GEOM::TPythonDump pd(aFunction);
1137   pd << aGlued << " = geompy.MakeGlueFacesByList("
1138      << theShapes << ", " << theTolerance << ", " << theFaces << ", "
1139      << (bool)doKeepNonSolids << ", " << (bool)doGlueAllEdges << ")";
1140
1141   // to provide warning
1142   if (!isWarning) SetErrorCode(OK);
1143   return aGlued;
1144 }
1145
1146 //=============================================================================
1147 /*!
1148  *  MakeGlueEdges
1149  */
1150 //=============================================================================
1151 Handle(GEOM_Object)
1152 GEOMImpl_IShapesOperations::MakeGlueEdges (std::list< Handle(GEOM_Object) >& theShapes,
1153                                            const Standard_Real               theTolerance)
1154 {
1155   SetErrorCode(KO);
1156
1157   Handle(TColStd_HSequenceOfTransient) objects = GEOM_Object::GetLastFunctions( theShapes );
1158   if ( objects.IsNull() || objects->IsEmpty() ) {
1159     SetErrorCode("NULL argument shape");
1160     return NULL;
1161   }
1162
1163   //Add a new Glued object
1164   Handle(GEOM_Object) aGlued = GetEngine()->AddObject(GetDocID(), GEOM_GLUED);
1165
1166   //Add a new Glue function
1167   Handle(GEOM_Function) aFunction;
1168   aFunction = aGlued->AddFunction(GEOMImpl_GlueDriver::GetID(), GLUE_EDGES);
1169   if (aFunction.IsNull()) return NULL;
1170
1171   //Check if the function is set correctly
1172   if (aFunction->GetDriverGUID() != GEOMImpl_GlueDriver::GetID()) return NULL;
1173
1174   GEOMImpl_IGlue aCI (aFunction);
1175
1176   aCI.SetBase( objects );
1177   aCI.SetTolerance(theTolerance);
1178   aCI.SetKeepNonSolids(true);
1179
1180   //Compute the sub-shape value
1181   Standard_Boolean isWarning = Standard_False;
1182   try {
1183     OCC_CATCH_SIGNALS;
1184     if (!GetSolver()->ComputeFunction(aFunction)) {
1185       SetErrorCode("Shape driver failed to glue edges");
1186       return NULL;
1187     }
1188   }
1189   catch (Standard_Failure) {
1190     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
1191     SetErrorCode(aFail->GetMessageString());
1192     // to provide warning
1193     if (!aFunction->GetValue().IsNull()) {
1194       isWarning = Standard_True;
1195     } else {
1196       return NULL;
1197     }
1198   }
1199
1200   //Make a Python command
1201   GEOM::TPythonDump(aFunction) << aGlued << " = geompy.MakeGlueEdges("
1202     << theShapes << ", " << theTolerance << ")";
1203
1204   // to provide warning
1205   if (!isWarning) SetErrorCode(OK);
1206   return aGlued;
1207 }
1208
1209 //=============================================================================
1210 /*!
1211  *  GetGlueShapes
1212  */
1213 //=============================================================================
1214 Handle(TColStd_HSequenceOfTransient)
1215 GEOMImpl_IShapesOperations::GetGlueShapes (std::list< Handle(GEOM_Object) >& theShapes,
1216                                            const Standard_Real               theTolerance,
1217                                            const TopAbs_ShapeEnum            theType)
1218 {
1219   SetErrorCode(KO);
1220
1221   TopoDS_Shape aShape;
1222   TopTools_SequenceOfShape shapes;
1223   std::list< Handle(GEOM_Object) >::iterator s = theShapes.begin();
1224   Handle(GEOM_Object) lastCreatedGO;
1225   for ( ; s != theShapes.end(); ++s )
1226   {
1227     Handle(GEOM_Object) go = *s;
1228     if ( go.IsNull() ) return NULL;
1229     aShape = go->GetValue();
1230     if ( aShape.IsNull() ) return NULL;
1231     shapes.Append( aShape );
1232     lastCreatedGO = GEOM::GetCreatedLast( lastCreatedGO, go );
1233   }
1234   if ( shapes.Length() > 1 )
1235   {
1236     TopoDS_Compound compound;
1237     BRep_Builder builder;
1238     builder.MakeCompound( compound );
1239     for ( int i = 1; i <= shapes.Length(); ++i )
1240       builder.Add( compound, shapes( i ) );
1241
1242     aShape = compound;
1243   }
1244
1245   Handle(TColStd_HSequenceOfTransient) aSeq = new TColStd_HSequenceOfTransient;
1246
1247   GEOMAlgo_GlueDetector aGluer;
1248   aGluer.SetArgument(aShape);
1249   aGluer.SetTolerance(theTolerance);
1250   aGluer.Perform();
1251   Standard_Integer iErr = aGluer.ErrorStatus();
1252   if (iErr) return NULL;
1253
1254   std::vector< TopTools_IndexedMapOfShape* > anIndices( shapes.Length(), NULL );
1255   Handle(TColStd_HArray1OfInteger) anArray;
1256   Handle(GEOM_Object) anObj;
1257
1258   TopTools_ListOfShape listOnePerSet;
1259
1260   const TopTools_DataMapOfShapeListOfShape& aImages = aGluer.Images();
1261   TopTools_DataMapIteratorOfDataMapOfShapeListOfShape aItDMSLS (aImages);
1262   for (int index = 1; aItDMSLS.More(); aItDMSLS.Next(), ++index) {
1263     // some key shape
1264     //const TopoDS_Shape& aSkey = aItDMSLS.Key();
1265
1266     // list of shapes of the argument that can be glued
1267     const TopTools_ListOfShape& aLSD = aItDMSLS.Value();
1268
1269     //listShape.Append(aLSD.First());
1270     TopoDS_Shape aValue = aLSD.First();
1271
1272     if (aValue.ShapeType() == theType) {
1273       listOnePerSet.Append(aValue);
1274     }
1275   }
1276
1277   // for stable order of returned entities
1278   GEOMUtils::SortShapes(listOnePerSet, Standard_False);
1279
1280   TopTools_ListIteratorOfListOfShape aListIt (listOnePerSet);
1281   for (; aListIt.More(); aListIt.Next())
1282   {
1283     TopoDS_Shape aValue = aListIt.Value();
1284     // find a shape to add aValue as a sub-shape
1285     anObj.Nullify();
1286     s = theShapes.begin();
1287     for ( int i = 0; i < shapes.Length(); ++i, ++s )
1288     {
1289       Handle(GEOM_Object) object = *s;
1290       if ( !anIndices[i] ) {
1291         anIndices[i] = new TopTools_IndexedMapOfShape;
1292         TopExp::MapShapes( object->GetValue(), *anIndices[i]);
1293       }
1294       if (int index = anIndices[i]->FindIndex( aValue )) {
1295         anArray = new TColStd_HArray1OfInteger(1,1);
1296         anArray->SetValue(1, index);
1297         anObj = GetEngine()->AddSubShape( object, anArray);
1298         break;
1299       }
1300     }
1301     if (!anObj.IsNull())
1302       aSeq->Append(anObj);
1303   }
1304   for ( size_t i = 0 ; i < anIndices.size(); ++i )
1305     delete anIndices[i];
1306
1307   // Make a Python command
1308   if ( aSeq->Length() > 0)
1309   {
1310     Handle(GEOM_Function) aFunction = lastCreatedGO->GetLastFunction();
1311     GEOM::TPythonDump pd (aFunction, /*append=*/true);
1312     pd << aSeq
1313        << " = geompy." << (theType == TopAbs_FACE ? "GetGlueFaces" : "GetGlueEdges" )
1314        << "( " << theShapes << ", " << theTolerance << ")";
1315   }
1316
1317   SetErrorCode(OK);
1318
1319   return aSeq;
1320 }
1321
1322 //=============================================================================
1323 /*!
1324  *  MakeGlueEdgesByList
1325  */
1326 //=============================================================================
1327 Handle(GEOM_Object)
1328 GEOMImpl_IShapesOperations::MakeGlueEdgesByList (std::list< Handle(GEOM_Object) >& theShapes,
1329                                                  const Standard_Real               theTolerance,
1330                                                  std::list<Handle(GEOM_Object)>&   theEdges)
1331 {
1332   SetErrorCode(KO);
1333
1334   Handle(TColStd_HSequenceOfTransient) objects = GEOM_Object::GetLastFunctions( theShapes );
1335   if ( objects.IsNull() || objects->IsEmpty() ) {
1336     SetErrorCode("NULL argument shape");
1337     return NULL;
1338   }
1339   Handle(TColStd_HSequenceOfTransient) anEdges = GEOM_Object::GetLastFunctions( theEdges );
1340   if ( anEdges.IsNull() ) {
1341     SetErrorCode("NULL argument shape for the shape construction");
1342     return NULL;
1343   }
1344   //Add a new Glued object
1345   Handle(GEOM_Object) aGlued = GetEngine()->AddObject(GetDocID(), GEOM_GLUED);
1346
1347   //Add a new Glue function
1348   Handle(GEOM_Function) aFunction;
1349   aFunction = aGlued->AddFunction(GEOMImpl_GlueDriver::GetID(), GLUE_EDGES_BY_LIST);
1350   if (aFunction.IsNull()) return NULL;
1351
1352   //Check if the function is set correctly
1353   if (aFunction->GetDriverGUID() != GEOMImpl_GlueDriver::GetID()) return NULL;
1354
1355   GEOMImpl_IGlue aCI (aFunction);
1356
1357   aCI.SetBase( objects );
1358   aCI.SetTolerance(theTolerance);
1359   aCI.SetKeepNonSolids(true);
1360   aCI.SetFaces(anEdges);
1361
1362   //Compute the sub-shape value
1363   Standard_Boolean isWarning = Standard_False;
1364   try {
1365     OCC_CATCH_SIGNALS;
1366     if (!GetSolver()->ComputeFunction(aFunction)) {
1367       SetErrorCode("Shape driver failed to glue edges");
1368       return NULL;
1369     }
1370   }
1371   catch (Standard_Failure) {
1372     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
1373     SetErrorCode(aFail->GetMessageString());
1374     // to provide warning
1375     if (!aFunction->GetValue().IsNull()) {
1376       isWarning = Standard_True;
1377     } else {
1378       return NULL;
1379     }
1380   }
1381
1382   //Make a Python command
1383
1384   GEOM::TPythonDump pd (aFunction);
1385   pd << aGlued << " = geompy.MakeGlueEdgesByList("
1386      << theShapes << ", " << theTolerance << ", " << theEdges << " )";
1387
1388   // to provide warning
1389   if (!isWarning) SetErrorCode(OK);
1390   return aGlued;
1391 }
1392
1393 //=============================================================================
1394 /*!
1395  *  GetExistingSubObjects
1396  */
1397 //=============================================================================
1398 Handle(TColStd_HSequenceOfTransient)
1399 GEOMImpl_IShapesOperations::GetExistingSubObjects(Handle(GEOM_Object)    theShape,
1400                                                   const Standard_Boolean theGroupsOnly)
1401 {
1402   // note: this method does not return fields
1403
1404   Standard_Integer types = theGroupsOnly ? Groups : Groups|SubShapes;
1405   Handle(TColStd_HSequenceOfTransient) results = GetExistingSubObjects(theShape, types);
1406
1407   if (results->Length() > 0) {
1408     //Make a Python command
1409     TCollection_AsciiString anAsciiList;
1410     for (int i = 1; i <= results->Length(); i++)
1411     {
1412       Handle(GEOM_BaseObject) obj = Handle(GEOM_BaseObject)::DownCast( results->Value(i));
1413       obj->GetEntryString();
1414       if ( i < results->Length() )
1415         anAsciiList += ",";
1416     }
1417     
1418     GEOM::TPythonDump pd (theShape->GetLastFunction(), /*append=*/true);
1419     pd << "[" << anAsciiList.ToCString();
1420     pd << "] = geompy.GetExistingSubObjects(";
1421     pd << theShape << ", " << (bool)theGroupsOnly << ")";
1422   }
1423
1424   return results;
1425 }
1426
1427 Handle(TColStd_HSequenceOfTransient)
1428 GEOMImpl_IShapesOperations::GetExistingSubObjects(Handle(GEOM_Object)    theShape,
1429                                                   const Standard_Integer theTypes)
1430 {
1431   SetErrorCode(KO);
1432
1433   if (theShape.IsNull()) return NULL;
1434
1435   Handle(GEOM_Function) aMainShape = theShape->GetLastFunction();
1436   if (aMainShape.IsNull()) return NULL;
1437
1438   Handle(TColStd_HSequenceOfTransient) aSeq = new TColStd_HSequenceOfTransient;
1439   SetErrorCode(NOT_FOUND_ANY);
1440
1441   if (!aMainShape->HasSubShapeReferences()) return aSeq;
1442   const TDataStd_ListOfExtendedString& aListEntries = aMainShape->GetSubShapeReferences();
1443   if (aListEntries.IsEmpty()) return aSeq;
1444
1445   SetErrorCode(KO);
1446
1447   TDataStd_ListIteratorOfListOfExtendedString anIt (aListEntries);
1448   for (; anIt.More(); anIt.Next()) {
1449     TCollection_ExtendedString anEntry = anIt.Value();
1450     Standard_Integer aStrLen = anEntry.LengthOfCString();
1451     char* anEntryStr = new char[aStrLen+1];
1452     anEntry.ToUTF8CString(anEntryStr);
1453     Handle(GEOM_BaseObject) anObj = GetEngine()->GetObject(GetDocID(), anEntryStr, false);
1454     if (!anObj.IsNull() ) {
1455       bool isGroup    = anObj->IsKind(STANDARD_TYPE(GEOM_Object)) && anObj->GetType() == GEOM_GROUP;
1456       bool isSubShape = anObj->IsKind(STANDARD_TYPE(GEOM_Object)) && anObj->GetType() != GEOM_GROUP;
1457       bool isField    = anObj->IsKind(STANDARD_TYPE(GEOM_Field));
1458       if (theTypes & Groups    && isGroup ||
1459           theTypes & SubShapes && isSubShape ||
1460           theTypes & Fields    && isField) {
1461         aSeq->Append(anObj);
1462       }
1463     }
1464     delete [] anEntryStr;
1465   }
1466
1467   if (aSeq->Length() == 0) {
1468     SetErrorCode(NOT_FOUND_ANY);
1469     return aSeq;
1470   }
1471
1472   SetErrorCode(OK);
1473
1474   return aSeq;
1475 }
1476
1477 //=============================================================================
1478 /*!
1479  *  MakeExplode
1480  */
1481 //=============================================================================
1482 Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::MakeExplode
1483                                           (Handle(GEOM_Object)    theShape,
1484                                            const Standard_Integer theShapeType,
1485                                            const Standard_Boolean isSorted,
1486                                            const ExplodeType      theExplodeType)
1487 {
1488   SetErrorCode(KO);
1489
1490   if (theShape.IsNull()) return NULL;
1491   TopoDS_Shape aShape = theShape->GetValue();
1492   if (aShape.IsNull()) return NULL;
1493
1494   Handle(GEOM_Function) aMainShape = theShape->GetLastFunction();
1495
1496   Handle(TColStd_HSequenceOfTransient) aSeq = new TColStd_HSequenceOfTransient;
1497   Handle(GEOM_Object) anObj;
1498   TopTools_MapOfShape mapShape;
1499   TopTools_ListOfShape listShape;
1500
1501   if (aShape.ShapeType() == TopAbs_COMPOUND &&
1502       (theShapeType == TopAbs_SHAPE || theShapeType == TopAbs_FLAT || theShapeType == TopAbs_COMPOUND))
1503   {
1504     TopoDS_Iterator It (aShape, Standard_True, Standard_True);
1505     for (; It.More(); It.Next()) {
1506       TopoDS_Shape SS = It.Value();
1507       if (mapShape.Add(SS)) {
1508         if (theShapeType == TopAbs_FLAT) {
1509           AddFlatSubShapes(SS, listShape, mapShape);
1510         }
1511         else if (theShapeType == TopAbs_SHAPE || theShapeType == SS.ShapeType()) {
1512           listShape.Append(SS);
1513         }
1514         // VSR: for EXPLODE_NEW_INCLUDE_MAIN and EXPLODE_OLD_INCLUDE_MAIN:
1515         // it seems it is necessary to add top-level shape if theShapeType == TopAbs_COMPOUND
1516       }
1517     }
1518   }
1519   else if (theExplodeType != EXPLODE_NEW_EXCLUDE_MAIN || aShape.ShapeType() != theShapeType) // issue 0021079
1520   {
1521     TopExp_Explorer exp (aShape, TopAbs_ShapeEnum(theShapeType));
1522     for (; exp.More(); exp.Next())
1523       if (mapShape.Add(exp.Current()))
1524         listShape.Append(exp.Current());
1525   }
1526
1527   if (listShape.IsEmpty()){
1528     //SetErrorCode("The given shape has no sub-shapes of the requested type");
1529     SetErrorCode(NOT_FOUND_ANY); // NPAL18017
1530     return aSeq;
1531   }
1532
1533   if (isSorted) {
1534     bool isOldSorting = false;
1535     if (theExplodeType == EXPLODE_OLD_INCLUDE_MAIN)
1536       isOldSorting = true;
1537     GEOMUtils::SortShapes(listShape, isOldSorting);
1538   }
1539
1540   TopTools_IndexedMapOfShape anIndices;
1541   TopExp::MapShapes(aShape, anIndices);
1542   Handle(TColStd_HArray1OfInteger) anArray;
1543
1544   TopTools_ListIteratorOfListOfShape itSub (listShape);
1545   TCollection_AsciiString anAsciiList, anEntry;
1546   for (int index = 1; itSub.More(); itSub.Next(), ++index)
1547   {
1548     TopoDS_Shape aValue = itSub.Value();
1549     anArray = new TColStd_HArray1OfInteger(1,1);
1550     anArray->SetValue(1, anIndices.FindIndex(aValue));
1551
1552     //anObj = GetEngine()->AddSubShape(theShape, anArray);
1553     {
1554       anObj = GetEngine()->AddObject(GetDocID(), GEOM_SUBSHAPE);
1555       Handle(GEOM_Function) aFunction = anObj->AddFunction(GEOM_Object::GetSubShapeID(), 1);
1556       if (aFunction.IsNull()) return aSeq;
1557
1558       GEOM_ISubShape aSSI (aFunction);
1559       aSSI.SetMainShape(aMainShape);
1560       aSSI.SetIndices(anArray);
1561
1562       // Set function value directly, as we know it.
1563       // Usage of Solver here would lead to significant loss of time,
1564       // because GEOM_SubShapeDriver will build TopTools_IndexedMapOfShape
1565       // on the main shape for each being calculated sub-shape separately.
1566       aFunction->SetValue(aValue);
1567
1568       // Put this subshape in the list of sub-shapes of theMainShape
1569       aMainShape->AddSubShapeReference(aFunction);
1570     }
1571     if (!anObj.IsNull()) {
1572           aSeq->Append(anObj);
1573
1574           // for python command
1575           TDF_Tool::Entry(anObj->GetEntry(), anEntry);
1576           anAsciiList += anEntry;
1577           anAsciiList += ",";
1578         }
1579       }
1580
1581   //Make a Python command
1582   anAsciiList.Trunc(anAsciiList.Length() - 1);
1583
1584   GEOM::TPythonDump pd (aMainShape, /*append=*/true);
1585   pd << "[" << anAsciiList.ToCString() << "] = geompy.";
1586   switch (theExplodeType) {
1587   case EXPLODE_NEW_EXCLUDE_MAIN:
1588     pd << "ExtractShapes(" << theShape << ", "
1589        << TopAbs_ShapeEnum(theShapeType) << ", " << (isSorted ? "True" : "False") << ")";
1590     break;
1591   case EXPLODE_NEW_INCLUDE_MAIN:
1592     pd << "SubShapeAll" << (isSorted ? "SortedCentres(" : "(")
1593        << theShape << ", " << TopAbs_ShapeEnum(theShapeType) << ")";
1594     break;
1595   case EXPLODE_OLD_INCLUDE_MAIN:
1596     pd << "SubShapeAll" << (isSorted ? "Sorted(" : "(")
1597        << theShape << ", " << TopAbs_ShapeEnum(theShapeType) << ")";
1598     break;
1599   default: ;
1600   }
1601   SetErrorCode(OK);
1602
1603   return aSeq;
1604 }
1605
1606 //=============================================================================
1607 /*!
1608  *  SubShapeAllIDs
1609  */
1610 //=============================================================================
1611 Handle(TColStd_HSequenceOfInteger) GEOMImpl_IShapesOperations::SubShapeAllIDs
1612                                           (Handle(GEOM_Object)    theShape,
1613                                            const Standard_Integer theShapeType,
1614                                            const Standard_Boolean isSorted,
1615                                            const ExplodeType      theExplodeType)
1616 {
1617   SetErrorCode(KO);
1618
1619   if (theShape.IsNull()) return NULL;
1620   TopoDS_Shape aShape = theShape->GetValue();
1621   if (aShape.IsNull()) return NULL;
1622
1623   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
1624   TopTools_MapOfShape mapShape;
1625   TopTools_ListOfShape listShape;
1626
1627   if (aShape.ShapeType() == TopAbs_COMPOUND &&
1628       (theShapeType == TopAbs_SHAPE || theShapeType == TopAbs_FLAT || theShapeType == TopAbs_COMPOUND))
1629   {
1630     TopoDS_Iterator It (aShape, Standard_True, Standard_True);
1631     for (; It.More(); It.Next()) {
1632       TopoDS_Shape SS = It.Value();
1633       if (mapShape.Add(SS)) {
1634         if (theShapeType == TopAbs_FLAT) {
1635           AddFlatSubShapes(SS, listShape, mapShape);
1636         }
1637         else if (theShapeType == TopAbs_SHAPE || theShapeType == SS.ShapeType()) {
1638           listShape.Append(SS);
1639         }
1640       }
1641     }
1642   }
1643   else if (theExplodeType != EXPLODE_NEW_EXCLUDE_MAIN || aShape.ShapeType() != theShapeType) // issue 0021079
1644   {
1645     TopExp_Explorer exp (aShape, TopAbs_ShapeEnum(theShapeType));
1646     for (; exp.More(); exp.Next())
1647       if (mapShape.Add(exp.Current()))
1648         listShape.Append(exp.Current());
1649   }
1650
1651   if (listShape.IsEmpty()) {
1652     //SetErrorCode("The given shape has no sub-shapes of the requested type");
1653     SetErrorCode(NOT_FOUND_ANY); // NPAL18017
1654     return aSeq;
1655   }
1656
1657   if (isSorted) {
1658     bool isOldSorting = false;
1659     if (theExplodeType == EXPLODE_OLD_INCLUDE_MAIN)
1660       isOldSorting = true;
1661     GEOMUtils::SortShapes(listShape, isOldSorting);
1662   }
1663
1664   TopTools_IndexedMapOfShape anIndices;
1665   TopExp::MapShapes(aShape, anIndices);
1666   Handle(TColStd_HArray1OfInteger) anArray;
1667
1668   TopTools_ListIteratorOfListOfShape itSub (listShape);
1669   for (int index = 1; itSub.More(); itSub.Next(), ++index) {
1670     TopoDS_Shape aValue = itSub.Value();
1671     aSeq->Append(anIndices.FindIndex(aValue));
1672   }
1673
1674   Handle(GEOM_Function) aFunction = theShape->GetLastFunction();
1675
1676   //Make a Python command
1677   GEOM::TPythonDump pd (aFunction, /*append=*/true);
1678   pd << "listSubShapeIDs = geompy.SubShapeAll";
1679   switch (theExplodeType) {
1680   case EXPLODE_NEW_EXCLUDE_MAIN:
1681     break;
1682   case EXPLODE_NEW_INCLUDE_MAIN:
1683     pd << (isSorted ? "SortedCentresIDs(" : "IDs(")
1684        << theShape << ", " << TopAbs_ShapeEnum(theShapeType) << ")";
1685     break;
1686   case EXPLODE_OLD_INCLUDE_MAIN:
1687     pd << (isSorted ? "SortedIDs(" : "IDs(")
1688        << theShape << ", " << TopAbs_ShapeEnum(theShapeType) << ")";
1689     break;
1690   default: ;
1691   }
1692
1693   SetErrorCode(OK);
1694   return aSeq;
1695 }
1696
1697 //=============================================================================
1698 /*!
1699  *  GetSubShape
1700  */
1701 //=============================================================================
1702 Handle(GEOM_Object) GEOMImpl_IShapesOperations::GetSubShape
1703                                           (Handle(GEOM_Object)    theMainShape,
1704                                            const Standard_Integer theID)
1705 {
1706   SetErrorCode(KO);
1707
1708   if (theMainShape.IsNull()) return NULL;
1709
1710   Handle(TColStd_HArray1OfInteger) anArray = new TColStd_HArray1OfInteger(1,1);
1711   anArray->SetValue(1, theID);
1712   Handle(GEOM_Object) anObj = GetEngine()->AddSubShape(theMainShape, anArray,true);
1713   if (anObj.IsNull()) {
1714     SetErrorCode("Can not get a sub-shape with the given ID");
1715     return NULL;
1716   }
1717
1718   Handle(GEOM_Function) aFunction = anObj->GetLastFunction();
1719
1720   //Make a Python command
1721   GEOM::TPythonDump(aFunction) << anObj << " = geompy.GetSubShape("
1722                                << theMainShape << ", [" << theID << "])";
1723
1724   SetErrorCode(OK);
1725   return anObj;
1726 }
1727
1728 //=============================================================================
1729 /*!
1730  *  MakeSubShapes
1731  */
1732 //=============================================================================
1733 Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::MakeSubShapes
1734                                 (Handle(GEOM_Object)              theMainShape,
1735                                  Handle(TColStd_HArray1OfInteger) theIndices)
1736 {
1737   SetErrorCode(KO);
1738
1739   Handle(TColStd_HSequenceOfTransient) aSeq = new TColStd_HSequenceOfTransient;
1740
1741   if (!theIndices->Length()) {
1742     SetErrorCode(NOT_FOUND_ANY);
1743     return aSeq;
1744   }
1745
1746   if (theMainShape.IsNull()) return NULL;
1747   TopoDS_Shape aShape = theMainShape->GetValue();
1748   if (aShape.IsNull()) return NULL;
1749
1750   Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
1751
1752   TopTools_IndexedMapOfShape anIndices;
1753   TopExp::MapShapes(aShape, anIndices);
1754
1755   Handle(TColStd_HArray1OfInteger) anArray;
1756   Handle(GEOM_Object) anObj;
1757
1758   TCollection_AsciiString anAsciiList, anEntry;
1759   Standard_Integer i, low = theIndices->Lower(), up = theIndices->Upper();
1760   for (i = low; i <= up; i++) {
1761     int id = theIndices->Value(i);
1762     if (1 <= id && id <= anIndices.Extent()) {
1763       TopoDS_Shape aValue = anIndices.FindKey(id);
1764       anArray = new TColStd_HArray1OfInteger(1,1);
1765       anArray->SetValue(1, id);
1766
1767       anObj = GetEngine()->AddObject(GetDocID(), GEOM_SUBSHAPE);
1768       if (!anObj.IsNull()) {
1769         Handle(GEOM_Function) aFunction = anObj->AddFunction(GEOM_Object::GetSubShapeID(), 1);
1770         if (aFunction.IsNull()) return aSeq;
1771
1772         GEOM_ISubShape aSSI (aFunction);
1773         aSSI.SetMainShape(aMainShape);
1774         aSSI.SetIndices(anArray);
1775
1776         // Set function value directly, as we know it.
1777         // Usage of Solver here would lead to significant loss of time,
1778         // because GEOM_SubShapeDriver will build TopTools_IndexedMapOfShape
1779         // on the main shape for each being calculated sub-shape separately.
1780         aFunction->SetValue(aValue);
1781
1782         // Put this sub-shape in the list of sub-shapes of theMainShape
1783         aMainShape->AddSubShapeReference(aFunction);
1784
1785         aSeq->Append(anObj);
1786
1787         // for python command
1788         TDF_Tool::Entry(anObj->GetEntry(), anEntry);
1789         anAsciiList += anEntry;
1790         anAsciiList += ",";
1791       }
1792     }
1793   }
1794
1795   //Make a Python command
1796   anAsciiList.Trunc(anAsciiList.Length() - 1);
1797
1798   GEOM::TPythonDump pd (aMainShape, /*append=*/true);
1799   pd << "[" << anAsciiList.ToCString() << "] = geompy.SubShapes("
1800      << theMainShape << ", [" ;
1801   for (i = low; i <= up - 1; i++) {
1802     pd << theIndices->Value(i) << ", ";
1803   }
1804   pd << theIndices->Value(up) << "])";
1805
1806   SetErrorCode(OK);
1807
1808   return aSeq;
1809 }
1810
1811 //=============================================================================
1812 /*!
1813  *  GetSubShapeIndex
1814  */
1815 //=============================================================================
1816 Standard_Integer GEOMImpl_IShapesOperations::GetSubShapeIndex (Handle(GEOM_Object) theMainShape,
1817                                                                Handle(GEOM_Object) theSubShape)
1818 {
1819   SetErrorCode(KO);
1820
1821   TopoDS_Shape aMainShape = theMainShape->GetValue();
1822   TopoDS_Shape aSubShape = theSubShape->GetValue();
1823
1824   if (aMainShape.IsNull() || aSubShape.IsNull()) return -1;
1825
1826   TopTools_IndexedMapOfShape anIndices;
1827   TopExp::MapShapes(aMainShape, anIndices);
1828 //   if (anIndices.Contains(aSubShape)) {
1829 //     SetErrorCode(OK);
1830 //     return anIndices.FindIndex(aSubShape);
1831 //   }
1832   int id = anIndices.FindIndex(aSubShape);
1833   if (id > 0)
1834   {
1835     SetErrorCode(OK);
1836     return id;
1837   }
1838   return -1;
1839 }
1840
1841
1842
1843 //=============================================================================
1844 /*!
1845  *  GetSubShapeIndices
1846  */
1847 //=============================================================================
1848 Handle(TColStd_HSequenceOfInteger) GEOMImpl_IShapesOperations::GetSubShapesIndices (Handle(GEOM_Object) theMainShape,
1849                                                                                     std::list<Handle(GEOM_Object)> theSubShapes)
1850 {
1851   MESSAGE("GEOMImpl_IShapesOperations::GetSubShapesIndices")
1852   SetErrorCode(KO);
1853   
1854   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
1855   
1856   TopoDS_Shape aMainShape = theMainShape->GetValue();
1857   if (aMainShape.IsNull())
1858   {
1859     MESSAGE("NULL main shape")
1860     return NULL;
1861   }
1862   
1863   TopTools_IndexedMapOfShape anIndices;
1864   TopExp::MapShapes(aMainShape, anIndices);
1865   
1866   std::list<Handle(GEOM_Object)>::iterator it;
1867   for (it=theSubShapes.begin(); it != theSubShapes.end(); ++it)
1868   {
1869     TopoDS_Shape aSubShape = (*it)->GetValue(); 
1870     if (aSubShape.IsNull())
1871     {
1872       MESSAGE("NULL subshape")
1873       return NULL;
1874     }
1875     int id = anIndices.FindIndex(aSubShape);
1876     aSeq->Append(id);
1877   }  
1878   
1879   SetErrorCode(OK);
1880   return aSeq;
1881 }
1882
1883
1884 //=============================================================================
1885 /*!
1886  *  GetTopologyIndex
1887  */
1888 //=============================================================================
1889 Standard_Integer GEOMImpl_IShapesOperations::GetTopologyIndex (Handle(GEOM_Object) theMainShape,
1890                                                                Handle(GEOM_Object) theSubShape)
1891 {
1892   SetErrorCode(OK);
1893
1894   TopoDS_Shape aMainShape = theMainShape->GetValue();
1895   TopoDS_Shape aSubShape = theSubShape->GetValue();
1896
1897   if (aMainShape.IsNull() || aSubShape.IsNull()) {
1898     SetErrorCode("Null argument shape given");
1899     return -1;
1900   }
1901
1902   int index = 1;
1903   if (aSubShape.ShapeType() == TopAbs_COMPOUND) {
1904     TopoDS_Iterator it;
1905     TopTools_ListOfShape CL;
1906     CL.Append(aMainShape);
1907     TopTools_ListIteratorOfListOfShape itC;
1908     for (itC.Initialize(CL); itC.More(); itC.Next()) {
1909       for (it.Initialize(itC.Value()); it.More(); it.Next()) {
1910         if (it.Value().ShapeType() == TopAbs_COMPOUND) {
1911           if (it.Value().IsSame(aSubShape))
1912             return index;
1913           else
1914             index++;
1915           CL.Append(it.Value());
1916         }
1917       }
1918     }
1919   } else {
1920     TopExp_Explorer anExp (aMainShape, aSubShape.ShapeType());
1921     TopTools_MapOfShape M;
1922     for (; anExp.More(); anExp.Next()) {
1923       if (M.Add(anExp.Current())) {
1924         if (anExp.Current().IsSame(aSubShape))
1925           return index;
1926         index++;
1927       }
1928     }
1929   }
1930
1931   SetErrorCode("The sub-shape does not belong to the main shape");
1932   return -1;
1933 }
1934
1935 //=============================================================================
1936 /*!
1937  *  GetShapeTypeString
1938  */
1939 //=============================================================================
1940 TCollection_AsciiString GEOMImpl_IShapesOperations::GetShapeTypeString (Handle(GEOM_Object) theShape)
1941 {
1942   SetErrorCode(KO);
1943
1944   TCollection_AsciiString aTypeName ("Null Shape");
1945
1946   TopoDS_Shape aShape = theShape->GetValue();
1947   if (aShape.IsNull())
1948     return aTypeName;
1949
1950   switch (aShape.ShapeType() )
1951   {
1952   case TopAbs_COMPOUND:
1953     aTypeName = "Compound";
1954     break;
1955   case  TopAbs_COMPSOLID:
1956     aTypeName = "Compound Solid";
1957     break;
1958   case TopAbs_SOLID:
1959     aTypeName = "Solid";
1960     break;
1961   case TopAbs_SHELL:
1962     aTypeName = "Shell";
1963     break;
1964   case TopAbs_FACE:
1965     {
1966       BRepAdaptor_Surface surf (TopoDS::Face(aShape));
1967       if (surf.GetType() == GeomAbs_Plane)
1968         aTypeName = "Plane";
1969       else if (surf.GetType() == GeomAbs_Cylinder)
1970         aTypeName = "Cylindrical Face";
1971       else if (surf.GetType() == GeomAbs_Sphere)
1972         aTypeName = "Spherical Face";
1973       else if (surf.GetType() == GeomAbs_Torus)
1974         aTypeName = "Toroidal Face";
1975       else if (surf.GetType() == GeomAbs_Cone)
1976         aTypeName = "Conical Face";
1977       else
1978         aTypeName = "GEOM::FACE";
1979     }
1980     break;
1981   case TopAbs_WIRE:
1982     aTypeName = "Wire";
1983     break;
1984   case TopAbs_EDGE:
1985     {
1986       BRepAdaptor_Curve curv (TopoDS::Edge(aShape));
1987       if (curv.GetType() == GeomAbs_Line) {
1988         if ((Abs(curv.FirstParameter()) >= 1E6) ||
1989             (Abs(curv.LastParameter()) >= 1E6))
1990           aTypeName = "Line";
1991         else
1992           aTypeName = "Edge";
1993       } else if (curv.GetType() == GeomAbs_Circle) {
1994         if (curv.IsClosed())
1995           aTypeName = "Circle";
1996         else
1997           aTypeName = "Arc";
1998       } else {
1999         aTypeName = "Edge";
2000       }
2001     }
2002     break;
2003   case TopAbs_VERTEX:
2004     aTypeName = "Vertex";
2005     break;
2006   case TopAbs_SHAPE:
2007     aTypeName = "Shape";
2008     break;
2009   default:
2010     aTypeName = "Shape of unknown type";
2011   }
2012
2013   return aTypeName;
2014 }
2015
2016 //=============================================================================
2017 /*!
2018  *  IsSubShapeBelongsTo
2019  */
2020 //=============================================================================
2021 Standard_Boolean GEOMImpl_IShapesOperations::IsSubShapeBelongsTo( Handle(GEOM_Object) theSubObject,
2022                                                                   const Standard_Integer theSubObjectIndex,
2023                                                                   Handle(GEOM_Object) theObject,
2024                                                                   const Standard_Integer theObjectIndex)
2025 {
2026   SetErrorCode(KO);
2027
2028   if ( theObject.IsNull() || theSubObject.IsNull() )
2029     return false;
2030
2031   TopoDS_Shape shape    = theObject->GetValue();
2032   TopoDS_Shape subShape = theSubObject->GetValue();
2033
2034   if ( shape.IsNull() || subShape.IsNull() )
2035     return false;
2036
2037   TopTools_IndexedMapOfShape anIndices;
2038   if ( theObjectIndex > 0 ) {
2039     TopExp::MapShapes( shape, anIndices );
2040     shape = anIndices.FindKey(theObjectIndex);
2041   }
2042   if ( theSubObjectIndex > 0 ) {
2043     TopExp::MapShapes( subShape, anIndices );
2044     subShape = anIndices.FindKey(theSubObjectIndex);
2045   }
2046
2047   TopExp::MapShapes( shape, anIndices );
2048
2049   const Standard_Boolean isBelongTo = anIndices.Contains(subShape);
2050
2051   SetErrorCode(OK);
2052
2053   return isBelongTo;
2054 }
2055
2056 //=============================================================================
2057 /*!
2058  *  NumberOfSubShapes
2059  */
2060 //=============================================================================
2061 Standard_Integer GEOMImpl_IShapesOperations::NumberOfSubShapes
2062                                           (Handle(GEOM_Object)    theShape,
2063                                            const Standard_Integer theShapeType)
2064 {
2065   SetErrorCode(KO);
2066   Standard_Integer nbShapes = 0;
2067
2068   if (theShape.IsNull()) return -1;
2069   TopoDS_Shape aShape = theShape->GetValue();
2070   if (aShape.IsNull()) return -1;
2071
2072   /*
2073   TopTools_MapOfShape mapShape;
2074
2075   if (aShape.ShapeType() == TopAbs_COMPOUND &&
2076       (TopAbs_ShapeEnum(theShapeType) == TopAbs_SHAPE ||
2077        TopAbs_ShapeEnum(theShapeType) == TopAbs_COMPSOLID ||
2078        TopAbs_ShapeEnum(theShapeType) == TopAbs_COMPOUND)) {
2079     TopoDS_Iterator It (aShape, Standard_True, Standard_True);
2080     for (; It.More(); It.Next()) {
2081       if (mapShape.Add(It.Value())) {
2082         if (TopAbs_ShapeEnum(theShapeType) == TopAbs_SHAPE ||
2083             TopAbs_ShapeEnum(theShapeType) == It.Value().ShapeType()) {
2084           nbShapes++;
2085         }
2086       }
2087     }
2088   } else {
2089     TopExp_Explorer exp (aShape, TopAbs_ShapeEnum(theShapeType));
2090     for (; exp.More(); exp.Next())
2091       if (mapShape.Add(exp.Current()))
2092         nbShapes++;
2093   }
2094   */
2095
2096   try {
2097     if (theShapeType == TopAbs_FLAT) {
2098       TopTools_MapOfShape aMapOfShape;
2099       TopTools_ListOfShape aListOfShape;
2100       AddFlatSubShapes(aShape, aListOfShape, aMapOfShape);
2101       nbShapes = aListOfShape.Extent();
2102     }
2103     else {
2104       OCC_CATCH_SIGNALS;
2105       int iType, nbTypes [TopAbs_SHAPE];
2106       for (iType = 0; iType < TopAbs_SHAPE; ++iType)
2107         nbTypes[iType] = 0;
2108       nbTypes[aShape.ShapeType()]++;
2109       
2110       TopTools_MapOfShape aMapOfShape;
2111       aMapOfShape.Add(aShape);
2112       TopTools_ListOfShape aListOfShape;
2113       aListOfShape.Append(aShape);
2114       
2115       TopTools_ListIteratorOfListOfShape itL (aListOfShape);
2116       for (; itL.More(); itL.Next()) {
2117         TopoDS_Iterator it (itL.Value());
2118         for (; it.More(); it.Next()) {
2119           TopoDS_Shape s = it.Value();
2120           if (aMapOfShape.Add(s)) {
2121             aListOfShape.Append(s);
2122             nbTypes[s.ShapeType()]++;
2123           }
2124         }
2125       }
2126       
2127       if (TopAbs_ShapeEnum(theShapeType) == TopAbs_SHAPE)
2128         nbShapes = aMapOfShape.Extent();
2129       else
2130         nbShapes = nbTypes[theShapeType];
2131     }
2132   }
2133   catch (Standard_Failure) {
2134     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
2135     SetErrorCode(aFail->GetMessageString());
2136     return -1;
2137   }
2138
2139   SetErrorCode(OK);
2140   return nbShapes;
2141 }
2142
2143 //=============================================================================
2144 /*!
2145  *  ReverseShape
2146  */
2147 //=============================================================================
2148 Handle(GEOM_Object) GEOMImpl_IShapesOperations::ReverseShape(Handle(GEOM_Object) theShape)
2149 {
2150   SetErrorCode(KO);
2151
2152   if (theShape.IsNull()) return NULL;
2153
2154   /*
2155   //Add a new reversed object
2156   Handle(GEOM_Object) aReversed = GetEngine()->AddObject(GetDocID(), theShape->GetType());
2157
2158   //Add a new Revese function
2159   Handle(GEOM_Function) aFunction;
2160   aFunction = aReversed->AddFunction(GEOMImpl_ShapeDriver::GetID(), REVERSE_ORIENTATION);
2161   if (aFunction.IsNull()) return NULL;
2162
2163   //Check if the function is set correctly
2164   if (aFunction->GetDriverGUID() != GEOMImpl_ShapeDriver::GetID()) return NULL;
2165
2166   GEOMImpl_IShapes aSI (aFunction);
2167
2168   Handle(GEOM_Function) aRefShape = theShape->GetLastFunction();
2169   if (aRefShape.IsNull()) return NULL;
2170
2171   aSI.SetBase(aRefShape);
2172
2173   //Compute the sub-shape value
2174   try {
2175     OCC_CATCH_SIGNALS;
2176     if (!GetSolver()->ComputeFunction(aFunction)) {
2177       SetErrorCode("Shape driver failed to reverse shape");
2178       return NULL;
2179     }
2180   }
2181   catch (Standard_Failure) {
2182     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
2183     SetErrorCode(aFail->GetMessageString());
2184     return NULL;
2185   }
2186
2187   //Make a Python command
2188   GEOM::TPythonDump(aFunction) << aReversed
2189     << " = geompy.ChangeOrientation(" << theShape << ")";
2190
2191   SetErrorCode(OK);
2192   */
2193
2194   Handle(GEOM_Object) aReversed;
2195
2196   GEOM_Engine* anEngine = GetEngine();
2197   //GEOMImpl_Gen* aGen = dynamic_cast<GEOMImpl_Gen*>(anEngine);
2198   GEOMImpl_Gen* aGen = (GEOMImpl_Gen*)anEngine;
2199
2200   if (aGen) {
2201     GEOMImpl_IHealingOperations* anIHealingOperations =
2202       aGen->GetIHealingOperations(GetDocID());
2203     aReversed = anIHealingOperations->ChangeOrientationCopy(theShape);
2204     SetErrorCode(anIHealingOperations->GetErrorCode());
2205   }
2206
2207   return aReversed;
2208 }
2209
2210 //=============================================================================
2211 /*!
2212  *  GetFreeFacesIDs
2213  */
2214 //=============================================================================
2215 Handle(TColStd_HSequenceOfInteger) GEOMImpl_IShapesOperations::GetFreeFacesIDs
2216                                                  (Handle(GEOM_Object) theShape)
2217 {
2218   SetErrorCode(KO);
2219
2220   if (theShape.IsNull()) return NULL;
2221   TopoDS_Shape aShape = theShape->GetValue();
2222   if (aShape.IsNull()) return NULL;
2223
2224   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
2225
2226   TopTools_IndexedDataMapOfShapeListOfShape mapFaceBlocks;
2227   GEOMImpl_Block6Explorer::MapShapesAndAncestors
2228     (aShape, TopAbs_FACE, TopAbs_SOLID, mapFaceBlocks);
2229
2230   Standard_Integer ind = 1, nbFaces = mapFaceBlocks.Extent();
2231
2232   if (nbFaces == 0) {
2233     SetErrorCode("The given shape has no faces");
2234     return aSeq;
2235   }
2236
2237   TopTools_IndexedMapOfShape anIndices;
2238   TopExp::MapShapes(aShape, anIndices);
2239
2240   Standard_Integer id;
2241   for (; ind <= nbFaces; ind++) {
2242     if (mapFaceBlocks.FindFromIndex(ind).Extent() != 2) {
2243       id = anIndices.FindIndex(mapFaceBlocks.FindKey(ind));
2244       aSeq->Append(id);
2245     }
2246   }
2247
2248   //The explode doesn't change object so no new function is required.
2249   Handle(GEOM_Function) aFunction = theShape->GetLastFunction();
2250
2251   //Make a Python command
2252   GEOM::TPythonDump(aFunction, /*append=*/true)
2253     << "listFreeFacesIDs = geompy.GetFreeFacesIDs(" << theShape << ")";
2254
2255   SetErrorCode(OK);
2256   return aSeq;
2257 }
2258
2259 //=======================================================================
2260 //function : GetSharedShapes
2261 //purpose  :
2262 //=======================================================================
2263 Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::GetSharedShapes
2264                                                 (Handle(GEOM_Object)    theShape1,
2265                                                  Handle(GEOM_Object)    theShape2,
2266                                                  const Standard_Integer theShapeType)
2267 {
2268   SetErrorCode(KO);
2269
2270   if (theShape1.IsNull() || theShape2.IsNull()) return NULL;
2271
2272   TopoDS_Shape aShape1 = theShape1->GetValue();
2273   TopoDS_Shape aShape2 = theShape2->GetValue();
2274
2275   if (aShape1.IsNull() || aShape2.IsNull()) return NULL;
2276
2277   TopTools_IndexedMapOfShape anIndices;
2278   TopExp::MapShapes(aShape1, anIndices);
2279   Handle(TColStd_HArray1OfInteger) anArray;
2280
2281   TopTools_IndexedMapOfShape mapShape1;
2282   TopExp::MapShapes(aShape1, TopAbs_ShapeEnum(theShapeType), mapShape1);
2283
2284   Handle(GEOM_Object) anObj;
2285   Handle(TColStd_HSequenceOfTransient) aSeq = new TColStd_HSequenceOfTransient;
2286   TCollection_AsciiString anAsciiList, anEntry;
2287
2288   TopTools_MapOfShape mapShape2;
2289   TopExp_Explorer exp (aShape2, TopAbs_ShapeEnum(theShapeType));
2290   for (; exp.More(); exp.Next()) {
2291     TopoDS_Shape aSS = exp.Current();
2292     if (mapShape2.Add(aSS) && mapShape1.Contains(aSS)) {
2293       anArray = new TColStd_HArray1OfInteger(1,1);
2294       anArray->SetValue(1, anIndices.FindIndex(aSS));
2295       anObj = GetEngine()->AddSubShape(theShape1, anArray);
2296       aSeq->Append(anObj);
2297
2298       // for python command
2299       TDF_Tool::Entry(anObj->GetEntry(), anEntry);
2300       anAsciiList += anEntry;
2301       anAsciiList += ",";
2302     }
2303   }
2304
2305   if (aSeq->IsEmpty()) {
2306     SetErrorCode(NOT_FOUND_ANY);
2307     return aSeq;
2308   }
2309
2310   //Make a Python command
2311   anAsciiList.Trunc(anAsciiList.Length() - 1);
2312
2313   Handle(GEOM_Function) aFunction = anObj->GetLastFunction();
2314
2315   GEOM::TPythonDump(aFunction) << "[" << anAsciiList.ToCString()
2316     << "] = geompy.GetSharedShapes(" << theShape1 << ", "
2317       << theShape2 << ", " << TopAbs_ShapeEnum(theShapeType) << ")";
2318
2319   SetErrorCode(OK);
2320   return aSeq;
2321 }
2322
2323 //=======================================================================
2324 //function : GetSharedShapes
2325 //purpose  :
2326 //
2327 // NOTE on the implementation
2328 // 
2329 // 1) Resulting sub-shapes are published as a children of the 1st input shape
2330 //    from theShapes list. Due to this reason only direct sub-shapes of the 1st
2331 //    shape can be contained in the result of the operation (i.e. shares between
2332 //    2nd/3rd, etc couples cannot be retrieved.
2333 // 2) An exception from above case is when a single compound is specified as an
2334 //    input. In this case we search shares between its top-level content, so we
2335 //    are able to search shares between all possible couples of shapes.
2336 // 3) Parameter theMultiShare controls what types of shares to search:
2337 //    - True: get sub-shapes that are shared between ALL input shapes;
2338 //    - False: get shares between couples of input sub-shapes (see points 1 and 2).
2339 //
2340 // Thus, we have the following cases:
2341 // [1] theShapes = N shapes (N>1), theMultiShare = True
2342 //     Result: sub-shapes that are shared by all theShapes
2343 // [2] theShapes = N shapes (N>1), theMultiShare = False
2344 //     Result: sub-shapes of 1st shape from theShapes that are shared with any shape
2345 //     from theShapes
2346 // [3] theShapes = 1 shape, theMultiShare = True
2347 //     Result: sub-shapes that are shared by all top-level sub-objects of theShapes[0]
2348 // [4] theShapes = 1 shape, theMultiShare = False
2349 //     Result: sub-shapes of all possible couples of all top-level sub-objects of
2350 //     theShapes[0].
2351 //=======================================================================
2352 Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::GetSharedShapes
2353                                      (std::list<Handle(GEOM_Object)> & theShapes,
2354                                       const Standard_Integer           theShapeType,
2355                                       const bool                       theMultiShare)
2356 {
2357   SetErrorCode(KO);
2358
2359   int aLen = theShapes.size();
2360   if (aLen < 1) return NULL;
2361
2362   std::list<Handle(GEOM_Object)>::iterator it = theShapes.begin();
2363
2364   // main object is always first in the input list
2365   // it is the object from which sub-shapes indices are taken
2366   // and where results are published
2367   Handle(GEOM_Object) aMainObj = *it;
2368   Handle(GEOM_Function) aMainShape = aMainObj->GetLastFunction();
2369
2370   // collect all shapes from the input list (including first one) for processing
2371   TopTools_SequenceOfShape shapeSeq;
2372   for (; it != theShapes.end(); it++) {
2373     Handle(GEOM_Function) aRefShape = (*it)->GetLastFunction();
2374     if (aRefShape.IsNull()) {
2375       SetErrorCode("NULL shape for GetSharedShapes");
2376       return NULL;
2377     }
2378     TopoDS_Shape aShape = aRefShape->GetValue();
2379     if (aShape.IsNull()) {
2380       SetErrorCode("NULL shape for GetSharedShapes");
2381       return NULL;
2382     }
2383     shapeSeq.Append( aShape );
2384   }
2385
2386   // if only single shape is specified as input
2387   // collect all ites top-level sub-shapes for processing
2388   if ( shapeSeq.Length() == 1 )
2389   {
2390     TopoDS_Shape aShape = shapeSeq.First();
2391     shapeSeq.Clear();
2392     for ( TopoDS_Iterator it( aShape ); it.More(); it.Next() )
2393       shapeSeq.Append( it.Value() );
2394   }
2395
2396   // map all sub-shapes in a main shape to their indices
2397   TopTools_IndexedMapOfShape anIndices;
2398   TopExp::MapShapes(aMainShape->GetValue(), anIndices);
2399   TopTools_MapOfShape mapShape;
2400
2401   // find shared shapes
2402
2403   // here we will collect all shares
2404   TopTools_ListOfShape aShared;
2405
2406   // number of iterations
2407   int nbIters  =  theMultiShare || theShapes.size() > 1 ? 1 : shapeSeq.Length()-1;
2408   // numShares factor to search (i.e. by what nb of shapes each found sub-shape should be shared)
2409   int nbShares =  theMultiShare ? shapeSeq.Length()-1 : 1;
2410     
2411   for ( int iter = 1; iter <= nbIters; iter++) {
2412     for ( int ind = iter+1; ind <= shapeSeq.Length(); ind++) {
2413       if ( ind-1+nbShares > shapeSeq.Length() ) break;
2414       TopoDS_Compound aCurrSelection;
2415       TopoDS_Shape aShape1 = shapeSeq.Value( iter );
2416       TopTools_IndexedMapOfShape mapSelected;
2417       TopExp::MapShapes(aShape1, TopAbs_ShapeEnum(theShapeType), mapSelected);
2418       for ( int s = 0; s < nbShares; s++ ) {
2419         BRep_Builder B;
2420         TopoDS_Compound aCompound;
2421         B.MakeCompound(aCompound);
2422         const TopoDS_Shape& aShape2 = shapeSeq.Value( ind+s );
2423         TopTools_MapOfShape mapShape2;
2424         TopExp_Explorer exp (aShape2, TopAbs_ShapeEnum(theShapeType));
2425         for (; exp.More(); exp.Next()) {
2426           const TopoDS_Shape& aSS = exp.Current();
2427           if (mapShape2.Add(aSS) && mapSelected.Contains(aSS)) {
2428             B.Add(aCompound, aSS);
2429           }
2430         }
2431         mapSelected.Clear();
2432         aCurrSelection = aCompound;
2433         TopExp::MapShapes(aCurrSelection, TopAbs_ShapeEnum(theShapeType), mapSelected);
2434       }
2435       TopoDS_Iterator itSel(aCurrSelection, Standard_True, Standard_True);
2436       for (; itSel.More(); itSel.Next()) {
2437         const TopoDS_Shape& aSS = itSel.Value();
2438         if (mapShape.Add(aSS) )
2439           aShared.Append(aSS);
2440       }
2441     }
2442   }
2443
2444   Handle(TColStd_HSequenceOfTransient) aSeq = new TColStd_HSequenceOfTransient;
2445
2446   if (aShared.IsEmpty()){
2447     SetErrorCode(NOT_FOUND_ANY);
2448     return aSeq;
2449   }
2450
2451   // create GEOM_Object for each found shared shape (collected in aShared)
2452   TCollection_AsciiString anAsciiList;
2453   Handle(GEOM_Object) anObj;
2454   TopTools_ListIteratorOfListOfShape itSub (aShared);
2455   for (; itSub.More(); itSub.Next()) {
2456     TopoDS_Shape aValue = itSub.Value();
2457     Handle(TColStd_HArray1OfInteger) anArray = new TColStd_HArray1OfInteger(1,1);
2458     anArray->SetValue(1, anIndices.FindIndex(aValue));
2459     anObj = GetEngine()->AddSubShape(aMainObj, anArray);
2460     aSeq->Append(anObj);
2461
2462     // for python command
2463     TCollection_AsciiString anEntry;
2464     TDF_Tool::Entry(anObj->GetEntry(), anEntry);
2465     anAsciiList += anEntry;
2466     anAsciiList += ",";
2467   }
2468
2469   // make a Python command
2470   anAsciiList.Trunc(anAsciiList.Length() - 1);
2471
2472   GEOM::TPythonDump pd (anObj->GetLastFunction());
2473   pd << "[" << anAsciiList.ToCString()
2474      << "] = geompy.GetSharedShapesMulti(";
2475
2476   if ( aLen > 1 )
2477     pd << "[";
2478
2479   it = theShapes.begin();
2480   pd << (*it++);
2481   while (it != theShapes.end()) {
2482     pd << ", " << (*it++);
2483   }
2484   if ( aLen > 1 )
2485     pd << "]";
2486
2487   pd << ", " << TopAbs_ShapeEnum(theShapeType) << ", " << theMultiShare << ")";
2488
2489   SetErrorCode(OK);
2490   return aSeq;
2491 }
2492
2493 //=============================================================================
2494 /*!
2495  *
2496  */
2497 //=============================================================================
2498 static GEOM::TPythonDump& operator<< (GEOM::TPythonDump&   theDump,
2499                                       const GEOMAlgo_State theState)
2500 {
2501   switch (theState) {
2502   case GEOMAlgo_ST_IN:
2503     theDump << "GEOM.ST_IN";
2504     break;
2505   case GEOMAlgo_ST_OUT:
2506     theDump << "GEOM.ST_OUT";
2507     break;
2508   case GEOMAlgo_ST_ON:
2509     theDump << "GEOM.ST_ON";
2510     break;
2511   case GEOMAlgo_ST_ONIN:
2512     theDump << "GEOM.ST_ONIN";
2513     break;
2514   case GEOMAlgo_ST_ONOUT:
2515     theDump << "GEOM.ST_ONOUT";
2516     break;
2517   default:
2518     theDump << "GEOM.ST_UNKNOWN";
2519     break;
2520   }
2521   return theDump;
2522 }
2523
2524 //=======================================================================
2525 //function : checkTypeShapesOn
2526 /*!
2527  * \brief Checks if theShapeType parameter of GetShapesOnXXX() is OK
2528  * \param theShapeType - the shape type to check
2529  * \retval bool  - result of the check
2530  */
2531 //=======================================================================
2532 bool GEOMImpl_IShapesOperations::checkTypeShapesOn(const Standard_Integer theShapeType)
2533 {
2534   if (theShapeType != TopAbs_VERTEX &&
2535       theShapeType != TopAbs_EDGE &&
2536       theShapeType != TopAbs_FACE &&
2537       theShapeType != TopAbs_SOLID) {
2538     SetErrorCode("Only solids, vertices, edges or faces can be found by this method");
2539     return false;
2540   }
2541   return true;
2542 }
2543
2544 //=======================================================================
2545 //function : makePlane
2546   /*!
2547    * \brief Creates Geom_Plane
2548     * \param theAx1 - shape object defining plane parameters
2549     * \retval Handle(Geom_Surface) - resulting surface
2550    */
2551 //=======================================================================
2552 Handle(Geom_Surface) GEOMImpl_IShapesOperations::makePlane(const TopoDS_Shape& anAx1)
2553 {
2554   if (anAx1.ShapeType() != TopAbs_EDGE) return NULL;
2555   TopoDS_Edge anEdge = TopoDS::Edge(anAx1);
2556   TopoDS_Vertex V1, V2;
2557   TopExp::Vertices(anEdge, V1, V2, Standard_True);
2558   if (V1.IsNull() || V2.IsNull()) {
2559     SetErrorCode("Bad edge given for the plane normal vector");
2560     return NULL;
2561   }
2562   gp_Pnt aLoc = BRep_Tool::Pnt(V1);
2563   gp_Vec aVec (aLoc, BRep_Tool::Pnt(V2));
2564   if (aVec.Magnitude() < Precision::Confusion()) {
2565     SetErrorCode("Vector with null magnitude given");
2566     return NULL;
2567   }
2568   return new Geom_Plane(aLoc, aVec);
2569 }
2570
2571 //=======================================================================
2572 //function : makeCylinder
2573   /*!
2574    * \brief Creates Geom_CylindricalSurface
2575     * \param theAx1 - edge defining cylinder axis
2576     * \param theRadius - cylinder radius
2577     * \retval Handle(Geom_Surface) - resulting surface
2578    */
2579 //=======================================================================
2580 Handle(Geom_Surface) GEOMImpl_IShapesOperations::makeCylinder(const TopoDS_Shape& anAxis,
2581                                                               const Standard_Real theRadius)
2582 {
2583   //Axis of the cylinder
2584   if (anAxis.ShapeType() != TopAbs_EDGE) {
2585     SetErrorCode("Not an edge given for the axis");
2586     return NULL;
2587   }
2588   TopoDS_Edge anEdge = TopoDS::Edge(anAxis);
2589   TopoDS_Vertex V1, V2;
2590   TopExp::Vertices(anEdge, V1, V2, Standard_True);
2591   if (V1.IsNull() || V2.IsNull()) {
2592     SetErrorCode("Bad edge given for the axis");
2593     return NULL;
2594   }
2595   gp_Pnt aLoc = BRep_Tool::Pnt(V1);
2596   gp_Vec aVec (aLoc, BRep_Tool::Pnt(V2));
2597   if (aVec.Magnitude() < Precision::Confusion()) {
2598     SetErrorCode("Vector with null magnitude given");
2599     return NULL;
2600   }
2601
2602   gp_Ax3 anAx3 (aLoc, aVec);
2603   return new Geom_CylindricalSurface(anAx3, theRadius);
2604 }
2605
2606 //=======================================================================
2607 //function : getShapesOnBoxIDs
2608   /*!
2609    * \brief Find IDs of sub-shapes complying with given status about surface
2610     * \param theBox - the box to check state of sub-shapes against
2611     * \param theShape - the shape to explore
2612     * \param theShapeType - type of sub-shape of theShape
2613     * \param theState - required state
2614     * \retval Handle(TColStd_HSequenceOfInteger) - IDs of found sub-shapes
2615    */
2616 //=======================================================================
2617 Handle(TColStd_HSequenceOfInteger)
2618   GEOMImpl_IShapesOperations::getShapesOnBoxIDs(const Handle(GEOM_Object)& theBox,
2619                                                 const Handle(GEOM_Object)& theShape,
2620                                                 const Standard_Integer theShapeType,
2621                                                 GEOMAlgo_State theState)
2622 {
2623   Handle(TColStd_HSequenceOfInteger) aSeqOfIDs;
2624
2625   TopoDS_Shape aBox = theBox->GetValue();
2626   TopoDS_Shape aShape = theShape->GetValue();
2627
2628   // Check presence of triangulation, build if need
2629   if (!GEOMUtils::CheckTriangulation(aShape)) {
2630     SetErrorCode("Cannot build triangulation on the shape");
2631     return aSeqOfIDs;
2632   }
2633
2634   // Call algo
2635   GEOMAlgo_FinderShapeOn2 aFinder;
2636   Standard_Real aTol = 0.0001; // default value
2637
2638   Handle(GEOMAlgo_ClsfBox) aClsfBox = new GEOMAlgo_ClsfBox;
2639   aClsfBox->SetBox(aBox);
2640
2641   aFinder.SetShape(aShape);
2642   aFinder.SetTolerance(aTol);
2643   aFinder.SetClsf(aClsfBox);
2644   aFinder.SetShapeType( (TopAbs_ShapeEnum)theShapeType );
2645   aFinder.SetState(theState);
2646   aFinder.Perform();
2647
2648   // Interprete results
2649   Standard_Integer iErr = aFinder.ErrorStatus();
2650   // the detailed description of error codes is in GEOMAlgo_FinderShapeOn2.cxx
2651   if (iErr) {
2652     MESSAGE(" iErr : " << iErr);
2653     TCollection_AsciiString aMsg (" iErr : ");
2654     aMsg += TCollection_AsciiString(iErr);
2655     SetErrorCode(aMsg);
2656     return aSeqOfIDs;
2657   }
2658   Standard_Integer iWrn = aFinder.WarningStatus();
2659   // the detailed description of warning codes is in GEOMAlgo_FinderShapeOn2.cxx
2660   if (iWrn) {
2661     MESSAGE(" *** iWrn : " << iWrn);
2662   }
2663
2664   const TopTools_ListOfShape& listSS = aFinder.Shapes(); // the result
2665
2666   if (listSS.Extent() < 1) {
2667     //SetErrorCode("Not a single sub-shape of the requested type found on the given surface");
2668     SetErrorCode(NOT_FOUND_ANY); // NPAL18017
2669     return aSeqOfIDs;
2670   }
2671
2672   // Fill sequence of object IDs
2673   aSeqOfIDs = new TColStd_HSequenceOfInteger;
2674
2675   TopTools_IndexedMapOfShape anIndices;
2676   TopExp::MapShapes(aShape, anIndices);
2677
2678   TopTools_ListIteratorOfListOfShape itSub (listSS);
2679   for (int index = 1; itSub.More(); itSub.Next(), ++index) {
2680     int id = anIndices.FindIndex(itSub.Value());
2681     aSeqOfIDs->Append(id);
2682   }
2683
2684   return aSeqOfIDs;
2685 }
2686
2687 //=======================================================================
2688 //function : GetShapesOnBoxIDs
2689 /*!
2690    * \brief Find sub-shapes complying with given status about surface
2691     * \param theBox - the box to check state of sub-shapes against
2692     * \param theShape - the shape to explore
2693     * \param theShapeType - type of sub-shape of theShape
2694     * \param theState - required state
2695     * \retval Handle(TColStd_HSequenceOfInteger) - IDs of found sub-shapes
2696  */
2697 //=======================================================================
2698 Handle(TColStd_HSequenceOfInteger)
2699     GEOMImpl_IShapesOperations::GetShapesOnBoxIDs(const Handle(GEOM_Object)& theBox,
2700                                                   const Handle(GEOM_Object)& theShape,
2701                                                   const Standard_Integer theShapeType,
2702                                                   GEOMAlgo_State theState)
2703 {
2704   // Find sub-shapes ids
2705   Handle(TColStd_HSequenceOfInteger) aSeqOfIDs =
2706     getShapesOnBoxIDs (theBox, theShape, theShapeType, theState);
2707   if ( aSeqOfIDs.IsNull()  || aSeqOfIDs->Length() == 0 )
2708     return NULL;
2709
2710   // The GetShapesOnBox() doesn't change object so no new function is required.
2711   Handle(GEOM_Function) aFunction = GEOM::GetCreatedLast(theShape,theBox)->GetLastFunction();
2712
2713   // Make a Python command
2714   GEOM::TPythonDump(aFunction, /*append=*/true)
2715     << "listShapesOnBoxIDs = geompy.GetShapesOnBoxIDs("
2716     << theBox << ", "
2717     << theShape << ", "
2718     << TopAbs_ShapeEnum(theShapeType) << ", "
2719     << theState << ")";
2720
2721   SetErrorCode(OK);
2722   return aSeqOfIDs;
2723 }
2724
2725 //=======================================================================
2726 //function : GetShapesOnBox
2727 /*!
2728    * \brief Find sub-shapes complying with given status about surface
2729     * \param theBox - the box to check state of sub-shapes against
2730     * \param theShape - the shape to explore
2731     * \param theShapeType - type of sub-shape of theShape
2732     * \param theState - required state
2733     * \retval Handle(TColStd_HSequenceOfTransient) - found sub-shapes
2734  */
2735 //=======================================================================
2736 Handle(TColStd_HSequenceOfTransient)
2737     GEOMImpl_IShapesOperations::GetShapesOnBox(const Handle(GEOM_Object)& theBox,
2738                                                const Handle(GEOM_Object)&  theShape,
2739                                                const Standard_Integer theShapeType,
2740                                                GEOMAlgo_State theState)
2741 {
2742   // Find sub-shapes ids
2743   Handle(TColStd_HSequenceOfInteger) aSeqOfIDs =
2744     getShapesOnBoxIDs (theBox, theShape, theShapeType, theState);
2745   if ( aSeqOfIDs.IsNull()  || aSeqOfIDs->Length() == 0 )
2746     return NULL;
2747
2748   // Find objects by indices
2749   TCollection_AsciiString anAsciiList;
2750   Handle(TColStd_HSequenceOfTransient) aSeq;
2751   aSeq = getObjectsShapesOn( theShape, aSeqOfIDs, anAsciiList );
2752   if ( aSeq.IsNull() || aSeq->IsEmpty() )
2753     return NULL;
2754
2755   // Make a Python command
2756
2757   Handle(GEOM_Object) anObj = Handle(GEOM_Object)::DownCast( aSeq->Value( 1 ));
2758   Handle(GEOM_Function) aFunction = anObj->GetLastFunction();
2759
2760   GEOM::TPythonDump(aFunction)
2761     << "[" << anAsciiList.ToCString() << "] = geompy.GetShapesOnBox("
2762     << theBox << ", "
2763     << theShape << ", "
2764     << TopAbs_ShapeEnum(theShapeType) << ", "
2765     << theState << ")";
2766
2767   SetErrorCode(OK);
2768   return aSeq;
2769 }
2770
2771 //=======================================================================
2772 //function : getShapesOnShapeIDs
2773 /*!
2774  * \brief Find IDs of sub-shapes complying with given status about surface
2775  * \param theCheckShape - the shape to check state of sub-shapes against
2776  * \param theShape - the shape to explore
2777  * \param theShapeType - type of sub-shape of theShape
2778  * \param theState - required state
2779  * \retval Handle(TColStd_HSequenceOfInteger) - IDs of found sub-shapes
2780  */
2781 //=======================================================================
2782 Handle(TColStd_HSequenceOfInteger)
2783   GEOMImpl_IShapesOperations::getShapesOnShapeIDs
2784                                  (const Handle(GEOM_Object)& theCheckShape,
2785                                   const Handle(GEOM_Object)& theShape,
2786                                   const Standard_Integer theShapeType,
2787                                   GEOMAlgo_State theState)
2788 {
2789   Handle(TColStd_HSequenceOfInteger) aSeqOfIDs;
2790
2791   TopoDS_Shape aCheckShape = theCheckShape->GetValue();
2792   TopoDS_Shape aShape = theShape->GetValue();
2793   TopTools_ListOfShape res;
2794
2795   // Check presence of triangulation, build if need
2796   if (!GEOMUtils::CheckTriangulation(aShape)) {
2797     SetErrorCode("Cannot build triangulation on the shape");
2798     return aSeqOfIDs;
2799   }
2800
2801   // Compute classification tolerance.
2802   TopTools_IndexedMapOfShape aMapVtx;
2803   Standard_Real              aTol = Precision::Confusion();
2804
2805   TopExp::MapShapes(aShape, TopAbs_VERTEX, aMapVtx);
2806
2807   Standard_Integer i;
2808   Standard_Integer aNbVtx = aMapVtx.Extent();
2809
2810   for (i = 1; i <= aNbVtx; ++i) {
2811     const TopoDS_Vertex aVtx    = TopoDS::Vertex(aMapVtx.FindKey(i));
2812     const Standard_Real aVtxTol = BRep_Tool::Tolerance(aVtx);
2813
2814     if (aTol < aVtxTol) {
2815       aTol = aVtxTol;
2816     }
2817   }
2818
2819   // Bound the tolerance value.
2820   if (aTol > 0.0001) {
2821     aTol = 0.0001;
2822   }
2823
2824   // Call algo
2825   GEOMAlgo_FinderShapeOn2 aFinder;
2826
2827   Handle(GEOMAlgo_ClsfSolid) aClsfSolid = new GEOMAlgo_ClsfSolid;
2828   aClsfSolid->SetShape(aCheckShape);
2829
2830   aFinder.SetShape(aShape);
2831   aFinder.SetTolerance(aTol);
2832   aFinder.SetClsf(aClsfSolid);
2833   aFinder.SetShapeType( (TopAbs_ShapeEnum)theShapeType );
2834   aFinder.SetState(theState);
2835   aFinder.Perform();
2836
2837   // Interprete results
2838   Standard_Integer iErr = aFinder.ErrorStatus();
2839   // the detailed description of error codes is in GEOMAlgo_FinderShapeOn2.cxx
2840   if (iErr) {
2841     if (iErr == 41) {
2842       SetErrorCode("theCheckShape must be a solid");
2843     }
2844     else {
2845       MESSAGE(" iErr : " << iErr);
2846       TCollection_AsciiString aMsg (" iErr : ");
2847       aMsg += TCollection_AsciiString(iErr);
2848       SetErrorCode(aMsg);
2849     }
2850     return aSeqOfIDs;
2851   }
2852   Standard_Integer iWrn = aFinder.WarningStatus();
2853   // the detailed description of warning codes is in GEOMAlgo_FinderShapeOn2.cxx
2854   if (iWrn) {
2855     MESSAGE(" *** iWrn : " << iWrn);
2856   }
2857
2858   const TopTools_ListOfShape& listSS = aFinder.Shapes(); // the result
2859
2860   if (listSS.Extent() < 1) {
2861     //SetErrorCode("Not a single sub-shape of the requested type found on the given surface");
2862     SetErrorCode(NOT_FOUND_ANY); // NPAL18017
2863   }
2864
2865   // Fill sequence of object IDs
2866   aSeqOfIDs = new TColStd_HSequenceOfInteger;
2867
2868   TopTools_IndexedMapOfShape anIndices;
2869   TopExp::MapShapes(aShape, anIndices);
2870
2871   TopTools_ListIteratorOfListOfShape itSub (listSS);
2872   for (int index = 1; itSub.More(); itSub.Next(), ++index) {
2873     int id = anIndices.FindIndex(itSub.Value());
2874     aSeqOfIDs->Append(id);
2875   }
2876
2877   return aSeqOfIDs;
2878 }
2879
2880 //=======================================================================
2881 //function : GetShapesOnShapeIDs
2882 /*!
2883  * \brief Find sub-shapes complying with given status about surface
2884  * \param theCheckShape - the shape to check state of sub-shapes against
2885  * \param theShape - the shape to explore
2886  * \param theShapeType - type of sub-shape of theShape
2887  * \param theState - required state
2888  * \retval Handle(TColStd_HSequenceOfInteger) - IDs of found sub-shapes
2889  */
2890 //=======================================================================
2891 Handle(TColStd_HSequenceOfInteger)
2892     GEOMImpl_IShapesOperations::GetShapesOnShapeIDs
2893                             (const Handle(GEOM_Object)& theCheckShape,
2894                              const Handle(GEOM_Object)& theShape,
2895                              const Standard_Integer theShapeType,
2896                              GEOMAlgo_State theState)
2897 {
2898   Handle(TColStd_HSequenceOfInteger) aSeqOfIDs =
2899     getShapesOnShapeIDs (theCheckShape, theShape, theShapeType, theState);
2900
2901   if ( aSeqOfIDs.IsNull()  || aSeqOfIDs->Length() == 0 )
2902     return NULL;
2903
2904   // The GetShapesOnShape() doesn't change object so no new function is required.
2905   Handle(GEOM_Function) aFunction =
2906     GEOM::GetCreatedLast(theShape,theCheckShape)->GetLastFunction();
2907
2908   // Make a Python command
2909   GEOM::TPythonDump(aFunction, /*append=*/true)
2910     << "listShapesOnBoxIDs = geompy.GetShapesOnShapeIDs("
2911     << theCheckShape << ", "
2912     << theShape << ", "
2913     << TopAbs_ShapeEnum(theShapeType) << ", "
2914     << theState << ")";
2915
2916   SetErrorCode(OK);
2917   return aSeqOfIDs;
2918 }
2919
2920 //=======================================================================
2921 //function : GetShapesOnShape
2922 /*!
2923  * \brief Find sub-shapes complying with given status about surface
2924  * \param theCheckShape - the shape to check state of sub-shapes against
2925  * \param theShape - the shape to explore
2926  * \param theShapeType - type of sub-shape of theShape
2927  * \param theState - required state
2928  * \retval Handle(TColStd_HSequenceOfTransient) - found sub-shapes
2929  */
2930 //=======================================================================
2931 Handle(TColStd_HSequenceOfTransient)
2932   GEOMImpl_IShapesOperations::GetShapesOnShape
2933                              (const Handle(GEOM_Object)& theCheckShape,
2934                               const Handle(GEOM_Object)&  theShape,
2935                               const Standard_Integer theShapeType,
2936                               GEOMAlgo_State theState)
2937 {
2938   Handle(TColStd_HSequenceOfInteger) aSeqOfIDs =
2939     getShapesOnShapeIDs (theCheckShape, theShape, theShapeType, theState);
2940   if ( aSeqOfIDs.IsNull()  || aSeqOfIDs->Length() == 0 )
2941     return NULL;
2942
2943   // Find objects by indices
2944   TCollection_AsciiString anAsciiList;
2945   Handle(TColStd_HSequenceOfTransient) aSeq;
2946   aSeq = getObjectsShapesOn( theShape, aSeqOfIDs, anAsciiList );
2947
2948   if ( aSeq.IsNull() || aSeq->IsEmpty() )
2949     return NULL;
2950
2951   // Make a Python command
2952
2953   Handle(GEOM_Object) anObj = Handle(GEOM_Object)::DownCast( aSeq->Value( 1 ));
2954   Handle(GEOM_Function) aFunction = anObj->GetLastFunction();
2955
2956   GEOM::TPythonDump(aFunction)
2957     << "[" << anAsciiList.ToCString() << "] = geompy.GetShapesOnShape("
2958     << theCheckShape << ", "
2959     << theShape << ", "
2960     << TopAbs_ShapeEnum(theShapeType) << ", "
2961     << theState << ")";
2962
2963   SetErrorCode(OK);
2964   return aSeq;
2965 }
2966
2967 //=======================================================================
2968 //function : GetShapesOnShapeAsCompound
2969 //=======================================================================
2970 Handle(GEOM_Object) GEOMImpl_IShapesOperations::GetShapesOnShapeAsCompound
2971                              (const Handle(GEOM_Object)& theCheckShape,
2972                               const Handle(GEOM_Object)&  theShape,
2973                               const Standard_Integer theShapeType,
2974                               GEOMAlgo_State theState)
2975 {
2976   Handle(TColStd_HSequenceOfInteger) aSeqOfIDs =
2977     getShapesOnShapeIDs (theCheckShape, theShape, theShapeType, theState);
2978
2979   if ( aSeqOfIDs.IsNull()  || aSeqOfIDs->Length() == 0 )
2980     return NULL;
2981
2982   // Find objects by indices
2983   TCollection_AsciiString anAsciiList;
2984   Handle(TColStd_HSequenceOfTransient) aSeq;
2985   aSeq = getObjectsShapesOn( theShape, aSeqOfIDs, anAsciiList );
2986
2987   if ( aSeq.IsNull() || aSeq->IsEmpty() )
2988     return NULL;
2989
2990   TopoDS_Compound aCompound;
2991   BRep_Builder B;
2992   B.MakeCompound(aCompound);
2993   int i = 1;
2994   for(; i<=aSeq->Length(); i++) {
2995     Handle(GEOM_Object) anObj = Handle(GEOM_Object)::DownCast(aSeq->Value(i));
2996     TopoDS_Shape aShape_i = anObj->GetValue();
2997     B.Add(aCompound,aShape_i);
2998   }
2999
3000   //Add a new result object
3001   Handle(GEOM_Object) aRes = GetEngine()->AddObject(GetDocID(), GEOM_SHAPES_ON_SHAPE);
3002   Handle(GEOM_Function) aFunction =
3003     aRes->AddFunction(GEOMImpl_ShapeDriver::GetID(), SHAPES_ON_SHAPE);
3004   aFunction->SetValue(aCompound);
3005
3006   aSeq->Clear();
3007   aSeq->Append( theCheckShape->GetLastFunction() );
3008   aSeq->Append( theShape->GetLastFunction() );
3009
3010   GEOMImpl_IShapes aCI( aFunction );
3011   aCI.SetShapes( aSeq );
3012   aCI.SetSubShapeType( theShapeType );
3013   aCI.SetTolerance( theState );
3014
3015   GEOM::TPythonDump(aFunction)
3016     << aRes << " = geompy.GetShapesOnShapeAsCompound("
3017     << theCheckShape << ", "
3018     << theShape << ", "
3019     << TopAbs_ShapeEnum(theShapeType) << ", "
3020     << theState << ")";
3021
3022   SetErrorCode(OK);
3023
3024   return aRes;
3025 }
3026
3027 //=============================================================================
3028 /*!
3029  *  GetSubShapeEdgeSorted
3030  */
3031 //=============================================================================
3032 Handle(TColStd_HSequenceOfTransient)
3033     GEOMImpl_IShapesOperations::GetSubShapeEdgeSorted
3034                           (const Handle(GEOM_Object) &theShape,
3035                            const Handle(GEOM_Object) &theStartPoint)
3036 {
3037   // Get the sorted edges indices.
3038   Handle(TColStd_HSequenceOfInteger) aSortedIDs =
3039     getSubShapeEdgeSortedIDs(theShape, theStartPoint);
3040
3041   // Get object by indices.
3042   TCollection_AsciiString              anAsciiList;
3043   Handle(TColStd_HSequenceOfTransient) aSeq =
3044     getObjectsShapesOn(theShape, aSortedIDs, anAsciiList);
3045
3046   if (aSeq.IsNull() || aSeq->IsEmpty()) {
3047     SetErrorCode("Empty sequence of edges");
3048     return NULL;
3049   }
3050
3051   // Make a Python command
3052   Handle(GEOM_Object)   anObj     =
3053     Handle(GEOM_Object)::DownCast(aSeq->Value(1));
3054   Handle(GEOM_Function) aFunction = anObj->GetLastFunction();
3055
3056   GEOM::TPythonDump(aFunction)
3057     << "[" << anAsciiList.ToCString() << "] = geompy.GetSubShapeEdgeSorted("
3058     << theShape << ", " << theStartPoint << ")";
3059
3060   SetErrorCode(OK);
3061
3062   return aSeq;
3063 }
3064
3065 //=======================================================================
3066 //function : getShapesOnSurfaceIDs
3067   /*!
3068    * \brief Find IDs of sub-shapes complying with given status about surface
3069     * \param theSurface - the surface to check state of sub-shapes against
3070     * \param theShape - the shape to explore
3071     * \param theShapeType - type of sub-shape of theShape
3072     * \param theState - required state
3073     * \retval Handle(TColStd_HSequenceOfInteger) - IDs of found sub-shapes
3074    */
3075 //=======================================================================
3076 Handle(TColStd_HSequenceOfInteger)
3077   GEOMImpl_IShapesOperations::getShapesOnSurfaceIDs(const Handle(Geom_Surface)& theSurface,
3078                                                     const TopoDS_Shape&         theShape,
3079                                                     TopAbs_ShapeEnum            theShapeType,
3080                                                     GEOMAlgo_State              theState)
3081 {
3082   Handle(TColStd_HSequenceOfInteger) aSeqOfIDs;
3083
3084   // Check presence of triangulation, build if need
3085   if (!GEOMUtils::CheckTriangulation(theShape)) {
3086     SetErrorCode("Cannot build triangulation on the shape");
3087     return aSeqOfIDs;
3088   }
3089
3090   // BEGIN: Mantis issue 0020961: Error on a pipe T-Shape
3091   // Compute tolerance
3092   Standard_Real T, VertMax = -RealLast();
3093   try {
3094     OCC_CATCH_SIGNALS;
3095     for (TopExp_Explorer ExV (theShape, TopAbs_VERTEX); ExV.More(); ExV.Next()) {
3096       TopoDS_Vertex Vertex = TopoDS::Vertex(ExV.Current());
3097       T = BRep_Tool::Tolerance(Vertex);
3098       if (T > VertMax)
3099         VertMax = T;
3100     }
3101   }
3102   catch (Standard_Failure) {
3103     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
3104     SetErrorCode(aFail->GetMessageString());
3105     return aSeqOfIDs;
3106   }
3107   // END: Mantis issue 0020961
3108
3109   // Call algo
3110   GEOMAlgo_FinderShapeOn2   aFinder;
3111   Handle(GEOMAlgo_ClsfSurf) aClsfSurf = new GEOMAlgo_ClsfSurf;
3112   Standard_Real             aTol      = VertMax; // Mantis issue 0020961
3113
3114   aClsfSurf->SetSurface(theSurface);
3115   aFinder.SetShape(theShape);
3116   aFinder.SetTolerance(aTol);
3117   aFinder.SetClsf(aClsfSurf);
3118   aFinder.SetShapeType(theShapeType);
3119   aFinder.SetState(theState);
3120
3121   // Sets the minimal number of inner points for the faces that do not have own
3122   // inner points at all (for e.g. rectangular planar faces have just 2 triangles).
3123   // Default value=3
3124   aFinder.SetNbPntsMin(3);
3125   // Sets the maximal number of inner points for edges or faces.
3126   // It is usefull for the cases when this number is very big (e.g =2000) to improve
3127   // the performance. If this value =0, all inner points will be taken into account.
3128   // Default value=0
3129   aFinder.SetNbPntsMax(100);
3130
3131   aFinder.Perform();
3132
3133   // Interprete results
3134   Standard_Integer iErr = aFinder.ErrorStatus();
3135   // the detailed description of error codes is in GEOMAlgo_FinderShapeOn2.cxx
3136   if (iErr) {
3137     MESSAGE(" iErr : " << iErr);
3138     TCollection_AsciiString aMsg (" iErr : ");
3139     aMsg += TCollection_AsciiString(iErr);
3140     SetErrorCode(aMsg);
3141     return aSeqOfIDs;
3142   }
3143   Standard_Integer iWrn = aFinder.WarningStatus();
3144   // the detailed description of warning codes is in GEOMAlgo_FinderShapeOn2.cxx
3145   if (iWrn) {
3146     MESSAGE(" *** iWrn : " << iWrn);
3147   }
3148
3149   const TopTools_ListOfShape& listSS = aFinder.Shapes(); // the result
3150
3151   if (listSS.Extent() < 1) {
3152     //SetErrorCode("Not a single sub-shape of the requested type found on the given surface");
3153     SetErrorCode(NOT_FOUND_ANY); // NPAL18017
3154     return aSeqOfIDs;
3155   }
3156
3157   // Fill sequence of object IDs
3158   aSeqOfIDs = new TColStd_HSequenceOfInteger;
3159
3160   TopTools_IndexedMapOfShape anIndices;
3161   TopExp::MapShapes(theShape, anIndices);
3162
3163   TopTools_ListIteratorOfListOfShape itSub (listSS);
3164   for (int index = 1; itSub.More(); itSub.Next(), ++index) {
3165     int id = anIndices.FindIndex(itSub.Value());
3166     aSeqOfIDs->Append(id);
3167   }
3168
3169   return aSeqOfIDs;
3170 }
3171
3172 //=======================================================================
3173 //function : getObjectsShapesOn
3174 /*!
3175  * \brief Find shape objects and their entries by their ids
3176  * \param theShapeIDs - incoming shape ids
3177  * \param theShapeEntries - outgoing entries like "entry1, entry2, ..."
3178  * \retval Handle(TColStd_HSequenceOfTransient) - found shape objects
3179  */
3180 //=======================================================================
3181 Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::
3182  getObjectsShapesOn(const Handle(GEOM_Object)&                theShape,
3183                     const Handle(TColStd_HSequenceOfInteger)& theShapeIDs,
3184                     TCollection_AsciiString &                 theShapeEntries)
3185 {
3186   Handle(TColStd_HSequenceOfTransient) aSeq;
3187
3188   if ( !theShapeIDs.IsNull() && theShapeIDs->Length() > 0 )
3189   {
3190     aSeq = new TColStd_HSequenceOfTransient;
3191     Handle(TColStd_HArray1OfInteger) anArray = new TColStd_HArray1OfInteger(1,1);
3192     TCollection_AsciiString anEntry;
3193     for ( int i = 1; i <= theShapeIDs->Length(); ++i )
3194     {
3195       anArray->SetValue(1, theShapeIDs->Value( i ));
3196       Handle(GEOM_Object) anObj = GetEngine()->AddSubShape(theShape, anArray);
3197       aSeq->Append( anObj );
3198
3199       TDF_Tool::Entry(anObj->GetEntry(), anEntry);
3200       if ( i != 1 ) theShapeEntries += ",";
3201       theShapeEntries += anEntry;
3202     }
3203   }
3204   return aSeq;
3205 }
3206
3207 //=============================================================================
3208 /*!
3209  *  getSubShapeEdgeSortedIDs
3210  */
3211 //=============================================================================
3212 Handle(TColStd_HSequenceOfInteger)
3213     GEOMImpl_IShapesOperations::getSubShapeEdgeSortedIDs
3214                                (const Handle(GEOM_Object) &theShape,
3215                                 const Handle(GEOM_Object) &theStartPoint)
3216 {
3217   Handle(TColStd_HSequenceOfInteger) aResult;
3218
3219   if (theShape.IsNull() || theStartPoint.IsNull()) {
3220     SetErrorCode("NULL GEOM object");
3221     return aResult;
3222   }
3223
3224   const TopoDS_Shape aShape      = theShape->GetValue();
3225   const TopoDS_Shape aStartPoint = theStartPoint->GetValue();
3226
3227   if (aShape.IsNull() || aStartPoint.IsNull()) {
3228     SetErrorCode("NULL Shape");
3229     return aResult;
3230   }
3231
3232   if (aStartPoint.ShapeType() != TopAbs_VERTEX) {
3233     SetErrorCode("Starting point is not a vertex");
3234     return aResult;
3235   }
3236
3237   TopExp_Explorer      anExp(aShape, TopAbs_EDGE);
3238   TopTools_MapOfShape  aMapFence;
3239   TopTools_ListOfShape anEdges;
3240
3241   for (; anExp.More(); anExp.Next()) {
3242     const TopoDS_Shape &anEdge = anExp.Current();
3243
3244     if (aMapFence.Add(anEdge)) {
3245       anEdges.Append(anEdge);
3246     }
3247   }
3248
3249   if (anEdges.IsEmpty()) {
3250     SetErrorCode("Shape doesn't contain edges");
3251     return aResult;
3252   }
3253
3254   // Step 1: Sort edges
3255   GEOMUtils::SortShapes(anEdges, Standard_False);
3256
3257   TopTools_ListIteratorOfListOfShape anIter(anEdges);
3258   TopoDS_Vertex                      aV[2];
3259   TopTools_DataMapOfShapeListOfShape aMapVE;
3260
3261   // Step 2: Fill the map vertex - list of edges.
3262   for (; anIter.More(); anIter.Next()) {
3263     TopoDS_Edge anEdge = TopoDS::Edge(anIter.Value());
3264
3265     TopExp::Vertices(anEdge, aV[0], aV[1]);
3266
3267     const Standard_Integer aNbV = aV[0].IsSame(aV[1]) ? 1 : 2;
3268     Standard_Integer       i;
3269
3270     for (i = 0; i < aNbV; ++i) {
3271       if (aV[i].IsNull() == Standard_False) {
3272         if (!aMapVE.IsBound(aV[i])) {
3273           // There is no this vertex in the map.
3274           aMapVE.Bind(aV[i], TopTools_ListOfShape());
3275         }
3276
3277         // Add the edge to the list bound with the vertex aV[i].
3278         TopTools_ListOfShape &aLEdges = aMapVE.ChangeFind(aV[i]);
3279
3280         aLEdges.Append(anEdge);
3281       }
3282     }
3283   }
3284
3285   // Step 3: Find starting point in aMapVE.
3286   TopoDS_Vertex aStartVtx = TopoDS::Vertex(aStartPoint);
3287
3288   if (!aMapVE.IsBound(aStartVtx)) {
3289     aStartVtx = getSameVertex(aShape, aStartVtx);
3290
3291     if (aStartVtx.IsNull()) {
3292       SetErrorCode("Invalid Starting point");
3293       return aResult;
3294     }
3295   }
3296
3297   TopTools_IndexedMapOfShape anIndices;
3298   TopTools_MapOfShape        aMapVFence;
3299   TopoDS_Shape               aCurVtx  = aStartVtx;
3300   TopoDS_Edge                aCurEdge =
3301     TopoDS::Edge(aMapVE.Find(aCurVtx).First());
3302
3303   aResult = new TColStd_HSequenceOfInteger;
3304   TopExp::MapShapes(aShape, anIndices);
3305
3306   // Step 4: Fill the list of sorted edges.
3307   while (aMapVFence.Add(aCurVtx)) {
3308     // Append the ID of the current edge to the list of sorted.
3309     aResult->Append(anIndices.FindIndex(aCurEdge));
3310     TopExp::Vertices(aCurEdge, aV[0], aV[1]);
3311
3312     // Get the next vertex.
3313     if (aCurVtx.IsSame(aV[0])) {
3314       if (aCurVtx.IsSame(aV[1])) {
3315         // There is no next vertex.
3316         break;
3317       } else {
3318         aCurVtx = aV[1];
3319       }
3320     } else {
3321       aCurVtx = aV[0];
3322     }
3323
3324     if (aCurVtx.IsNull()) {
3325       // There is no next vertex.
3326       break;
3327     }
3328
3329     // Get the next edge.
3330     const TopTools_ListOfShape         &aLEdges = aMapVE.Find(aCurVtx);
3331     TopTools_ListIteratorOfListOfShape  anEIter(aLEdges);
3332
3333     for (; anEIter.More(); anEIter.Next()) {
3334       const TopoDS_Shape &aLocalEdge = anEIter.Value();
3335
3336       if (aLocalEdge.IsNull() == Standard_False) {
3337         if (!aCurEdge.IsSame(aLocalEdge)) {
3338           aCurEdge = TopoDS::Edge(aLocalEdge);
3339           break;
3340         }
3341       }
3342     }
3343
3344     if (!anEIter.More()) {
3345       // There is no next edge.
3346       break;
3347     }
3348   }
3349
3350   return aResult;
3351 }
3352
3353 //=======================================================================
3354 //function : getShapesOnSurface
3355 /*!
3356    * \brief Find sub-shapes complying with given status about surface
3357     * \param theSurface - the surface to check state of sub-shapes against
3358     * \param theShape - the shape to explore
3359     * \param theShapeType - type of sub-shape of theShape
3360     * \param theState - required state
3361     * \param theShapeEntries - outgoing entries like "entry1, entry2, ..."
3362     * \retval Handle(TColStd_HSequenceOfInteger) - IDs of found sub-shapes
3363  */
3364 //=======================================================================
3365 Handle(TColStd_HSequenceOfTransient)
3366     GEOMImpl_IShapesOperations::getShapesOnSurface(const Handle(Geom_Surface)& theSurface,
3367                                                    const Handle(GEOM_Object)&  theShape,
3368                                                    TopAbs_ShapeEnum            theShapeType,
3369                                                    GEOMAlgo_State              theState,
3370                                                    TCollection_AsciiString &   theShapeEntries)
3371 {
3372   // Find sub-shapes ids
3373   Handle(TColStd_HSequenceOfInteger) aSeqOfIDs =
3374     getShapesOnSurfaceIDs (theSurface, theShape->GetValue(), theShapeType, theState);
3375   if ( aSeqOfIDs.IsNull()  || aSeqOfIDs->Length() == 0 )
3376     return NULL;
3377
3378   return getObjectsShapesOn( theShape, aSeqOfIDs, theShapeEntries );
3379 }
3380
3381 //=============================================================================
3382 /*!
3383  *  GetShapesOnPlane
3384  */
3385 //=============================================================================
3386 Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::GetShapesOnPlane
3387                                         (const Handle(GEOM_Object)& theShape,
3388                                          const Standard_Integer     theShapeType,
3389                                          const Handle(GEOM_Object)& theAx1,
3390                                          const GEOMAlgo_State       theState)
3391 {
3392   SetErrorCode(KO);
3393
3394   if (theShape.IsNull() || theAx1.IsNull()) return NULL;
3395
3396   TopoDS_Shape aShape = theShape->GetValue();
3397   TopoDS_Shape anAx1  = theAx1->GetValue();
3398
3399   if (aShape.IsNull() || anAx1.IsNull()) return NULL;
3400
3401   TopAbs_ShapeEnum aShapeType = TopAbs_ShapeEnum(theShapeType);
3402   if ( !checkTypeShapesOn( theShapeType ))
3403     return NULL;
3404
3405   // Create plane
3406   Handle(Geom_Surface) aPlane = makePlane( anAx1 );
3407   if ( aPlane.IsNull() )
3408     return NULL;
3409
3410   // Find objects
3411   TCollection_AsciiString anAsciiList;
3412   Handle(TColStd_HSequenceOfTransient) aSeq;
3413   aSeq = getShapesOnSurface( aPlane, theShape, aShapeType, theState, anAsciiList );
3414   if ( aSeq.IsNull() || aSeq->Length() == 0 )
3415     return NULL;
3416
3417   // Make a Python command
3418
3419   Handle(GEOM_Object) anObj = Handle(GEOM_Object)::DownCast( aSeq->Value( 1 ));
3420   Handle(GEOM_Function) aFunction = anObj->GetLastFunction();
3421
3422   GEOM::TPythonDump(aFunction) << "[" << anAsciiList.ToCString()
3423     << "] = geompy.GetShapesOnPlane(" << theShape << ", "
3424       << aShapeType << ", " << theAx1 << ", " << theState << ")";
3425
3426   SetErrorCode(OK);
3427   return aSeq;
3428 }
3429
3430 //=============================================================================
3431 /*!
3432  *  GetShapesOnPlaneWithLocation
3433  */
3434 //=============================================================================
3435 Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::GetShapesOnPlaneWithLocation
3436                                         (const Handle(GEOM_Object)& theShape,
3437                                          const Standard_Integer     theShapeType,
3438                                          const Handle(GEOM_Object)& theAx1,
3439                                          const Handle(GEOM_Object)& thePnt,
3440                                          const GEOMAlgo_State       theState)
3441 {
3442   SetErrorCode(KO);
3443
3444   if (theShape.IsNull() || theAx1.IsNull() || thePnt.IsNull()) return NULL;
3445
3446   TopoDS_Shape aShape = theShape->GetValue();
3447   TopoDS_Shape anAx1  = theAx1->GetValue();
3448   TopoDS_Shape anPnt = thePnt->GetValue();
3449
3450   if (aShape.IsNull() || anAx1.IsNull() || anPnt.IsNull()) return NULL;
3451
3452   TopAbs_ShapeEnum aShapeType = TopAbs_ShapeEnum(theShapeType);
3453   if ( !checkTypeShapesOn( theShapeType ))
3454     return NULL;
3455
3456   // Create plane
3457   if ( anAx1.ShapeType() != TopAbs_EDGE || anPnt.ShapeType() != TopAbs_VERTEX ) return NULL;
3458   TopoDS_Vertex V1, V2, V3;
3459   TopoDS_Edge anEdge = TopoDS::Edge(anAx1);
3460   TopExp::Vertices(anEdge, V1, V2, Standard_True);
3461
3462   if (V1.IsNull() || V2.IsNull()) {
3463     SetErrorCode("Bad edge given for the plane normal vector");
3464     return NULL;
3465   }
3466   V3 = TopoDS::Vertex(anPnt);
3467
3468   if(V3.IsNull()) {
3469     SetErrorCode("Bad vertex given for the plane location");
3470       return NULL;
3471   }
3472   gp_Pnt aLoc = BRep_Tool::Pnt(V3);
3473   gp_Vec aVec(BRep_Tool::Pnt(V1),BRep_Tool::Pnt(V2));
3474
3475   if (aVec.Magnitude() < Precision::Confusion()) {
3476     SetErrorCode("Vector with null magnitude given");
3477     return NULL;
3478   }
3479   Handle(Geom_Surface) aPlane = new Geom_Plane(aLoc, aVec);
3480
3481   if ( aPlane.IsNull() )
3482     return NULL;
3483
3484   // Find objects
3485   TCollection_AsciiString anAsciiList;
3486   Handle(TColStd_HSequenceOfTransient) aSeq;
3487   aSeq = getShapesOnSurface( aPlane, theShape, aShapeType, theState, anAsciiList );
3488   if ( aSeq.IsNull() || aSeq->Length() == 0 )
3489     return NULL;
3490
3491   // Make a Python command
3492
3493   Handle(GEOM_Object) anObj = Handle(GEOM_Object)::DownCast( aSeq->Value( 1 ));
3494   Handle(GEOM_Function) aFunction = anObj->GetLastFunction();
3495
3496   GEOM::TPythonDump(aFunction) << "[" << anAsciiList.ToCString()
3497     << "] = geompy.GetShapesOnPlaneWithLocation(" << theShape << ", "
3498     << aShapeType << ", " << theAx1 << ", "<< thePnt <<", " << theState << ")";
3499
3500   SetErrorCode(OK);
3501   return aSeq;
3502 }
3503
3504 //=============================================================================
3505 /*!
3506  *  GetShapesOnCylinder
3507  */
3508 //=============================================================================
3509 Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::GetShapesOnCylinder
3510                                           (const Handle(GEOM_Object)& theShape,
3511                                            const Standard_Integer     theShapeType,
3512                                            const Handle(GEOM_Object)& theAxis,
3513                                            const Standard_Real        theRadius,
3514                                            const GEOMAlgo_State       theState)
3515 {
3516   SetErrorCode(KO);
3517
3518   if (theShape.IsNull() || theAxis.IsNull()) return NULL;
3519
3520   TopoDS_Shape aShape = theShape->GetValue();
3521   TopoDS_Shape anAxis = theAxis->GetValue();
3522
3523   if (aShape.IsNull() || anAxis.IsNull()) return NULL;
3524
3525   TopAbs_ShapeEnum aShapeType = TopAbs_ShapeEnum(theShapeType);
3526   if ( !checkTypeShapesOn( aShapeType ))
3527     return NULL;
3528
3529   // Create a cylinder surface
3530   Handle(Geom_Surface) aCylinder = makeCylinder( anAxis, theRadius );
3531   if ( aCylinder.IsNull() )
3532     return NULL;
3533
3534   // Find objects
3535   TCollection_AsciiString anAsciiList;
3536   Handle(TColStd_HSequenceOfTransient) aSeq;
3537   aSeq = getShapesOnSurface( aCylinder, theShape, aShapeType, theState, anAsciiList );
3538   if ( aSeq.IsNull() || aSeq->Length() == 0 )
3539     return NULL;
3540
3541   // Make a Python command
3542
3543   Handle(GEOM_Object) anObj = Handle(GEOM_Object)::DownCast( aSeq->Value( 1 ));
3544   Handle(GEOM_Function) aFunction = anObj->GetLastFunction();
3545
3546   GEOM::TPythonDump(aFunction) << "[" << anAsciiList.ToCString()
3547     << "] = geompy.GetShapesOnCylinder(" << theShape << ", " << aShapeType
3548       << ", " << theAxis << ", " << theRadius << ", " << theState << ")";
3549
3550   SetErrorCode(OK);
3551   return aSeq;
3552 }
3553
3554 //=============================================================================
3555 /*!
3556  *  GetShapesOnCylinderWithLocation
3557  */
3558 //=============================================================================
3559 Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::GetShapesOnCylinderWithLocation
3560                                           (const Handle(GEOM_Object)& theShape,
3561                                            const Standard_Integer     theShapeType,
3562                                            const Handle(GEOM_Object)& theAxis,
3563                                            const Handle(GEOM_Object)& thePnt,
3564                                            const Standard_Real        theRadius,
3565                                            const GEOMAlgo_State       theState)
3566 {
3567   SetErrorCode(KO);
3568
3569   if (theShape.IsNull() || theAxis.IsNull() || thePnt.IsNull()) return NULL;
3570
3571   TopoDS_Shape aShape = theShape->GetValue();
3572   TopoDS_Shape anAxis = theAxis->GetValue();
3573   TopoDS_Shape aPnt   = thePnt->GetValue();
3574
3575   if (aShape.IsNull() || anAxis.IsNull() || aPnt.IsNull()) return NULL;
3576
3577   if (aPnt.ShapeType() != TopAbs_VERTEX )
3578   {
3579     SetErrorCode("Bottom location point must be vertex");
3580     return NULL;
3581   }
3582
3583   TopAbs_ShapeEnum aShapeType = TopAbs_ShapeEnum(theShapeType);
3584   if ( !checkTypeShapesOn( aShapeType ))
3585     return NULL;
3586
3587   // Create a cylinder surface
3588   Handle(Geom_Surface) aCylinder = makeCylinder( anAxis, theRadius );
3589   if ( aCylinder.IsNull() )
3590     return NULL;
3591
3592   // translate the surface
3593   Handle(Geom_CylindricalSurface) aCylSurface =
3594     Handle(Geom_CylindricalSurface)::DownCast( aCylinder );
3595   if ( aCylSurface.IsNull() )
3596   {
3597     SetErrorCode("Unexpected surface type instead of Geom_CylindricalSurface");
3598     return NULL;
3599   }
3600   gp_Pnt fromLoc = aCylSurface->Cylinder().Location();
3601   gp_Pnt toLoc   = BRep_Tool::Pnt( TopoDS::Vertex( aPnt ));
3602   aCylinder->Translate( fromLoc, toLoc );
3603
3604   // Find objects
3605   TCollection_AsciiString anAsciiList;
3606   Handle(TColStd_HSequenceOfTransient) aSeq;
3607   aSeq = getShapesOnSurface( aCylinder, theShape, aShapeType, theState, anAsciiList );
3608   if ( aSeq.IsNull() || aSeq->Length() == 0 )
3609     return NULL;
3610
3611   // Make a Python command
3612
3613   Handle(GEOM_Object) anObj = Handle(GEOM_Object)::DownCast( aSeq->Value( 1 ));
3614   Handle(GEOM_Function) aFunction = anObj->GetLastFunction();
3615
3616   GEOM::TPythonDump(aFunction)
3617     << "[" << anAsciiList.ToCString()
3618     << "] = geompy.GetShapesOnCylinderWithLocation(" << theShape << ", " << aShapeType << ", "
3619     << theAxis << ", " << thePnt << ", " << theRadius << ", " << theState << ")";
3620
3621   SetErrorCode(OK);
3622   return aSeq;
3623 }
3624
3625 //=============================================================================
3626 /*!
3627  *  GetShapesOnSphere
3628  */
3629 //=============================================================================
3630 Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::GetShapesOnSphere
3631                                           (const Handle(GEOM_Object)& theShape,
3632                                            const Standard_Integer     theShapeType,
3633                                            const Handle(GEOM_Object)& theCenter,
3634                                            const Standard_Real        theRadius,
3635                                            const GEOMAlgo_State       theState)
3636 {
3637   SetErrorCode(KO);
3638
3639   if (theShape.IsNull() || theCenter.IsNull()) return NULL;
3640
3641   TopoDS_Shape aShape  = theShape->GetValue();
3642   TopoDS_Shape aCenter = theCenter->GetValue();
3643
3644   if (aShape.IsNull() || aCenter.IsNull()) return NULL;
3645
3646   TopAbs_ShapeEnum aShapeType = TopAbs_ShapeEnum(theShapeType);
3647   if ( !checkTypeShapesOn( aShapeType ))
3648     return NULL;
3649
3650   // Center of the sphere
3651   if (aCenter.ShapeType() != TopAbs_VERTEX) return NULL;
3652   gp_Pnt aLoc = BRep_Tool::Pnt(TopoDS::Vertex(aCenter));
3653
3654   gp_Ax3 anAx3 (aLoc, gp::DZ());
3655   Handle(Geom_SphericalSurface) aSphere =
3656     new Geom_SphericalSurface(anAx3, theRadius);
3657
3658   // Find objects
3659   TCollection_AsciiString anAsciiList;
3660   Handle(TColStd_HSequenceOfTransient) aSeq;
3661   aSeq = getShapesOnSurface( aSphere, theShape, aShapeType, theState, anAsciiList );
3662   if ( aSeq.IsNull() || aSeq->Length() == 0 )
3663     return NULL;
3664
3665   // Make a Python command
3666
3667   Handle(GEOM_Object) anObj = Handle(GEOM_Object)::DownCast( aSeq->Value( 1 ));
3668   Handle(GEOM_Function) aFunction = anObj->GetLastFunction();
3669
3670   GEOM::TPythonDump(aFunction) << "[" << anAsciiList.ToCString()
3671     << "] = geompy.GetShapesOnSphere(" << theShape << ", " << aShapeType
3672       << ", " << theCenter << ", " << theRadius << ", " << theState << ")";
3673
3674   SetErrorCode(OK);
3675   return aSeq;
3676 }
3677
3678 //=============================================================================
3679 /*!
3680  *  GetShapesOnPlaneIDs
3681  */
3682 //=============================================================================
3683 Handle(TColStd_HSequenceOfInteger) GEOMImpl_IShapesOperations::GetShapesOnPlaneIDs
3684                                         (const Handle(GEOM_Object)& theShape,
3685                                          const Standard_Integer     theShapeType,
3686                                          const Handle(GEOM_Object)& theAx1,
3687                                          const GEOMAlgo_State       theState)
3688 {
3689   SetErrorCode(KO);
3690
3691   if (theShape.IsNull() || theAx1.IsNull()) return NULL;
3692
3693   TopoDS_Shape aShape = theShape->GetValue();
3694   TopoDS_Shape anAx1  = theAx1->GetValue();
3695
3696   if (aShape.IsNull() || anAx1.IsNull()) return NULL;
3697
3698   TopAbs_ShapeEnum aShapeType = TopAbs_ShapeEnum(theShapeType);
3699   if ( !checkTypeShapesOn( aShapeType ))
3700     return NULL;
3701
3702   // Create plane
3703   Handle(Geom_Surface) aPlane = makePlane( anAx1 );
3704   if ( aPlane.IsNull() )
3705     return NULL;
3706
3707   // Find object IDs
3708   Handle(TColStd_HSequenceOfInteger) aSeq;
3709   aSeq = getShapesOnSurfaceIDs( aPlane, aShape, aShapeType, theState );
3710
3711   // The GetShapesOnPlaneIDs() doesn't change object so no new function is required.
3712   Handle(GEOM_Function) aFunction = GEOM::GetCreatedLast(theShape,theAx1)->GetLastFunction();
3713
3714   // Make a Python command
3715   GEOM::TPythonDump(aFunction, /*append=*/true)
3716     << "listShapesOnPlane = geompy.GetShapesOnPlaneIDs"
3717     << "(" << theShape << "," << aShapeType << "," << theAx1 << "," << theState << ")";
3718
3719   SetErrorCode(OK);
3720   return aSeq;
3721 }
3722
3723 //=============================================================================
3724 /*!
3725  *  GetShapesOnPlaneWithLocationIDs
3726  */
3727 //=============================================================================
3728 Handle(TColStd_HSequenceOfInteger) GEOMImpl_IShapesOperations::GetShapesOnPlaneWithLocationIDs
3729                                         (const Handle(GEOM_Object)& theShape,
3730                                          const Standard_Integer     theShapeType,
3731                                          const Handle(GEOM_Object)& theAx1,
3732                                          const Handle(GEOM_Object)& thePnt,
3733                                          const GEOMAlgo_State       theState)
3734 {
3735   SetErrorCode(KO);
3736
3737   if (theShape.IsNull() || theAx1.IsNull() || thePnt.IsNull()) return NULL;
3738
3739   TopoDS_Shape aShape = theShape->GetValue();
3740   TopoDS_Shape anAx1  = theAx1->GetValue();
3741   TopoDS_Shape anPnt  = thePnt->GetValue();
3742
3743   if (aShape.IsNull() || anAx1.IsNull() || anPnt.IsNull()) return NULL;
3744
3745   TopAbs_ShapeEnum aShapeType = TopAbs_ShapeEnum(theShapeType);
3746   if ( !checkTypeShapesOn( aShapeType ))
3747     return NULL;
3748
3749   // Create plane
3750   if (anAx1.ShapeType() != TopAbs_EDGE || anPnt.ShapeType() != TopAbs_VERTEX) return NULL;
3751   TopoDS_Edge anEdge = TopoDS::Edge(anAx1);
3752   TopoDS_Vertex V1, V2, V3;
3753   TopExp::Vertices(anEdge, V1, V2, Standard_True);
3754   if (V1.IsNull() || V2.IsNull()) {
3755     SetErrorCode("Bad edge given for the plane normal vector");
3756     return NULL;
3757   }
3758   V3 = TopoDS::Vertex(anPnt);
3759   if(V3.IsNull()) {
3760     SetErrorCode("Bad vertex given for the plane location");
3761       return NULL;
3762   }
3763   gp_Pnt aLoc = BRep_Tool::Pnt(V3);
3764   gp_Vec aVec(BRep_Tool::Pnt(V1),BRep_Tool::Pnt(V2));
3765   if (aVec.Magnitude() < Precision::Confusion()) {
3766     SetErrorCode("Vector with null magnitude given");
3767     return NULL;
3768   }
3769
3770   Handle(Geom_Surface) aPlane = new Geom_Plane(aLoc, aVec);
3771   if ( aPlane.IsNull() )
3772     return NULL;
3773
3774   // Find object IDs
3775   Handle(TColStd_HSequenceOfInteger) aSeq;
3776   aSeq = getShapesOnSurfaceIDs( aPlane, aShape, aShapeType, theState );
3777
3778   // The GetShapesOnPlaneIDs() doesn't change object so no new function is required.
3779   Handle(GEOM_Function) aFunction = GEOM::GetCreatedLast(theShape,theAx1)->GetLastFunction();
3780
3781   // Make a Python command
3782   GEOM::TPythonDump(aFunction, /*append=*/true)
3783     << "listShapesOnPlane = geompy.GetShapesOnPlaneWithLocationIDs"
3784     << "(" << theShape << ", " << aShapeType << ", " << theAx1 << ", "<< thePnt << ", "  << theState << ")";
3785
3786   SetErrorCode(OK);
3787   return aSeq;
3788 }
3789
3790 //=============================================================================
3791 /*!
3792  *  GetShapesOnCylinderIDs
3793  */
3794 //=============================================================================
3795 Handle(TColStd_HSequenceOfInteger) GEOMImpl_IShapesOperations::GetShapesOnCylinderIDs
3796                                           (const Handle(GEOM_Object)& theShape,
3797                                            const Standard_Integer     theShapeType,
3798                                            const Handle(GEOM_Object)& theAxis,
3799                                            const Standard_Real        theRadius,
3800                                            const GEOMAlgo_State       theState)
3801 {
3802   SetErrorCode(KO);
3803
3804   if (theShape.IsNull() || theAxis.IsNull()) return NULL;
3805
3806   TopoDS_Shape aShape = theShape->GetValue();
3807   TopoDS_Shape anAxis = theAxis->GetValue();
3808
3809   if (aShape.IsNull() || anAxis.IsNull()) return NULL;
3810
3811   TopAbs_ShapeEnum aShapeType = TopAbs_ShapeEnum(theShapeType);
3812   if ( !checkTypeShapesOn( aShapeType ))
3813     return NULL;
3814
3815   // Create a cylinder surface
3816   Handle(Geom_Surface) aCylinder = makeCylinder( anAxis, theRadius );
3817   if ( aCylinder.IsNull() )
3818     return NULL;
3819
3820   // Find object IDs
3821   Handle(TColStd_HSequenceOfInteger) aSeq;
3822   aSeq = getShapesOnSurfaceIDs( aCylinder, aShape, aShapeType, theState );
3823
3824   // The GetShapesOnCylinder() doesn't change object so no new function is required.
3825   Handle(GEOM_Function) aFunction = GEOM::GetCreatedLast(theShape,theAxis)->GetLastFunction();
3826
3827   // Make a Python command
3828   GEOM::TPythonDump(aFunction, /*append=*/true)
3829     << "listShapesOnCylinder = geompy.GetShapesOnCylinderIDs"
3830     << "(" << theShape << ", " << aShapeType << ", " << theAxis << ", "
3831     << theRadius << ", " << theState << ")";
3832
3833   SetErrorCode(OK);
3834   return aSeq;
3835 }
3836
3837 //=============================================================================
3838 /*!
3839  *  GetShapesOnCylinderWithLocationIDs
3840  */
3841 //=============================================================================
3842 Handle(TColStd_HSequenceOfInteger) GEOMImpl_IShapesOperations::GetShapesOnCylinderWithLocationIDs
3843                                           (const Handle(GEOM_Object)& theShape,
3844                                            const Standard_Integer     theShapeType,
3845                                            const Handle(GEOM_Object)& theAxis,
3846                                            const Handle(GEOM_Object)& thePnt,
3847                                            const Standard_Real        theRadius,
3848                                            const GEOMAlgo_State       theState)
3849 {
3850   SetErrorCode(KO);
3851
3852   if (theShape.IsNull() || theAxis.IsNull() || thePnt.IsNull()) return NULL;
3853
3854   TopoDS_Shape aShape = theShape->GetValue();
3855   TopoDS_Shape anAxis = theAxis->GetValue();
3856   TopoDS_Shape aPnt   = thePnt->GetValue();
3857
3858   if (aShape.IsNull() || anAxis.IsNull() || aPnt.IsNull()) return NULL;
3859
3860   if (aPnt.ShapeType() != TopAbs_VERTEX )
3861   {
3862     SetErrorCode("Bottom location point must be vertex");
3863     return NULL;
3864   }
3865
3866   TopAbs_ShapeEnum aShapeType = TopAbs_ShapeEnum(theShapeType);
3867   if ( !checkTypeShapesOn( aShapeType ))
3868     return NULL;
3869
3870   // Create a cylinder surface
3871   Handle(Geom_Surface) aCylinder = makeCylinder( anAxis, theRadius );
3872   if ( aCylinder.IsNull() )
3873     return NULL;
3874
3875   // translate the surface
3876   Handle(Geom_CylindricalSurface) aCylSurface =
3877     Handle(Geom_CylindricalSurface)::DownCast( aCylinder );
3878   if ( aCylSurface.IsNull() )
3879   {
3880     SetErrorCode("Unexpected surface type instead of Geom_CylindricalSurface");
3881     return NULL;
3882   }
3883   gp_Pnt fromLoc = aCylSurface->Cylinder().Location();
3884   gp_Pnt toLoc   = BRep_Tool::Pnt( TopoDS::Vertex( aPnt ));
3885   aCylinder->Translate( fromLoc, toLoc );
3886
3887   // Find object IDs
3888   Handle(TColStd_HSequenceOfInteger) aSeq;
3889   aSeq = getShapesOnSurfaceIDs( aCylinder, aShape, aShapeType, theState );
3890
3891   // The GetShapesOnCylinder() doesn't change object so no new function is required.
3892   Handle(GEOM_Function) aFunction =
3893     GEOM::GetCreatedLast(theShape, GEOM::GetCreatedLast(thePnt,theAxis))->GetLastFunction();
3894
3895   // Make a Python command
3896   GEOM::TPythonDump(aFunction, /*append=*/true)
3897     << "listShapesOnCylinder = geompy.GetShapesOnCylinderWithLocationIDs"
3898     << "(" << theShape << ", " << aShapeType << ", " << theAxis << ", "
3899     << thePnt << ", " << theRadius << ", " << theState << ")";
3900
3901   SetErrorCode(OK);
3902   return aSeq;
3903 }
3904
3905 //=============================================================================
3906 /*!
3907  *  GetShapesOnSphereIDs
3908  */
3909 //=============================================================================
3910 Handle(TColStd_HSequenceOfInteger) GEOMImpl_IShapesOperations::GetShapesOnSphereIDs
3911                                           (const Handle(GEOM_Object)& theShape,
3912                                            const Standard_Integer     theShapeType,
3913                                            const Handle(GEOM_Object)& theCenter,
3914                                            const Standard_Real        theRadius,
3915                                            const GEOMAlgo_State       theState)
3916 {
3917   SetErrorCode(KO);
3918
3919   if (theShape.IsNull() || theCenter.IsNull()) return NULL;
3920
3921   TopoDS_Shape aShape  = theShape->GetValue();
3922   TopoDS_Shape aCenter = theCenter->GetValue();
3923
3924   if (aShape.IsNull() || aCenter.IsNull()) return NULL;
3925
3926   TopAbs_ShapeEnum aShapeType = TopAbs_ShapeEnum(theShapeType);
3927   if ( !checkTypeShapesOn( aShapeType ))
3928     return NULL;
3929
3930   // Center of the sphere
3931   if (aCenter.ShapeType() != TopAbs_VERTEX) return NULL;
3932   gp_Pnt aLoc = BRep_Tool::Pnt(TopoDS::Vertex(aCenter));
3933
3934   gp_Ax3 anAx3 (aLoc, gp::DZ());
3935   Handle(Geom_SphericalSurface) aSphere =
3936     new Geom_SphericalSurface(anAx3, theRadius);
3937
3938   // Find object IDs
3939   Handle(TColStd_HSequenceOfInteger) aSeq;
3940   aSeq = getShapesOnSurfaceIDs( aSphere, aShape, aShapeType, theState );
3941
3942   // The GetShapesOnSphere() doesn't change object so no new function is required.
3943   Handle(GEOM_Function) aFunction = GEOM::GetCreatedLast(theShape,theCenter)->GetLastFunction();
3944
3945   // Make a Python command
3946   GEOM::TPythonDump(aFunction, /*append=*/true)
3947     << "listShapesOnCylinder = geompy.GetShapesOnSphereIDs"
3948     << "(" << theShape << ", " << aShapeType << ", " << theCenter << ", "
3949     << theRadius << ", " << theState << ")";
3950
3951   SetErrorCode(OK);
3952   return aSeq;
3953 }
3954
3955 //=======================================================================
3956 //function : getShapesOnQuadrangleIDs
3957   /*!
3958    * \brief Find IDs of sub-shapes complying with given status about quadrangle
3959     * \param theShape - the shape to explore
3960     * \param theShapeType - type of sub-shape of theShape
3961     * \param theTopLeftPoint - top left quadrangle corner
3962     * \param theTopRigthPoint - top right quadrangle corner
3963     * \param theBottomLeftPoint - bottom left quadrangle corner
3964     * \param theBottomRigthPoint - bottom right quadrangle corner
3965     * \param theState - required state
3966     * \retval Handle(TColStd_HSequenceOfInteger) - IDs of found sub-shapes
3967    */
3968 //=======================================================================
3969 Handle(TColStd_HSequenceOfInteger)
3970   GEOMImpl_IShapesOperations::getShapesOnQuadrangleIDs (const Handle(GEOM_Object)& theShape,
3971                                                         const Standard_Integer     theShapeType,
3972                                                         const Handle(GEOM_Object)& theTopLeftPoint,
3973                                                         const Handle(GEOM_Object)& theTopRigthPoint,
3974                                                         const Handle(GEOM_Object)& theBottomLeftPoint,
3975                                                         const Handle(GEOM_Object)& theBottomRigthPoint,
3976                                                         const GEOMAlgo_State       theState)
3977 {
3978   SetErrorCode(KO);
3979
3980   if ( theShape.IsNull() ||
3981        theTopLeftPoint.IsNull() ||
3982        theTopRigthPoint.IsNull() ||
3983        theBottomLeftPoint.IsNull() ||
3984        theBottomRigthPoint.IsNull() )
3985     return NULL;
3986
3987   TopoDS_Shape aShape = theShape->GetValue();
3988   TopoDS_Shape aTL = theTopLeftPoint->GetValue();
3989   TopoDS_Shape aTR = theTopRigthPoint->GetValue();
3990   TopoDS_Shape aBL = theBottomLeftPoint->GetValue();
3991   TopoDS_Shape aBR = theBottomRigthPoint->GetValue();
3992
3993   if (aShape.IsNull() ||
3994       aTL.IsNull() ||
3995       aTR.IsNull() ||
3996       aBL.IsNull() ||
3997       aBR.IsNull() ||
3998       aTL.ShapeType() != TopAbs_VERTEX ||
3999       aTR.ShapeType() != TopAbs_VERTEX ||
4000       aBL.ShapeType() != TopAbs_VERTEX ||
4001       aBR.ShapeType() != TopAbs_VERTEX )
4002     return NULL;
4003
4004   TopAbs_ShapeEnum aShapeType = TopAbs_ShapeEnum(theShapeType);
4005   if ( !checkTypeShapesOn( aShapeType ))
4006     return NULL;
4007
4008   Handle(TColStd_HSequenceOfInteger) aSeqOfIDs;
4009
4010   // Check presence of triangulation, build if need
4011   if (!GEOMUtils::CheckTriangulation(aShape)) {
4012     SetErrorCode("Cannot build triangulation on the shape");
4013     return aSeqOfIDs;
4014   }
4015
4016   // Call algo
4017   gp_Pnt aPntTL = BRep_Tool::Pnt(TopoDS::Vertex(aTL));
4018   gp_Pnt aPntTR = BRep_Tool::Pnt(TopoDS::Vertex(aTR));
4019   gp_Pnt aPntBL = BRep_Tool::Pnt(TopoDS::Vertex(aBL));
4020   gp_Pnt aPntBR = BRep_Tool::Pnt(TopoDS::Vertex(aBR));
4021
4022   GEOMAlgo_FinderShapeOn2  aFinder;
4023   Handle(GEOMAlgo_ClsfQuad) aClsfQuad = new GEOMAlgo_ClsfQuad;
4024
4025   Standard_Real aTol = 0.0001; // default value
4026
4027   aClsfQuad->SetCorners(aPntTL, aPntTR, aPntBL, aPntBR);
4028   aFinder.SetShape(aShape);
4029   aFinder.SetTolerance(aTol);
4030   aFinder.SetClsf(aClsfQuad);
4031   aFinder.SetShapeType(aShapeType);
4032   aFinder.SetState(theState);
4033
4034   // Sets the minimal number of inner points for the faces that do not have own
4035   // inner points at all (for e.g. rectangular planar faces have just 2 triangles).
4036   // Default value=3
4037   aFinder.SetNbPntsMin(3);
4038   // Sets the maximal number of inner points for edges or faces.
4039   // It is usefull for the cases when this number is very big (e.g =2000) to improve
4040   // the performance. If this value =0, all inner points will be taken into account.
4041   // Default value=0
4042   aFinder.SetNbPntsMax(100);
4043
4044   aFinder.Perform();
4045
4046   // Interprete results
4047   Standard_Integer iErr = aFinder.ErrorStatus();
4048   // the detailed description of error codes is in GEOMAlgo_FinderShapeOn2.cxx
4049   if (iErr) {
4050     MESSAGE(" iErr : " << iErr);
4051     TCollection_AsciiString aMsg (" iErr : ");
4052     aMsg += TCollection_AsciiString(iErr);
4053     SetErrorCode(aMsg);
4054     return aSeqOfIDs;
4055   }
4056   Standard_Integer iWrn = aFinder.WarningStatus();
4057   // the detailed description of warning codes is in GEOMAlgo_FinderShapeOn2.cxx
4058   if (iWrn) {
4059     MESSAGE(" *** iWrn : " << iWrn);
4060   }
4061
4062   const TopTools_ListOfShape& listSS = aFinder.Shapes(); // the result
4063
4064   if (listSS.Extent() < 1) {
4065     //SetErrorCode("Not a single sub-shape of the requested type found on the given surface");
4066     SetErrorCode(NOT_FOUND_ANY); // NPAL18017
4067     return aSeqOfIDs;
4068   }
4069
4070   // Fill sequence of object IDs
4071   aSeqOfIDs = new TColStd_HSequenceOfInteger;
4072
4073   TopTools_IndexedMapOfShape anIndices;
4074   TopExp::MapShapes(aShape, anIndices);
4075
4076   TopTools_ListIteratorOfListOfShape itSub (listSS);
4077   for (int index = 1; itSub.More(); itSub.Next(), ++index) {
4078     int id = anIndices.FindIndex(itSub.Value());
4079     aSeqOfIDs->Append(id);
4080   }
4081   return aSeqOfIDs;
4082 }
4083
4084 //=======================================================================
4085 //function : GetShapesOnQuadrangle
4086   /*!
4087    * \brief Find sub-shapes complying with given status about quadrangle
4088     * \param theShape - the shape to explore
4089     * \param theShapeType - type of sub-shape of theShape
4090     * \param theTopLeftPoint - top left quadrangle corner
4091     * \param theTopRigthPoint - top right quadrangle corner
4092     * \param theBottomLeftPoint - bottom left quadrangle corner
4093     * \param theBottomRigthPoint - bottom right quadrangle corner
4094     * \param theState - required state
4095     * \retval Handle(TColStd_HSequenceOfInteger) - IDs of found sub-shapes
4096    */
4097 //=======================================================================
4098 Handle(TColStd_HSequenceOfTransient)
4099     GEOMImpl_IShapesOperations::GetShapesOnQuadrangle (const Handle(GEOM_Object)& theShape,
4100                                                        const Standard_Integer     theShapeType,
4101                                                        const Handle(GEOM_Object)& theTopLeftPoint,
4102                                                        const Handle(GEOM_Object)& theTopRigthPoint,
4103                                                        const Handle(GEOM_Object)& theBottomLeftPoint,
4104                                                        const Handle(GEOM_Object)& theBottomRigthPoint,
4105                                                        const GEOMAlgo_State       theState)
4106 {
4107   // Find indices
4108   Handle(TColStd_HSequenceOfInteger) aSeqOfIDs =
4109     getShapesOnQuadrangleIDs( theShape,
4110                               theShapeType,
4111                               theTopLeftPoint,
4112                               theTopRigthPoint,
4113                               theBottomLeftPoint,
4114                               theBottomRigthPoint,
4115                               theState);
4116   if ( aSeqOfIDs.IsNull() || aSeqOfIDs->IsEmpty() )
4117     return NULL;
4118
4119   // Find objects by indices
4120   TCollection_AsciiString anAsciiList;
4121   Handle(TColStd_HSequenceOfTransient) aSeq;
4122   aSeq = getObjectsShapesOn( theShape, aSeqOfIDs, anAsciiList );
4123   if ( aSeq.IsNull() || aSeq->IsEmpty() )
4124     return NULL;
4125
4126   // Make a Python command
4127
4128   Handle(GEOM_Object) anObj = Handle(GEOM_Object)::DownCast( aSeq->Value( 1 ));
4129   Handle(GEOM_Function) aFunction = anObj->GetLastFunction();
4130
4131   GEOM::TPythonDump(aFunction)
4132     << "[" << anAsciiList.ToCString() << "] = geompy.GetShapesOnQuadrangle("
4133     << theShape << ", "
4134     << TopAbs_ShapeEnum(theShapeType) << ", "
4135     << theTopLeftPoint << ", "
4136     << theTopRigthPoint << ", "
4137     << theBottomLeftPoint << ", "
4138     << theBottomRigthPoint << ", "
4139     << theState << ")";
4140
4141   SetErrorCode(OK);
4142   return aSeq;
4143 }
4144
4145 //=======================================================================
4146 //function : GetShapesOnQuadrangleIDs
4147   /*!
4148    * \brief Find IDs of sub-shapes complying with given status about quadrangle
4149     * \param theShape - the shape to explore
4150     * \param theShapeType - type of sub-shape of theShape
4151     * \param theTopLeftPoint - top left quadrangle corner
4152     * \param theTopRigthPoint - top right quadrangle corner
4153     * \param theBottomLeftPoint - bottom left quadrangle corner
4154     * \param theBottomRigthPoint - bottom right quadrangle corner
4155     * \param theState - required state
4156     * \retval Handle(TColStd_HSequenceOfInteger) - IDs of found sub-shapes
4157    */
4158 //=======================================================================
4159 Handle(TColStd_HSequenceOfInteger)
4160   GEOMImpl_IShapesOperations::GetShapesOnQuadrangleIDs (const Handle(GEOM_Object)& theShape,
4161                                                         const Standard_Integer     theShapeType,
4162                                                         const Handle(GEOM_Object)& theTopLeftPoint,
4163                                                         const Handle(GEOM_Object)& theTopRigthPoint,
4164                                                         const Handle(GEOM_Object)& theBottomLeftPoint,
4165                                                         const Handle(GEOM_Object)& theBottomRigthPoint,
4166                                                         const GEOMAlgo_State       theState)
4167 {
4168   // Find indices
4169   Handle(TColStd_HSequenceOfInteger) aSeqOfIDs =
4170     getShapesOnQuadrangleIDs( theShape,
4171                               theShapeType,
4172                               theTopLeftPoint,
4173                               theTopRigthPoint,
4174                               theBottomLeftPoint,
4175                               theBottomRigthPoint,
4176                               theState);
4177   if ( aSeqOfIDs.IsNull() || aSeqOfIDs->IsEmpty() )
4178     return NULL;
4179
4180   // Make a Python command
4181
4182   // The GetShapesOnCylinder() doesn't change object so no new function is required.
4183   Handle(GEOM_Object) lastObj = GEOM::GetCreatedLast(theShape,theTopLeftPoint);
4184   lastObj = GEOM::GetCreatedLast(lastObj,theTopRigthPoint);
4185   lastObj = GEOM::GetCreatedLast(lastObj,theBottomRigthPoint);
4186   lastObj = GEOM::GetCreatedLast(lastObj,theBottomLeftPoint);
4187   Handle(GEOM_Function) aFunction = lastObj->GetLastFunction();
4188
4189   GEOM::TPythonDump(aFunction, /*append=*/true)
4190     << "listShapesOnQuadrangle = geompy.GetShapesOnQuadrangleIDs("
4191     << theShape << ", "
4192     << TopAbs_ShapeEnum(theShapeType) << ", "
4193     << theTopLeftPoint << ", "
4194     << theTopRigthPoint << ", "
4195     << theBottomLeftPoint << ", "
4196     << theBottomRigthPoint << ", "
4197     << theState << ")";
4198
4199   SetErrorCode(OK);
4200   return aSeqOfIDs;
4201 }
4202
4203 //=============================================================================
4204 /*!
4205  *  case GetInPlace:
4206  *  default:
4207  */
4208 //=============================================================================
4209 Handle(GEOM_Object) GEOMImpl_IShapesOperations::GetInPlace (Handle(GEOM_Object) theShapeWhere,
4210                                                             Handle(GEOM_Object) theShapeWhat)
4211 {
4212   SetErrorCode(KO);
4213
4214   if (theShapeWhere.IsNull() || theShapeWhat.IsNull()) return NULL;
4215
4216   TopoDS_Shape aWhere = theShapeWhere->GetValue();
4217   TopoDS_Shape aWhat  = theShapeWhat->GetValue();
4218
4219   if (aWhere.IsNull() || aWhat.IsNull()) {
4220     SetErrorCode("Error: aWhere and aWhat TopoDS_Shape are Null.");
4221     return NULL;
4222   }
4223
4224   // Searching for the sub-shapes inside the ShapeWhere shape
4225   GEOMAlgo_GetInPlace aGIP;
4226
4227   if (!GEOMAlgo_GetInPlaceAPI::GetInPlace(aWhere, aWhat, aGIP)) {
4228     SetErrorCode("Error in GEOMAlgo_GetInPlace");
4229     return NULL;
4230   }
4231
4232   // Add direct result.
4233   TopTools_ListOfShape        aLSA;
4234   const TopoDS_Shape         &aShapeResult = aGIP.Result();
4235   TopTools_MapOfShape         aMFence;
4236   TopTools_IndexedMapOfShape  aWhereIndices;
4237   Standard_Integer            aShapeType = -1;
4238
4239   TopExp::MapShapes(aWhere, aWhereIndices);
4240
4241   if (aShapeResult.IsNull() == Standard_False) {
4242     TopoDS_Iterator  anIt(aShapeResult);
4243     Standard_Boolean isFirst = Standard_True;
4244
4245     for (; anIt.More(); anIt.Next()) {
4246       const TopoDS_Shape &aPart = anIt.Value();
4247
4248       if(aWhereIndices.Contains(aPart) && aMFence.Add(aPart)) {
4249         const TopAbs_ShapeEnum aType = aPart.ShapeType();
4250
4251         if (aShapeType == -1) {
4252           // Initialization.
4253           aShapeType = aType;
4254         } else if (aShapeType != TopAbs_SHAPE && aShapeType != aType) {
4255           // Different types.
4256           aShapeType = TopAbs_SHAPE;
4257         }
4258
4259         aLSA.Append(aPart);
4260       }
4261     }
4262   }
4263
4264   if (aLSA.Extent() == 0) {
4265     SetErrorCode(NOT_FOUND_ANY); // Not found any Results
4266     return NULL;
4267   }
4268
4269   Handle(TColStd_HArray1OfInteger) aModifiedArray = new TColStd_HArray1OfInteger (1, aLSA.Extent());
4270   TopTools_ListIteratorOfListOfShape anIterModif (aLSA);
4271   for (Standard_Integer imod = 1; anIterModif.More(); anIterModif.Next(), imod++) {
4272     aModifiedArray->SetValue(imod, aWhereIndices.FindIndex(anIterModif.Value()));
4273   }
4274
4275   //Add a new object
4276   Handle(GEOM_Object) aResult = GetEngine()->AddSubShape(theShapeWhere, aModifiedArray);
4277   if (aResult.IsNull()) {
4278     SetErrorCode("Error in algorithm: result found, but cannot be returned.");
4279     return NULL;
4280   }
4281
4282   const Standard_Boolean isSameType = (aShapeType != TopAbs_SHAPE);
4283
4284   if ((aModifiedArray->Length() > 1 && isSameType) ||
4285       theShapeWhat->GetType() == GEOM_GROUP) {
4286     //Set a GROUP type
4287     aResult->SetType(GEOM_GROUP);
4288
4289     //Set a sub-shape type
4290     TopoDS_Shape aFirstFound = aLSA.First();
4291     TopAbs_ShapeEnum aShapeType = aFirstFound.ShapeType();
4292
4293     TDF_Label aFreeLabel = aResult->GetFreeLabel();
4294     TDataStd_Integer::Set(aFreeLabel, (Standard_Integer)aShapeType);
4295   }
4296
4297   //Make a Python command
4298   Handle(GEOM_Function) aFunction = aResult->GetFunction(1);
4299
4300   GEOM::TPythonDump(aFunction) << aResult << " = geompy.GetInPlace("
4301     << theShapeWhere << ", " << theShapeWhat << ", True)";
4302
4303   SetErrorCode(OK);
4304   return aResult;
4305 }
4306
4307 //=============================================================================
4308 /*!
4309  *  case GetInPlaceOld:
4310  *  default:
4311  */
4312 //=============================================================================
4313 Handle(GEOM_Object) GEOMImpl_IShapesOperations::GetInPlaceOld
4314                             (Handle(GEOM_Object) theShapeWhere,
4315                              Handle(GEOM_Object) theShapeWhat)
4316 {
4317   SetErrorCode(KO);
4318
4319   if (theShapeWhere.IsNull() || theShapeWhat.IsNull()) return NULL;
4320
4321   TopoDS_Shape           aWhere = theShapeWhere->GetValue();
4322   TopoDS_Shape           aWhat  = theShapeWhat->GetValue();
4323   TopTools_ListOfShape   aModifiedList;
4324   const Standard_Integer iErr   =
4325     GEOMAlgo_GetInPlaceAPI::GetInPlaceOld(aWhere, aWhat, aModifiedList);
4326
4327   if (iErr) {
4328     switch (iErr) {
4329       case 1:
4330         SetErrorCode("Error: aWhere and aWhat TopoDS_Shape are Null.");
4331         break;
4332       case 2:
4333         SetErrorCode
4334           ("Error: An attempt to extract a shape of not supported type.");
4335         break;
4336       case 3:
4337         SetErrorCode(NOT_FOUND_ANY);
4338         break;
4339       default:
4340         SetErrorCode("Shape driver failed");
4341         break;
4342     }
4343
4344     return NULL;
4345   }
4346
4347   TopTools_IndexedMapOfShape aWhereIndices;
4348   TopExp::MapShapes(aWhere, aWhereIndices);
4349
4350   Handle(TColStd_HArray1OfInteger)   aModifiedArray =
4351     new TColStd_HArray1OfInteger (1, aModifiedList.Extent());
4352   TopTools_ListIteratorOfListOfShape anIterModif (aModifiedList);
4353   Standard_Integer                   imod;
4354   Standard_Integer                   aShapeType = -1;
4355
4356   for (imod = 1; anIterModif.More(); anIterModif.Next(), imod++) {
4357     const Standard_Integer anIndex =
4358       aWhereIndices.FindIndex(anIterModif.Value());
4359     const TopAbs_ShapeEnum aType   = anIterModif.Value().ShapeType();
4360
4361     if (aShapeType == -1) {
4362       // Initialization.
4363       aShapeType = aType;
4364     } else if (aShapeType != TopAbs_SHAPE && aShapeType != aType) {
4365       // Different types.
4366       aShapeType = TopAbs_SHAPE;
4367     }
4368
4369     aModifiedArray->SetValue(imod, anIndex);
4370   }
4371
4372   //Add a new object
4373   Handle(GEOM_Object) aResult =
4374     GetEngine()->AddSubShape(theShapeWhere, aModifiedArray);
4375
4376   if (aResult.IsNull()) {
4377     SetErrorCode("Error in algorithm: result found, but cannot be returned.");
4378     return NULL;
4379   }
4380
4381   const Standard_Boolean isSameType = (aShapeType != TopAbs_SHAPE);
4382
4383   if ((aModifiedArray->Length() > 1 && isSameType) ||
4384       theShapeWhat->GetType() == GEOM_GROUP) {
4385     //Set a GROUP type
4386     aResult->SetType(GEOM_GROUP);
4387
4388     //Set a sub-shape type
4389     TopoDS_Shape aFirstFound = aWhereIndices.FindKey(aModifiedArray->Value(1));
4390     TopAbs_ShapeEnum aShapeType = aFirstFound.ShapeType();
4391
4392     TDF_Label aFreeLabel = aResult->GetFreeLabel();
4393     TDataStd_Integer::Set(aFreeLabel, (Standard_Integer)aShapeType);
4394   }
4395
4396   //Make a Python command
4397   Handle(GEOM_Function) aFunction = aResult->GetFunction(1);
4398
4399   GEOM::TPythonDump(aFunction) << aResult << " = geompy.GetInPlace("
4400     << theShapeWhere << ", " << theShapeWhat << ", False)";
4401
4402   SetErrorCode(OK);
4403
4404   return aResult;
4405 }
4406
4407 //=======================================================================
4408 //function : GetInPlaceByHistory
4409 //purpose  :
4410 //=======================================================================
4411 Handle(GEOM_Object) GEOMImpl_IShapesOperations::GetInPlaceByHistory
4412                                           (Handle(GEOM_Object) theShapeWhere,
4413                                            Handle(GEOM_Object) theShapeWhat)
4414 {
4415   SetErrorCode(KO);
4416
4417   if (theShapeWhere.IsNull() || theShapeWhat.IsNull()) return NULL;
4418
4419   TopoDS_Shape aWhere = theShapeWhere->GetValue();
4420   TopoDS_Shape aWhat  = theShapeWhat->GetValue();
4421
4422   if (aWhere.IsNull() || aWhat.IsNull()) return NULL;
4423
4424   Handle(GEOM_Function) aWhereFunction = theShapeWhere->GetLastFunction();
4425   if (aWhereFunction.IsNull()) return NULL;
4426
4427   //Fill array of indices
4428   TopTools_IndexedMapOfShape aWhereIndices;
4429
4430   TopExp::MapShapes(aWhere, aWhereIndices);
4431
4432   // process shape
4433   TopTools_ListOfShape aModifiedList;
4434   bool isFound = GEOMAlgo_GetInPlaceAPI::GetInPlaceByHistory
4435     (aWhereFunction, aWhereIndices, aWhat, aModifiedList);
4436
4437   if (!isFound || aModifiedList.Extent() < 1) {
4438     SetErrorCode("Error: No history found for the sought shape or its sub-shapes.");
4439     return NULL;
4440   }
4441
4442   Handle(TColStd_HArray1OfInteger)   aModifiedArray =
4443     new TColStd_HArray1OfInteger (1, aModifiedList.Extent());
4444   TopTools_ListIteratorOfListOfShape anIterModif (aModifiedList);
4445   Standard_Integer                   imod;
4446   Standard_Integer                   aShapeType = -1;
4447
4448   for (imod = 1; anIterModif.More(); anIterModif.Next(), imod++) {
4449     const Standard_Integer anIndex =
4450       aWhereIndices.FindIndex(anIterModif.Value());
4451     const TopAbs_ShapeEnum aType   = anIterModif.Value().ShapeType();
4452
4453     if (aShapeType == -1) {
4454       // Initialization.
4455       aShapeType = aType;
4456     } else if (aShapeType != TopAbs_SHAPE && aShapeType != aType) {
4457       // Different types.
4458       aShapeType = TopAbs_SHAPE;
4459     }
4460
4461     aModifiedArray->SetValue(imod, anIndex);
4462   }
4463
4464   //Add a new object
4465   Handle(GEOM_Object) aResult = GetEngine()->AddSubShape(theShapeWhere, aModifiedArray);
4466   if (aResult.IsNull()) {
4467     SetErrorCode("Error in algorithm: result found, but cannot be returned.");
4468     return NULL;
4469   }
4470
4471   const Standard_Boolean isSameType = (aShapeType != TopAbs_SHAPE);
4472
4473   if ((aModifiedArray->Length() > 1 && isSameType) ||
4474       theShapeWhat->GetType() == GEOM_GROUP) {
4475     //Set a GROUP type
4476     aResult->SetType(GEOM_GROUP);
4477
4478     //Set a sub-shape type
4479     TopoDS_Shape aFirstFound = aWhereIndices.FindKey(aModifiedArray->Value(1));
4480     TopAbs_ShapeEnum aShapeType = aFirstFound.ShapeType();
4481
4482     TDF_Label aFreeLabel = aResult->GetFreeLabel();
4483     TDataStd_Integer::Set(aFreeLabel, (Standard_Integer)aShapeType);
4484   }
4485
4486   //Make a Python command
4487   Handle(GEOM_Function) aFunction = aResult->GetFunction(1);
4488
4489   GEOM::TPythonDump(aFunction) << aResult << " = geompy.GetInPlaceByHistory("
4490                                << theShapeWhere << ", " << theShapeWhat << ")";
4491
4492   SetErrorCode(OK);
4493   return aResult;
4494 }
4495
4496 //=======================================================================
4497 //function : isSameEdge
4498 //purpose  : Returns True if two edges coincide
4499 //=======================================================================
4500 static bool isSameEdge(const TopoDS_Edge& theEdge1, const TopoDS_Edge& theEdge2)
4501 {
4502   TopoDS_Vertex V11, V12, V21, V22;
4503   TopExp::Vertices(theEdge1, V11, V12);
4504   TopExp::Vertices(theEdge2, V21, V22);
4505   gp_Pnt P11 = BRep_Tool::Pnt(V11);
4506   gp_Pnt P12 = BRep_Tool::Pnt(V12);
4507   gp_Pnt P21 = BRep_Tool::Pnt(V21);
4508   gp_Pnt P22 = BRep_Tool::Pnt(V22);
4509   bool coincide = false;
4510
4511   //Check that ends of edges coincide
4512   if(P11.Distance(P21) <= MAX_TOLERANCE) {
4513     if(P12.Distance(P22) <= MAX_TOLERANCE) coincide =  true;
4514   }
4515   else if(P11.Distance(P22) <= MAX_TOLERANCE) {
4516     if(P12.Distance(P21) <= MAX_TOLERANCE) coincide = true;
4517   }
4518
4519   if(!coincide) return false;
4520
4521   if (BRep_Tool::Degenerated(theEdge1))
4522     if (BRep_Tool::Degenerated(theEdge2)) return true;
4523     else return false;
4524   else
4525     if (BRep_Tool::Degenerated(theEdge2)) return false;
4526
4527   double U11, U12, U21, U22;
4528   Handle(Geom_Curve) C1 = BRep_Tool::Curve(theEdge1, U11, U12);
4529   Handle(Geom_Curve) C2 = BRep_Tool::Curve(theEdge2, U21, U22);
4530
4531   //Check that both edges has the same geometry
4532   double range = U12-U11;
4533   double U = U11+ range/3.0;
4534   gp_Pnt P1 = C1->Value(U);     //Compute a point on one third of the edge's length
4535   U = U11+range*2.0/3.0;
4536   gp_Pnt P2 = C1->Value(U);     //Compute a point on two thirds of the edge's length
4537
4538   if(!GeomLib_Tool::Parameter(C2, P1, MAX_TOLERANCE, U) ||  U < U21 || U > U22)
4539     return false;
4540
4541   if(P1.Distance(C2->Value(U)) > MAX_TOLERANCE) return false;
4542
4543   if(!GeomLib_Tool::Parameter(C2, P2, MAX_TOLERANCE, U) || U < U21 || U > U22)
4544     return false;
4545
4546   if(P2.Distance(C2->Value(U)) > MAX_TOLERANCE) return false;
4547
4548   return true;
4549 }
4550
4551 #include <TopoDS_TShape.hxx>
4552 //=======================================================================
4553 //function : isSameFace
4554 //purpose  : Returns True if two faces coincide
4555 //=======================================================================
4556 static bool isSameFace(const TopoDS_Face& theFace1, const TopoDS_Face& theFace2)
4557 {
4558   TopExp_Explorer E(theFace1, TopAbs_EDGE);
4559   TopTools_ListOfShape LS1, LS2;
4560   for(; E.More(); E.Next()) LS1.Append(E.Current());
4561
4562   E.Init(theFace2, TopAbs_EDGE);
4563   for(; E.More(); E.Next()) LS2.Append(E.Current());
4564
4565   //Compare the number of edges in the faces
4566   if(LS1.Extent() != LS2.Extent()) return false;
4567
4568   double aMin = RealFirst(), aMax = RealLast();
4569   double xminB1=aMax, yminB1=aMax, zminB1=aMax, xminB2=aMax, yminB2=aMax, zminB2=aMax;
4570   double xmaxB1=aMin, ymaxB1=aMin, zmaxB1=aMin, xmaxB2=aMin, ymaxB2=aMin, zmaxB2=aMin;
4571
4572   for(E.Init(theFace1, TopAbs_VERTEX); E.More(); E.Next()) {
4573     gp_Pnt P = BRep_Tool::Pnt(TopoDS::Vertex(E.Current()));
4574     if(P.X() < xminB1) xminB1 = P.X();
4575     if(P.Y() < yminB1) yminB1 = P.Y();
4576     if(P.Z() < zminB1) zminB1 = P.Z();
4577     if(P.X() > xmaxB1) xmaxB1 = P.X();
4578     if(P.Y() > ymaxB1) ymaxB1 = P.Y();
4579     if(P.Z() > zmaxB1) zmaxB1 = P.Z();
4580   }
4581
4582   for(E.Init(theFace2, TopAbs_VERTEX); E.More(); E.Next()) {
4583     gp_Pnt P = BRep_Tool::Pnt(TopoDS::Vertex(E.Current()));
4584     if(P.X() < xminB2) xminB2 = P.X();
4585     if(P.Y() < yminB2) yminB2 = P.Y();
4586     if(P.Z() < zminB2) zminB2 = P.Z();
4587     if(P.X() > xmaxB2) xmaxB2 = P.X();
4588     if(P.Y() > ymaxB2) ymaxB2 = P.Y();
4589     if(P.Z() > zmaxB2) zmaxB2 = P.Z();
4590   }
4591
4592   //Compare the bounding boxes of both faces
4593   if(gp_Pnt(xminB1, yminB1, zminB1).Distance(gp_Pnt(xminB2, yminB2, zminB2)) > MAX_TOLERANCE)
4594     return false;
4595
4596   if(gp_Pnt(xmaxB1, ymaxB1, zmaxB1).Distance(gp_Pnt(xmaxB2, ymaxB2, zmaxB2)) > MAX_TOLERANCE)
4597     return false;
4598
4599   Handle(Geom_Surface) S1 = BRep_Tool::Surface(theFace1);
4600   Handle(Geom_Surface) S2 = BRep_Tool::Surface(theFace2);
4601
4602   //Check if there a coincidence of two surfaces at least in two points
4603   double U11, U12, V11, V12, U21, U22, V21, V22;
4604   BRepTools::UVBounds(theFace1, U11, U12, V11, V12);
4605   BRepTools::UVBounds(theFace2, U21, U22, V21, V22);
4606
4607   double rangeU = U12-U11;
4608   double rangeV = V12-V11;
4609   double U = U11 + rangeU/3.0;
4610   double V = V11 + rangeV/3.0;
4611   gp_Pnt P1 = S1->Value(U, V);
4612   U = U11+rangeU*2.0/3.0;
4613   V = V11+rangeV*2.0/3.0;
4614   gp_Pnt P2 = S1->Value(U, V);
4615
4616   if (!GeomLib_Tool::Parameters(S2, P1, MAX_TOLERANCE, U, V) || U < U21 || U > U22 || V < V21 || V > V22)
4617     return false;
4618
4619   if (P1.Distance(S2->Value(U,V)) > MAX_TOLERANCE) return false;
4620
4621   if (!GeomLib_Tool::Parameters(S2, P2, MAX_TOLERANCE, U, V) || U < U21 || U > U22 || V < V21 || V > V22)
4622     return false;
4623
4624   if (P2.Distance(S2->Value(U, V)) > MAX_TOLERANCE) return false;
4625
4626   //Check that each edge of the Face1 has a counterpart in the Face2
4627   TopTools_MapOfOrientedShape aMap;
4628   TopTools_ListIteratorOfListOfShape LSI1(LS1);
4629   for(; LSI1.More(); LSI1.Next()) {
4630     TopoDS_Edge E = TopoDS::Edge(LSI1.Value());
4631     bool isFound = false;
4632     TopTools_ListIteratorOfListOfShape LSI2(LS2);
4633     for(; LSI2.More(); LSI2.Next()) {
4634       TopoDS_Shape aValue = LSI2.Value();
4635       if(aMap.Contains(aValue)) continue; //To avoid checking already found edge several times
4636       if(isSameEdge(E, TopoDS::Edge(aValue))) {
4637         aMap.Add(aValue);
4638         isFound = true;
4639         break;
4640       }
4641     }
4642     if(!isFound) return false;
4643   }
4644
4645   return true;
4646 }
4647
4648 //=======================================================================
4649 //function : isSameSolid
4650 //purpose  : Returns True if two solids coincide
4651 //=======================================================================
4652 bool isSameSolid(const TopoDS_Solid& theSolid1, const TopoDS_Solid& theSolid2)
4653 {
4654   TopExp_Explorer E(theSolid1, TopAbs_FACE);
4655   TopTools_ListOfShape LS1, LS2;
4656   for(; E.More(); E.Next()) LS1.Append(E.Current());
4657   E.Init(theSolid2, TopAbs_FACE);
4658   for(; E.More(); E.Next()) LS2.Append(E.Current());
4659
4660   if(LS1.Extent() != LS2.Extent()) return false;
4661
4662   double aMin = RealFirst(), aMax = RealLast();
4663   double xminB1=aMax, yminB1=aMax, zminB1=aMax, xminB2=aMax, yminB2=aMax, zminB2=aMax;
4664   double xmaxB1=aMin, ymaxB1=aMin, zmaxB1=aMin, xmaxB2=aMin, ymaxB2=aMin, zmaxB2=aMin;
4665
4666   for(E.Init(theSolid1, TopAbs_VERTEX); E.More(); E.Next()) {
4667     gp_Pnt P = BRep_Tool::Pnt(TopoDS::Vertex(E.Current()));
4668     if(P.X() < xminB1) xminB1 = P.X();
4669     if(P.Y() < yminB1) yminB1 = P.Y();
4670     if(P.Z() < zminB1) zminB1 = P.Z();
4671     if(P.X() > xmaxB1) xmaxB1 = P.X();
4672     if(P.Y() > ymaxB1) ymaxB1 = P.Y();
4673     if(P.Z() > zmaxB1) zmaxB1 = P.Z();
4674   }
4675
4676   for(E.Init(theSolid2, TopAbs_VERTEX); E.More(); E.Next()) {
4677     gp_Pnt P = BRep_Tool::Pnt(TopoDS::Vertex(E.Current()));
4678     if(P.X() < xminB2) xminB2 = P.X();
4679     if(P.Y() < yminB2) yminB2 = P.Y();
4680     if(P.Z() < zminB2) zminB2 = P.Z();
4681     if(P.X() > xmaxB2) xmaxB2 = P.X();
4682     if(P.Y() > ymaxB2) ymaxB2 = P.Y();
4683     if(P.Z() > zmaxB2) zmaxB2 = P.Z();
4684   }
4685
4686   //Compare the bounding boxes of both solids
4687   if(gp_Pnt(xminB1, yminB1, zminB1).Distance(gp_Pnt(xminB2, yminB2, zminB2)) > MAX_TOLERANCE)
4688     return false;
4689
4690   if(gp_Pnt(xmaxB1, ymaxB1, zmaxB1).Distance(gp_Pnt(xmaxB2, ymaxB2, zmaxB2)) > MAX_TOLERANCE)
4691     return false;
4692
4693   //Check that each face of the Solid1 has a counterpart in the Solid2
4694   TopTools_MapOfOrientedShape aMap;
4695   TopTools_ListIteratorOfListOfShape LSI1(LS1);
4696   for(; LSI1.More(); LSI1.Next()) {
4697     TopoDS_Face F = TopoDS::Face(LSI1.Value());
4698     bool isFound = false;
4699     TopTools_ListIteratorOfListOfShape LSI2(LS2);
4700     for(; LSI2.More(); LSI2.Next()) {
4701       if(aMap.Contains(LSI2.Value())) continue; //To avoid checking already found faces several times
4702       if(isSameFace(F, TopoDS::Face(LSI2.Value()))) {
4703         aMap.Add(LSI2.Value());
4704         isFound = true;
4705         break;
4706       }
4707     }
4708     if(!isFound) return false;
4709   }
4710
4711   return true;
4712 }
4713
4714 //=======================================================================
4715 //function : GetSame
4716 //purpose  :
4717 //=======================================================================
4718 Handle(GEOM_Object) GEOMImpl_IShapesOperations::GetSame(const Handle(GEOM_Object)& theShapeWhere,
4719                                                         const Handle(GEOM_Object)& theShapeWhat)
4720 {
4721   SetErrorCode(KO);
4722   if (theShapeWhere.IsNull() || theShapeWhat.IsNull()) return NULL;
4723
4724   TopoDS_Shape aWhere = theShapeWhere->GetValue();
4725   TopoDS_Shape aWhat  = theShapeWhat->GetValue();
4726
4727   if (aWhere.IsNull() || aWhat.IsNull()) return NULL;
4728
4729   int anIndex = -1;
4730   bool isFound = false;
4731   TopoDS_Shape aSubShape;
4732   TopTools_MapOfShape aMap;
4733
4734   if (aWhat.ShapeType() == TopAbs_COMPOUND || aWhat.ShapeType() == TopAbs_COMPSOLID) {
4735     TopoDS_Iterator It (aWhat, Standard_True, Standard_True);
4736     if (It.More()) aWhat = It.Value();
4737     It.Next();
4738     if (It.More()) {
4739       SetErrorCode("Compounds of two or more shapes are not allowed for aWhat argument");
4740       return NULL;
4741     }
4742   }
4743
4744   switch (aWhat.ShapeType()) {
4745     case TopAbs_VERTEX: {
4746       aSubShape = getSameVertex(aWhere, TopoDS::Vertex(aWhat));
4747       isFound   = !aSubShape.IsNull();
4748       break;
4749                         }
4750     case TopAbs_EDGE: {
4751       TopoDS_Edge anEdge = TopoDS::Edge(aWhat);
4752       TopExp_Explorer E(aWhere, TopAbs_EDGE);
4753       for(; E.More(); E.Next()) {
4754         if(!aMap.Add(E.Current())) continue;
4755         if(isSameEdge(anEdge, TopoDS::Edge(E.Current()))) {
4756           aSubShape = E.Current();
4757           isFound = true;
4758           break;
4759         }
4760       }
4761       break;
4762                       }
4763     case TopAbs_FACE: {
4764       TopoDS_Face aFace = TopoDS::Face(aWhat);
4765       TopExp_Explorer E(aWhere, TopAbs_FACE);
4766       for(; E.More(); E.Next()) {
4767         if(!aMap.Add(E.Current())) continue;
4768         if(isSameFace(aFace, TopoDS::Face(E.Current()))) {
4769           aSubShape = E.Current();
4770           isFound = true;
4771           break;
4772         }
4773       }
4774       break;
4775                       }
4776     case TopAbs_SOLID: {
4777       TopoDS_Solid aSolid = TopoDS::Solid(aWhat);
4778       TopExp_Explorer E(aWhere, TopAbs_SOLID);
4779       for(; E.More(); E.Next()) {
4780         if(!aMap.Add(E.Current())) continue;
4781         if(isSameSolid(aSolid, TopoDS::Solid(E.Current()))) {
4782           aSubShape = E.Current();
4783           isFound = true;
4784           break;
4785         }
4786       }
4787       break;
4788                        }
4789     default:
4790       return NULL;
4791   }
4792
4793   if (isFound) {
4794     TopTools_IndexedMapOfShape anIndices;
4795     TopExp::MapShapes(aWhere, anIndices);
4796     if (anIndices.Contains(aSubShape))
4797       anIndex = anIndices.FindIndex(aSubShape);
4798   }
4799
4800   if (anIndex < 0) return NULL;
4801
4802   Handle(TColStd_HArray1OfInteger) anArray = new TColStd_HArray1OfInteger(1,1);
4803
4804   anArray->SetValue(1, anIndex);
4805
4806   Handle(GEOM_Object) aResult = GetEngine()->AddSubShape(theShapeWhere, anArray);
4807   Handle(GEOM_Function) aFunction = aResult->GetLastFunction();
4808
4809   GEOM::TPythonDump(aFunction) << aResult << " = geompy.GetSame("
4810     << theShapeWhere << ", " << theShapeWhat << ")";
4811
4812   SetErrorCode(OK);
4813
4814   return aResult;
4815 }
4816
4817
4818 //=======================================================================
4819 //function : GetSameIDs
4820 //purpose  :
4821 //=======================================================================
4822 Handle(TColStd_HSequenceOfInteger) GEOMImpl_IShapesOperations::GetSameIDs
4823                                                        (const Handle(GEOM_Object)& theShapeWhere,
4824                                                         const Handle(GEOM_Object)& theShapeWhat)
4825 {
4826   SetErrorCode(KO);
4827   if (theShapeWhere.IsNull() || theShapeWhat.IsNull()) return NULL;
4828
4829   TopoDS_Shape aWhere = theShapeWhere->GetValue();
4830   TopoDS_Shape aWhat  = theShapeWhat->GetValue();
4831
4832   if (aWhere.IsNull() || aWhat.IsNull()) return NULL;
4833
4834   TopTools_ListOfShape listShape;
4835   TopTools_MapOfShape aMap;
4836
4837   if (aWhat.ShapeType() == TopAbs_COMPOUND || aWhat.ShapeType() == TopAbs_COMPSOLID) {
4838     TopoDS_Iterator It (aWhat, Standard_True, Standard_True);
4839     if (It.More()) aWhat = It.Value();
4840     It.Next();
4841     if (It.More()) {
4842       SetErrorCode("Compounds of two or more shapes are not allowed for aWhat argument");
4843       return NULL;
4844     }
4845   }
4846
4847   switch (aWhat.ShapeType()) {
4848     case TopAbs_VERTEX: {
4849       gp_Pnt P = BRep_Tool::Pnt(TopoDS::Vertex(aWhat));
4850       TopExp_Explorer E(aWhere, TopAbs_VERTEX);
4851       for(; E.More(); E.Next()) {
4852         if(!aMap.Add(E.Current())) continue;
4853         gp_Pnt P2 = BRep_Tool::Pnt(TopoDS::Vertex(E.Current()));
4854         if(P.Distance(P2) <= MAX_TOLERANCE) {
4855           listShape.Append(E.Current());
4856         }
4857       }
4858       break;
4859                         }
4860     case TopAbs_EDGE: {
4861       TopoDS_Edge anEdge = TopoDS::Edge(aWhat);
4862       TopExp_Explorer E(aWhere, TopAbs_EDGE);
4863       for(; E.More(); E.Next()) {
4864         if(!aMap.Add(E.Current())) continue;
4865         if(isSameEdge(anEdge, TopoDS::Edge(E.Current()))) {
4866           listShape.Append(E.Current());
4867         }
4868       }
4869       break;
4870                       }
4871     case TopAbs_FACE: {
4872       TopoDS_Face aFace = TopoDS::Face(aWhat);
4873       TopExp_Explorer E(aWhere, TopAbs_FACE);
4874       for(; E.More(); E.Next()) {
4875         if(!aMap.Add(E.Current())) continue;
4876         if(isSameFace(aFace, TopoDS::Face(E.Current()))) {
4877           listShape.Append(E.Current());
4878         }
4879       }
4880       break;
4881                       }
4882     case TopAbs_SOLID: {
4883       TopoDS_Solid aSolid = TopoDS::Solid(aWhat);
4884       TopExp_Explorer E(aWhere, TopAbs_SOLID);
4885       for(; E.More(); E.Next()) {
4886         if(!aMap.Add(E.Current())) continue;
4887         if(isSameSolid(aSolid, TopoDS::Solid(E.Current()))) {
4888           listShape.Append(E.Current());
4889         }
4890       }
4891       break;
4892                        }
4893     default:
4894       return NULL;
4895   }
4896
4897   if ( !listShape.IsEmpty() ) {
4898     TopTools_IndexedMapOfShape anIndices;
4899     TopExp::MapShapes(aWhere, anIndices);
4900     TopTools_ListIteratorOfListOfShape itSub (listShape);
4901     Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
4902     for (; itSub.More(); itSub.Next()) {
4903       if (anIndices.Contains(itSub.Value()))
4904         aSeq->Append(anIndices.FindIndex(itSub.Value()));
4905     }
4906     SetErrorCode(OK);
4907     // The GetSameIDs() doesn't change object so no new function is required.
4908     Handle(GEOM_Function) aFunction = GEOM::GetCreatedLast(theShapeWhere,theShapeWhat)->GetLastFunction();
4909
4910   // Make a Python command
4911   GEOM::TPythonDump(aFunction, /*append=*/true)
4912     << "listSameIDs = geompy.GetSameIDs("
4913     << theShapeWhere << ", "
4914     << theShapeWhat << ")";
4915     return aSeq;
4916   } else {
4917     SetErrorCode(NOT_FOUND_ANY);
4918     return NULL;
4919   }
4920 }
4921
4922 //=======================================================================
4923 //function : ExtendEdge
4924 //purpose  :
4925 //=======================================================================
4926 Handle(GEOM_Object) GEOMImpl_IShapesOperations::ExtendEdge
4927                                       (const Handle(GEOM_Object) &theEdge,
4928                                        const Standard_Real        theMin,
4929                                        const Standard_Real        theMax)
4930 {
4931   SetErrorCode(KO);
4932
4933   if (theEdge.IsNull()) {
4934     return NULL;
4935   }
4936
4937   //Add a new Edge object
4938   Handle(GEOM_Object) aResEdge = GetEngine()->AddObject(GetDocID(), GEOM_EDGE);
4939
4940   //Add a new Vector function
4941   Handle(GEOM_Function) aFunction =
4942     aResEdge->AddFunction(GEOMImpl_ShapeDriver::GetID(), EDGE_UV);
4943
4944   //Check if the function is set correctly
4945   if (aFunction->GetDriverGUID() != GEOMImpl_ShapeDriver::GetID()) {
4946     return NULL;
4947   }
4948
4949   GEOMImpl_IShapeExtend aCI (aFunction);
4950
4951   Handle(GEOM_Function) anEdge = theEdge->GetLastFunction();
4952
4953   if (anEdge.IsNull()) {
4954     return NULL;
4955   }
4956
4957   aCI.SetShape(anEdge);
4958   aCI.SetUMin(theMin);
4959   aCI.SetUMax(theMax);
4960
4961   //Compute the Edge value
4962   try {
4963     OCC_CATCH_SIGNALS;
4964     if (!GetSolver()->ComputeFunction(aFunction)) {
4965       SetErrorCode("Shape driver failed");
4966
4967       return NULL;
4968     }
4969   }
4970   catch (Standard_Failure) {
4971     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
4972     SetErrorCode(aFail->GetMessageString());
4973
4974     return NULL;
4975   }
4976
4977   //Make a Python command
4978   GEOM::TPythonDump(aFunction)
4979              << aResEdge  << " = geompy.ExtendEdge("
4980              << theEdge << ", " << theMin << ", " << theMax << ")";
4981
4982   SetErrorCode(OK);
4983
4984   return aResEdge;
4985 }
4986
4987 //=======================================================================
4988 //function : ExtendFace
4989 //purpose  :
4990 //=======================================================================
4991 Handle(GEOM_Object) GEOMImpl_IShapesOperations::ExtendFace
4992                                       (const Handle(GEOM_Object) &theFace,
4993                                        const Standard_Real        theUMin,
4994                                        const Standard_Real        theUMax,
4995                                        const Standard_Real        theVMin,
4996                                        const Standard_Real        theVMax)
4997 {
4998   SetErrorCode(KO);
4999
5000   if (theFace.IsNull()) {
5001     return NULL;
5002   }
5003
5004   //Add a new Face object
5005   Handle(GEOM_Object) aResFace = GetEngine()->AddObject(GetDocID(), GEOM_FACE);
5006
5007   //Add a new Vector function
5008   Handle(GEOM_Function) aFunction =
5009     aResFace->AddFunction(GEOMImpl_ShapeDriver::GetID(), FACE_UV);
5010
5011   //Check if the function is set correctly
5012   if (aFunction->GetDriverGUID() != GEOMImpl_ShapeDriver::GetID()) {
5013     return NULL;
5014   }
5015
5016   GEOMImpl_IShapeExtend aCI (aFunction);
5017
5018   Handle(GEOM_Function) aFace = theFace->GetLastFunction();
5019
5020   if (aFace.IsNull()) {
5021     return NULL;
5022   }
5023
5024   aCI.SetShape(aFace);
5025   aCI.SetUMin(theUMin);
5026   aCI.SetUMax(theUMax);
5027   aCI.SetVMin(theVMin);
5028   aCI.SetVMax(theVMax);
5029
5030   //Compute the Face value
5031   try {
5032     OCC_CATCH_SIGNALS;
5033     if (!GetSolver()->ComputeFunction(aFunction)) {
5034       SetErrorCode("Shape driver failed");
5035
5036       return NULL;
5037     }
5038   }
5039   catch (Standard_Failure) {
5040     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
5041     SetErrorCode(aFail->GetMessageString());
5042
5043     return NULL;
5044   }
5045
5046   //Make a Python command
5047   GEOM::TPythonDump(aFunction)
5048              << aResFace  << " = geompy.ExtendFace("
5049              << theFace << ", " << theUMin << ", " << theUMax << ", "
5050              << theVMin << ", " << theVMax << ")";
5051
5052   SetErrorCode(OK);
5053
5054   return aResFace;
5055 }
5056
5057 //=======================================================================
5058 //function : MakeSurfaceFromFace
5059 //purpose  :
5060 //=======================================================================
5061 Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeSurfaceFromFace
5062                                       (const Handle(GEOM_Object) &theFace)
5063 {
5064   SetErrorCode(KO);
5065
5066   if (theFace.IsNull()) {
5067     return NULL;
5068   }
5069
5070   //Add a new Face object
5071   Handle(GEOM_Object) aResFace = GetEngine()->AddObject(GetDocID(), GEOM_FACE);
5072
5073   //Add a new Vector function
5074   Handle(GEOM_Function) aFunction =
5075     aResFace->AddFunction(GEOMImpl_ShapeDriver::GetID(), SURFACE_FROM_FACE);
5076
5077   //Check if the function is set correctly
5078   if (aFunction->GetDriverGUID() != GEOMImpl_ShapeDriver::GetID()) {
5079     return NULL;
5080   }
5081
5082   GEOMImpl_IShapeExtend aCI (aFunction);
5083
5084   Handle(GEOM_Function) aFace = theFace->GetLastFunction();
5085
5086   if (aFace.IsNull()) {
5087     return NULL;
5088   }
5089
5090   aCI.SetShape(aFace);
5091
5092   //Compute the Face value
5093   try {
5094     OCC_CATCH_SIGNALS;
5095     if (!GetSolver()->ComputeFunction(aFunction)) {
5096       SetErrorCode("Shape driver failed");
5097
5098       return NULL;
5099     }
5100   }
5101   catch (Standard_Failure) {
5102     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
5103     SetErrorCode(aFail->GetMessageString());
5104
5105     return NULL;
5106   }
5107
5108   //Make a Python command
5109   GEOM::TPythonDump(aFunction)
5110              << aResFace  << " = geompy.MakeSurfaceFromFace("
5111              << theFace << ")";
5112
5113   SetErrorCode(OK);
5114
5115   return aResFace;
5116 }