]> SALOME platform Git repositories - modules/geom.git/blob - src/GEOM/GEOM_Gen_i.cc
Salome HOME
0020504: EDF 1078 GEOM: Point color is not good at study loading
[modules/geom.git] / src / GEOM / GEOM_Gen_i.cc
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //  GEOM GEOM : implementaion of GEOM_Gen.idl and GEOM_Shape.idl
23 //  File   : GEOM_GEN_i.cc file
24 //  Author : Lucien PIGNOLONI
25 //  Module : GEOM
26 //  $Header$
27 //
28 using namespace std;
29 #include "GEOM_Gen_i.hh"
30
31 #include "Partition_Spliter.hxx"
32 #include "Archimede_VolumeSection.hxx"
33 #include "Sketcher_Profile.hxx"
34
35 #include "Utils_CorbaException.hxx"
36 #include "utilities.h"
37
38 #include <stdio.h>
39
40 // Cascade headers
41
42 #include <Standard_Failure.hxx>
43
44 #include <gp_Circ.hxx>
45 #include <gp_Pln.hxx>
46 #include <gp_Elips.hxx>
47 #include <Geom_Plane.hxx>
48 #include <Geom_Line.hxx>
49 #include <Geom_BezierCurve.hxx>
50 #include <Geom_BSplineCurve.hxx>
51 #include <GeomFill_Line.hxx>
52 #include <GeomFill_AppSurf.hxx>
53 #include <GeomFill_SectionGenerator.hxx>
54 #include <Geom_BSplineSurface.hxx>
55 #include <Geom_TrimmedCurve.hxx>
56 #include <GC_MakeArcOfCircle.hxx>
57 #include <GeomAPI_PointsToBSpline.hxx>
58 #include <GC_Root.hxx>
59
60 #include <BRepCheck_Analyzer.hxx>
61 #if OCC_VERSION_MAJOR >= 5
62 #include <BRepAlgo.hxx>
63 #else
64 #include <BRepAlgoAPI.hxx>
65 #endif
66 #include <BRepAlgo_FaceRestrictor.hxx>
67 #include <BRepAdaptor_Surface.hxx>
68 #include <BRepBuilderAPI_Copy.hxx>
69 #include <BRepAlgoAPI_Common.hxx>
70 #include <BRepAlgoAPI_Cut.hxx>
71 #include <BRepAlgoAPI_Fuse.hxx>
72 #include <BRepAlgoAPI_Section.hxx>
73 #include <BRepOffsetAPI_Sewing.hxx>
74 #include <BRepOffsetAPI_MakePipe.hxx>
75
76 #include <BRepBuilderAPI_MakeVertex.hxx>
77 #include <BRepBuilderAPI_MakeEdge.hxx>
78 #include <BRepBuilderAPI_MakeFace.hxx>
79
80 #include <BRepLib.hxx>
81 #include <BRepBndLib.hxx>
82 #include <Bnd_Box.hxx>
83
84 #include <BRepBuilderAPI_MakeShell.hxx>
85 #include <BRepPrim_Builder.hxx>
86 #include <BRepBuilderAPI_MakeSolid.hxx>
87 #include <BRepClass3d_SolidClassifier.hxx>
88
89 #include <BRepBuilderAPI_MakeWire.hxx>
90 #include <BRepBuilderAPI_Transform.hxx>
91 #include <BRepPrimAPI_MakeRevol.hxx>
92 #include <BRepPrimAPI_MakePrism.hxx>
93 #include <BRepPrimAPI_MakeTorus.hxx>
94 #include <BRepPrimAPI_MakeBox.hxx>
95 #include <BRepPrimAPI_MakeSphere.hxx>
96 #include <BRepPrimAPI_MakeCylinder.hxx>
97 #include <BRepPrimAPI_MakeCone.hxx>
98 #include <BRepFilletAPI_MakeFillet.hxx>
99 #include <BRepFilletAPI_MakeChamfer.hxx>
100 #include <BRepTools.hxx>
101 #include <BRepTools_Quilt.hxx>
102 #include <BRep_Tool.hxx>
103
104 #include <GeomAPI_ProjectPointOnCurve.hxx>
105
106 #include <BRepGProp.hxx>
107 #include <GProp_GProps.hxx>
108 #include <Precision.hxx>
109
110 //VRV: OCC 4.0 migration
111 #include <STEPControl_Reader.hxx>
112 #include <IGESControl_Reader.hxx>
113 //VRV: OCC 4.0 migration
114
115 #include <IFSelect_ReturnStatus.hxx>
116 #include <TColStd_HSequenceOfTransient.hxx>
117
118 //VRV: OCC 4.0 migration
119 #include <IGESControl_Writer.hxx>
120 #include <IGESControl_Controller.hxx>
121 #include <STEPControl_Writer.hxx>
122 #include <Interface_Static.hxx>
123 //#include <STEPControlStd_StepModelType.hxx>
124 //VRV: OCC 4.0 migration
125
126 #include <TopoDS_Shape.hxx>
127 #include <TopAbs.hxx>
128 #include <TopoDS_Wire.hxx>
129 #include <TopoDS_Edge.hxx>
130 #include <TopoDS_Compound.hxx>
131 #include <TopoDS_Solid.hxx>
132
133 #include <TopExp.hxx>
134 #include <TopExp_Explorer.hxx>
135 #include <TCollection_ExtendedString.hxx>
136 #include <TColgp_Array1OfPnt.hxx>
137 #include <TopoDS_Iterator.hxx>
138 #include <TopTools_MapOfShape.hxx>
139 #include <TopTools_MapIteratorOfMapOfShape.hxx>
140 #include <TopTools_ListIteratorOfListOfShape.hxx>
141 #include <TopTools_Array1OfShape.hxx>
142
143 #include <IGESData_IGESEntity.hxx>
144
145 #include <TDF_Tool.hxx>
146 #include <TDF_Label.hxx>
147 #include <TDataStd_Name.hxx>
148 #include <TDataStd_Comment.hxx>
149 #include <TDF_Reference.hxx>
150 #include <TDF_Data.hxx>
151 #include <TNaming_Builder.hxx>
152 #include <TNaming_NamedShape.hxx>
153 #include <TNaming_Tool.hxx>
154 //  #include <TDocStd_Owner.hxx>
155
156 #include "SALOMEDS_Tool.hxx"
157 #include "GEOMDS_Commands.hxx"
158 #include "GEOMDS_Explorer.hxx"
159
160 #include CORBA_SERVER_HEADER(SALOMEDS_Attributes)
161
162 #include "Utils_ExceptHandlers.hxx"
163
164 Standard_EXPORT static Standard_Boolean IsValid(const TopoDS_Shape& S) {
165 #if OCC_VERSION_MAJOR >= 5
166   return BRepAlgo::IsValid(S);
167 #else
168   return BRepAlgoAPI::IsValid(S);
169 #endif
170 }
171
172 //============================================================================
173 // function : GEOM_Gen_i()
174 // purpose  : constructor to be called for servant creation. 
175 //============================================================================
176 GEOM_Gen_i::GEOM_Gen_i(CORBA::ORB_ptr orb,
177                        PortableServer::POA_ptr poa,
178                        PortableServer::ObjectId * contId, 
179                        const char *instanceName, 
180                        const char *interfaceName) :
181   Engines_Component_i(orb, poa, contId, instanceName, interfaceName)
182 {
183   _thisObj = this ;
184   _id = _poa->activate_object(_thisObj);
185   // SCRUTE(this)
186   name_service = new SALOME_NamingService(_orb);
187   myOCAFApp    = new GEOMDS_Application();
188   myStudyID    = -1;
189   GetCurrentStudy(0);//for correct work of SuperVisor
190 }
191
192
193
194 //============================================================================
195 // function : ~GEOM_Gen_i()
196 // purpose  : destructor
197 //============================================================================
198 GEOM_Gen_i::~GEOM_Gen_i() {
199   delete name_service;
200 }
201
202
203 //============================================================================
204 // function : IORToLocalPersistentID()
205 // purpose  :
206 //============================================================================
207 char* GEOM_Gen_i::IORToLocalPersistentID(SALOMEDS::SObject_ptr theSObject,
208                                          const char* IORString,
209                                          CORBA::Boolean isMultiFile,
210                                          CORBA::Boolean isASCII)
211 {
212   GEOM::GEOM_Shape_var aShape = GEOM::GEOM_Shape::_narrow(_orb->string_to_object(IORString));
213   if (!CORBA::is_nil(aShape)) {
214     return aShape->ShapeId();
215   }
216   return 0;
217 }
218
219
220 //============================================================================
221 // function : LocalPersistentIDToIOR()
222 // purpose  : Create/Load CORBA object from a persistent ref (an entry)
223 //          : Used when a study is loaded
224 //          : The IOR (IORName) of object created is returned
225 //============================================================================
226 char* GEOM_Gen_i::LocalPersistentIDToIOR(SALOMEDS::SObject_ptr theSObject,
227                                          const char* aLocalPersistentID,
228                                          CORBA::Boolean isMultiFile,
229                                          CORBA::Boolean isASCII) 
230
231   SALOMEDS::Study_var myStudy = theSObject->GetStudy();
232   GetCurrentStudy(myStudy->StudyId());
233   Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(myStudyIDToDoc(myStudy->StudyId()));
234   CORBA::String_var aPersRefString = aLocalPersistentID;
235
236   /* For a GEOM::GEOM_Shape the pers_ref is the Entry in the OCAF document */
237   TCollection_ExtendedString MainIOR;
238   TDF_Label Lab;
239   TDF_Tool::Label(aDoc->GetData(), aPersRefString, Lab );
240
241   if (Lab.IsNull()) {
242     MESSAGE("Can not find label "<<aPersRefString<<" for study "<<myStudy->StudyId());
243     THROW_SALOME_CORBA_EXCEPTION("Incorrect GEOM data loaded",SALOME::BAD_PARAM);
244     //return ""; empty IORs raise new problem: "display" in popup crashes
245   }
246   
247   Handle(TNaming_NamedShape) NS;
248   Lab.FindAttribute( TNaming_NamedShape::GetID(), NS );
249   TopoDS_Shape S = TNaming_Tool::GetShape(NS);
250
251   /* shapetype, index=0, topo, orb, shapetype, ismain=true and name are setted and modified later ? */
252   GEOM::GEOM_Shape_var result = CreateObject(S);
253   GEOMDS_Commands GC( aDoc->Main() ) ;
254   
255   if ( GC.HasIOR(Lab) ) { /* shape already created/loaded */
256     return 0 ;
257   }
258
259   /******************* Dependent object (not a main shape) *********************/
260   if( GC.IsDependentShape(Lab) ) {
261     
262     TDF_Label mainLabel ;
263     Standard_Boolean mainShapeOk = GC.GetMainShapeLabel(Lab, mainLabel) ;
264     
265     /* Main object not yet loaded we load/create it */
266     if( !GC.HasIOR(mainLabel) ) {
267       
268       TCollection_AsciiString entry;
269       TDF_Tool::Entry(mainLabel,entry);
270       CORBA::String_var ent = CORBA::string_dup(entry.ToCString());
271       
272       /* Create the main object recursively */
273       MainIOR = LocalPersistentIDToIOR(theSObject, ent, isMultiFile, isASCII) ;
274     } else {
275       GC.ReturnNameIOR( mainLabel, MainIOR ); 
276     }
277     
278     result->MainName( TCollection_AsciiString(MainIOR).ToCString() ) ;      
279     result->IsMainShape(false) ;
280     result->ShapeId(aPersRefString);
281     
282     Handle(TDF_Reference) aRef;
283     Lab.FindAttribute( TDF_Reference::GetID(), aRef );
284     TDF_Label myL = aRef->Get() ;
285     Handle(TNaming_NamedShape) NN;
286     myL.FindAttribute( TNaming_NamedShape::GetID(), NN );
287     TopoDS_Shape mainTopo = TNaming_Tool::GetShape(NN);
288
289     GEOM::GEOM_Shape::ListOfSubShapeID_var ListOfID = new GEOM::GEOM_Shape::ListOfSubShapeID;
290     
291     if(S.ShapeType() != TopAbs_COMPOUND) {
292       /* to set the index of a unique sub shape (Explode All ONLY for the moment !) */
293       ListOfID->length(1);
294       int index = 1;
295       TopTools_MapOfShape M;
296       TopExp_Explorer Exp ;
297       for( Exp.Init(mainTopo, TopAbs_ShapeEnum( result->ShapeType() )) ; Exp.More(); Exp.Next() )  {
298         if ( M.Add(Exp.Current()) ) {
299           if(Exp.Current().IsSame(S) ) {
300             ListOfID[0] = index;
301             break;
302           }
303           index++ ;
304         }       
305       }
306       result->Index(ListOfID) ;
307       return result->Name(); 
308     }
309     else {
310       /* Here is a TopAbs_COMPOUND : we set the list/index for a compound : containing two or more sub shapes  */
311       /* Warning : the Corba shape has a shapetype Compound : in GEOMDS_Client we have to retrieve the kind of */
312       /* subshapes contained in this compound !                                                                */
313       TopTools_SequenceOfShape SS;
314       TopoDS_Iterator it ;
315       TopExp_Explorer exp ;
316       TopAbs_ShapeEnum subType ;
317       
318       /* Set all sub shapes in a sequence of shapes  */
319       for ( it.Initialize( S, true, true ) ; it.More(); it.Next() ) {
320         subType = it.Value().ShapeType() ;
321         SS.Append( it.Value() ) ;
322       }
323       
324       ListOfID->length( SS.Length() ) ;
325       int j, k ;  /* in TopTools_SequenceOfShape index start at 1 */
326       
327       for( k=1; k<=SS.Length(); k++ ) {
328         j = 1 ;
329         for( exp.Init( mainTopo, subType ); exp.More(); exp.Next() ) {  
330           if( exp.Current().IsSame( SS.Value(k) ) ) {
331             ListOfID[k-1] = j ;
332           }
333           j++ ;
334         }
335       }
336       result->Index(ListOfID) ;
337       return result->Name();
338     }
339     
340   }
341   /******************* Independent object (not a sub shape) *********************/
342   else {
343     result->IsMainShape(true) ;
344     if( !GC.AddIORNameAttribute(Lab, result->Name() ) )  {
345       MESSAGE("in LocalPersistentIDToIOR, NAME/IOR attribute already exist." << endl ) ;
346     }
347     Handle(TNaming_NamedShape) NamedShape ;  
348     bool notTested = Lab.FindAttribute(TNaming_NamedShape::GetID(), NamedShape) ;
349     result->ShapeId(aPersRefString);
350     return result->Name(); 
351   }
352 }
353
354 //============================================================================
355 // function : CanPublishInStudy
356 // purpose  : 
357 //============================================================================
358 bool GEOM_Gen_i::CanPublishInStudy(CORBA::Object_ptr theIOR)
359 {
360   GEOM::GEOM_Shape_var aShape = GEOM::GEOM_Shape::_narrow(theIOR);
361   return !(aShape->_is_nil());
362 }
363
364
365 //============================================================================
366 // function : PublishInStudy
367 // purpose  : 
368 //============================================================================
369 SALOMEDS::SObject_ptr GEOM_Gen_i::PublishInStudy(SALOMEDS::Study_ptr theStudy,
370                                                  SALOMEDS::SObject_ptr theSObject,
371                                                  CORBA::Object_ptr theObject,
372                                                  const char* theName) throw (SALOME::SALOME_Exception)
373 {
374   Unexpect aCatch(SALOME_SalomeException);
375   SALOMEDS::SObject_var aResultSO;
376   if(CORBA::is_nil(theObject)) return aResultSO;
377
378   GEOM::GEOM_Shape_var aShape = GEOM::GEOM_Shape::_narrow(theObject);
379   if(aShape->_is_nil()) return aResultSO;
380
381   if(theStudy->_is_nil()) return aResultSO;
382
383   SALOMEDS::GenericAttribute_var anAttr;
384   SALOMEDS::StudyBuilder_var     aStudyBuilder = theStudy->NewBuilder(); 
385
386   SALOMEDS::SComponent_var       aFather = theStudy->FindComponent("GEOM"); 
387   if (aFather->_is_nil()) {
388     aFather = aStudyBuilder->NewComponent("GEOM");
389     anAttr = aStudyBuilder->FindOrCreateAttribute(aFather, "AttributeName");
390     SALOMEDS::AttributeName_var aName = SALOMEDS::AttributeName::_narrow(anAttr);
391     aName->SetValue("Geometry");
392     anAttr = aStudyBuilder->FindOrCreateAttribute(aFather, "AttributePixMap");
393     SALOMEDS::AttributePixMap::_narrow(anAttr)->SetPixMap("ICON_OBJBROWSER_Geometry");
394     aStudyBuilder->DefineComponentInstance(aFather, GEOM_Gen::_this());
395   }
396   if (aFather->_is_nil()) return aResultSO;
397   
398   if (CORBA::is_nil(theSObject)) {
399     aResultSO = aStudyBuilder->NewObject(aFather);
400   } else {
401     if (!theSObject->ReferencedObject(aResultSO)) 
402       THROW_SALOME_CORBA_EXCEPTION("Publish in study supervision graph error",SALOME::BAD_PARAM);
403   }
404   anAttr = aStudyBuilder->FindOrCreateAttribute(aResultSO, "AttributeIOR");
405   SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
406   anIOR->SetValue(aShape->Name());
407
408   anAttr = aStudyBuilder->FindOrCreateAttribute(aResultSO, "AttributePixMap");
409   SALOMEDS::AttributePixMap_var aPixmap = SALOMEDS::AttributePixMap::_narrow(anAttr);
410   TCollection_AsciiString aShapeName("Shape_");  
411
412   if ( aShape->ShapeType() == GEOM::COMPOUND ) {
413     aPixmap->SetPixMap( "ICON_OBJBROWSER_COMPOUND" );
414     aShapeName = "Compound_";
415   } else if ( aShape->ShapeType() == GEOM::COMPSOLID ) {
416     aPixmap->SetPixMap( "ICON_OBJBROWSER_COMPSOLID" );
417     aShapeName = "Compsolid_";
418   } else if ( aShape->ShapeType() == GEOM::SOLID ) {
419     aPixmap->SetPixMap( "ICON_OBJBROWSER_SOLID" );
420     aShapeName = "Solid_";
421   } else if ( aShape->ShapeType() == GEOM::SHELL ) {
422     aPixmap->SetPixMap( "ICON_OBJBROWSER_SHELL" );
423     aShapeName = "Shell_";
424   } else if ( aShape->ShapeType() == GEOM::FACE ) {
425     aPixmap->SetPixMap( "ICON_OBJBROWSER_FACE" );
426     aShapeName = "Face_";
427   } else if ( aShape->ShapeType() == GEOM::WIRE ) {
428     aPixmap->SetPixMap( "ICON_OBJBROWSER_WIRE" );
429     aShapeName = "Wire_";
430   } else if ( aShape->ShapeType() == GEOM::EDGE ) {
431     aPixmap->SetPixMap( "ICON_OBJBROWSER_EDGE" );
432     aShapeName = "Edge_";
433   } else if ( aShape->ShapeType() == GEOM::VERTEX ) {
434     aPixmap->SetPixMap( "ICON_OBJBROWSER_VERTEX" );
435     aShapeName = "Vertex_";
436   }                                          
437   if (strlen(theName) == 0) aShapeName += TCollection_AsciiString(aResultSO->Tag());
438   else aShapeName = TCollection_AsciiString((char*)theName);
439
440   //Set a name of the added shape
441   anAttr = aStudyBuilder->FindOrCreateAttribute(aResultSO, "AttributeName");
442   SALOMEDS::AttributeName_var aNameAttrib = SALOMEDS::AttributeName::_narrow(anAttr);
443   aNameAttrib->SetValue(aShapeName.ToCString());
444
445   //Add a reference to published object
446 //    aStudyBuilder->Addreference(theObject, aResultSO);
447   return aResultSO._retn();
448 }
449
450  
451 //============================================================================
452 // function : Save()
453 // purpose  : save OCAF/Geom document
454 //============================================================================
455 SALOMEDS::TMPFile* GEOM_Gen_i::Save(SALOMEDS::SComponent_ptr theComponent,
456                                     const char* theURL,
457                                     bool isMultiFile) {
458   SALOMEDS::TMPFile_var aStreamFile;
459   // Get a temporary directory to store a file
460   TCollection_AsciiString aTmpDir = (isMultiFile)?TCollection_AsciiString((char*)theURL):(char*)SALOMEDS_Tool::GetTmpDir().c_str();
461   // Create a list to store names of created files
462   SALOMEDS::ListOfFileNames_var aSeq = new SALOMEDS::ListOfFileNames;
463   aSeq->length(1);
464   // Prepare a file name to open
465   TCollection_AsciiString aNameWithExt("");
466   if (isMultiFile)
467     aNameWithExt = TCollection_AsciiString((char*)SALOMEDS_Tool::GetNameFromPath(theComponent->GetStudy()->URL()).c_str());
468   aNameWithExt += TCollection_AsciiString("_GEOM.sgd");
469   aSeq[0] = aNameWithExt.ToCString();
470   // Build a full file name of temporary file
471   TCollection_AsciiString aFullName = aTmpDir + aNameWithExt;
472   // Save GEOM component in this file
473   myOCAFApp->SaveAs(myCurrentOCAFDoc, aFullName);
474   // Conver a file to the byte stream
475   aStreamFile = SALOMEDS_Tool::PutFilesToStream(aTmpDir.ToCString(), aSeq.in(), isMultiFile);
476   // Remove the created file and tmp directory
477   if (!isMultiFile) SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.ToCString(), aSeq.in(), true);
478   // Return the created byte stream
479   return aStreamFile._retn();
480 }
481
482 SALOMEDS::TMPFile* GEOM_Gen_i::SaveASCII(SALOMEDS::SComponent_ptr theComponent,
483                                          const char* theURL,
484                                          bool isMultiFile) {
485   SALOMEDS::TMPFile_var aStreamFile = Save(theComponent, theURL, isMultiFile);
486   return aStreamFile._retn();
487 }
488
489
490 CORBA::Boolean GEOM_Gen_i::Load(SALOMEDS::SComponent_ptr theComponent,
491                                 const SALOMEDS::TMPFile& theStream,
492                                 const char* theURL,
493                                 bool isMultiFile) {
494
495   if (theStream.length() <= 9) {
496     MESSAGE("The TMPFile is too short : " << theStream.length() << " bytes ");
497     return false;
498   }
499
500   // Get a temporary directory for a file
501   TCollection_AsciiString aTmpDir = isMultiFile?TCollection_AsciiString((char*)theURL):(char*)SALOMEDS_Tool::GetTmpDir().c_str();
502   // Conver the byte stream theStream to a file and place it in tmp directory
503   SALOMEDS::ListOfFileNames_var aSeq = SALOMEDS_Tool::PutStreamToFiles(theStream,
504                                                                        aTmpDir.ToCString(),
505                                                                        isMultiFile);
506
507   // Prepare a file name to open
508   TCollection_AsciiString aNameWithExt("");
509   if (isMultiFile)
510     aNameWithExt = TCollection_AsciiString((char*)SALOMEDS_Tool::GetNameFromPath(theComponent->GetStudy()->URL()).c_str());
511   aNameWithExt += TCollection_AsciiString("_GEOM.sgd");
512   TCollection_AsciiString aFullName = aTmpDir + aNameWithExt;
513
514   // Open document
515   if (myOCAFApp->Open(aFullName, myCurrentOCAFDoc) != CDF_RS_OK) return false;
516
517   // Remove the created file and tmp directory
518   if (!isMultiFile) SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.ToCString(), aSeq.in(), true);
519
520   SALOMEDS::Study_var Study = theComponent->GetStudy();
521   TCollection_AsciiString name( Study->Name() );
522
523   int StudyID = Study->StudyId();
524   myStudyIDToDoc.Bind( StudyID, myCurrentOCAFDoc );  
525   myStudyID = StudyID;
526     
527   /* We clear all IOR (nameIOR) attributes of all objects before reconstruction */
528   /* This information will be setted when each object is reconstructed          */
529   GEOMDS_Commands GC( myCurrentOCAFDoc->Main() ) ;
530   GC.ClearAllIOR(myCurrentOCAFDoc->Main());
531
532   return true;
533 }
534
535 CORBA::Boolean GEOM_Gen_i::LoadASCII(SALOMEDS::SComponent_ptr theComponent,
536                                      const SALOMEDS::TMPFile& theStream,
537                                      const char* theURL,
538                                      bool isMultiFile) {
539   return Load(theComponent, theStream, theURL, isMultiFile);
540 }
541
542 //  //============================================================================
543 //  // function : Save()
544 //  // purpose  : save OCAF/Geom document
545 //  //============================================================================
546 //  void GEOM_Gen_i::Save(const char *IORSComponent, const char *aUrlOfFile) 
547 //  {
548
549 //    TCollection_ExtendedString path((char*)aUrlOfFile);
550 //    TCollection_ExtendedString pathWithExt = path + TCollection_ExtendedString(".sgd");
551 //    myOCAFApp->SaveAs(myCurrentOCAFDoc,pathWithExt);
552 //  }
553
554
555 //  //============================================================================
556 //  // function : Load()
557 //  // purpose  : Load OCAF/Geom document
558 //  //============================================================================
559 //  void GEOM_Gen_i::Load(const char *IORSComponent, const char *aUrlOfFile) 
560 //  {
561
562 //    TCollection_ExtendedString path((char*)aUrlOfFile);
563 //    TCollection_ExtendedString pathWithExt = path + TCollection_ExtendedString(".sgd");
564
565 //    myOCAFApp->Open(pathWithExt,myCurrentOCAFDoc);
566
567 //    SALOMEDS::SComponent_var SC = SALOMEDS::SComponent::_narrow(_orb->string_to_object(IORSComponent));
568 //    SALOMEDS::Study_var Study = SC->GetStudy();
569 //    TCollection_AsciiString name( Study->Name() );
570
571 //    int StudyID = Study->StudyId();
572 //    myStudyIDToDoc.Bind( StudyID, myCurrentOCAFDoc );  
573 //    myStudyID = StudyID;
574
575 //    /* We clear all IOR (nameIOR) attributes of all objects before reconstruction */
576 //    /* This information will be setted when each object is reconstructed          */
577 //    GEOMDS_Commands GC( myCurrentOCAFDoc->Main() ) ;
578 //    GC.ClearAllIOR(myCurrentOCAFDoc->Main());
579
580 //    return ;
581 //  }
582
583
584 //============================================================================
585 // function : Close()
586 // purpose  :
587 //============================================================================
588 void GEOM_Gen_i::Close(SALOMEDS::SComponent_ptr theComponent)
589 {
590   int anID = theComponent->GetStudy()->StudyId();
591   if (anID == myStudyID) GetCurrentStudy(0); // set default value of current study ID, if current is deleted
592   if (myStudyIDToDoc.IsBound(anID)) {
593     // close document in the application
594 //      Handle(TDocStd_Owner) anOwner;
595     Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(myStudyIDToDoc.Find(anID));
596 //      Handle(TDocStd_Document) anEmptyDoc;
597 //      if (aDoc->Main().Root().FindAttribute(TDocStd_Owner::GetID(), anOwner)) {
598 //        anOwner->SetDocument(anEmptyDoc);
599 //        MESSAGE("********** Nullify owner of document");
600 //      }
601     myOCAFApp->Close(aDoc);
602     myStudyIDToDoc.UnBind(anID); // remove document from GEOM documents data map
603     }
604 }
605
606 //============================================================================
607 // function : CanCopy()
608 // purpose  :
609 //============================================================================
610 CORBA::Boolean GEOM_Gen_i::CanCopy(SALOMEDS::SObject_ptr theObject) {
611   // Try to retrieve known by Geometry component GEOM_shape by given IOR
612   SALOMEDS::GenericAttribute_var anAttr;
613   if (!theObject->FindAttribute(anAttr, "AttributeIOR")) return false;
614   GEOM::GEOM_Shape_var aShape = GetIORFromString(SALOMEDS::AttributeIOR::_narrow(anAttr)->Value());
615   // If the object is null one it can't be copied: return false
616   if (aShape->_is_nil()) return false;
617   return true;
618 }
619
620 //============================================================================
621 // function : CopyFrom()
622 // purpose  :
623 //============================================================================
624 SALOMEDS::TMPFile* GEOM_Gen_i::CopyFrom(SALOMEDS::SObject_ptr theObject, CORBA::Long& theObjectID) {
625   // Declare a sequence of the byte to store the copied object
626   SALOMEDS::TMPFile_var aStreamFile = new SALOMEDS::TMPFile;
627
628   // Try to get GEOM_Shape object by given SObject
629   SALOMEDS::GenericAttribute_var anAttr;
630   if (!theObject->FindAttribute(anAttr, "AttributeIOR")) return false;
631   GEOM::GEOM_Shape_var aShape = GetIORFromString(SALOMEDS::AttributeIOR::_narrow(anAttr)->Value());
632   // If the object is null one it can't be copied: return false
633   if (aShape->_is_nil()) return aStreamFile._retn();
634  
635   GetCurrentStudy(theObject->GetStudy()->StudyId());
636
637   // Convert a TopoDS_Shape to a stream of bytes
638   TopoDS_Shape aTopology = GetTopoShape(aShape);
639   if (aTopology.IsNull()) return aStreamFile._retn();
640   ostrstream aStreamedShape;
641   BRepTools::Write(aTopology, aStreamedShape);
642   int aSize = aStreamedShape.pcount();
643   char* aBuffer = new char[aSize];
644   memcpy(aBuffer, aStreamedShape.str(), aSize);
645   aStreamedShape.rdbuf()->freeze(0);
646
647   aStreamFile = new SALOMEDS::TMPFile(aSize, aSize, (CORBA::Octet*)aBuffer, 1);
648   
649   // Assign an ID = 1 the the type GEOM_Shape
650   theObjectID = 1;
651
652   // Return created TMPFile
653   return aStreamFile._retn();
654 }
655
656 //============================================================================
657 // function : CanPaste()
658 // purpose  :
659 //============================================================================
660 CORBA::Boolean GEOM_Gen_i::CanPaste(const char* theComponentName, CORBA::Long theObjectID) {
661   // The Geometry component can paste only objects copied by Geometry component
662   // and with the object type = 1
663 //    MESSAGE("********** GEOM_Gen_i::CanPaste ("<<theComponentName<<","<<theObjectID<<")");
664   if (strcmp(theComponentName, ComponentDataType()) != 0 || theObjectID != 1) return false;
665   return true;
666 }
667
668 //============================================================================
669 // function : PasteInto()
670 // purpose  :
671 //============================================================================
672 SALOMEDS::SObject_ptr GEOM_Gen_i::PasteInto(const SALOMEDS::TMPFile& theStream,
673                                             CORBA::Long theObjectID,
674                                             SALOMEDS::SObject_ptr theObject) {
675   // Find the current Study and StudyBuilder
676   SALOMEDS::Study_var aStudy = theObject->GetStudy();
677   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
678
679   // Retrieve a TopoDS_Shape from byte stream
680   TopoDS_Shape aTopology;
681   istrstream aStreamedBrep((char*) &theStream[0], theStream.length());
682   BRep_Builder aBuilder;
683   try {
684     BRepTools::Read(aTopology, aStreamedBrep, aBuilder);
685   } catch (Standard_Failure) {
686     MESSAGE("GEOM_Gen_i::PasteInto exception");
687     return false;
688   }
689   
690   // Create new object in Geometry component using retrieved topology
691   GEOM::GEOM_Shape_var aShape = CreateObject(aTopology);
692   GetCurrentStudy(aStudy->StudyId());
693   const char *anEntry = InsertInLabel(aTopology, aShape->Name(), myCurrentOCAFDoc) ;
694   aShape->ShapeId(anEntry) ;
695
696   // SObject of the created shape is theObject or new Child of Component if theObject == geom component
697   SALOMEDS::SObject_var aNewSO;
698   if (strcmp(theObject->GetFatherComponent()->GetID(),theObject->GetID()) == 0) {
699     aNewSO = aStudyBuilder->NewObject(theObject);
700   } else aNewSO = SALOMEDS::SObject::_duplicate(theObject);
701   // Add IORAttribute to the Study and set IOR of the created GEOM_Shape to it
702   SALOMEDS::GenericAttribute_var anAttr = aStudyBuilder->FindOrCreateAttribute(aNewSO, "AttributeIOR");
703   SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
704   anIOR->SetValue(aShape->Name());
705
706   // Return the created in the Study SObject
707   return aNewSO._retn();
708 }
709
710 //============================================================================
711 // function : ComponentDataType()
712 // purpose  :
713 //============================================================================
714 char* GEOM_Gen_i::ComponentDataType()
715 {
716   return CORBA::string_dup("GEOM");
717 }
718
719 //============================================================================
720 // function : register() 
721 // purpose  : register 'name' in 'name_service'
722 //============================================================================
723 void GEOM_Gen_i::register_name(char * name)
724 {
725   GEOM::GEOM_Gen_ptr g = GEOM::GEOM_Gen::_narrow(POA_GEOM::GEOM_Gen::_this());
726   name_service->Register(g, name); 
727 }
728
729
730
731 //================================================================================
732 // function : SequenceOfShapeFromListOfGeomShape()
733 // purpose  : Define a sequence of shapes from 'listShapes' and return its length.
734 //          : No control is made on shapes !
735 //================================================================================
736 int GEOM_Gen_i::SequenceOfShapeFromListOfGeomShape( const GEOM::GEOM_Gen::ListOfGeomShapes& listShapes,
737                                                     TopTools_SequenceOfShape& SS )
738 {
739   int nbShapes = listShapes.length() ;
740   if( nbShapes < 1)
741     return 0 ;
742   
743   for(int i=0; i<nbShapes; i++) {
744     GEOM::GEOM_Shape_var aGeomShape = listShapes[i] ;
745     TopoDS_Shape aShape = GetTopoShape(aGeomShape) ;
746     SS.Append(aShape) ;
747   }
748   return nbShapes ;
749 }
750
751
752
753
754 //=================================================================================
755 // function : GetTopoShape()
756 // purpose  : Returns a TopoDS_Shape from a GEOM::GEOM_Shape_ptr in 'myCurrentOCAFDoc'
757 //          : A null shape is returned if not possible
758 //=================================================================================
759 TopoDS_Shape GEOM_Gen_i::GetTopoShape(GEOM::GEOM_Shape_ptr shape_ptr)
760
761   TopoDS_Shape tds ;
762
763   TDF_Label lab ;
764   Handle(TDF_Data) D = myCurrentOCAFDoc->GetData() ;
765   TDF_Tool::Label( D, shape_ptr->ShapeId(), lab, true ) ;
766   Handle(TNaming_NamedShape) NamedShape ;  
767   bool res = lab.FindAttribute(TNaming_NamedShape::GetID(), NamedShape) ;
768
769   if( !res ) {
770     return tds ; /* a null shape is returned */
771   }
772   else {
773     return TNaming_Tool::GetShape(NamedShape) ;
774   }
775 }
776
777
778
779 //=================================================================================
780 // function : GetStringFromIOR()
781 // purpose  : returns a string that represents  a 'GEOM::GEOM_Shape_var'
782 //=================================================================================
783 const char* GEOM_Gen_i::GetStringFromIOR(GEOM::GEOM_Shape_var shapeIOR) {
784   const char * ret = _orb->object_to_string(shapeIOR) ;
785   return ret ;
786 }
787
788
789
790 //=================================================================================
791 // function : GetIORFromString()
792 // purpose  : returns a 'GEOM::GEOM_Shape_var' from a string representing it
793 //=================================================================================
794 GEOM::GEOM_Shape_ptr GEOM_Gen_i::GetIORFromString(const char* stringIOR) {
795   GEOM::GEOM_Shape_var shapeIOR;
796   if(strcmp(stringIOR,"") != 0){
797     CORBA::Object_var anObject = _orb->string_to_object(stringIOR);
798     if(!CORBA::is_nil(anObject))
799       shapeIOR =  GEOM::GEOM_Shape::_narrow(anObject.in()) ;
800   }
801   return shapeIOR._retn() ;
802 }
803
804
805
806 //==================================================================================
807 // function : InsertInLabel()
808 // purpose  : Insert S = Shape and mystr = name in a new Label of Geom/OCAF document
809 //          : and returns the corresponding OCAF entry
810 //==================================================================================
811 const char * GEOM_Gen_i::InsertInLabel(TopoDS_Shape S, const char *mystr, Handle(TDocStd_Document) OCAFDoc)
812 {
813   GEOMDS_Commands GC(OCAFDoc->Main());
814   /* add attributs S and mystr in a new label */
815   TDF_Label Lab = GC.AddShape (S, (char*)mystr);
816
817   TCollection_AsciiString entry;
818   TDF_Tool::Entry(Lab,entry);
819   const char *ent = entry.ToCString() ;
820   return ent ;
821 }
822
823
824 //==================================================================================
825 // function : InsertInLabelDependentShape()
826 // purpose  : Insert S = Shape and its nameIor in a new Label of Geom/OCAF document
827 //          : insert also a reference attribute (a label) to the main shape 'mainshap_ptr'.
828 //          : and returns the corresponding OCAF entry of the new label.
829 //==================================================================================
830 const char * GEOM_Gen_i::InsertInLabelDependentShape( TopoDS_Shape S,
831                                                       const char *nameIor,
832                                                       GEOM::GEOM_Shape_ptr mainshape_ptr,
833                                                       Handle(TDocStd_Document) OCAFDoc )
834 {
835   GEOMDS_Commands GC(OCAFDoc->Main());
836   /* add attributs S and nameIor in a new label */
837
838   /* retrieve the label of the main shape in the document */
839   TDF_Label mainRefLab;
840   TDF_Tool::Label(OCAFDoc->GetData(), mainshape_ptr->ShapeId(), mainRefLab);
841
842   /* add attributs : S, nameIor and ref to main */
843   TDF_Label Lab = GC.AddDependentShape(S, (char*)nameIor, mainRefLab);
844
845   TCollection_AsciiString entry;
846   TDF_Tool::Entry(Lab, entry);
847   const char *ent = entry.ToCString() ;
848   return ent ;
849 }
850
851
852 //=================================================================================
853 // function : InsertInLabelOneArgument()
854 // purpose  :
855 //=================================================================================
856 void GEOM_Gen_i::InsertInLabelOneArgument(TopoDS_Shape main_topo,
857                                           GEOM::GEOM_Shape_ptr shape_ptr,
858                                           TopoDS_Shape result_topo,     
859                                           GEOM::GEOM_Shape_ptr result,  
860                                           Handle(TDocStd_Document) OCAFDoc)
861 {
862   /* Put shape and name into geom/OCAF doc */
863   GEOMDS_Commands GC(OCAFDoc->Main());
864   /* Add attributs 'shape' and 'name_ior' in a new label */
865   TDF_Label Lab = GC.Generated( main_topo, result_topo, result->Name() );
866   TCollection_AsciiString entry;
867   TDF_Tool::Entry(Lab, entry);
868   result->ShapeId( entry.ToCString() ) ;
869   
870   /* Create a new label */
871   TDF_Label NewLab = Lab.NewChild();
872   TCollection_ExtendedString Value("Arguments");
873   TDataStd_Name::Set(NewLab,Value);
874   
875   TDF_Label NewLab1 = NewLab.NewChild();
876   TDF_Label RefLab;
877   TDF_Tool::Label(OCAFDoc->GetData(), shape_ptr->ShapeId(), RefLab);
878   TDF_Reference::Set(NewLab1, RefLab);
879 }
880
881
882 //=================================================================================
883 // function : InsertInLabelMoreArguments()
884 // purpose  :
885 //=================================================================================
886 void GEOM_Gen_i::InsertInLabelMoreArguments(TopoDS_Shape main_topo,
887                                             GEOM::GEOM_Shape_ptr result,
888                                             const GEOM::GEOM_Gen::ListOfIOR& ListShapes,                                
889                                             Handle(TDocStd_Document) OCAFDoc)
890 {
891   /* Put shape and name into geom/OCAF doc */
892   GEOMDS_Commands GC(OCAFDoc->Main());
893   /* Add attributs TopoDS and name_ior in a new label */
894   TDF_Label Lab = GC.AddShape(main_topo, result->Name() );
895   TCollection_AsciiString entry;
896   TDF_Tool::Entry(Lab, entry);
897   
898   /* Create a new label */
899   TDF_Label NewLab = Lab.NewChild();
900   TCollection_ExtendedString Value("Arguments");
901   TDataStd_Name::Set(NewLab, Value);
902
903   for (unsigned int ind = 0; ind < ListShapes.length(); ind++) {
904     
905     TDF_Label NewLab1 = NewLab.NewChild();    
906     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[ind] );
907     
908     TDF_Label RefLab;
909     TDF_Tool::Label(OCAFDoc->GetData(), aShape->ShapeId(), RefLab);
910     TDF_Reference::Set(NewLab1, RefLab);
911   }
912   result->ShapeId(entry.ToCString());
913 }
914
915
916
917 //=================================================================================
918 // function: NbLabels()
919 // purpose : 
920 //=================================================================================
921 CORBA::Short GEOM_Gen_i::NbLabels()
922 {
923   TDF_ChildIterator ChildIterator(myCurrentOCAFDoc->Main());
924   unsigned int i = 1;
925   
926   while (ChildIterator.More()) {
927     i++;
928     ChildIterator.Next();
929   }
930   return i;
931   //  return TDF_Tool::NbLabels( myCurrentOCAFDoc->Main() );
932 }
933
934
935
936 //=================================================================================
937 // function: GetCurrentStudy()
938 // purpose : Finds or creates the geom/OCAF document corresponding to the index
939 // 'StudyID'
940 //=================================================================================
941 void GEOM_Gen_i::GetCurrentStudy(CORBA::Long StudyID)
942 {
943   /* If StudyID is known we link myCurrentOCAFDoc to it */
944   if (myStudyIDToDoc.IsBound(StudyID)) {
945     myCurrentOCAFDoc =  Handle(TDocStd_Document)::DownCast(myStudyIDToDoc(StudyID));
946   }
947   /* Create a new OCAFDoc and link it to 'StudyID' argument */
948   else { 
949     myOCAFApp->NewDocument("SALOME_GEOM",myCurrentOCAFDoc);
950     myStudyIDToDoc.Bind(StudyID,myCurrentOCAFDoc);
951   } 
952   myStudyID = StudyID;
953 }
954
955
956 //================================================================================
957 // function : CreateObject() 
958 // purpose  : private function to create a complete CORBA object and return it
959 //================================================================================
960 GEOM::GEOM_Shape_ptr GEOM_Gen_i::CreateObject(TopoDS_Shape& tds)
961 {
962 //   if ( tds.ShapeType() == TopAbs_COMPOUND ) {
963 //     TopoDS_Iterator itr(tds);
964 //     TopoDS_Shape res;
965 //     int i = 0;
966 //     while (itr.More()) {
967 //       i++;
968 //       res = itr.Value();
969 //       itr.Next();
970 //     }
971     
972 //     if ( i == 1 )
973 //       tds = res;
974 //   }
975
976   GEOM::shape_type st = GEOM::shape_type(tds.ShapeType()) ; /* casting */
977   
978   /* Create the CORBA servant holding the TopoDS_Shape */
979   GEOM::GEOM_Gen_ptr engine = POA_GEOM::GEOM_Gen::_this();
980   GEOM::GEOM_Shape::ListOfSubShapeID_var index = new GEOM::GEOM_Shape::ListOfSubShapeID;
981   index->length(0);  
982   GEOM_Shape_i * shape_servant = new GEOM_Shape_i(tds, _orb, engine, index, st, true);
983   GEOM::GEOM_Shape_var shape = GEOM::GEOM_Shape::_narrow(shape_servant->_this()); 
984   
985   /* Create and set the name (IOR of shape converted into a string) */
986   string name_ior = _orb->object_to_string(shape) ;
987   shape->Name( name_ior.c_str() );  
988   shape->NameType( "" );
989   return shape;
990 }
991
992 //=======================================================================
993 //function : CreateSubObject
994 //purpose  : 
995 //=======================================================================
996
997 GEOM::GEOM_Shape_ptr GEOM_Gen_i::CreateSubObject(const TopoDS_Shape& SubShape,
998                                                  const GEOM::GEOM_Shape_ptr MainShape,
999                                                  const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID)
1000 {
1001   GEOM::shape_type st = GEOM::shape_type(SubShape.ShapeType()) ; /* casting */
1002   
1003   /* Create the CORBA servant holding the TopoDS_Shape */
1004   GEOM::GEOM_Gen_ptr engine = POA_GEOM::GEOM_Gen::_this();
1005   GEOM_Shape_i * shape_servant =
1006     new GEOM_Shape_i(SubShape, _orb, engine, ListOfID, st, false);
1007   GEOM::GEOM_Shape_var shape = GEOM::GEOM_Shape::_narrow(shape_servant->_this()); 
1008   
1009     /* Create and set the name (IOR of shape converted into a string) */
1010   string name_ior = _orb->object_to_string(shape) ;
1011   shape->Name( name_ior.c_str() );
1012     /* create and set the mainname (IOR of shape converted into a string) */
1013   const char *mainname_ior = _orb->object_to_string(MainShape) ;
1014   shape->MainName(mainname_ior);
1015     /* precaution : NameType will be set precisely in GUI */    
1016   shape->NameType( "" );
1017     /* add 'SubShape' its 'nameIOR' and a reference to the main shape thanks to method below  */
1018   const char *entry =
1019     InsertInLabelDependentShape(SubShape, shape->Name(), MainShape, myCurrentOCAFDoc) ;
1020   shape->ShapeId( entry ) ;
1021  
1022   return shape;
1023 }
1024
1025 //=======================================================================
1026 // function : SuppressFacesGlue()
1027 // purpose  : Define a compound of shells after suppress of mapFaces in the 
1028 //          : shape S and return the number of shells of the compound.
1029 //=======================================================================
1030 int GEOM_Gen_i::SuppressFacesGlue( const TopoDS_Shape& S,
1031                                    const TopTools_MapOfShape& mapFaces,
1032                                    TopoDS_Shape& aCompoundOfShells )
1033   throw (SALOME::SALOME_Exception)
1034 {  
1035   Unexpect aCatch(SALOME_SalomeException);
1036   BRepTools_Quilt Glue;
1037   aCompoundOfShells.Nullify() ;
1038   
1039   for ( TopExp_Explorer exp( S, TopAbs_FACE); exp.More(); exp.Next() ) {
1040     const TopoDS_Face& F = TopoDS::Face(exp.Current());
1041     if ( !mapFaces.Contains(F) ) {
1042       /* this face must not to be suppressed */
1043       Glue.Add(F);
1044     }
1045   }
1046   
1047   /* Use specif method to calculate the compound of shells */
1048   aCompoundOfShells = Glue.Shells();
1049   
1050   if( aCompoundOfShells.ShapeType() != TopAbs_COMPOUND ) {
1051     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::SuppressFacesGlue() : not a GEOM::COMPOUND", SALOME::BAD_PARAM);
1052   }
1053
1054   /* explore Compound for verification and return the number of shells */
1055   int numberOfShell = 0 ;
1056   for ( TopExp_Explorer exp1( aCompoundOfShells, TopAbs_SHELL); exp1.More(); exp1.Next() )
1057     numberOfShell++ ;
1058
1059   return numberOfShell ;
1060 }
1061
1062
1063 //=====================================================================================
1064 // function : GetIndexTopology()
1065 // purpose  : return the index of a sub shape in a shape (index starts at 1)
1066 //          : Return -1 if not found
1067 //=====================================================================================
1068 int GEOM_Gen_i::GetIndexTopology(const TopoDS_Shape& subshape, const TopoDS_Shape& mainShape) 
1069
1070   if( mainShape.IsNull() || subshape.IsNull() ) 
1071     return -1 ; 
1072
1073   int index = 1; 
1074   if (subshape.ShapeType() == TopAbs_COMPOUND) 
1075     { 
1076       TopoDS_Iterator it; 
1077       TopTools_ListOfShape CL; 
1078       CL.Append( mainShape ); 
1079       TopTools_ListIteratorOfListOfShape itC; 
1080       for (itC.Initialize( CL ); itC.More(); itC.Next()) 
1081         { 
1082           for (it.Initialize( itC.Value() );  it.More(); it.Next()) 
1083             { 
1084               if ( it.Value().ShapeType() == TopAbs_COMPOUND) 
1085                 {
1086                   if (it.Value().IsSame(subshape)) 
1087                     return index; 
1088                   else 
1089                     index++; 
1090                   CL.Append( it.Value() ); 
1091                 }
1092             } 
1093         } 
1094     } 
1095   else 
1096     { 
1097       TopExp_Explorer Exp ( mainShape,  subshape.ShapeType() ); 
1098       TopTools_MapOfShape M; 
1099       while ( Exp.More() ) 
1100         { 
1101           if ( M.Add(Exp.Current()) ) 
1102             { 
1103               if ( Exp.Current().IsSame(subshape) ) 
1104                 return index; 
1105               index++; 
1106             } 
1107           Exp.Next(); 
1108         } 
1109     } 
1110   return -1; 
1111
1112
1113
1114 //================================================================================
1115 // function : IndexOfFacesOfSubShell()
1116 // purpose  : Return a list of indices corresponding to the faces of a 'subShell'
1117 //          : in the main shape 'S'
1118 //================================================================================
1119 GEOM::GEOM_Shape::ListOfSubShapeID* GEOM_Gen_i::IndexOfFacesOfSubShell( const TopoDS_Shape& S,
1120                                                                   const TopoDS_Shape subShell )
1121   throw (SALOME::SALOME_Exception)
1122 {
1123
1124   Unexpect aCatch(SALOME_SalomeException);
1125   GEOM::GEOM_Shape::ListOfSubShapeID_var ListOfID = new GEOM::GEOM_Shape::ListOfSubShapeID;
1126   ListOfID->length(0) ;
1127   if( subShell.IsNull() || subShell.ShapeType() != TopAbs_SHELL ) {
1128     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::IndexOfFacesOfSubShell() : null shape or not a GEOM::SHELL", SALOME::BAD_PARAM);
1129   }
1130
1131   /* put faces of subShell in a Map of faces */
1132   int j = 0 ;
1133   TopTools_MapOfShape mapFaces ;
1134   for( TopExp_Explorer Exp1( subShell, TopAbs_FACE );  Exp1.More(); Exp1.Next() ) {
1135     mapFaces.Add(Exp1.Current() ) ;
1136     j++ ;
1137   }
1138
1139   if( j<1 )
1140     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::IndexOfFacesOfSubShell() : no faces in sub shell", SALOME::BAD_PARAM);
1141   
1142   /* Find index of each face of subshell in the main topology and put its index in ListOfID */
1143   int size = 0 ;
1144   for ( TopExp_Explorer Exp2(S, TopAbs_FACE); Exp2.More();  Exp2.Next() ) {
1145     
1146     const TopoDS_Face& F = TopoDS::Face( Exp2.Current() ) ;
1147
1148     if( mapFaces.Contains(F) )  {
1149       int n = GetIndexTopology( F, S ) ;
1150       if( n<=0 ) {
1151         THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::IndexOfFacesOfSubShell() : no index found", SALOME::BAD_PARAM);    
1152       }
1153       size++;
1154       ListOfID->length(size) ;
1155       ListOfID[size-1] = n ;
1156     }
1157   }
1158
1159   return ListOfID._retn() ;
1160 }
1161
1162
1163
1164 //================================================================================
1165 // function : ListOfIDIntoMapOfShapes()
1166 // purpose  : Define a MapOfShapes from a main topology 'S' a 'subShapeType'
1167 //          : and a list of indices 'L'.
1168 //          : Return true if 'aMap' is not empty
1169 //================================================================================
1170 bool GEOM_Gen_i::ListOfIDIntoMapOfShapes( const TopoDS_Shape& S,
1171                                           const GEOM::GEOM_Shape::ListOfSubShapeID& L,
1172                                           const int subShapeType,
1173                                           TopTools_MapOfShape& aMap )
1174 {
1175   if( L.length() < 1 || S.IsNull() ) {
1176     return false ;
1177   }
1178   
1179   aMap.Clear() ; 
1180   for( int k=0; k<L.length(); k++ ) {
1181     /* indices start at 1 in list L */
1182     int j = 1 ;
1183     TopExp_Explorer exp ;
1184     TopTools_MapOfShape M; 
1185     for(  exp.Init( S, TopAbs_ShapeEnum(subShapeType) ); exp.More(); exp.Next() ) {
1186       if ( M.Add(exp.Current()) ) 
1187         { 
1188           if( L[k] == j ) {
1189             aMap.Add( exp.Current() ) ;
1190           }
1191           j++ ;
1192         }
1193     }
1194   }
1195   return true ;
1196 }
1197
1198
1199
1200 //================================================================================
1201 // function : ListOfIDIntoSequenceOfShapes()
1202 // purpose  : Define 'aSequenceOfShapes' from a main topology 'S' a 'subShapeType'
1203 //          : and a list of indices 'L'.
1204 //          : Return true if 'aSequenceOfShapes' is not empty
1205 //================================================================================
1206 bool GEOM_Gen_i::ListOfIDIntoSequenceOfShapes( const TopoDS_Shape& S,
1207                                                const GEOM::GEOM_Shape::ListOfSubShapeID& L,
1208                                                const int subShapeType,
1209                                                TopTools_SequenceOfShape& aSequenceOfShapes )
1210 {
1211   if( L.length() < 1 || S.IsNull() ) {
1212     return false ;
1213   }
1214   
1215   aSequenceOfShapes.Clear() ; 
1216   for( int k=0; k<L.length(); k++ ) {
1217     /* indices start at 1 in list L */
1218     int j = 1 ;
1219     TopExp_Explorer exp ;
1220     for(  exp.Init( S, TopAbs_ShapeEnum(subShapeType) ); exp.More(); exp.Next() ) {
1221       if( L[k] == j ) {
1222         aSequenceOfShapes.Append( exp.Current() ) ;
1223       }
1224       j++ ;
1225     }
1226   }
1227   return true ;
1228 }
1229
1230
1231
1232 //================================================================================
1233 // function : SuppressFaces()
1234 // purpose  : Suppress faces contained in ListOfID from 'shape'.
1235 //          : Return a list of Geom shapes each one is a main shape GEOM::FACE or GEOM::SHELL
1236 //================================================================================
1237 GEOM::GEOM_Gen::ListOfGeomShapes* GEOM_Gen_i::SuppressFaces( GEOM::GEOM_Shape_ptr shape,
1238                                                                 const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID ) 
1239   throw (SALOME::SALOME_Exception)
1240 {
1241   Unexpect aCatch(SALOME_SalomeException);
1242   GEOM::GEOM_Gen::ListOfGeomShapes_var listOfGeomShapes = new GEOM::GEOM_Gen::ListOfGeomShapes;
1243   listOfGeomShapes->length(0) ;
1244
1245   TopoDS_Shape mainShape = GetTopoShape(shape);
1246   if( mainShape.IsNull() )
1247     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::SuppressFaces() : null argument shape", SALOME::BAD_PARAM);
1248   
1249   if( ListOfID.length() < 1 )
1250     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::SuppressFaces() : empty ListOfID", SALOME::BAD_PARAM);
1251   
1252   /* Define 'mapFaces' a map of faces to be suppressed in mainShape */
1253   TopTools_MapOfShape mapFaces ;
1254   if( !ListOfIDIntoMapOfShapes(mainShape, ListOfID, TopAbs_FACE, mapFaces ) ) {
1255     return listOfGeomShapes._retn();
1256   }
1257     
1258   /* Call algorithm to calculate a compound of shells resulting of face suppression */
1259   int numberOfShells = 0 ;
1260   TopoDS_Shape aCompoundOfShells ;
1261   numberOfShells = SuppressFacesGlue(mainShape, mapFaces, aCompoundOfShells) ;
1262   if(numberOfShells < 1) {
1263     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::Suppressfaces() : no shells", SALOME::BAD_PARAM);
1264   }
1265  
1266   /* Create a shell for each shell contained in 'aCompoundOfShells' and             */ 
1267   /* put it in the list of GeomShapes to be returned.                               */
1268   /* But if the shell is composed of only a face we create a face and not a shell   */
1269   int i = 0 ;
1270   for( TopExp_Explorer exp(aCompoundOfShells, TopAbs_SHELL); exp.More(); exp.Next() ) {
1271
1272     const TopoDS_Shell& aShell = TopoDS::Shell( exp.Current() );    
1273     if( aShell.IsNull() ) {
1274       THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::Suppressfaces() : null shell", SALOME::BAD_PARAM);
1275     }
1276     
1277     GEOM::GEOM_Shape::ListOfSubShapeID_var aList = new GEOM::GEOM_Shape::ListOfSubShapeID;
1278     aList = IndexOfFacesOfSubShell(mainShape, aShell) ;
1279
1280      if( aList->length() < 1 ) {
1281       THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::SuppressFaces() : aList is empty", SALOME::BAD_PARAM);
1282     }
1283
1284     TopoDS_Shape aShellOrFace ;
1285     /* Only a face into the shell : we create a single face instead of a shell : 'aList' is unchanged  */
1286     if( aList->length() == 1 ) {
1287       TopExp_Explorer exp ;
1288       exp.Init( aShell, TopAbs_FACE ) ;
1289       exp.More() ;
1290       aShellOrFace = exp.Current() ;
1291     }
1292     else {
1293       aShellOrFace = aShell ;
1294     }
1295     
1296     /* Create CORBA object */
1297     GEOM::GEOM_Shape_var result = CreateObject(aShellOrFace) ;
1298     if( CORBA::is_nil(result) ) {
1299       THROW_SALOME_CORBA_EXCEPTION("Suppress Faces aborted : null result", SALOME::BAD_PARAM);
1300     }
1301
1302     InsertInLabelOneArgument(mainShape, shape, aShellOrFace, result, myCurrentOCAFDoc) ;
1303     i++ ;
1304     listOfGeomShapes->length(i) ;
1305     listOfGeomShapes[i-1] = result ;
1306   }
1307
1308   return listOfGeomShapes._retn() ;
1309 }
1310
1311
1312
1313 //================================================================================
1314 // function : IsShapeInSequence()
1315 // purpose  : return true is aShape is in SS. The test method is 'IsSame()'
1316 //================================================================================
1317 bool GEOM_Gen_i::IsShapeInSequence(const TopTools_SequenceOfShape& SS, const TopoDS_Shape& aShape)
1318 {
1319   if( aShape.IsNull() || SS.IsEmpty() ) 
1320     return false ;  
1321   for( int i=1; i<=SS.Length(); i++) {
1322     if( SS.Value(i).IsSame(aShape) )
1323       return true ;
1324   }
1325   return false ;
1326 }
1327
1328
1329 //================================================================================
1330 // function : FreeEdgesFromMapOfFace()
1331 // purpose  : Define MS a map of all edges of faces of 'MSfaces'
1332 //          : All multiple edges are removed !
1333 //================================================================================
1334 void GEOM_Gen_i::FreeEdgesFromMapOfFace( const TopTools_MapOfShape& MSfaces,
1335                                          TopTools_MapOfShape& MS )
1336 {
1337   MS.Clear() ;
1338   TopTools_MapOfShape Multiple ;
1339   TopTools_MapIteratorOfMapOfShape it ;
1340   for( it.Initialize(MSfaces); it.More(); it.Next() ) {
1341     TopoDS_Shape aFace = it.Key() ;
1342     TopExp_Explorer exp ;
1343     for( exp.Init( aFace, TopAbs_EDGE); exp.More(); exp.Next() ) {
1344       if( !Multiple.Contains( exp.Current() ) && !MS.Add( exp.Current() ) ) {
1345         MS.Remove( exp.Current() ) ;
1346         Multiple.Add( exp.Current() ) ;
1347       }
1348     }
1349   }
1350   return ;
1351 }
1352
1353
1354 //================================================================================
1355 // function : MapRemoveSequence()
1356 // purpose  : In term of shapes ST = MS - SSRemove
1357 //          :
1358 //================================================================================
1359 void GEOM_Gen_i::MapRemoveSequence( const TopTools_MapOfShape& MS,
1360                                     const TopTools_SequenceOfShape& SSRemove,
1361                                     TopTools_SequenceOfShape& ST ) 
1362 {
1363   ST.Clear() ;
1364   TopTools_MapIteratorOfMapOfShape it ;
1365   for( it.Initialize(MS); it.More(); it.Next() ) {
1366     TopoDS_Shape aShape = it.Key() ;
1367     if( !IsShapeInSequence( SSRemove, aShape ) )
1368       ST.Append( aShape ) ;
1369   }
1370   return ;
1371 }
1372
1373
1374
1375 //================================================================================
1376 // function : SuppressHoleSubRoutine()
1377 // purpose  : Define recursively 'MSfacesSuppress' a list of faces to suppress in a hole
1378 //================================================================================
1379 void GEOM_Gen_i::SuppressHoleSubRoutine( const TopoDS_Shape& mainShape,
1380                                          const TopoDS_Face& aFace,
1381                                          const TopTools_SequenceOfShape& SSedgesOfWire, 
1382                                          const TopTools_IndexedDataMapOfShapeListOfShape& aMapEdgesFaces,
1383                                          const TopTools_MapOfShape& MSfaces,                                     
1384                                          TopTools_MapOfShape& MSfacesSuppress,
1385                                          const Standard_Boolean withEndFace,
1386                                          const TopoDS_Face& endFace,
1387                                          TopTools_MapOfShape& MSwireEndEdges )
1388   throw (SALOME::SALOME_Exception)
1389 {  
1390   Unexpect aCatch(SALOME_SalomeException);
1391   TopTools_MapOfShape MS ;
1392   TopTools_SequenceOfShape SU ;
1393   FreeEdgesFromMapOfFace(MSfaces, MS) ;        /* MS = free edges of MSfaces */
1394   MapRemoveSequence(MS, SSedgesOfWire, SU) ;   /* SU = MS - SSedgesOfWire    */
1395
1396   if( SU.IsEmpty() ) {
1397     return ;
1398   }
1399
1400   /* Here SU contains new edges to find new faces to suppress                                          */
1401   /* Define the list of faces of SU edges that aren't in faces of MSfacesSuppress in order to add into */
1402   /* For each edge we have a map of all its faces : it's in 'aMapEdgesFaces'                           */
1403   TopTools_MapOfShape MSfacesTmp ;
1404   for( int v=1; v<=SU.Length(); v++ ) {
1405     TopoDS_Shape E = SU.Value(v) ;
1406     TopoDS_Shape F ;
1407     TopTools_ListOfShape LF ;
1408     int ind = aMapEdgesFaces.FindIndex(E) ;
1409     
1410     /* LF is the list of faces for an edge of SU : may be empty no matter */
1411     LF = aMapEdgesFaces.FindFromIndex(ind) ;
1412     
1413     TopTools_ListIteratorOfListOfShape it ;
1414     for( it.Initialize(LF); it.More(); it.Next() ) {
1415       F = it.Value() ;
1416       if( withEndFace == false ) {
1417         if( F.IsSame(aFace) )
1418           THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHoleSubRoutine() : hole traversing or ?", SALOME::BAD_PARAM);
1419         if( !MSfacesSuppress.Contains(F) ) {
1420           MSfacesSuppress.Add(F) ;
1421           MSfacesTmp.Add(F) ; // Dont remove the 'if' !
1422         }
1423       }
1424       else { /* withEndFace == true */
1425         if( F.IsSame(aFace) && !F.IsSame(endFace) )
1426           THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHoleSubRoutine() : hole traversing incoherent ?", SALOME::BAD_PARAM);
1427         
1428         if( F.IsSame(endFace) ) {
1429           /* We have reached endFace if selection was correct so we add  */
1430           /* edge in a map to find later the corresponding endWire (hole */
1431           MSwireEndEdges.Add(E) ;
1432         }
1433         else {
1434           if( !MSfacesSuppress.Contains(F) ) {
1435             MSfacesSuppress.Add(F) ;
1436             MSfacesTmp.Add(F) ;
1437           }
1438         }
1439       }
1440     }
1441   }
1442   /* Call recursively this routine */
1443   SuppressHoleSubRoutine( mainShape, aFace, SSedgesOfWire, aMapEdgesFaces, MSfacesTmp, MSfacesSuppress, withEndFace, endFace, MSwireEndEdges ) ; 
1444 }
1445
1446
1447
1448 //================================================================================
1449 // function : GetShapeFromIndex()
1450 // purpose  : Find 'tds' a sub shape of 'aShape' according to 'aList' that contains
1451 //          : a unique index !
1452 //          : Warning : index must be setted with the same exploration logic !
1453 //          : So 'index' is calculated with no shape doublons !
1454 //================================================================================
1455 bool GEOM_Gen_i::GetShapeFromIndex( const TopoDS_Shape& aShape,
1456                                     const TopAbs_ShapeEnum aType, 
1457                                     const int index,
1458                                     TopoDS_Shape& tds )
1459
1460 {
1461   if (aShape.IsNull() || index < 1) 
1462     return false ;
1463   /* Indices start at 1 */
1464   int j = 1 ;
1465   bool found = false ;
1466   TopExp_Explorer exp ;
1467   TopTools_MapOfShape M;
1468   for( exp.Init( aShape, aType ); exp.More(); exp.Next() ) {
1469     if( M.Add(exp.Current()) ) { /* if not a doublon : we compare */
1470       if( index == j ) {
1471         tds =  exp.Current() ;
1472         return true ;
1473       }
1474       j++ ;
1475     }
1476   }
1477   return false ;
1478 }
1479
1480
1481
1482 //================================================================================
1483 // function : SuppressHolesInFaceOrShell()  Main method.
1484 // purpose  : Suppress holes identified by wires in a single face or shell
1485 //
1486 //================================================================================
1487 GEOM::GEOM_Shape_ptr GEOM_Gen_i::SuppressHolesInFaceOrShell( GEOM::GEOM_Shape_ptr shapeFaceShell,
1488                                                        const GEOM::GEOM_Shape::ListOfSubShapeID& ListIdWires )
1489   throw (SALOME::SALOME_Exception)
1490 {
1491   Unexpect aCatch(SALOME_SalomeException);
1492   GEOM::GEOM_Shape_var result;
1493
1494   if( ListIdWires.length() < 1 )
1495     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHolesInFace : no holes selected", SALOME::BAD_PARAM);
1496   
1497   const TopoDS_Shape tds = GetTopoShape(shapeFaceShell) ;
1498   if( tds.IsNull() || !IsValid(tds) )
1499     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHolesInFace() : non valid main argument", SALOME::BAD_PARAM);
1500   
1501   /* Create a map of wires/holes to suppress */
1502   TopTools_MapOfShape MapHoles ;
1503   for ( int i = 0; i < ListIdWires.length(); i++ ) {
1504     TopoDS_Shape W ;    
1505     if( !GetShapeFromIndex( tds, TopAbs_WIRE, ListIdWires[i], W ) )
1506       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHolesInFace() : bad index ?", SALOME::BAD_PARAM);
1507     MapHoles.Add( W ) ;
1508   }
1509
1510   /* Test if argument is a face or shell */
1511   bool isFace ;
1512   if( tds.ShapeType() == TopAbs_FACE )
1513     isFace = true ;
1514   else if ( tds.ShapeType() == TopAbs_SHELL )
1515     isFace = false ;
1516   else
1517     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHolesInFace() : not a face or a shell", SALOME::BAD_PARAM); 
1518
1519   /* Define two maps : all faces and faces to that will be modified */
1520   TopTools_MapOfShape MapFacesToModify ;
1521   TopTools_MapOfShape MapFacesAll ;
1522   TopExp_Explorer expF ;
1523   for( expF.Init( tds, TopAbs_FACE);  expF.More(); expF.Next() ) {
1524     TopoDS_Face F = TopoDS::Face( expF.Current() ) ;
1525     MapFacesAll.Add(F) ;
1526     TopExp_Explorer expW ;
1527     for( expW.Init( F, TopAbs_WIRE);  expW.More(); expW.Next() ) {
1528       TopoDS_Wire W = TopoDS::Wire( expW.Current() ) ;
1529       if( MapHoles.Contains(W) ) {
1530         MapFacesToModify.Add(F) ;
1531       }
1532     }
1533   }
1534
1535   /* Define faces not modified */
1536   TopTools_MapOfShape MapFacesNotModified ;
1537   TopTools_MapIteratorOfMapOfShape it ;
1538   for( it.Initialize(MapFacesAll); it.More(); it.Next() ) {
1539     TopoDS_Face FF = TopoDS::Face( it.Key() ) ;
1540     if( !MapFacesToModify.Contains(FF) )
1541       MapFacesNotModified.Add(FF) ;
1542   }
1543
1544   if( MapFacesToModify.IsEmpty() )
1545     THROW_SALOME_CORBA_EXCEPTION("Error : empty map of faces", SALOME::BAD_PARAM); 
1546   
1547   if( isFace && MapFacesToModify.Extent() != 1 )
1548     THROW_SALOME_CORBA_EXCEPTION("Incoherent", SALOME::BAD_PARAM);
1549   
1550   /* Main argument is a face */
1551   if( isFace && MapFacesToModify.Extent() == 1 ) {
1552     TopoDS_Face resultFace ;
1553     if( !RebuildFaceRemovingHoles( TopoDS::Face(tds), MapHoles, resultFace ) )
1554       THROW_SALOME_CORBA_EXCEPTION(" Problem : !RebuildFaceRemovingHoles()", SALOME::BAD_PARAM);
1555     /* Creation of CORBA object : face topology */
1556     result = CreateObject(resultFace);
1557     InsertInLabelOneArgument(tds, shapeFaceShell, resultFace, result, myCurrentOCAFDoc) ;
1558     return result ;
1559   }
1560
1561   /* Main argument is a shell : rebuild faces modified */
1562   TopTools_MapOfShape MapFacesModified ;
1563   for( it.Initialize(MapFacesToModify); it.More(); it.Next() ) {
1564     TopoDS_Face FF = TopoDS::Face( it.Key() ) ;
1565     TopoDS_Face resF ;
1566     if( !RebuildFaceRemovingHoles( FF, MapHoles, resF ) )
1567       THROW_SALOME_CORBA_EXCEPTION(" Problem shell : !RebuildFaceRemovingHoles()", SALOME::BAD_PARAM);
1568     MapFacesModified.Add(resF) ;
1569   }
1570
1571   /* Rebuild the shell with faces modified and non modified */
1572   TopoDS_Shell resultShell ;
1573   BRepPrim_Builder B;
1574   B.MakeShell(resultShell) ;
1575   TopTools_MapIteratorOfMapOfShape it1 ;
1576   for( it1.Initialize(MapFacesModified); it1.More(); it1.Next() )
1577     B.AddShellFace( resultShell,TopoDS::Face( it1.Key() ) ) ;
1578   for( it1.Initialize(MapFacesNotModified); it1.More(); it1.Next() )
1579     B.AddShellFace( resultShell,TopoDS::Face( it1.Key() ) ) ;
1580   
1581   B.CompleteShell(resultShell) ;
1582   
1583   if( resultShell.IsNull() )
1584     THROW_SALOME_CORBA_EXCEPTION("Null or not valid result Shell", SALOME::BAD_PARAM) ;
1585   
1586   /* Creation of CORBA object : shell topology */
1587   result = CreateObject(resultShell);
1588   InsertInLabelOneArgument(tds, shapeFaceShell, resultShell, result, myCurrentOCAFDoc) ;
1589   return result ;
1590 }
1591
1592
1593 //================================================================================
1594 // function : RebuildFaceRemovingHoles()
1595 // purpose  : Rebuild a face removing holes that are in 'mapHoles'.
1596 //          : NB : 'mapHoles' may content more holes than necessary
1597 //================================================================================
1598 bool GEOM_Gen_i::RebuildFaceRemovingHoles( const TopoDS_Face& aFace,
1599                                            const TopTools_MapOfShape& mapHoles,
1600                                            TopoDS_Shape& resultFace )
1601 {
1602   /* Get the outer wire of the face 'aFace' */
1603   TopoDS_Wire outW = BRepTools::OuterWire( aFace ) ;
1604   if( outW.IsNull() || !IsValid(outW) )
1605     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHolesInFace : bad outer wire of 'aFace'", SALOME::BAD_PARAM);
1606   
1607   /* Rebuild a face avoiding holes in the map 'mapHoles' */  
1608   Handle(Geom_Surface) Surface = BRep_Tool::Surface(aFace) ;
1609   TopoDS_Face F2 = BRepBuilderAPI_MakeFace( Surface, outW, true ) ;
1610   
1611   if( F2.Orientation() != aFace.Orientation() )
1612     F2.Orientation( aFace.Orientation() ) ;
1613   
1614   BRepBuilderAPI_MakeFace aBuilder( F2 ) ;
1615   bool foundAndKeepHoles = false ;
1616   TopExp_Explorer exp ;
1617   
1618   for( exp.Init( aFace, TopAbs_WIRE);  exp.More(); exp.Next() ) {
1619     TopoDS_Wire hole = TopoDS::Wire( exp.Current() ) ;
1620     if( !mapHoles.Contains(hole) && !exp.Current().IsEqual(outW) ) {
1621       aBuilder.Add( hole) ;      
1622       if( !aBuilder.IsDone() )
1623         THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHolesInFace : builder problem !", SALOME::BAD_PARAM);      
1624       
1625       resultFace = TopoDS::Face(aBuilder) ;
1626       foundAndKeepHoles = true ;
1627     }
1628   }
1629   
1630   if( !foundAndKeepHoles )
1631     resultFace = F2 ;
1632   else
1633     resultFace = TopoDS::Face(aBuilder) ;
1634   
1635   return true ;
1636 }
1637
1638
1639
1640
1641 //================================================================================
1642 // function : SuppressHole() Main method.
1643 // purpose  : Suppress an hole identified by a wire in a face of shape
1644 //          : ListIdFace contains a unique index of face in shape
1645 //          : ListIdWire contains a unique index of wire in face !!!
1646 //          : ListIdEndFace is used only when hole traverse.
1647 //================================================================================
1648 GEOM::GEOM_Shape_ptr GEOM_Gen_i::SuppressHole( GEOM::GEOM_Shape_ptr shape,
1649                                          const GEOM::GEOM_Shape::ListOfSubShapeID& ListIdFace,
1650                                          const GEOM::GEOM_Shape::ListOfSubShapeID& ListIdWire,
1651                                          const GEOM::GEOM_Shape::ListOfSubShapeID& ListIdEndFace )
1652   throw (SALOME::SALOME_Exception)
1653 {
1654   Unexpect aCatch(SALOME_SalomeException);
1655   GEOM::GEOM_Shape_var result;
1656   TopoDS_Face aFace ;
1657   TopoDS_Wire aWire ;  
1658   TopoDS_Face endFace ;
1659   bool withEndFace ;
1660   TopoDS_Shape tmp ;
1661   
1662   /* Retrieve 'aShape' the initial main shape selection */
1663   const TopoDS_Shape aShape = GetTopoShape(shape);
1664   
1665   if( !IsValid(aShape) )
1666     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHole() : non valid main shape", SALOME::BAD_PARAM);
1667   
1668   if( ListIdFace.length() != 1 || ListIdWire.length() != 1 )
1669     THROW_SALOME_CORBA_EXCEPTION("bad list", SALOME::BAD_PARAM);  
1670   
1671   /* Retrieve 'aFace' selection */
1672   if( !GetShapeFromIndex( aShape, TopAbs_FACE, ListIdFace[0], tmp ) ) {
1673     THROW_SALOME_CORBA_EXCEPTION("face not found", SALOME::BAD_PARAM);
1674   }
1675   else {
1676     aFace = TopoDS::Face(tmp) ;
1677   }
1678   if( !IsValid(aFace) )
1679     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHole() : face shape not valid", SALOME::BAD_PARAM);  
1680   
1681    /* Retrieve 'aWire' selection : Warning : index of wire refers to the face ! */
1682   TopoDS_Shape aTmp ;
1683   if( !GetShapeFromIndex( aFace, TopAbs_WIRE, ListIdWire[0], aTmp ) ) {
1684     THROW_SALOME_CORBA_EXCEPTION("wire not found", SALOME::BAD_PARAM);
1685   }
1686   else {
1687     aWire = TopoDS::Wire(aTmp) ;
1688   }
1689   if( !IsValid(aWire) )
1690     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHole() : bad wire" , SALOME::BAD_PARAM);
1691
1692   /* Get the outer wire of aFace */
1693   TopoDS_Wire outerW = BRepTools::OuterWire( aFace ) ;
1694   if( outerW.IsNull() || !IsValid(outerW) ) 
1695     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHole() : bad outer wire", SALOME::BAD_PARAM);
1696   
1697   /* Test bad user selection aWire */
1698   if( aWire.IsSame(outerW) )
1699     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHole() : outerW = aWire", SALOME::BAD_PARAM);
1700    
1701   /* Test if 'endFace' is used  as argument and seems to be a valid one          */
1702   /* NB : 'endFace' is optional and used when hole to suppress traverse 'aShape' */
1703   if( ListIdEndFace.length() == 0 ) {
1704     withEndFace = false ;
1705   }
1706   else {
1707     TopoDS_Shape aTemp ;
1708     if( !GetShapeFromIndex( aShape, TopAbs_FACE, ListIdEndFace[0], aTemp ) || tmp.IsNull() || !IsValid(aTemp) )
1709       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHole() : non valid endFace", SALOME::BAD_PARAM);
1710
1711     /* Test if 'endFace' as at least one hole */    
1712     endFace = TopoDS::Face(aTemp) ;  
1713
1714     TopExp_Explorer fExp ;
1715     int nbWires = 0 ;
1716     for( fExp.Init(endFace, TopAbs_WIRE);  fExp.More(); fExp.Next() ) {
1717       TopoDS_Wire W = TopoDS::Wire( fExp.Current() ) ;
1718       if( !W.IsNull() && IsValid(W) )
1719         nbWires++ ;
1720     }
1721     if(nbWires > 1)
1722       withEndFace = true ; /* at least 2 wires : outer wire plus an hole or more */
1723     else
1724       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHole() : end face selection ?", SALOME::BAD_PARAM);
1725   }
1726   
1727   /* Find edges of aWire and test if degenerated */
1728   TopTools_SequenceOfShape SSedgesOfWire ;
1729   TopExp_Explorer wireExp ;  
1730   for( wireExp.Init(aWire, TopAbs_EDGE);  wireExp.More(); wireExp.Next() ) {
1731     TopoDS_Edge E = TopoDS::Edge( wireExp.Current() ) ;
1732     if( E.IsNull() || BRep_Tool::Degenerated(E) ) {
1733       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SupressHole() : found bad edge", SALOME::BAD_PARAM);
1734     }
1735     else {
1736       SSedgesOfWire.Append( wireExp.Current() ) ;
1737     }
1738   }
1739   if( SSedgesOfWire.Length() < 1 )
1740     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SupressHole() : no edge(s) for aWire", SALOME::BAD_PARAM); 
1741   
1742   /* Retrieve face ancestors of all edges of 'aWire' but avoiding 'aFace' */ 
1743   
1744   TopTools_IndexedDataMapOfShapeListOfShape aMapEdgesFaces;
1745   TopTools_MapIteratorOfMapOfShape anIt ;
1746   TopTools_MapOfShape MFSuppress ;
1747   TopTools_MapOfShape MFSuppressTmp ;
1748   bool wireOnFace = false ;
1749  
1750   TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, aMapEdgesFaces) ;  
1751   for( int h=1; h<=SSedgesOfWire.Length(); h++ ) {
1752     
1753     TopoDS_Shape anEdgeOfWire = SSedgesOfWire.Value(h) ;
1754     int ind = aMapEdgesFaces.FindIndex(anEdgeOfWire) ;
1755     if(ind < 1)
1756       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SupressHole() : index of edge", SALOME::BAD_PARAM);
1757     
1758     TopTools_ListOfShape LF;
1759     LF = aMapEdgesFaces.FindFromIndex(ind) ; /* Contains all faces ancestors of an edge of wire */
1760     if( LF.IsEmpty() )
1761       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SupressHole() : no face for an edge", SALOME::BAD_PARAM);
1762     
1763     /* Filter faces avoiding 'aFace' */
1764     TopTools_ListIteratorOfListOfShape it ;
1765     for( it.Initialize(LF); it.More(); it.Next() ) {
1766       TopoDS_Face F = TopoDS::Face( it.Value() ) ;
1767       if( !F.IsSame(aFace) ) { 
1768         MFSuppressTmp.Add(F) ;
1769         MFSuppress.Add(F) ;
1770       }
1771       else {
1772         wireOnFace = true ;
1773       }
1774     }
1775   }
1776   
1777   if( !wireOnFace ) {
1778     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SupressHole() : wire not on selected face", SALOME::BAD_PARAM);  
1779   }
1780
1781   /* Call routine to define faces to suppress and and optional endWire on endFace */
1782   TopTools_MapOfShape MSwireEndEdges ; /* will contain edges of final wire (hole) */
1783   SuppressHoleSubRoutine( aShape, aFace, SSedgesOfWire, aMapEdgesFaces, MFSuppressTmp, MFSuppress, withEndFace, endFace, MSwireEndEdges ) ;
1784
1785   TopoDS_Wire endWire ;
1786   if( withEndFace ) {
1787     
1788     if( MSwireEndEdges.Extent() < 1 )
1789       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SupressHole() : MSwireEndEdges.Extent() < 1", SALOME::BAD_PARAM);
1790
1791     if( !FindCompareWireHoleOnFace( endFace, MSwireEndEdges, endWire ) )           
1792       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SupressHole() : no endWire found", SALOME::BAD_PARAM);    
1793    }
1794    
1795   /* Build 'resTds' : a shape containing a compound of faces */
1796   TopoDS_Shape resTds;
1797   if( !withEndFace && !BuildShapeHoleNotTraversing( aShape, aFace, aWire, MFSuppress, resTds ) )
1798     THROW_SALOME_CORBA_EXCEPTION("Rebuild result shape has aborted", SALOME::BAD_PARAM);
1799   
1800   if( withEndFace && !BuildShapeHoleTraversing( aShape, aFace, aWire, MFSuppress, endFace, endWire, resTds ) )
1801     THROW_SALOME_CORBA_EXCEPTION("Rebuild result shape has aborted (end hole)", SALOME::BAD_PARAM); 
1802   
1803   /* Reconstruction of final shape with 'resTds' : a compound of faces after hole suppressing */
1804   /* Actual limitation is : 'aShape' must not contain more than a solid or a shell !          */
1805   TopoDS_Shape finalShape ;
1806  
1807   TopExp_Explorer exp ;
1808   unsigned int nbSolid = 0 ;
1809   TopoDS_Solid aSolid ;
1810   for( exp.Init(aShape, TopAbs_SOLID); exp.More(); exp.Next() ) {
1811     aSolid = TopoDS::Solid( exp.Current() ) ;
1812     nbSolid++ ;
1813     if( nbSolid > 1 )
1814       THROW_SALOME_CORBA_EXCEPTION("Limitation : main shape contents more than one solid", SALOME::BAD_PARAM);  
1815   }
1816    
1817   unsigned int nbShell = 0 ;
1818   TopoDS_Shell aShell ;
1819   for( exp.Init(aShape, TopAbs_SHELL); exp.More(); exp.Next() ) {
1820     aShell = TopoDS::Shell( exp.Current() ) ;
1821     nbShell++ ;
1822     if( nbShell > 1 )
1823       THROW_SALOME_CORBA_EXCEPTION("Limitation : main shape contents more than one shell", SALOME::BAD_PARAM);
1824   }
1825   
1826   /* No shells and no solids : can send a compound even for a single face, see GUI ! */
1827   if( nbShell == 0 ) {
1828     finalShape = resTds ;
1829   }
1830   
1831   /* a shell */
1832   TopoDS_Shell shellResult ;
1833   if( nbShell == 1 ) {
1834     if ( !BuildShellWithFaceCompound( TopoDS::Compound(resTds), shellResult ) ) 
1835       THROW_SALOME_CORBA_EXCEPTION("Error after BuildShellWithFaceCompound()", SALOME::BAD_PARAM);
1836     finalShape = shellResult ;
1837   }
1838   
1839   /* a solid with a shell */
1840   if( nbSolid == 1 && nbShell == 1) {
1841     BRepBuilderAPI_MakeSolid B;
1842     B.Add(shellResult) ;
1843     if( !B.IsDone() )
1844       THROW_SALOME_CORBA_EXCEPTION("Error : !B.IsDone()", SALOME::BAD_PARAM);  
1845     finalShape = B.Solid() ;
1846   }
1847
1848   result = CreateObject(finalShape);
1849   InsertInLabelOneArgument(aShape, shape, finalShape, result, myCurrentOCAFDoc) ;
1850   return result ;
1851 }
1852
1853
1854
1855 //================================================================================
1856 // function : BuildShellWithFaceCompound()
1857 // purpose  : Build a shell with a compound of faces.
1858 //================================================================================
1859 bool GEOM_Gen_i::BuildShellWithFaceCompound( const TopoDS_Compound Comp,
1860                                              TopoDS_Shell& resultShell )
1861 {
1862   resultShell.Nullify() ;
1863   BRepPrim_Builder B ;
1864   B.MakeShell(resultShell) ;  
1865   TopExp_Explorer ex ;
1866   int i = 0 ;
1867   for( ex.Init( Comp, TopAbs_FACE); ex.More(); ex.Next() ) {
1868     TopoDS_Face F = TopoDS::Face( ex.Current() ) ;
1869     if( !IsValid(F) ) {
1870       return false ;
1871     }
1872     B.AddShellFace( resultShell, F ) ;
1873   }
1874   B.CompleteShell(resultShell) ;
1875   if( resultShell.IsNull() ) {
1876     return false ;
1877   }  
1878   return true ;
1879 }
1880
1881
1882 //================================================================================
1883 // function : FindCompareWireHoleOnFace()
1884 // purpose  : Try to find a wire on 'aFace' which edges are same than those
1885 //          : into 'MSwireEdges' map. 'aFoundWire' is defined and 'true' returned.
1886 //          : 'MSwireEdges' represents generally an hole an 'aFace'.
1887 //          : The outer wire of 'aFace' is avoided !
1888 //================================================================================
1889 bool GEOM_Gen_i::FindCompareWireHoleOnFace( const TopoDS_Face& F,
1890                                             const TopTools_MapOfShape& MSwireEdges,
1891                                             TopoDS_Wire& aFoundWire )
1892 {
1893   aFoundWire.Nullify() ;
1894   
1895   if( F.IsNull() )
1896     return false ;
1897   
1898   /* Get the outer wire of aFace */
1899   TopoDS_Wire outerW = BRepTools::OuterWire(F) ;
1900   if( outerW.IsNull() || !IsValid(outerW) ) {
1901     return false ;
1902   }
1903   
1904   int nbEdges = MSwireEdges.Extent() ;
1905   if( nbEdges < 1 ) {
1906     return false ;
1907   }
1908   
1909   TopExp_Explorer exp1 ;
1910   TopExp_Explorer exp2 ;
1911   for ( exp1.Init(F, TopAbs_WIRE) ; exp1.More(); exp1.Next() ) {
1912     TopoDS_Wire W = TopoDS::Wire( exp1.Current() ) ;
1913     int i = 0 ;
1914     if( !W.IsSame(outerW) ) {
1915       for ( exp2.Init( W, TopAbs_EDGE) ; exp2.More(); exp2.Next() ) {
1916         TopoDS_Edge E = TopoDS::Edge( exp2.Current() ) ;
1917         if( MSwireEdges.Contains(E) ) {
1918           i++ ;
1919           if( i == nbEdges ) {
1920             aFoundWire = W ;
1921             return true ;
1922           }
1923         }
1924       }
1925     }
1926   }
1927   return false ;
1928 }
1929
1930
1931 //================================================================================
1932 // function : BuildShapeHoleNotTraversing()
1933 // purpose  : Define 'resultTds' a reconstruction of 'aShape' after modification
1934 //          : on 'aFace' where 'aWire is removed' and suppression of faces 'MFSuppress'
1935 //          : ( Used as a sub routine of SuppressHole() )
1936 //================================================================================
1937 bool GEOM_Gen_i::BuildShapeHoleNotTraversing( const TopoDS_Shape& aShape,
1938                                               const TopoDS_Face& aFace,
1939                                               const TopoDS_Wire& aWire,
1940                                               const TopTools_MapOfShape& MFSuppress,
1941                                               TopoDS_Shape& resultTds )
1942   throw (SALOME::SALOME_Exception)
1943 {
1944   Unexpect aCatch(SALOME_SalomeException);
1945   BRep_Builder B;
1946   TopExp_Explorer exp ;
1947   TopoDS_Face newFace ;
1948   
1949   resultTds.Nullify() ;
1950   TopoDS_Compound Comp ;
1951   B.MakeCompound (Comp);
1952   
1953   try  {
1954     
1955     /* Explore all faces of 'aShape' to rebuild a compound */
1956     for ( exp.Init(aShape, TopAbs_FACE) ; exp.More(); exp.Next() ) {
1957       
1958       TopoDS_Face F1 = TopoDS::Face( exp.Current() );
1959       /* Rebuild face(s) not suppressed */
1960       if( !MFSuppress.Contains(F1) ) {
1961         
1962         if( F1.IsEqual( aFace ) ) {
1963           TopTools_MapOfShape MSwire ;
1964           MSwire.Add(aWire) ;
1965           if( !RebuildFaceRemovingHoles(aFace, MSwire, newFace) ) {
1966             return false ;
1967           }
1968           B.Add( Comp, newFace ) ;
1969         }
1970         else {
1971           /* For any other face not suppressed */
1972           B.Add( Comp, F1 ) ;
1973         }
1974       }
1975     }
1976   }
1977   catch(Standard_Failure) {
1978     THROW_SALOME_CORBA_EXCEPTION("in BuildShapeHoleNotTraversing() : Exception catched", SALOME::BAD_PARAM);
1979   }  
1980   resultTds = Comp ;
1981   return true ;
1982 }
1983
1984
1985
1986 //================================================================================
1987 // function : BuildShapeHoleTraversing()
1988 // purpose  : Define 'resultTds' a reconstruction of 'aShape' after modifications.
1989 //          : On 'aFace'    'aWire    is removed'
1990 //          : On 'endFace'  'endWire' is removed.
1991 //          : Faces of 'MFSuppress' are removed.
1992 //          : ( Used as a sub routine of SuppressHole() )
1993 //================================================================================
1994 bool GEOM_Gen_i::BuildShapeHoleTraversing( const TopoDS_Shape& aShape,
1995                                            const TopoDS_Face& aFace,
1996                                            const TopoDS_Wire& aWire,
1997                                            const TopTools_MapOfShape& MFSuppress,
1998                                            const TopoDS_Face& endFace,
1999                                            const TopoDS_Wire& endWire,
2000                                            TopoDS_Shape& resultTds )
2001   throw (SALOME::SALOME_Exception)
2002 {
2003   Unexpect aCatch(SALOME_SalomeException);
2004   BRep_Builder B;
2005   TopExp_Explorer exp ;
2006   TopoDS_Face newFace ;
2007
2008   resultTds.Nullify() ;
2009   TopoDS_Compound Comp ;
2010   B.MakeCompound (Comp);
2011   
2012   /* Necessary to use general method */
2013   TopTools_MapOfShape MSwire1  ;
2014   MSwire1.Add(aWire) ; 
2015   TopTools_MapOfShape MSwire2 ;
2016   MSwire2.Add(endWire) ;
2017
2018   try  {    
2019     
2020     /* Explore all faces of 'aShape' to rebuild a compound */
2021     for ( exp.Init(aShape, TopAbs_FACE) ; exp.More(); exp.Next() ) {
2022       TopoDS_Face F1 = TopoDS::Face( exp.Current() );      
2023       
2024       /* Rebuild face(s) not suppressed */
2025       if( !MFSuppress.Contains(F1) ) {
2026         
2027         /* Rebuild 'aFace' */
2028         if( F1.IsEqual( aFace ) && !F1.IsEqual( endFace ) ) {
2029           if( !RebuildFaceRemovingHoles(aFace, MSwire1, newFace) ) {
2030             return false ;
2031           }
2032           B.Add(Comp, newFace) ;
2033         }       
2034         
2035         /* Rebuild 'endFace' */
2036         if( !F1.IsEqual( aFace ) && F1.IsEqual( endFace ) ) {
2037           if( !RebuildFaceRemovingHoles(endFace, MSwire2, newFace) ) {
2038             return false ;
2039           }
2040           B.Add(Comp, newFace) ;
2041         }
2042         
2043         /* Hole in the same face : aFace = endFace */
2044         if( F1.IsEqual( aFace ) && F1.IsEqual( endFace ) ) {
2045           TopoDS_Face FF ;
2046           if( !RebuildFaceRemovingHoles(aFace, MSwire1, newFace) || !RebuildFaceRemovingHoles(newFace, MSwire2, FF) ) {
2047             return false ;
2048           }
2049           B.Add( Comp, FF ) ;
2050         }
2051         
2052         /* For any other face not suppressed */
2053         if( !F1.IsEqual(aFace) && !F1.IsEqual( endFace ) ) {      
2054           B.Add( Comp, F1 ) ;
2055         }
2056         
2057       }
2058     }
2059   }
2060   catch(Standard_Failure) {
2061     THROW_SALOME_CORBA_EXCEPTION("in BuildShapeHoleTraversing() : Exception catched", SALOME::BAD_PARAM);
2062   }  
2063   resultTds = Comp ;
2064   return true ;
2065 }
2066
2067 //=======================================================================
2068 //function : SortShapes
2069 //purpose  : 
2070 //=======================================================================
2071
2072 static void SortShapes(TopTools_ListOfShape& SL)
2073 {
2074   Standard_Integer MaxShapes = SL.Extent();
2075   TopTools_Array1OfShape  aShapes (1,MaxShapes);
2076   TColStd_Array1OfInteger OrderInd(1,MaxShapes);
2077   TColStd_Array1OfReal    MidXYZ  (1,MaxShapes); //X,Y,Z;
2078   TColStd_Array1OfReal    Length  (1,MaxShapes); //X,Y,Z;
2079   
2080   // Computing of CentreOfMass
2081   Standard_Integer Index;
2082   GProp_GProps GPr;
2083   gp_Pnt GPoint;
2084   TopTools_ListIteratorOfListOfShape it(SL);
2085   for (Index=1;  it.More();  Index++)
2086   {
2087     TopoDS_Shape S = it.Value();
2088     SL.Remove( it ); // == it.Next()
2089     aShapes(Index) = S;
2090     OrderInd.SetValue (Index, Index);
2091     if (S.ShapeType() == TopAbs_VERTEX)
2092     {
2093       GPoint = BRep_Tool::Pnt( TopoDS::Vertex( S ));
2094       Length.SetValue( Index, (Standard_Real) S.Orientation());
2095     }
2096     else
2097     {
2098       BRepGProp::LinearProperties (S, GPr);
2099       GPoint = GPr.CentreOfMass();
2100       Length.SetValue( Index, GPr.Mass() );
2101     }
2102     MidXYZ.SetValue(Index,
2103                     GPoint.X()*999 + GPoint.Y()*99 + GPoint.Z()*0.9);
2104   }
2105   // Sorting
2106   Standard_Integer aTemp;
2107   Standard_Boolean exchange, Sort = Standard_True;
2108   while (Sort)
2109   {
2110     Sort = Standard_False;
2111     for (Index=1; Index < MaxShapes; Index++)
2112     {
2113       if (MidXYZ(OrderInd(Index)) > MidXYZ(OrderInd(Index+1)))
2114         exchange = Standard_True;
2115       else if (MidXYZ(OrderInd(Index)) == MidXYZ(OrderInd(Index+1)) &&
2116                Length(OrderInd(Index)) >  Length(OrderInd(Index+1)) )
2117         exchange = Standard_True;
2118       else
2119         exchange = Standard_False;
2120       if (exchange)
2121       {
2122         aTemp = OrderInd(Index);
2123         OrderInd(Index) = OrderInd(Index+1);
2124         OrderInd(Index+1) = aTemp;
2125         Sort = Standard_True;
2126       }
2127     }
2128   }
2129   for (Index=1; Index <= MaxShapes; Index++)
2130     SL.Append( aShapes( OrderInd(Index) ));
2131 }
2132
2133 //================================================================================
2134 // function : SubShape()
2135 // purpose  : Method for GUI or TUI
2136 //================================================================================
2137
2138 GEOM::GEOM_Shape_ptr GEOM_Gen_i::SubShape(GEOM::GEOM_Shape_ptr shape,
2139                                           CORBA::Short ShapeType, 
2140                                           const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID)
2141      throw (SALOME::SALOME_Exception)
2142 {
2143   Unexpect aCatch(SALOME_SalomeException);
2144   return SubShapesOne(shape, (TopAbs_ShapeEnum) ShapeType, ListOfID);
2145 }
2146
2147 //================================================================================
2148 // function : SubShapeSorted()
2149 // purpose  : Method for GUI or TUI
2150 //================================================================================
2151
2152 GEOM::GEOM_Shape_ptr GEOM_Gen_i::SubShapeSorted(GEOM::GEOM_Shape_ptr shape,
2153                                                 CORBA::Short ShapeType, 
2154                                                 const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID)
2155      throw (SALOME::SALOME_Exception)
2156 {
2157   Unexpect aCatch(SALOME_SalomeException);
2158   return SubShapesOne(shape, (TopAbs_ShapeEnum) ShapeType, ListOfID, Standard_True);
2159 }
2160
2161 //================================================================================
2162 // function : SubShapesOne()
2163 // purpose  :
2164 //================================================================================
2165
2166 GEOM::GEOM_Shape_ptr GEOM_Gen_i::SubShapesOne( GEOM::GEOM_Shape_ptr shape,
2167                                               const TopAbs_ShapeEnum ShapeType, 
2168                                               const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID,
2169                                               const Standard_Boolean Sort)
2170   throw (SALOME::SALOME_Exception)
2171 {
2172   Unexpect aCatch(SALOME_SalomeException);
2173   GEOM::GEOM_Shape_var result;
2174   TopoDS_Shape mainShape;
2175   TopoDS_Shape mainTopo = GetTopoShape(shape);
2176
2177   bool main = false;
2178   while ( !main ) {
2179     if ( shape->IsMainShape() ) {
2180       mainShape = GetTopoShape(shape);
2181       main = true;
2182     } else
2183       shape = GetIORFromString( shape->MainName() );
2184   }
2185   
2186   if(ListOfID.length() < 1) {
2187     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::SubShape() : bad list of shapes",
2188                                  SALOME::BAD_PARAM);
2189   }
2190   
2191   /* Create a sequence of all sub shapes */
2192   TopTools_ListOfShape listShape;
2193
2194   TopTools_MapOfShape mapShape;
2195   TopExp_Explorer exp ;
2196   for ( exp.Init( mainShape, TopAbs_ShapeEnum(ShapeType)) ; exp.More(); exp.Next() ) {
2197     if ( mapShape.Add( exp.Current() ) )
2198       listShape.Append ( exp.Current() );
2199   }
2200
2201   if (listShape.IsEmpty()) return shape;
2202
2203   if (Sort)
2204     SortShapes(listShape);
2205
2206   TopTools_SequenceOfShape SS;
2207   TopTools_ListIteratorOfListOfShape it (listShape);
2208   for (; it.More(); it.Next())
2209     SS.Append( it.Value() );
2210
2211   TopoDS_Shape SubShape;
2212   if (ListOfID.length() == 1)
2213     SubShape = SS.Value(ListOfID[0]);
2214   else
2215   {
2216     BRep_Builder B;
2217     TopoDS_Compound Comp;
2218     B.MakeCompound (Comp);
2219     unsigned int ind;
2220     for ( ind = 0; ind < ListOfID.length(); ind++ )
2221       B.Add( Comp, SS.Value(ListOfID[ind]) );
2222     SubShape = Comp;
2223   }
2224
2225   if ( !TNaming_Tool::HasLabel( myCurrentOCAFDoc->Main(), SubShape ) ) 
2226     result = CreateSubObject( SubShape, shape, ListOfID);
2227   else {
2228     int TransDef;
2229     TDF_Label Lab = TNaming_Tool::Label( myCurrentOCAFDoc->Main(), SubShape, TransDef );
2230     Handle(TDataStd_Name) Att;
2231     if ( Lab.FindAttribute( TDataStd_Name::GetID(), Att ) ) {
2232       TCollection_AsciiString nameIOR( Att->Get() );
2233       result = GEOM::GEOM_Shape::_narrow(_orb->string_to_object( nameIOR.ToCString() ));
2234       if ( strcmp( result->MainName(), _orb->object_to_string(shape) ) != 0 ) {
2235         result = CreateSubObject( SubShape, shape, ListOfID);
2236       }
2237     }
2238   }
2239
2240   return result;
2241 }
2242
2243
2244 //================================================================================
2245 // function : SubShapeAll()
2246 // purpose  : Explode a shape in all sub shapes with a type (Method for TUI or GUI)
2247 //================================================================================
2248
2249 GEOM::GEOM_Gen::ListOfGeomShapes* GEOM_Gen_i::SubShapeAll(GEOM::GEOM_Shape_ptr shape,
2250                                                           CORBA::Short ShapeType)
2251      throw (SALOME::SALOME_Exception)
2252 {
2253   Unexpect aCatch(SALOME_SalomeException);
2254   return SubShapesAll(shape, (TopAbs_ShapeEnum) ShapeType);
2255 }
2256
2257 //================================================================================
2258 // function : SubShapeAllSorted()
2259 // purpose  : Explode a shape in all sub shapes with a type (Method for TUI or GUI)
2260 //================================================================================
2261
2262 GEOM::GEOM_Gen::ListOfGeomShapes* GEOM_Gen_i::SubShapeAllSorted(GEOM::GEOM_Shape_ptr shape,
2263                                                                 CORBA::Short ShapeType)
2264      throw (SALOME::SALOME_Exception)
2265 {
2266   Unexpect aCatch(SALOME_SalomeException);
2267   return SubShapesAll(shape, (TopAbs_ShapeEnum) ShapeType, Standard_True);
2268 }
2269
2270 //================================================================================
2271 // function : SubShapeAllSorted()
2272 // purpose  :
2273 //================================================================================
2274
2275 GEOM::GEOM_Gen::ListOfGeomShapes* GEOM_Gen_i::SubShapesAll(GEOM::GEOM_Shape_ptr shape,
2276                                                            const TopAbs_ShapeEnum ShapeType,
2277                                                            const Standard_Boolean Sort)
2278   throw (SALOME::SALOME_Exception)
2279 {
2280   /* List of sub shapes returned */
2281   Unexpect aCatch(SALOME_SalomeException);
2282   GEOM::GEOM_Gen::ListOfGeomShapes_var listOfGeomShapes = new GEOM::GEOM_Gen::ListOfGeomShapes;
2283   listOfGeomShapes->length(0) ;
2284   
2285   TopoDS_Shape mainTopo = GetTopoShape(shape);
2286   TopoDS_Shape mainShape;
2287   bool main = false;
2288   while ( !main ) {
2289     if ( shape->IsMainShape() ) {
2290       mainShape = GetTopoShape(shape);
2291       main = true;
2292     } else
2293       shape = GetIORFromString( shape->MainName() );
2294   }
2295
2296   if( mainTopo.IsNull() ) {
2297     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::SubShapeAll() : null main shape",
2298                                  SALOME::BAD_PARAM);
2299   }
2300   
2301   /* List/index : field set for any sub shape */
2302   GEOM::GEOM_Shape::ListOfSubShapeID_var ListOfID = new GEOM::GEOM_Shape::ListOfSubShapeID;
2303   ListOfID->length(1) ;
2304
2305     // retrieve all subshapes
2306   TopTools_MapOfShape mapShape;
2307   TopTools_ListOfShape listShape;
2308     
2309   if (mainTopo.ShapeType()==TopAbs_COMPOUND  &&  ShapeType==TopAbs_SHAPE)
2310   {
2311     TopoDS_Iterator It(mainTopo,Standard_True,Standard_True );  
2312     for ( ; It.More(); It.Next() ) 
2313       if (mapShape.Add( It.Value() ))
2314         listShape.Append( It.Value() );
2315   }
2316   else
2317   {
2318     TopExp_Explorer exp ( mainTopo, ShapeType);
2319     for ( ; exp.More(); exp.Next() ) 
2320       if (mapShape.Add( exp.Current() ))
2321         listShape.Append( exp.Current() );
2322   }
2323
2324   if (Sort)
2325     SortShapes(listShape);
2326     
2327   /* Create all sub shapes */
2328   int index;
2329   GEOM::GEOM_Shape_var result;
2330     
2331   TopTools_ListIteratorOfListOfShape itSub (listShape);
2332   for (index = 1; itSub.More(); itSub.Next(), ++index)
2333   {
2334     const TopoDS_Shape& SubShape = itSub.Value();
2335     // check if SubShape is already in OCAFDS and ...
2336     if ( TNaming_Tool::HasLabel( myCurrentOCAFDoc->Main(), SubShape ) )
2337     {
2338       int TransDef;
2339       TDF_Label Lab = TNaming_Tool::Label( myCurrentOCAFDoc->Main(), SubShape, TransDef );
2340       Handle(TDataStd_Name) Att;
2341       if ( Lab.FindAttribute( TDataStd_Name::GetID(), Att ) )
2342       {
2343         TCollection_AsciiString nameIOR( Att->Get() );
2344         result = GEOM::GEOM_Shape::_narrow(_orb->string_to_object( nameIOR.ToCString() ));
2345         // ... it is subshape of <shape>
2346         if ( strcmp( result->MainName(), _orb->object_to_string(shape) ) == 0 ) 
2347         {
2348           listOfGeomShapes->length(index) ;
2349           listOfGeomShapes[index-1] = result ;
2350           continue;
2351         }
2352       }
2353     }
2354
2355 //      if (Sort)
2356 //        ListOfID[0] = index;
2357 //      else
2358     ListOfID[0] = GetIndexTopology( SubShape, mainShape ) ;
2359     result = CreateSubObject( SubShape, shape, ListOfID);
2360     /* Add each sub shape in the list returned */
2361     listOfGeomShapes->length(index) ;
2362     listOfGeomShapes[index-1] = result ;      
2363   }
2364
2365   return listOfGeomShapes._retn() ;
2366 }
2367
2368 //=================================================================================
2369 // function : MakeBoolean()
2370 // purpose  : Boolean operation according to the type 'operation'
2371 //=================================================================================
2372 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeBoolean(GEOM::GEOM_Shape_ptr shape1,
2373                                              GEOM::GEOM_Shape_ptr shape2,
2374                                              CORBA::Long operation) 
2375   throw (SALOME::SALOME_Exception)
2376 {
2377   Unexpect aCatch(SALOME_SalomeException);
2378   GEOM::GEOM_Shape_var result;
2379   TopoDS_Shape shape ;
2380   TopoDS_Shape aShape1  ;
2381   TopoDS_Shape aShape2  ;
2382
2383   try {
2384     aShape1 = GetTopoShape(shape1) ;
2385     aShape2 = GetTopoShape(shape2) ;
2386     
2387     if( aShape1.IsNull() || aShape2.IsNull() ) {
2388       THROW_SALOME_CORBA_EXCEPTION("Boolean aborted : argument shape is null", SALOME::BAD_PARAM);
2389     }
2390     
2391     switch (operation)
2392       {
2393       case 1 :   /* Common */
2394         shape = BRepAlgoAPI_Common(aShape1, aShape2).Shape();
2395         break ;
2396       case 2 :   /* Cut */
2397         shape = BRepAlgoAPI_Cut(aShape1, aShape2).Shape();
2398         break ;
2399       case 3 :   /* Fuse */
2400         shape = BRepAlgoAPI_Fuse(aShape1, aShape2).Shape();
2401         break ;
2402       case 4 :   /* Section */
2403         shape = BRepAlgoAPI_Section(aShape1, aShape2).Shape();
2404         break ;
2405       default :
2406         MESSAGE("Boolean operation not known : " << operation ) ;
2407         return result ;
2408       }
2409   }
2410   catch(Standard_Failure) {
2411     THROW_SALOME_CORBA_EXCEPTION("Exception catched in boolean operation", SALOME::BAD_PARAM);
2412   }
2413     
2414   /* We test the validity of resulting shape */
2415   if( !IsValid(shape) ) {
2416     THROW_SALOME_CORBA_EXCEPTION("Boolean aborted : non valid shape result", SALOME::BAD_PARAM);
2417   }
2418         
2419   result = CreateObject(shape) ;
2420       
2421   /* put shape and name into geom/OCAF doc */
2422   GEOMDS_Commands GC(myCurrentOCAFDoc->Main());
2423   /* add attributs 'shape' and' name_io'r in a new label */
2424   TDF_Label Lab = GC.Generated(aShape1, shape, result->Name() );
2425   TCollection_AsciiString entry;
2426   TDF_Tool::Entry(Lab, entry);
2427   result->ShapeId( entry.ToCString() ) ;
2428       
2429   /* Create a new label */
2430   TDF_Label NewLab = Lab.NewChild();
2431   TCollection_ExtendedString Value("Arguments");
2432   TDataStd_Name::Set(NewLab,Value);
2433   
2434   TDF_Label NewLab1 = NewLab.NewChild();
2435   TDF_Label RefLab;
2436   TDF_Tool::Label(myCurrentOCAFDoc->GetData(), shape1->ShapeId(), RefLab);
2437   TDF_Reference::Set(NewLab1, RefLab);
2438   
2439   TDF_Label NewLab2 = NewLab.NewChild();
2440   TDF_Tool::Label(myCurrentOCAFDoc->GetData(), shape2->ShapeId(), RefLab);
2441   TDF_Reference::Set(NewLab2, RefLab);
2442   return result ;
2443 }
2444
2445
2446 //=================================================================================
2447 // function : MakeFuse()
2448 // purpose  : Special purpose !
2449 //=================================================================================
2450 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeFuse(GEOM::GEOM_Shape_ptr shape1,
2451                                     GEOM::GEOM_Shape_ptr shape2)
2452   throw (SALOME::SALOME_Exception)
2453 {
2454   Unexpect aCatch(SALOME_SalomeException);
2455   GEOM::GEOM_Shape_var result;
2456   TopoDS_Shape aShape1 = GetTopoShape(shape1) ;
2457   TopoDS_Shape aShape2 = GetTopoShape(shape2) ;
2458   if( aShape1.IsNull() || aShape2.IsNull() ) {
2459     THROW_SALOME_CORBA_EXCEPTION("Fuse aborted : shape in argument is null", SALOME::BAD_PARAM);
2460   }
2461   TopoDS_Shape shape;
2462   try {
2463     shape  = BRepAlgoAPI_Fuse(aShape1, aShape2).Shape();
2464   }
2465   catch(Standard_Failure) {
2466     THROW_SALOME_CORBA_EXCEPTION("Exception catched in Fuse operation", SALOME::BAD_PARAM);
2467   }
2468
2469   /* We test the validity of resulting shape */
2470   if( !IsValid(shape) ) {
2471     THROW_SALOME_CORBA_EXCEPTION("Fuse aborted : non valid shape result", SALOME::BAD_PARAM);
2472   }
2473
2474   result = CreateObject(shape) ;
2475
2476   /* put shape and name into geom/OCAF doc */
2477   GEOMDS_Commands GC(myCurrentOCAFDoc->Main());
2478   /* add attributs 'shape' and' name_io'r in a new label */
2479   TDF_Label Lab = GC.Generated(aShape1, shape, result->Name() );
2480   TCollection_AsciiString entry;
2481   TDF_Tool::Entry(Lab, entry);
2482   result->ShapeId( entry.ToCString() ) ;
2483
2484   /* Create a new label */
2485   TDF_Label NewLab = Lab.NewChild();
2486   TCollection_ExtendedString Value("Arguments");
2487   TDataStd_Name::Set(NewLab,Value);
2488
2489   TDF_Label NewLab1 = NewLab.NewChild();
2490   TDF_Label RefLab;
2491   TDF_Tool::Label(myCurrentOCAFDoc->GetData(), shape1->ShapeId(), RefLab);
2492   TDF_Reference::Set(NewLab1, RefLab);
2493
2494   TDF_Label NewLab2 = NewLab.NewChild();
2495   TDF_Tool::Label(myCurrentOCAFDoc->GetData(), shape2->ShapeId(), RefLab);
2496   TDF_Reference::Set(NewLab2, RefLab);
2497   return result ;
2498 }
2499
2500
2501 //================================================================================
2502 // function : MakeAxisStruct()
2503 // purpose  : Create a structure GEOM::AxisStruct (see IDL file)
2504 //================================================================================
2505 GEOM::AxisStruct GEOM_Gen_i::MakeAxisStruct(CORBA::Double x,
2506                                       CORBA::Double y,
2507                                       CORBA::Double z,
2508                                       CORBA::Double vx,
2509                                       CORBA::Double vy,
2510                                       CORBA::Double vz) 
2511 {
2512   GEOM::AxisStruct A ;
2513   A.x  = x ;   A.y  = y ;   A.z  = z ;
2514   A.vx = vx ;  A.vy = vy ;  A.vz = vz ;
2515   return A ;
2516 }
2517
2518
2519 //================================================================================
2520 // function : MakePointStruct()
2521 // purpose  : Create a structure GEOM::PointStruct (see IDL file)
2522 //================================================================================
2523 GEOM::PointStruct GEOM_Gen_i::MakePointStruct(CORBA::Double x,
2524                                         CORBA::Double y,
2525                                         CORBA::Double z)
2526 {
2527   beginService( "GEOM_Gen_i::MakePointStruct" );
2528   GEOM::PointStruct p ;
2529   p.x = x ;   p.y = y ;   p.z = z ;
2530   endService( "GEOM_Gen_i::MakePointStruct" );
2531   return p ;
2532 }
2533
2534 //================================================================================
2535 // function : MakeDirection()
2536 // purpose  : Create a structure GEOM::DirStruct (see IDL file)
2537 //================================================================================
2538 GEOM::DirStruct GEOM_Gen_i::MakeDirection(const GEOM::PointStruct& p)
2539
2540   GEOM::DirStruct d ;
2541   d.PS.x = p.x ;  d.PS.y = p.y ;  d.PS.z = p.z ;
2542   return d ;
2543 }
2544
2545 //=================================================================================
2546 // function : MakeBox()
2547 // purpose  : Create a box topology.
2548 //=================================================================================
2549 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeBox(CORBA::Double x1,
2550                                          CORBA::Double y1,
2551                                          CORBA::Double z1,
2552                                          CORBA::Double x2,
2553                                          CORBA::Double y2,
2554                                          CORBA::Double z2) 
2555      throw (SALOME::SALOME_Exception)
2556 {
2557   Unexpect aCatch(SALOME_SalomeException);
2558   gp_Pnt P1(x1,y1,z1);
2559   gp_Pnt P2(x2,y2,z2);
2560   GEOM::GEOM_Shape_var result ;
2561   TopoDS_Shape tds ;
2562   try {
2563     tds = BRepPrimAPI_MakeBox(P1,P2).Shape();
2564   }
2565   catch(Standard_Failure) {
2566     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeBox", SALOME::BAD_PARAM);
2567   }
2568
2569   if (tds.IsNull()) {
2570     THROW_SALOME_CORBA_EXCEPTION("Make Box aborted : null shape", SALOME::BAD_PARAM);
2571   } 
2572
2573   result = CreateObject(tds);
2574   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
2575   result->ShapeId(entry) ;
2576   return result;  
2577 }
2578
2579
2580 //================================================================================
2581 // function : MakeCylinder
2582 // purpose  : Create a cylinder topology
2583 //================================================================================
2584 GEOM::GEOM_Shape_ptr  GEOM_Gen_i::MakeCylinder(const GEOM::PointStruct& pstruct,
2585                                                const GEOM::DirStruct& dstruct,
2586                                                CORBA::Double radius,
2587                                                CORBA::Double height) 
2588   throw (SALOME::SALOME_Exception)
2589 {
2590   Unexpect aCatch(SALOME_SalomeException);
2591   GEOM::GEOM_Shape_var result;
2592   TopoDS_Shape tds ;
2593   gp_Pnt p(pstruct.x, pstruct.y, pstruct.z) ;
2594   gp_Dir d(dstruct.PS.x, dstruct.PS.y, dstruct.PS.z) ;
2595   gp_Ax2 axis(p, d) ;
2596
2597   try {
2598     tds = BRepPrimAPI_MakeCylinder(axis, radius, height).Shape();
2599   }
2600   catch(Standard_Failure) {
2601     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeCylinder", SALOME::BAD_PARAM);
2602   }
2603   
2604   if (tds.IsNull()) {
2605     THROW_SALOME_CORBA_EXCEPTION("Make Cylinder aborted", SALOME::BAD_PARAM);
2606   } 
2607   result = CreateObject(tds);
2608   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
2609   result->ShapeId(entry);
2610   return result ;  
2611 }
2612
2613 //================================================================================
2614 // function : MakeSphere()
2615 // purpose  : Make a sphere topology
2616 //================================================================================
2617 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeSphere(CORBA::Double x1,
2618                                       CORBA::Double y1,
2619                                       CORBA::Double z1,
2620                                       CORBA::Double radius) 
2621   throw (SALOME::SALOME_Exception)
2622 {
2623   Unexpect aCatch(SALOME_SalomeException);
2624   GEOM::GEOM_Shape_var result ;
2625   TopoDS_Shape tds ;
2626   try {
2627     tds = BRepPrimAPI_MakeSphere(gp_Pnt(x1,y1,z1), radius).Shape();
2628   }
2629   catch(Standard_Failure) {
2630     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeSphere", SALOME::BAD_PARAM);
2631   }
2632   
2633   if (tds.IsNull()) {
2634     THROW_SALOME_CORBA_EXCEPTION("Make Sphere aborted", SALOME::BAD_PARAM);
2635   } 
2636   result = CreateObject(tds) ;  
2637   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
2638   result->ShapeId(entry);
2639   return result;  
2640 }
2641
2642 //================================================================================
2643 // function : MakeTorus()
2644 // purpose  : Create a torus topology
2645 //================================================================================
2646 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeTorus( const GEOM::PointStruct& pstruct,
2647                                       const GEOM::DirStruct& dstruct,
2648                                       CORBA::Double major_radius,
2649                                       CORBA::Double minor_radius )
2650   throw (SALOME::SALOME_Exception)
2651 {
2652   Unexpect aCatch(SALOME_SalomeException);
2653   GEOM::GEOM_Shape_var result;
2654   TopoDS_Shape tds ;
2655   gp_Pnt p(pstruct.x, pstruct.y, pstruct.z) ;
2656   gp_Dir d(dstruct.PS.x, dstruct.PS.y, dstruct.PS.z) ;
2657   gp_Ax2 axis(p, d) ;
2658
2659   try {
2660   tds = BRepPrimAPI_MakeTorus(axis, major_radius, minor_radius).Shape();
2661   }
2662   catch(Standard_Failure) {
2663     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeTorus", SALOME::BAD_PARAM);
2664   }
2665
2666   if (tds.IsNull()) {
2667     THROW_SALOME_CORBA_EXCEPTION("Make torus aborted", SALOME::BAD_PARAM);
2668   }
2669   result = CreateObject(tds);
2670   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
2671   result->ShapeId(entry);
2672   return result ;
2673 }
2674
2675
2676 //================================================================================
2677 // function : MakeCone()
2678 // purpose  : Create a cone topology
2679 //================================================================================
2680 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeCone(const GEOM::PointStruct& pstruct,
2681                                     const GEOM::DirStruct& dstruct,
2682                                     CORBA::Double radius1,
2683                                     CORBA::Double radius2,
2684                                     CORBA::Double height)
2685   throw (SALOME::SALOME_Exception)
2686 {
2687   Unexpect aCatch(SALOME_SalomeException);
2688   GEOM::GEOM_Shape_var result;
2689   TopoDS_Shape tds ;
2690   gp_Pnt p(pstruct.x, pstruct.y, pstruct.z) ;
2691   gp_Dir d(dstruct.PS.x, dstruct.PS.y, dstruct.PS.z) ;
2692   gp_Ax2 axis(p, d) ;
2693   
2694   try {
2695     /* Cone doesn't work if same radius */
2696     if( fabs(radius1-radius2) <= Precision::Confusion() ) {
2697       tds = BRepPrimAPI_MakeCylinder(axis, (radius1+radius2)/2.0, height).Shape();
2698     }
2699     else {
2700       tds = BRepPrimAPI_MakeCone(axis, radius1, radius2, height).Shape();
2701     }
2702   }
2703   catch(Standard_Failure) {
2704     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeCone", SALOME::BAD_PARAM);
2705   }
2706
2707   if (tds.IsNull()) {
2708     THROW_SALOME_CORBA_EXCEPTION("Make Cone aborted", SALOME::BAD_PARAM);
2709   }
2710   result = CreateObject(tds);
2711   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
2712   result->ShapeId(entry);
2713   return result ;
2714 }
2715
2716
2717
2718 //==================================================================================
2719 // function : ImportIGES()
2720 // purpose  : Import shape from an IGES (IGS) file
2721 //          : LPN modified 7 mai 2002
2722 //==================================================================================
2723 GEOM::GEOM_Shape_ptr GEOM_Gen_i::ImportIGES(const char* filename)
2724   throw (SALOME::SALOME_Exception)
2725 {
2726   Unexpect aCatch(SALOME_SalomeException);
2727   GEOM::GEOM_Shape_var result ;
2728   //VRV: OCC 4.0 migration
2729   IGESControl_Reader aReader;  
2730   //VRV: OCC 4.0 migration
2731   try {
2732     IFSelect_ReturnStatus stat = aReader.ReadFile((char*)filename);
2733     if ( stat != IFSelect_RetDone ) {
2734       THROW_SALOME_CORBA_EXCEPTION("Error in reading import file", SALOME::BAD_PARAM);    }
2735     
2736     MESSAGE("ImportIGES : all Geometry Transfer" << endl ) ;
2737 #if OCC_VERSION_MAJOR >= 5
2738     aReader.ClearShapes();
2739     aReader.TransferRoots();
2740 #else
2741     aReader.Clear();
2742     aReader.TransferRoots(false);
2743 #endif
2744     MESSAGE("ImportIGES : count of shapes produced = " << aReader.NbShapes() << endl );    
2745     TopoDS_Shape shape = aReader.OneShape();
2746
2747     if ( !shape.IsNull() ) {      
2748       /* Final CORBA object creation */
2749       result = CreateObject(shape) ;
2750       const char *entry = InsertInLabel( shape, result->Name(), myCurrentOCAFDoc ) ;
2751       result->ShapeId(entry);
2752       return result ;
2753     }
2754   }
2755   catch(Standard_Failure) {
2756     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ImportIGES()", SALOME::BAD_PARAM);
2757   } 
2758   
2759   THROW_SALOME_CORBA_EXCEPTION("Import IGES aborted : internal error", SALOME::BAD_PARAM);
2760 }
2761
2762
2763
2764 //==================================================================================
2765 // function : ImportSTEP()
2766 // purpose  : Import shape from an STEP (stp) file
2767 //          : 'result' is a compound of shapes if file contains more entities.
2768 //==================================================================================
2769 GEOM::GEOM_Shape_ptr GEOM_Gen_i::ImportSTEP(const char* filename)
2770   throw (SALOME::SALOME_Exception)
2771 {
2772   Unexpect aCatch(SALOME_SalomeException);
2773   GEOM::GEOM_Shape_var result ;
2774   //VRV: OCC 4.0 migration
2775   STEPControl_Reader aReader;
2776   //VRV: OCC 4.0 migration
2777
2778   TopoDS_Compound compound;
2779   BRep_Builder B;
2780   B.MakeCompound( compound );
2781   
2782   try {
2783     IFSelect_ReturnStatus status = aReader.ReadFile((char*)filename);
2784     
2785     if (status == IFSelect_RetDone) {
2786       Standard_Boolean failsonly = Standard_False ;
2787       aReader.PrintCheckLoad (failsonly, IFSelect_ItemsByEntity);
2788       /* Root transfers */
2789       Standard_Integer nbr = aReader.NbRootsForTransfer();
2790       aReader.PrintCheckTransfer (failsonly, IFSelect_ItemsByEntity);
2791       
2792       for ( Standard_Integer n=1; n <= nbr; n++) {
2793         
2794         Standard_Boolean ok = aReader.TransferRoot(n);
2795         /* Collecting resulting entities */
2796         Standard_Integer nbs = aReader.NbShapes();
2797         if (nbs == 0)
2798           THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM) ;      
2799         
2800         for ( Standard_Integer i=1; i<=nbs; i++ ) {       
2801           TopoDS_Shape aShape = aReader.Shape(i);
2802           if ( aShape.IsNull() )
2803             THROW_SALOME_CORBA_EXCEPTION("Null shape in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM) ;   
2804           
2805           /* For a single entity */
2806           if(nbr == 1 && nbs == 1) {      
2807             result = CreateObject(aShape) ;
2808             const char *entry = InsertInLabel(aShape, result->Name(), myCurrentOCAFDoc) ;
2809             result->ShapeId(entry);
2810             return result ;
2811           }
2812           else {
2813             B.Add( compound, aShape ) ;
2814           }
2815         }
2816       }
2817
2818      TopoDS_Shape tds = compound ; 
2819      result = CreateObject(tds) ;
2820      if( CORBA::is_nil(result) )
2821        THROW_SALOME_CORBA_EXCEPTION("Translation aborted : null result", SALOME::BAD_PARAM);
2822      const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
2823      result->ShapeId(entry);
2824      return result ;
2825     }
2826     
2827   }
2828   catch(Standard_Failure) {
2829     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM);
2830   }  
2831   return result ;
2832 }
2833
2834
2835 //==================================================================================
2836 // function : Partition()
2837 // purpose  :
2838 //==================================================================================
2839
2840 GEOM::GEOM_Shape_ptr
2841   GEOM_Gen_i::Partition(const GEOM::GEOM_Gen::ListOfIOR& ListShapes, 
2842                         const GEOM::GEOM_Gen::ListOfIOR& ListTools,
2843                         const GEOM::GEOM_Gen::ListOfIOR& ListKeepInside,
2844                         const GEOM::GEOM_Gen::ListOfIOR& ListRemoveInside,
2845                         const CORBA::Short               Limit)
2846 throw (SALOME::SALOME_Exception)
2847 {
2848   Unexpect aCatch(SALOME_SalomeException);
2849   GEOM::GEOM_Shape_var aResult;  
2850   TopoDS_Shape tds ;
2851   //MESSAGE ("In Partition");
2852   try {
2853
2854     unsigned int ind, nbshapes = 0;
2855     nbshapes += ListShapes.length() + ListTools.length();
2856     nbshapes += ListKeepInside.length() + ListRemoveInside.length();
2857     
2858     Partition_Spliter PS;
2859     TopTools_MapOfShape ShapesMap(nbshapes), ToolsMap(nbshapes);
2860     
2861     // add object shapes that are in ListShapes;
2862     for ( ind = 0; ind < ListShapes.length(); ind++) {
2863       
2864       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[ind] );
2865       TopoDS_Shape Shape = GetTopoShape(aShape);
2866       if(Shape.IsNull() ) {
2867         //MESSAGE ( "In Partition a shape is null" );
2868         THROW_SALOME_CORBA_EXCEPTION("In Partition a shape is null", SALOME::BAD_PARAM);
2869       }
2870       if ( ShapesMap.Add( Shape ))
2871         PS.AddShape(Shape);
2872     }
2873     
2874     // add tool shapes that are in ListTools and not in ListShapes;
2875     for (ind = 0; ind < ListTools.length(); ind++) {
2876       
2877       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListTools[ind] );
2878       TopoDS_Shape Shape = GetTopoShape(aShape);
2879       if(Shape.IsNull() ) {
2880         THROW_SALOME_CORBA_EXCEPTION("In Partition a shape is null", SALOME::BAD_PARAM);
2881       }
2882       if ( !ShapesMap.Contains( Shape ) && ToolsMap.Add( Shape ))
2883         PS.AddTool(Shape);
2884     }
2885     
2886     // add shapes that are in ListKeepInside, as object shapes;
2887     for (ind = 0; ind < ListKeepInside.length(); ind++) {
2888       
2889       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListKeepInside[ind] );
2890       TopoDS_Shape Shape = GetTopoShape(aShape);
2891       if(Shape.IsNull() ) {
2892         //MESSAGE ( "In Partition a Keep Inside shape is null" );
2893         THROW_SALOME_CORBA_EXCEPTION("In Partition a shape is null", SALOME::BAD_PARAM);
2894       }
2895       if (!ToolsMap.Contains( Shape ) &&
2896           ShapesMap.Add( Shape ))
2897         PS.AddShape(Shape);
2898     }
2899     
2900     // add shapes that are in ListRemoveInside, as object shapes;
2901     for (ind = 0; ind < ListRemoveInside.length(); ind++) {
2902       
2903       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListRemoveInside[ind] );
2904       TopoDS_Shape Shape = GetTopoShape(aShape);
2905       if(Shape.IsNull() ) {
2906         //MESSAGE ( "In Partition a Remove Inside shape is null" );
2907         THROW_SALOME_CORBA_EXCEPTION("In Partition a shape is null", SALOME::BAD_PARAM);
2908       }
2909       if (!ToolsMap.Contains( Shape ) &&
2910           ShapesMap.Add( Shape ) )
2911         PS.AddShape(Shape);
2912     }
2913     
2914     //MESSAGE ( "Partition::Compute() " );
2915     PS.Compute ((TopAbs_ShapeEnum) Limit);
2916     //MESSAGE ( "Partition::Compute() - END" );
2917
2918     // suppress result outside of shapes in KInsideMap
2919     for (ind = 0; ind < ListKeepInside.length(); ind++) {
2920       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListKeepInside[ind] );
2921       TopoDS_Shape Shape = GetTopoShape(aShape);
2922       PS.KeepShapesInside( Shape );
2923     }
2924     
2925     // suppress result inside of shapes in RInsideMap
2926     for (ind = 0; ind < ListRemoveInside.length(); ind++) {
2927       
2928       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListRemoveInside[ind] );
2929       TopoDS_Shape Shape = GetTopoShape(aShape);
2930       PS.RemoveShapesInside( Shape );
2931     }
2932     
2933     tds = PS.Shape();
2934     
2935     if( !IsValid(tds) ) {
2936       //MESSAGE ( "In Partition: non valid shape result" );
2937       THROW_SALOME_CORBA_EXCEPTION("Partition aborted : non valid shape result", SALOME::BAD_PARAM);
2938     }
2939   }
2940   catch (Standard_Failure) {
2941     //MESSAGE ( "In Partition: Exception catched in GEOM_Gen_i::Partition()" );
2942     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::Partition", SALOME::BAD_PARAM);
2943   }
2944   
2945   aResult = CreateObject(tds) ;
2946
2947   /* add attributs S and mystr in a new label */
2948   GEOMDS_Commands GC(myCurrentOCAFDoc->Main());
2949   TDF_Label Lab = GC.AddShape(tds, aResult->Name() );
2950   TCollection_AsciiString entry;
2951   TDF_Tool::Entry(Lab,entry);
2952   aResult->ShapeId( entry.ToCString() ) ;
2953   
2954   // add arguments
2955   
2956   /* Create a new label */
2957   TDF_Label NewLab = Lab.NewChild();
2958   TCollection_ExtendedString Value("Arguments");
2959   TDataStd_Name::Set(NewLab,Value);
2960
2961   // object shapes
2962   for (unsigned int ind = 0; ind < ListShapes.length(); ind++) {
2963     TDF_Label NewLab1 = NewLab.NewChild();
2964     
2965     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[ind] );
2966     Standard_CString anEntry = aShape->ShapeId();
2967     TDF_Label RefLab;
2968     TDF_Tool::Label(myCurrentOCAFDoc->GetData(), anEntry, RefLab);
2969     TDF_Reference::Set(NewLab1,RefLab);
2970   }
2971   // tool shapes
2972   for (unsigned int ind = 0; ind < ListTools.length(); ind++) {
2973     TDF_Label NewLab1 = NewLab.NewChild();
2974     
2975     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListTools[ind] );
2976     Standard_CString anEntry = aShape->ShapeId();
2977     TDF_Label RefLab;
2978     TDF_Tool::Label(myCurrentOCAFDoc->GetData(), anEntry, RefLab);
2979     TDF_Reference::Set(NewLab1,RefLab);
2980   }
2981   // limit shapes 1
2982   for (unsigned int ind = 0; ind < ListKeepInside.length(); ind++) {
2983     TDF_Label NewLab1 = NewLab.NewChild();
2984     
2985     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListKeepInside[ind] );
2986     Standard_CString anEntry = aShape->ShapeId();
2987     TDF_Label RefLab;
2988     TDF_Tool::Label(myCurrentOCAFDoc->GetData(), anEntry, RefLab);
2989     TDF_Reference::Set(NewLab1,RefLab);
2990   }
2991   // limit shapes 2
2992   for (unsigned int ind = 0; ind < ListRemoveInside.length(); ind++) {
2993     TDF_Label NewLab1 = NewLab.NewChild();
2994     
2995     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListRemoveInside[ind] );
2996     Standard_CString anEntry = aShape->ShapeId();
2997     TDF_Label RefLab;
2998     TDF_Tool::Label(myCurrentOCAFDoc->GetData(), anEntry, RefLab);
2999     TDF_Reference::Set(NewLab1,RefLab);
3000   }
3001   
3002   return aResult;    
3003 }
3004
3005
3006
3007 //==================================================================================
3008 // function : MakeFilling()
3009 // purpose  : Create a surface from section curves filling
3010 //==================================================================================
3011 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeFilling(GEOM::GEOM_Shape_ptr myShape,
3012                                        CORBA::Short mindeg,
3013                                        CORBA::Short maxdeg,
3014                                        CORBA::Double tol3d,
3015                                        CORBA::Double tol2d,
3016                                        CORBA::Short nbiter,
3017                                        CORBA::Boolean theApprox)
3018   throw (SALOME::SALOME_Exception)
3019 {
3020   Unexpect aCatch(SALOME_SalomeException);
3021   GEOM::GEOM_Shape_var result ;
3022   TopoDS_Face tds ;
3023   TopoDS_Shape aShape = GetTopoShape(myShape) ;
3024   if( aShape.IsNull() || aShape.ShapeType() != TopAbs_COMPOUND ) {
3025     THROW_SALOME_CORBA_EXCEPTION("MakeFilling aborted : null shape or not a compound", SALOME::BAD_PARAM);
3026   } 
3027
3028   try {
3029     /* we verify the contents of the shape */
3030     TopExp_Explorer Ex ;
3031     TopoDS_Shape Scurrent ;     
3032     Standard_Real First, Last ;
3033     Handle(Geom_Curve) C ;
3034     GeomFill_SectionGenerator Section ;
3035     
3036     Standard_Integer i = 0 ;
3037     for(Ex.Init(aShape, TopAbs_EDGE); Ex.More(); Ex.Next()) {
3038       Scurrent = Ex.Current() ;
3039       if( Scurrent.IsNull() || Scurrent.ShapeType() != TopAbs_EDGE)  {
3040         THROW_SALOME_CORBA_EXCEPTION("Initial shape doesn't contain only edges !", SALOME::BAD_PARAM);
3041       }
3042       C = BRep_Tool::Curve(TopoDS::Edge(Scurrent), First, Last);
3043       if (C.IsNull()) continue;
3044       C = new Geom_TrimmedCurve(C, First, Last);
3045       Section.AddCurve(C) ;
3046       i++ ;
3047     }
3048     
3049     /* a 'tolerance' is used to compare 2 knots : see GeomFill_Generator.cdl */
3050     /* We set 'tolerance' = tol3d                                            */
3051     // Section.Perform( tol3d ) ; NRI */
3052     Section.Perform( Precision::Confusion() ) ;
3053     Handle(GeomFill_Line) Line = new GeomFill_Line(i) ;
3054     
3055     GeomFill_AppSurf App(mindeg, maxdeg, tol3d, tol2d, nbiter) ; /* user parameters */
3056     App.Perform(Line, Section, theApprox) ;
3057     
3058     if (!App.IsDone()) {
3059       THROW_SALOME_CORBA_EXCEPTION("Filling aborted : non valid shape result", SALOME::BAD_PARAM);
3060     }
3061     Standard_Integer UDegree, VDegree, NbUPoles, NbVPoles, NbUKnots, NbVKnots;
3062     App.SurfShape(UDegree, VDegree, NbUPoles, NbVPoles, NbUKnots, NbVKnots);    
3063     Handle(Geom_BSplineSurface) GBS = new Geom_BSplineSurface(App.SurfPoles(),
3064                                                               App.SurfWeights(),
3065                                                               App.SurfUKnots(),
3066                                                               App.SurfVKnots(),
3067                                                               App.SurfUMults(),
3068                                                               App.SurfVMults(),
3069                                                               App.UDegree(),
3070                                                               App.VDegree());
3071     
3072     if( GBS.IsNull() )  {
3073       THROW_SALOME_CORBA_EXCEPTION("Make Filling aborted", SALOME::BAD_PARAM);
3074     }
3075     tds  = BRepBuilderAPI_MakeFace(GBS) ;    
3076   }
3077   catch(Standard_Failure) {
3078     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeFilling", SALOME::BAD_PARAM);
3079   } 
3080   
3081   /* We test the validity of resulting shape */
3082   if( !IsValid(tds) ) {
3083     THROW_SALOME_CORBA_EXCEPTION("Filling aborted : non valid shape result", SALOME::BAD_PARAM);
3084   } 
3085   else {
3086     result = CreateObject(tds) ;
3087     InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
3088   }
3089  
3090   return result ;
3091 }
3092
3093
3094 //=================================================================================
3095 // function : MakeGlueFaces()
3096 // purpose  :
3097 //=================================================================================
3098
3099 TopoDS_Face GEOM_Gen_i::FindSameFace(const TopoDS_Shape& aShape, 
3100                                      const TopoDS_Face& F,
3101                                      double tol3d)
3102 {
3103   TopoDS_Face aFace;
3104   bool isSame = false;
3105   for (TopExp_Explorer exf(aShape,TopAbs_FACE); exf.More(); exf.Next())
3106     {
3107       //MESSAGE("--- test a face");
3108       int nbFound = 0;
3109       aFace = TopoDS::Face(exf.Current());
3110       TopTools_ListOfShape liste1;
3111       TopTools_ListOfShape liste2;
3112       for (TopExp_Explorer exp(aFace,TopAbs_VERTEX); exp.More(); exp.Next())
3113         {
3114           const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
3115           liste1.Append(V);
3116         }
3117       for (TopExp_Explorer exp(F,TopAbs_VERTEX); exp.More(); exp.Next())
3118         {
3119           const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
3120           liste2.Append(V);
3121         }
3122       isSame = false;
3123       if (liste1.Extent() == liste2.Extent())
3124         {
3125           TopTools_ListIteratorOfListOfShape it1(liste1);
3126           isSame = true;
3127           for (; it1.More(); it1.Next())
3128             {
3129               bool foundSamePoint = false;
3130               gp_Pnt P1 = BRep_Tool::Pnt(TopoDS::Vertex(it1.Value()));
3131               TopTools_ListIteratorOfListOfShape it2(liste2);
3132               for (it2; it2.More(); it2.Next())
3133                 {
3134                   gp_Pnt P2 = BRep_Tool::Pnt(TopoDS::Vertex(it2.Value()));
3135                   double d = P1.Distance(P2);
3136                   if (d < tol3d)
3137                     {
3138                       nbFound++;
3139                       //MESSAGE("    found Same Point : "<<nbFound<<" - "<<P1.X()<<" "<<P1.Y()<<" "<<P1.Z());
3140                       foundSamePoint = true;
3141                       break;
3142                     }
3143                 }
3144               isSame = isSame && foundSamePoint;
3145               if (! isSame) break; // a vertex does not correspond : not same face
3146             }
3147         }
3148       if (isSame)
3149         {
3150           //MESSAGE("    --- Found Same Face");
3151           break; // a face corresponding to F is found
3152         }
3153     }
3154   if (! isSame) aFace.Nullify(); // return null face
3155   return aFace;
3156 }
3157
3158 TopoDS_Edge GEOM_Gen_i::FindSameEdge(const TopoDS_Face& nf, 
3159                                      TopoDS_Edge& Eold,
3160                                      double tol3d)
3161 {
3162   TopoDS_Face newFace = TopoDS::Face(nf.Oriented(TopAbs_REVERSED));
3163   TopoDS_Vertex VFirst, VLast;
3164   TopExp::Vertices(Eold, VFirst, VLast);
3165   gp_Pnt Pf = BRep_Tool::Pnt(VFirst);
3166   gp_Pnt Pl = BRep_Tool::Pnt(VLast);
3167   TopoDS_Edge Enew;
3168   for (TopExp_Explorer ee(newFace,TopAbs_EDGE); ee.More(); ee.Next())
3169     {
3170       const TopoDS_Edge& E = TopoDS::Edge(ee.Current());
3171       TopoDS_Vertex VFn, VLn;
3172       TopExp::Vertices(E, VFn, VLn);
3173       gp_Pnt Pfn = BRep_Tool::Pnt(VFn);
3174       gp_Pnt Pln = BRep_Tool::Pnt(VLn);
3175       double dff = Pf.Distance(Pfn);
3176       double dfl = Pf.Distance(Pln);
3177       double dlf = Pl.Distance(Pfn);
3178       double dll = Pl.Distance(Pln);
3179       if ((dff < tol3d) && (dll <tol3d))
3180         {
3181           //MESSAGE("--- edge forward " <<Pf.X()<<" "<<Pf.Y()<<" "<<Pf.Z()<<" "<<Pl.X()<<" "<<Pl.Y()<<" "<<Pl.Z());
3182           Enew = TopoDS::Edge(E.Oriented(TopAbs_FORWARD));
3183           Eold = TopoDS::Edge(Eold.Oriented(TopAbs_FORWARD));
3184           break;
3185         } 
3186       if ((dfl < tol3d) && (dlf <tol3d))
3187         {
3188           //MESSAGE("--- edge reversed " <<Pf.X()<<" "<<Pf.Y()<<" "<<Pf.Z()<<" "<<Pl.X()<<" "<<Pl.Y()<<" "<<Pl.Z());
3189           Enew = TopoDS::Edge(E.Oriented(TopAbs_REVERSED));
3190           Eold = TopoDS::Edge(Eold.Oriented(TopAbs_FORWARD));
3191           break;
3192         } 
3193     }
3194   return Enew;
3195 }
3196
3197 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeGlueFaces(GEOM::GEOM_Shape_ptr myShape,
3198                                                double tol3d)
3199   throw (SALOME::SALOME_Exception)
3200 {
3201
3202   // prendre un premier shell dans la liste des shells
3203   // initialiser un compshell avec ce shell
3204   // tant qu'il reste des shells dans la liste
3205   //   chercher un shell qui a des faces en  commun avec le compshell
3206   //   creer un BRepTools_Quilt
3207   //   recenser les faces communes issues du compshell, les ajouter au quilt 
3208   //   recenser les faces restantes du shell a inclure, les ajouter au quilt
3209   //   recenser les edges en double, a remplacer
3210   //   pour chaque paire d'edge
3211   //     tester l'orientation relative des aretes
3212   //     bind dans le quilt de Eold.Forward et Enew.Forward (ou reverse)
3213   //   recuperer le nouveau shell
3214   // l'incorporer dans le compshell
3215   // appliquer BRepTools_SameParameter au compshell
3216   // (rendre parametres 2D des edges identiques aux parametres 3D)
3217
3218   Unexpect aCatch(SALOME_SalomeException);
3219   GEOM::GEOM_Shape_var result ;
3220   TopoDS_Shape tds ;
3221   TopoDS_Shape aShape = GetTopoShape(myShape) ;
3222   TopoDS_Compound C;
3223   BRep_Builder bu;
3224   bu.MakeCompound(C); // empty compound;
3225   TopTools_ListOfShape shellList;
3226   for (TopExp_Explorer exp(aShape,TopAbs_SHELL); exp.More(); exp.Next())
3227     {
3228       const TopoDS_Shell& S = TopoDS::Shell(exp.Current());
3229       shellList.Append(S);
3230     }
3231   TopTools_ListIteratorOfListOfShape its(shellList);
3232   if ( ! its.More())
3233     {
3234       THROW_SALOME_CORBA_EXCEPTION("glue aborted : no shell in shape", SALOME::BAD_PARAM);
3235     }
3236   TopoDS_Shell S = TopoDS::Shell(its.Value());
3237   bu.Add(C, S); // add first shell to compound
3238   shellList.Remove(its);
3239   its.Initialize(shellList);
3240   bool shellAdded = true;
3241   while ((shellList.Extent() > 0) && shellAdded)
3242     {
3243       //MESSAGE("more shells : "<< shellList.Extent());
3244       shellAdded = false;
3245       its.Initialize(shellList);
3246       for(; its.More(); its.Next())
3247         {
3248           //MESSAGE("one more shell to try");
3249           TopTools_ListOfShape newFaces; // common faces from new compound
3250           TopTools_ListOfShape oldFaces; // common faces from shell to add
3251           TopTools_ListOfShape addFaces; // not common faces from shell to add
3252           TopTools_ListOfShape newEdges; // common edges from new compound
3253           TopTools_ListOfShape oldEdges; // common edges from face to add
3254           TopoDS_Compound CFN;
3255           TopoDS_Compound CFO;
3256           bu.MakeCompound(CFN);       // empty compound for new faces
3257           bu.MakeCompound(CFO);       // empty compound for old faces
3258           S = TopoDS::Shell(its.Value());
3259           for (TopExp_Explorer exp(S,TopAbs_FACE); exp.More(); exp.Next())
3260             {
3261               //MESSAGE("--- try to find corresponding face in new compound");
3262               TopoDS_Face F = TopoDS::Face(exp.Current());
3263               TopoDS_Face newFace = FindSameFace(C,F,tol3d);
3264               if (! newFace.IsNull())
3265                 {
3266                   //MESSAGE("--- face found");
3267                   newFaces.Append(newFace); 
3268                   bu.Add(CFN, newFace); // common faces from new compound
3269                   oldFaces.Append(F);
3270                   for (TopExp_Explorer ee(F,TopAbs_EDGE);ee.More();ee.Next())
3271                     {
3272                       //MESSAGE("--- find edge pair");
3273                       TopoDS_Edge Eold = TopoDS::Edge(ee.Current());
3274                       const TopoDS_Edge& Enew = FindSameEdge(newFace, Eold, tol3d);
3275                       oldEdges.Append(Eold);
3276                       newEdges.Append(Enew);
3277                     }
3278                 }
3279               else
3280                 {
3281                   //MESSAGE("---");
3282                   addFaces.Append(F);
3283                   bu.Add(CFO, F); // not common faces from shell to add
3284                 }
3285             }
3286           if ( !newFaces.IsEmpty())
3287             {
3288               //MESSAGE("--- some faces found ---");
3289               shellAdded = true;
3290               BRepTools_Quilt glue;
3291               glue.Add(CFN);
3292               TopTools_ListIteratorOfListOfShape ito(oldEdges);
3293               TopTools_ListIteratorOfListOfShape itn(newEdges);
3294               for (; ito.More(); ito.Next())
3295                 {                 
3296                   //MESSAGE("--- bind");
3297                   glue.Bind(TopoDS::Edge(ito.Value()), TopoDS::Edge(itn.Value()));
3298                   itn.Next();
3299                 }
3300               glue.Add(CFO);
3301               TopoDS_Compound newc = TopoDS::Compound(glue.Shells());
3302               for (TopExp_Explorer exs(newc,TopAbs_SHELL); exs.More(); exs.Next())
3303                 {
3304                   TopoDS_Shell NS = TopoDS::Shell(exs.Current());
3305                   bu.Add(C, NS);
3306                 }
3307               shellList.Remove(its);
3308               //MESSAGE("--- remove shell from list");
3309               break;
3310             }
3311         }
3312     }
3313   //MESSAGE("---" << shellList.Extent() << " " << shellAdded);
3314
3315   TopExp_Explorer  exp(C,TopAbs_SHELL);
3316   Standard_Integer ish=0;
3317   TopoDS_Compound  Res;
3318   TopoDS_Solid     Sol;
3319   BRep_Builder     B;
3320   B.MakeCompound(Res);
3321   TopoDS_Shape theShape;
3322
3323   for (; exp.More(); exp.Next())
3324     {
3325       TopoDS_Shape Sh = exp.Current();
3326       B.MakeSolid(Sol);
3327       B.Add(Sol,Sh);
3328       BRepClass3d_SolidClassifier SC(Sol);
3329       SC.PerformInfinitePoint(1.E-6); // cf. BRepFill_Confusion() - BRepFill_Evolved.cxx
3330       if (SC.State() == TopAbs_IN)
3331         {
3332           B.MakeSolid(Sol);
3333           B.Add(Sol,Sh.Reversed());
3334         }
3335       B.Add(Res,Sol);
3336       ish++;
3337     }
3338   if (ish == 1) { theShape = Sol;}
3339   else          { theShape = Res;}
3340
3341   BRepLib::SameParameter(theShape, 1.E-5, Standard_True);
3342   tds = theShape;
3343   result = CreateObject(tds);    
3344   InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
3345   //MESSAGE("---");
3346   return result;
3347 }
3348
3349 //=================================================================================
3350 // function : MakeSewing()
3351 // purpose  :
3352 //=================================================================================
3353 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeSewing( const GEOM::GEOM_Gen::ListOfIOR& ListShapes,
3354                                        CORBA::Double precision )
3355   throw (SALOME::SALOME_Exception)
3356 {
3357   Unexpect aCatch(SALOME_SalomeException);
3358   GEOM::GEOM_Shape_var result ;
3359   TopoDS_Shape tds ;
3360   BRepOffsetAPI_Sewing aMethod ;
3361
3362   try {
3363     /* default OCC is 1.0e-06 */
3364     aMethod.Init(precision, Standard_False);  
3365     for ( unsigned int i = 0; i < ListShapes.length(); i++) {
3366       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[i] ); 
3367       TopoDS_Shape Shape = GetTopoShape(aShape) ;
3368       if( Shape.IsNull() ) {
3369         THROW_SALOME_CORBA_EXCEPTION("MakeSewing aborted : null shape during operation", SALOME::BAD_PARAM);
3370       } 
3371       aMethod.Add(Shape) ;  
3372     }  
3373     
3374     aMethod.Perform() ;
3375     tds = aMethod.SewedShape() ;
3376     if( !IsValid(tds) ) {
3377       THROW_SALOME_CORBA_EXCEPTION("Make Sewing aborted : non valid shape", SALOME::BAD_PARAM);
3378     }
3379     if( tds.IsNull() ) {
3380       THROW_SALOME_CORBA_EXCEPTION("Make Sewing aborted : null shape", SALOME::BAD_PARAM);
3381     }
3382   }
3383   catch (Standard_Failure) {
3384     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeSewing", SALOME::BAD_PARAM);
3385   }
3386   
3387   result = CreateObject(tds);
3388   InsertInLabelMoreArguments(tds, result, ListShapes, myCurrentOCAFDoc) ;
3389   return result;
3390 }
3391
3392 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeSewingShape( GEOM::GEOM_Shape_ptr aShape,
3393                                             CORBA::Double precision )
3394   throw (SALOME::SALOME_Exception)
3395 {
3396   Unexpect aCatch(SALOME_SalomeException);
3397   GEOM::GEOM_Shape_var result ;
3398   TopoDS_Shape tds, S ;
3399   BRepOffsetAPI_Sewing aMethod ;
3400
3401   try {
3402     S = GetTopoShape(aShape) ;
3403     if(S.IsNull() ) {
3404       THROW_SALOME_CORBA_EXCEPTION("In Sewing a Shape is null", SALOME::BAD_PARAM);
3405     }
3406
3407     /* default OCC is 1.0e-06 */
3408     aMethod.Init(precision, Standard_False);  
3409     for ( TopExp_Explorer exp( S, TopAbs_FACE); exp.More(); exp.Next() ) {
3410       const TopoDS_Face& F = TopoDS::Face(exp.Current());
3411       aMethod.Add(F) ;  
3412     }  
3413     
3414     aMethod.Perform() ;
3415     tds = aMethod.SewedShape() ;
3416     if( !IsValid(tds) ) {
3417       THROW_SALOME_CORBA_EXCEPTION("Make Sewing aborted : non valid shape", SALOME::BAD_PARAM);
3418     }
3419   }
3420   catch (Standard_Failure) {
3421     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeSewing", SALOME::BAD_PARAM);
3422   }
3423   
3424   result = CreateObject(tds);
3425   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3426   result->ShapeId(entry) ;
3427   return result;
3428 }
3429
3430 //==================================================================================
3431 // function : OrientationChange()
3432 // purpose  : Change the orientation of a new shape
3433 //          : TopAbs_FORWARD < -- > TopAbs_REVERSED
3434 //
3435 //          : WARNING : for the moment we make a new shape !
3436 //==================================================================================
3437 GEOM::GEOM_Shape_ptr GEOM_Gen_i::OrientationChange(GEOM::GEOM_Shape_ptr aShape)
3438   throw (SALOME::SALOME_Exception)
3439 {
3440   Unexpect aCatch(SALOME_SalomeException);
3441   GEOM::GEOM_Shape_var result ;  
3442   BRep_Builder aBuilder;  
3443
3444   TopoDS_Shape shape = GetTopoShape(aShape) ;
3445   if( shape.IsNull() ) {
3446     THROW_SALOME_CORBA_EXCEPTION("Shape is null", SALOME::BAD_PARAM);
3447   }
3448
3449   BRepBuilderAPI_Copy Copy(shape);
3450   if( Copy.IsDone() ) {
3451     TopoDS_Shape tds = Copy.Shape();
3452     if( tds.IsNull() ) {
3453       THROW_SALOME_CORBA_EXCEPTION("Orientation aborted : null shape", SALOME::BAD_PARAM);
3454     } 
3455   
3456     if( tds.Orientation() == TopAbs_FORWARD)
3457       tds.Orientation(TopAbs_REVERSED) ;
3458     else
3459       tds.Orientation(TopAbs_FORWARD) ;
3460     
3461     result = CreateObject(tds); 
3462     InsertInLabelOneArgument(shape, aShape, tds, result, myCurrentOCAFDoc) ;
3463   }
3464   return result ;
3465 }
3466
3467
3468 //==================================================================================
3469 // function : GetReferencedObjects()
3470 // purpose  :
3471 //==================================================================================
3472 GEOM::GEOM_Gen::ListOfIOR* GEOM_Gen_i::GetReferencedObjects(GEOM::GEOM_Shape_ptr shape)
3473 {
3474   GEOM::GEOM_Gen::ListOfIOR_var aList = new GEOM::GEOM_Gen::ListOfIOR;
3475   aList->length(0);
3476
3477   if (shape->_is_nil()) return aList._retn();
3478
3479   Standard_CString entry = shape->ShapeId();
3480   TDF_Label Lab;
3481   TDF_Tool::Label(myCurrentOCAFDoc->GetData(), entry, Lab);
3482
3483   Handle(TDataStd_Name) Att;
3484   Lab.FindAttribute(TDataStd_Name::GetID(),Att);
3485
3486   TDF_ChildIterator ChildIterator(Lab);
3487   if (ChildIterator.More()) {
3488     TDF_Label L = ChildIterator.Value();
3489     Handle(TDataStd_Name) Att;
3490     L.FindAttribute(TDataStd_Name::GetID(),Att);
3491     if (Att->Get().IsEqual(TCollection_ExtendedString("Arguments")) ) {
3492
3493       TDF_ChildIterator ChildIterator1(L);
3494       unsigned int i = 0;
3495
3496       while (ChildIterator1.More()) {
3497         TDF_Label L = ChildIterator1.Value();
3498
3499         Handle(TDF_Reference) Ref;
3500         if (L.FindAttribute(TDF_Reference::GetID(),Ref)) {
3501           i++;
3502         }
3503         ChildIterator1.Next();
3504       }
3505       aList->length(i);
3506       i = 0;
3507       TDF_ChildIterator ChildIterator2(L);
3508       while (ChildIterator2.More()) {    
3509         TDF_Label L = ChildIterator2.Value();
3510         Handle(TDF_Reference) Ref;
3511         if (L.FindAttribute(TDF_Reference::GetID(),Ref)) {
3512           TDF_Label L = Ref->Get();
3513           
3514           Handle(TDataStd_Name) Att;
3515           L.FindAttribute(TDataStd_Name::GetID(),Att);
3516           TCollection_AsciiString nameIOR (Att->Get()) ;
3517           aList[i] = CORBA::string_dup( nameIOR.ToCString() );
3518           i++;
3519         }
3520    
3521         ChildIterator2.Next();
3522       }
3523     }
3524   }
3525   return aList._retn();
3526 }
3527
3528 //==================================================================================
3529 // function : GetObjects()
3530 // purpose  :
3531 //==================================================================================
3532 GEOM::GEOM_Gen::ListOfIOR* GEOM_Gen_i::GetObjects(GEOM::GEOM_Shape_ptr shape)
3533 {
3534   GEOM::GEOM_Gen::ListOfIOR_var aList = new GEOM::GEOM_Gen::ListOfIOR;
3535   aList->length(0);
3536   
3537   Standard_CString entry = shape->ShapeId();
3538   TDF_Label Lab;
3539   TDF_Tool::Label(myCurrentOCAFDoc->GetData(), entry, Lab);
3540   
3541   Handle(TDataStd_Name) Att;
3542   Lab.FindAttribute(TDataStd_Name::GetID(),Att);
3543
3544   TDF_ChildIterator ChildIterator(Lab);
3545   unsigned int i = 0;
3546   while (ChildIterator.More()) {
3547     TDF_Label L = ChildIterator.Value();
3548     Handle(TDataStd_Name) Att;
3549     L.FindAttribute(TDataStd_Name::GetID(),Att);
3550
3551     if (!Att->Get().IsEqual(TCollection_ExtendedString("Arguments")) ) {
3552       i++;
3553     }
3554     ChildIterator.Next();
3555   }
3556
3557   aList->length(i);
3558   i = 0;
3559   TDF_ChildIterator ChildIterator1(Lab);
3560   while (ChildIterator1.More()) {
3561     TDF_Label L = ChildIterator1.Value();
3562     Handle(TDataStd_Name) Att;
3563     L.FindAttribute(TDataStd_Name::GetID(),Att);
3564
3565     if (!Att->Get().IsEqual(TCollection_ExtendedString("Arguments")) ) {
3566       TCollection_AsciiString nameIOR (Att->Get());
3567       aList[i] = CORBA::string_dup( nameIOR.ToCString() );
3568       i++;
3569     }
3570     ChildIterator1.Next();
3571   }
3572   return aList._retn();
3573 }
3574
3575
3576 //==================================================================================
3577 // function : Import
3578 // purpose  : Import shape from a BREP file
3579 //==================================================================================
3580 GEOM::GEOM_Shape_ptr GEOM_Gen_i::ImportBREP(const char* filename)
3581   throw (SALOME::SALOME_Exception)
3582 {
3583   Unexpect aCatch(SALOME_SalomeException);
3584   TopoDS_Shape tds ;
3585   GEOM::GEOM_Shape_var result ;
3586   
3587   try {
3588     BRep_Builder aBuilder;
3589     char* aCopyfilename = strdup(filename);
3590     BRepTools::Read(tds, aCopyfilename, aBuilder) ;
3591     free(aCopyfilename);
3592     if (tds.IsNull()) {
3593       THROW_SALOME_CORBA_EXCEPTION("Import BRep aborted", SALOME::BAD_PARAM);
3594     } 
3595   }
3596   catch(Standard_Failure) {
3597     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ImportBREP", SALOME::BAD_PARAM);
3598   }
3599
3600   result = CreateObject(tds) ;
3601   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3602   result->ShapeId(entry);
3603   return result; 
3604 }
3605
3606
3607 //================================================================================
3608 // function : MakePlane()
3609 // purpose  : Make a plane topology (non infinite)
3610 //================================================================================
3611 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakePlane(const GEOM::PointStruct& pstruct,
3612                                      const GEOM::DirStruct& dstruct,
3613                                      CORBA::Double trimsize) 
3614   throw (SALOME::SALOME_Exception)
3615 {
3616   Unexpect aCatch(SALOME_SalomeException);
3617   GEOM::GEOM_Shape_var result ;
3618   TopoDS_Shape tds ;
3619
3620   try {
3621     gp_Pnt aPoint(pstruct.x, pstruct.y, pstruct.z) ;
3622     gp_Dir aDirection(dstruct.PS.x, dstruct.PS.y, dstruct.PS.z) ;
3623     /*  we make a trimmed plane */
3624     gp_Pln gplane(aPoint, aDirection) ;    
3625     tds = BRepBuilderAPI_MakeFace(gplane, -trimsize, +trimsize, -trimsize, +trimsize) ;
3626   }
3627   catch(Standard_Failure) {
3628     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakePlane", SALOME::BAD_PARAM);
3629   }
3630
3631   if (tds.IsNull()) {
3632     THROW_SALOME_CORBA_EXCEPTION("Make Plane aborted : null shape", SALOME::BAD_PARAM);
3633    } 
3634   
3635   result = CreateObject(tds) ;
3636   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3637   result->ShapeId(entry);
3638   return result ;
3639 }
3640
3641 //=================================================================================
3642 // function : MakeVertex()
3643 // purpose  : Create a Vertex topology.
3644 //=================================================================================
3645 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeVertex(CORBA::Double x,
3646                                       CORBA::Double y,
3647                                       CORBA::Double z) 
3648   throw (SALOME::SALOME_Exception)
3649 {
3650   Unexpect aCatch(SALOME_SalomeException);
3651   GEOM::GEOM_Shape_var result ; 
3652   gp_Pnt P(x,y,z);
3653   TopoDS_Shape tds = BRepBuilderAPI_MakeVertex(P).Shape();
3654   if (tds.IsNull()) {
3655     THROW_SALOME_CORBA_EXCEPTION("Make Vertex/Point aborted", SALOME::BAD_PARAM);
3656   }
3657   tds.Infinite(true);
3658   result = CreateObject(tds) ;
3659   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3660   result->ShapeId(entry);
3661   return result ;
3662 }
3663
3664
3665 //=================================================================================
3666 // function : MakeFace()
3667 // purpose  : 
3668 //=================================================================================
3669 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeFace( GEOM::GEOM_Shape_ptr wire,
3670                                      CORBA::Boolean wantplanarface ) 
3671   throw (SALOME::SALOME_Exception) 
3672 {
3673   Unexpect aCatch(SALOME_SalomeException);
3674   GEOM::GEOM_Shape_var result ;
3675   TopoDS_Shape aShape;
3676   TopoDS_Shape tds;
3677
3678   try {
3679     aShape = GetTopoShape(wire) ;
3680     if( aShape.IsNull() || aShape.ShapeType() != TopAbs_WIRE ) {
3681       THROW_SALOME_CORBA_EXCEPTION("MakeFace aborted : null or inappropriate shape", SALOME::BAD_PARAM);
3682     }
3683     TopoDS_Wire W = TopoDS::Wire(aShape) ;
3684     tds = BRepBuilderAPI_MakeFace(W, wantplanarface).Shape() ;
3685     if( !tds.IsNull() ) {
3686       result = CreateObject(tds) ;
3687       InsertInLabelOneArgument(aShape, wire, tds, result, myCurrentOCAFDoc) ;
3688     }
3689     else {
3690       THROW_SALOME_CORBA_EXCEPTION("Null result in GEOM_Gen_i::MakeFace", SALOME::BAD_PARAM);
3691     }
3692   }
3693   catch (Standard_Failure) {
3694     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeFace", SALOME::BAD_PARAM);
3695   }  
3696   return result ;
3697 }
3698
3699
3700 //=================================================================================
3701 // function : MakeFaces()
3702 // purpose  : 
3703 //=================================================================================
3704 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeFaces(const GEOM::GEOM_Gen::ListOfIOR& ListShapes,
3705                                           CORBA::Boolean wantplanarface) 
3706   throw (SALOME::SALOME_Exception) 
3707 {
3708   GEOM::GEOM_Shape_var result;
3709
3710   try {
3711     GEOM::GEOM_Shape_var aShape = GetIORFromString(ListShapes[0]);    
3712     TopoDS_Shape Shape = GetTopoShape(aShape);
3713     if(Shape.IsNull() || Shape.ShapeType() != TopAbs_WIRE) {
3714       THROW_SALOME_CORBA_EXCEPTION("Shell aborted : null shape during operation", SALOME::BAD_PARAM);
3715     }
3716     TopoDS_Wire W = TopoDS::Wire(Shape);
3717     TopoDS_Shape FFace = BRepBuilderAPI_MakeFace(W, wantplanarface).Shape();
3718     if(!FFace.IsNull()) {
3719       if(ListShapes.length() == 1) {
3720         result = CreateObject(FFace);
3721         InsertInLabelMoreArguments(FFace, result, ListShapes, myCurrentOCAFDoc);
3722       }
3723       else if(ListShapes.length() >= 2) {
3724         TopoDS_Compound C;
3725         BRep_Builder aBuilder;
3726         aBuilder.MakeCompound(C);
3727         BRepAlgo_FaceRestrictor FR;
3728
3729         TopAbs_Orientation OriF = FFace.Orientation();
3730         TopoDS_Shape aLocalS = FFace.Oriented(TopAbs_FORWARD);
3731         FR.Init(TopoDS::Face(aLocalS), Standard_False, Standard_True);
3732
3733         for(unsigned int i = 0; i < ListShapes.length(); i++) {
3734           GEOM::GEOM_Shape_var aShape = GetIORFromString(ListShapes[i]);    
3735           TopoDS_Shape Shape = GetTopoShape(aShape);
3736           if(Shape.IsNull()) {
3737             THROW_SALOME_CORBA_EXCEPTION("Shell aborted : null shape during operation", SALOME::BAD_PARAM);
3738           }
3739           FR.Add(TopoDS::Wire(Shape));
3740         }
3741
3742         FR.Perform();
3743     
3744         if(FR.IsDone()) {
3745           int k = 0;
3746           TopoDS_Shape aFace;
3747           for(; FR.More(); FR.Next()) {
3748             aFace = FR.Current().Oriented(OriF);
3749             aBuilder.Add(C, aFace);
3750             k++;
3751           }
3752           if(k == 1) {
3753             result = CreateObject(aFace);
3754             InsertInLabelMoreArguments(aFace, result, ListShapes, myCurrentOCAFDoc);
3755           }
3756           else {
3757             result = CreateObject(C);
3758             InsertInLabelMoreArguments(C, result, ListShapes, myCurrentOCAFDoc);
3759           }
3760         }
3761       }
3762     }
3763     else {
3764       THROW_SALOME_CORBA_EXCEPTION("Null result in GEOM_Gen_i::MakeFace", SALOME::BAD_PARAM);
3765     }
3766   }
3767   catch (Standard_Failure) {
3768     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeFace", SALOME::BAD_PARAM);
3769   }
3770   return result;
3771 }
3772
3773
3774 //=================================================================================
3775 // function : MakeShell()
3776 // purpose  : Make a compound from a list containing one or more shapes
3777 //=================================================================================
3778 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeShell( const GEOM::GEOM_Gen::ListOfIOR& ListShapes )
3779   throw (SALOME::SALOME_Exception)
3780 {
3781   Unexpect aCatch(SALOME_SalomeException);
3782   GEOM::GEOM_Shape_var result ;
3783   BRepTools_Quilt Glue;
3784   TopoDS_Shape C;
3785
3786   for ( unsigned int i = 0; i < ListShapes.length(); i++) {
3787     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[i] );    
3788     TopoDS_Shape Shape = GetTopoShape(aShape) ;
3789     if( Shape.IsNull() ) {
3790        THROW_SALOME_CORBA_EXCEPTION("Shell aborted : null shape during operation", SALOME::BAD_PARAM);
3791     }
3792     Glue.Add(Shape) ;
3793   }
3794
3795   TopExp_Explorer exp(Glue.Shells(), TopAbs_SHELL);
3796   Standard_Integer ish = 0; 
3797   for (; exp.More(); exp.Next()) {
3798     C = exp.Current(); 
3799     ish++;
3800   }
3801
3802   if (ish != 1)
3803     C = Glue.Shells();
3804   
3805   if ( C.IsNull() ) {
3806     THROW_SALOME_CORBA_EXCEPTION("Null result : Shell operation aborted", SALOME::BAD_PARAM);
3807   }
3808   else {
3809     result = CreateObject(C) ;
3810     InsertInLabelMoreArguments(C, result, ListShapes, myCurrentOCAFDoc) ;
3811   }
3812   return result;
3813 }
3814
3815
3816 //=================================================================================
3817 // function : MakeSolid()
3818 // purpose  : Make a compound from a list containing one or more shapes
3819 //=================================================================================
3820 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeSolid( const GEOM::GEOM_Gen::ListOfIOR& ListShapes )
3821   throw (SALOME::SALOME_Exception)
3822 {
3823   Unexpect aCatch(SALOME_SalomeException);
3824   GEOM::GEOM_Shape_var result ;
3825   Standard_Integer ish = 0;
3826   TopoDS_Compound  Res;
3827   TopoDS_Solid     Sol;
3828   BRep_Builder     B;
3829   TopoDS_Shape     Shape;
3830
3831   B.MakeCompound(Res);
3832
3833   for ( unsigned int i = 0; i < ListShapes.length(); i++) {
3834     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[i] );    
3835     TopoDS_Shape Sh = GetTopoShape(aShape) ;
3836     if( Sh.IsNull() ) {
3837        THROW_SALOME_CORBA_EXCEPTION("Solid aborted : null shape during operation", SALOME::BAD_PARAM);
3838     }
3839     B.MakeSolid(Sol);
3840     B.Add(Sol,Sh);
3841     BRepClass3d_SolidClassifier SC(Sol);
3842     SC.PerformInfinitePoint(Precision::Confusion());
3843     if (SC.State() == TopAbs_IN) {
3844       B.MakeSolid(Sol);
3845       B.Add(Sol,Sh.Reversed());
3846     }
3847     B.Add(Res,Sol);
3848     ish++;
3849   }
3850   if (ish == 1) { Shape = Sol;}
3851   else          { Shape = Res;} 
3852   
3853   if ( Shape.IsNull() ) {
3854     THROW_SALOME_CORBA_EXCEPTION("Null result : Solid operation aborted", SALOME::BAD_PARAM);
3855   }
3856   else {
3857     result = CreateObject(Shape) ;
3858     InsertInLabelMoreArguments(Shape, result, ListShapes, myCurrentOCAFDoc) ;
3859   }
3860   return result;
3861 }
3862
3863
3864 //================================================================================
3865 // function : MakeLine
3866 // purpose  : Make a Line topology
3867 //================================================================================
3868 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeLine(const GEOM::PointStruct& pstruct,
3869                                     const GEOM::DirStruct& dstruct)
3870   throw (SALOME::SALOME_Exception)
3871 {
3872   Unexpect aCatch(SALOME_SalomeException);
3873   GEOM::GEOM_Shape_var result  ;
3874   gp_Pnt P1(pstruct.x, pstruct.y, pstruct.z);
3875   gp_Pnt P2(dstruct.PS.x, dstruct.PS.y, dstruct.PS.z) ;  
3876   TopoDS_Shape tds ;
3877   
3878   try {
3879     tds = BRepBuilderAPI_MakeEdge(P1, P2).Shape();
3880   }
3881   catch(Standard_Failure) {
3882     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeLine", SALOME::BAD_PARAM);
3883   }
3884
3885   if ( tds.IsNull() ) {
3886     THROW_SALOME_CORBA_EXCEPTION("Make Line aborted : null shape", SALOME::BAD_PARAM);
3887   }
3888   else {
3889     tds.Infinite(true);
3890     result = CreateObject(tds) ;
3891     const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3892     result->ShapeId(entry);
3893   }
3894   return result ;  
3895 }
3896
3897
3898 //================================================================================
3899 // function : MakeVector()
3900 // purpose  : Make a vector
3901 //================================================================================
3902 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeVector(const GEOM::PointStruct& pstruct1,
3903                                       const GEOM::PointStruct& pstruct2)
3904   throw (SALOME::SALOME_Exception)
3905 {
3906   Unexpect aCatch(SALOME_SalomeException);
3907   GEOM::GEOM_Shape_var result  ;
3908   TopoDS_Shape tds ;
3909   
3910   try {
3911     gp_Pnt P1(pstruct1.x, pstruct1.y, pstruct1.z);
3912     gp_Pnt P2(pstruct2.x, pstruct2.y, pstruct2.z) ;
3913     tds = BRepBuilderAPI_MakeEdge(P1, P2).Shape();
3914   }
3915   catch(Standard_Failure) {
3916     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeVector", SALOME::BAD_PARAM);
3917   }
3918
3919   if ( tds.IsNull() ) {
3920     THROW_SALOME_CORBA_EXCEPTION("Make Vector aborted : null shape", SALOME::BAD_PARAM);
3921   }
3922   else {
3923     result = CreateObject(tds) ;
3924     const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3925     result->ShapeId(entry);
3926   }
3927   return result ;  
3928 }
3929
3930
3931 //================================================================================
3932 // function : MakeCircle()
3933 // purpose  : 
3934 //================================================================================
3935 GEOM::GEOM_Shape_ptr  GEOM_Gen_i::MakeCircle(const GEOM::PointStruct& pstruct,
3936                                        const GEOM::DirStruct& dstruct,
3937                                        CORBA::Double radius)
3938   throw (SALOME::SALOME_Exception) 
3939 {
3940   Unexpect aCatch(SALOME_SalomeException);
3941   GEOM::GEOM_Shape_var result;
3942   TopoDS_Shape tds ;
3943
3944   try {
3945     gp_Pnt p(pstruct.x, pstruct.y, pstruct.z) ;
3946     gp_Dir d(dstruct.PS.x, dstruct.PS.y, dstruct.PS.z) ;
3947     gp_Ax2 axis(p, d) ;
3948     gp_Circ circ( axis, radius);    
3949     BRepBuilderAPI_MakeEdge MakeEdge( circ );
3950     tds = MakeEdge.Edge();
3951   }
3952   catch(Standard_Failure) {
3953     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeCircle", SALOME::BAD_PARAM);
3954   }
3955   if (tds.IsNull()) {
3956     THROW_SALOME_CORBA_EXCEPTION("Make Circle aborted", SALOME::BAD_PARAM);
3957   } 
3958   result = CreateObject(tds);
3959   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3960   result->ShapeId(entry);
3961   return result ;  
3962 }
3963
3964 //================================================================================
3965 // function : MakeEllipse()
3966 // purpose  : 
3967 //================================================================================
3968 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeEllipse( const GEOM::PointStruct& pstruct,
3969                                               const GEOM::DirStruct& dstruct,
3970                                               CORBA::Double radius_major,
3971                                               CORBA::Double radius_minor )
3972   throw (SALOME::SALOME_Exception) 
3973 {
3974   Unexpect aCatch(SALOME_SalomeException);
3975   GEOM::GEOM_Shape_var result;
3976   TopoDS_Shape tds ;
3977   
3978   try {
3979     gp_Pnt p(pstruct.x, pstruct.y, pstruct.z) ;
3980     gp_Dir d(dstruct.PS.x, dstruct.PS.y, dstruct.PS.z) ;
3981
3982     const gp_Ax2 axis(p, d) ;
3983     gp_Elips anEllipse( axis, radius_major, radius_minor ) ;
3984     BRepBuilderAPI_MakeEdge MakeEdge( anEllipse );
3985     tds = MakeEdge.Edge();
3986
3987   }
3988   catch(Standard_Failure) {
3989     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeEllipse", SALOME::BAD_PARAM);
3990   }
3991   if (tds.IsNull()) {
3992     THROW_SALOME_CORBA_EXCEPTION("Make Ellipse aborted", SALOME::BAD_PARAM);
3993   } 
3994   result = CreateObject(tds);
3995   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3996   result->ShapeId(entry);
3997   return result ;  
3998 }
3999
4000 //================================================================================
4001 // function : MakeArc()
4002 // purpose  : make an arc of circle from pInit to pEnd and passing on pCircle
4003 //================================================================================
4004 GEOM::GEOM_Shape_ptr  GEOM_Gen_i::MakeArc(const GEOM::PointStruct& pInit,
4005                                     const GEOM::PointStruct& pCircle,
4006                                     const GEOM::PointStruct& pEnd)
4007   throw (SALOME::SALOME_Exception) 
4008 {
4009   Unexpect aCatch(SALOME_SalomeException);
4010   GEOM::GEOM_Shape_var result;
4011   try {
4012     gp_Pnt pI(pInit.x, pInit.y, pInit.z) ;
4013     gp_Pnt pC(pCircle.x, pCircle.y, pCircle.z) ;
4014     gp_Pnt pE(pEnd.x, pEnd.y, pEnd.z) ;
4015     
4016     GC_MakeArcOfCircle arc( pI, pC, pE ) ;
4017     if( !arc.IsDone() ) {
4018       THROW_SALOME_CORBA_EXCEPTION("Arc not done", SALOME::BAD_PARAM);
4019     }
4020     BRepBuilderAPI_MakeEdge MakeEdge( arc );
4021     TopoDS_Shape tds = MakeEdge.Edge();
4022     if (tds.IsNull()) {
4023       THROW_SALOME_CORBA_EXCEPTION("Null result : arc not done", SALOME::BAD_PARAM);
4024     } 
4025     else {
4026       result = CreateObject(tds);
4027       const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
4028       result->ShapeId(entry);
4029     }
4030   }
4031   catch(Standard_Failure) {
4032     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeArc", SALOME::BAD_PARAM);
4033   }
4034   return result ;
4035 }
4036
4037 //=================================================================================
4038 // function : MakeSketcher()
4039 // purpose  : Make a wire from a list containing many points
4040 //=================================================================================
4041 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeSketcher( const char *Cmd )
4042   throw (SALOME::SALOME_Exception)
4043 {
4044   GEOM::GEOM_Shape_var result ;
4045   TopoDS_Shape tds ;
4046   try {
4047     Sketcher_Profile aProfile (Cmd);
4048     if(aProfile.IsDone())
4049       tds = aProfile.GetShape();
4050   }
4051   catch(Standard_Failure) {
4052     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeSketcher", SALOME::BAD_PARAM);
4053   }
4054
4055   if (tds.IsNull()) {
4056     THROW_SALOME_CORBA_EXCEPTION("MakeSketcher aborted : null shape", SALOME::BAD_PARAM);
4057   } 
4058   else {
4059     result = CreateObject(tds);
4060     const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
4061     result->ShapeId(entry) ;
4062   }
4063   return result;
4064 }
4065
4066
4067
4068 //=================================================================================
4069 // function : MakeBezier()
4070 // purpose  : Make a wire from a list containing many points
4071 //=================================================================================
4072 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeBezier( const GEOM::GEOM_Gen::ListOfIOR& ListShapes )
4073   throw (SALOME::SALOME_Exception)
4074 {
4075   GEOM::GEOM_Shape_var result;
4076   TopoDS_Shape tds, Shape;
4077   TColgp_Array1OfPnt CurvePoints(1, ListShapes.length());
4078   
4079   try {
4080     for(unsigned int i = 0; i < ListShapes.length(); i++) {
4081       GEOM::GEOM_Shape_var aShape = GetIORFromString(ListShapes[i]);    
4082       Shape = GetTopoShape(aShape);
4083       if(Shape.IsNull()) {
4084         THROW_SALOME_CORBA_EXCEPTION("MakeBezier aborted : null shape during operation", SALOME::BAD_PARAM);
4085       }
4086       if(Shape.ShapeType() == TopAbs_VERTEX) {
4087         const gp_Pnt& P = BRep_Tool::Pnt(TopoDS::Vertex(Shape));
4088         CurvePoints.SetValue(i + 1, P);
4089       }
4090     }
4091     Handle(Geom_BezierCurve) GBC = new Geom_BezierCurve(CurvePoints);
4092     tds = BRepBuilderAPI_MakeEdge(GBC);
4093   }
4094   catch(Standard_Failure) {
4095     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeBezier", SALOME::BAD_PARAM);
4096   }
4097   
4098   if( tds.IsNull() ) {
4099     THROW_SALOME_CORBA_EXCEPTION("Make Bezier operation aborted : null result", SALOME::BAD_PARAM);
4100   }
4101   else {
4102     result = CreateObject(tds);
4103     InsertInLabelMoreArguments(tds, result, ListShapes, myCurrentOCAFDoc);   
4104   }
4105   return result;
4106 }
4107
4108
4109 //=================================================================================
4110 // function : MakeInterpol()
4111 // purpose  : Make a wire from a list containing many points
4112 //=================================================================================
4113 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeInterpol( const GEOM::GEOM_Gen::ListOfIOR& ListShapes )
4114   throw (SALOME::SALOME_Exception)
4115 {
4116   GEOM::GEOM_Shape_var result;
4117   TopoDS_Shape tds, Shape;
4118   TColgp_Array1OfPnt CurvePoints(1, ListShapes.length());
4119   
4120   try {
4121     for(unsigned int i = 0; i < ListShapes.length(); i++) {
4122       GEOM::GEOM_Shape_var aShape = GetIORFromString(ListShapes[i]);    
4123       Shape = GetTopoShape(aShape);
4124       if(Shape.IsNull()) {
4125         THROW_SALOME_CORBA_EXCEPTION("MakeBSpline aborted : null shape during operation", SALOME::BAD_PARAM);
4126       }
4127       if(Shape.ShapeType() == TopAbs_VERTEX) {
4128         const gp_Pnt& P = BRep_Tool::Pnt(TopoDS::Vertex(Shape));
4129         CurvePoints.SetValue(i + 1, P);
4130       }
4131     }
4132     GeomAPI_PointsToBSpline GBC(CurvePoints);
4133     tds = BRepBuilderAPI_MakeEdge(GBC);
4134   }
4135   catch(Standard_Failure) {
4136     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeBSpline", SALOME::BAD_PARAM);
4137   }
4138   
4139   if( tds.IsNull() ) {
4140     THROW_SALOME_CORBA_EXCEPTION("Make BSpline operation aborted : null result", SALOME::BAD_PARAM);
4141   }
4142   else {
4143     result = CreateObject(tds) ;
4144     InsertInLabelMoreArguments(tds, result, ListShapes, myCurrentOCAFDoc) ;   
4145   }
4146   return result;
4147 }
4148
4149 //=================================================================================
4150 // function : MakeTranslation()
4151 // purpose  : Translate a 3D shape
4152 //=================================================================================
4153 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeTranslation( GEOM::GEOM_Shape_ptr myShape,
4154                                             CORBA::Double x,
4155                                             CORBA::Double y,
4156                                             CORBA::Double z)
4157   throw (SALOME::SALOME_Exception)
4158 {
4159   Unexpect aCatch(SALOME_SalomeException);
4160   GEOM::GEOM_Shape_var result ;
4161   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4162   if( aShape.IsNull() ) {
4163     THROW_SALOME_CORBA_EXCEPTION("Translation aborted : null shape", SALOME::BAD_PARAM);
4164   }
4165   gp_Vec theVector(x,y,z) ;
4166   gp_Trsf theTransformation ;
4167   theTransformation.SetTranslation(theVector) ;
4168   BRepBuilderAPI_Transform myBRepTransformation(aShape, theTransformation, Standard_False) ;
4169   TopoDS_Shape tds = myBRepTransformation.Shape() ;
4170
4171   result = CreateObject(tds) ;
4172   if( CORBA::is_nil(result) ) {
4173     THROW_SALOME_CORBA_EXCEPTION("Translation aborted : null result", SALOME::BAD_PARAM);
4174   }
4175   InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4176   return result;
4177 }
4178
4179
4180 //=================================================================================
4181 // function : MakeMultiTranslation1D()
4182 // purpose  : Multi-Translate a 3D shape
4183 //=================================================================================
4184 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeMultiTranslation1D( GEOM::GEOM_Shape_ptr myShape,
4185                                                    const GEOM::DirStruct& dir,
4186                                                    CORBA::Double step,
4187                                                    CORBA::Short nbtimes )
4188   throw (SALOME::SALOME_Exception)
4189 {
4190   Unexpect aCatch(SALOME_SalomeException);
4191   GEOM::GEOM_Shape_var result ;
4192   TopoDS_Shape tds ;
4193
4194   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4195   if( aShape.IsNull() )
4196     THROW_SALOME_CORBA_EXCEPTION("MakeMultiTranslation1D aborted : null shape", SALOME::BAD_PARAM);
4197   
4198   try {
4199     int i ;
4200     double DX, DY, DZ ;
4201     gp_Trsf theTransformation ;
4202     gp_Vec myVec ;
4203     gp_Vec Vec( dir.PS.x, dir.PS.y, dir.PS.z ) ;
4204     Vec.Normalize();
4205     TopoDS_Compound compound;
4206     BRep_Builder B;
4207     B.MakeCompound( compound );
4208     
4209     for ( i = 0; i < nbtimes; i++ ) {
4210       DX = i * step * Vec.X() ;
4211       DY = i * step * Vec.Y() ;
4212       DZ = i * step * Vec.Z() ;
4213       myVec.SetCoord( DX, DY, DZ ) ;
4214       theTransformation.SetTranslation(myVec) ;
4215       BRepBuilderAPI_Transform myBRepTransformation(aShape, theTransformation, Standard_False) ;
4216       B.Add( compound, myBRepTransformation.Shape() );
4217     }
4218     tds = compound ;
4219     result = CreateObject(tds) ;
4220   }
4221   catch (Standard_Failure) {
4222     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeMultiTranslation1D", SALOME::BAD_PARAM);
4223   }
4224     
4225   if( CORBA::is_nil(result) ) {
4226     THROW_SALOME_CORBA_EXCEPTION("MakeMultiTranslation1D aborted : null result", SALOME::BAD_PARAM);
4227   }
4228   InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4229   return result;
4230 }
4231
4232
4233 //=================================================================================
4234 // function : MakeMultiTranslation2D()
4235 // purpose  : Multi-Translate a 3D shape
4236 //=================================================================================
4237 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeMultiTranslation2D( GEOM::GEOM_Shape_ptr myShape,
4238                                                    const GEOM::DirStruct& dir1,
4239                                                    CORBA::Double step1,
4240                                                    CORBA::Short nbtimes1,
4241                                                    const GEOM::DirStruct& dir2,
4242                                                    CORBA::Double step2,
4243                                                    CORBA::Short nbtimes2 )
4244   throw (SALOME::SALOME_Exception)
4245 {
4246   Unexpect aCatch(SALOME_SalomeException);
4247   GEOM::GEOM_Shape_var result ;
4248   TopoDS_Shape tds ;
4249   
4250   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4251   if( aShape.IsNull() ) {
4252     THROW_SALOME_CORBA_EXCEPTION("MakeMultiTranslation2D aborted : null shape", SALOME::BAD_PARAM);
4253   }
4254   
4255   try {
4256     int i, j ;
4257     double DX, DY, DZ ;
4258     gp_Trsf theTransformation ;
4259     gp_Vec myVec ;
4260     gp_Vec Vec1( dir1.PS.x, dir1.PS.y, dir1.PS.z ) ;
4261     Vec1.Normalize();
4262     gp_Vec Vec2( dir2.PS.x, dir2.PS.y, dir2.PS.z ) ;
4263     Vec2.Normalize();
4264     TopoDS_Compound compound;
4265     BRep_Builder B;
4266     B.MakeCompound( compound );
4267     
4268     for ( i = 0; i < nbtimes1; i++ ) {
4269       for ( j = 0; j < nbtimes2; j++ ) {
4270         DX = i * step1 * Vec1.X() + j * step2 * Vec2.X() ;
4271         DY = i * step1 * Vec1.Y() + j * step2 * Vec2.Y() ;
4272         DZ = i * step1 * Vec1.Z() + j * step2 * Vec2.Z() ;
4273         myVec.SetCoord( DX, DY, DZ ) ;
4274         theTransformation.SetTranslation(myVec) ;
4275         BRepBuilderAPI_Transform myBRepTransformation(aShape, theTransformation, Standard_False) ;
4276         B.Add( compound, myBRepTransformation.Shape() );
4277       }
4278     }
4279     tds = compound ;
4280     result = CreateObject(tds) ;
4281   }
4282   catch(Standard_Failure) {
4283     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeMultiTranslation2D", SALOME::BAD_PARAM);
4284   }
4285    
4286   if( CORBA::is_nil(result) ) {
4287     THROW_SALOME_CORBA_EXCEPTION("MakeMultiTranslation2D aborted : null result", SALOME::BAD_PARAM);
4288   }
4289   InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4290   return result;
4291 }
4292
4293
4294 //=================================================================================
4295 // function : MakeMultiRotation1D()
4296 // purpose  : Multi-Rotate a 3D shape
4297 //=================================================================================
4298 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeMultiRotation1D( GEOM::GEOM_Shape_ptr myShape,
4299                                                 const GEOM::DirStruct& dir,
4300                                                 const GEOM::PointStruct& loc,
4301                                                 CORBA::Short nbtimes)
4302   throw (SALOME::SALOME_Exception)
4303 {
4304   Unexpect aCatch(SALOME_SalomeException);
4305   GEOM::GEOM_Shape_var result ;
4306   TopoDS_Shape tds ;
4307   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4308   if( aShape.IsNull() ) {
4309     THROW_SALOME_CORBA_EXCEPTION("MakeMultiRotation1D aborted : null shape", SALOME::BAD_PARAM);
4310   }
4311  
4312   try {
4313
4314     int i ;
4315     gp_Pnt P(loc.x, loc.y, loc.z) ;
4316     gp_Dir D(dir.PS.x, dir.PS.y, dir.PS.z) ;
4317     gp_Ax1 AX1(P, D) ;
4318     
4319     double angle = 360.0/nbtimes ;
4320     gp_Trsf theTransformation ;
4321     TopoDS_Compound compound;
4322     BRep_Builder B;
4323     B.MakeCompound( compound );
4324     
4325     for ( i = 0; i < nbtimes; i++ ) {
4326       theTransformation.SetRotation(AX1, i*angle*PI180) ;
4327       BRepBuilderAPI_Transform myBRepTransformation(aShape, theTransformation, Standard_False) ;
4328       B.Add( compound, myBRepTransformation.Shape() );
4329     }
4330     tds = compound ;
4331     result = CreateObject(tds) ;
4332   }
4333   catch(Standard_Failure) {
4334     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeMultiRotation1D", SALOME::BAD_PARAM);
4335   }
4336   
4337   if( CORBA::is_nil(result) ) {
4338     THROW_SALOME_CORBA_EXCEPTION("MakeMultiRotation1D aborted : null result", SALOME::BAD_PARAM);
4339   }
4340   InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4341   return result;
4342 }
4343
4344
4345 //=================================================================================
4346 // function : MakeMultiRotation2D()
4347 // purpose  : Multi-Rotate a 3D shape
4348 //=================================================================================
4349 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeMultiRotation2D( GEOM::GEOM_Shape_ptr myShape,
4350                                                 const GEOM::DirStruct& dir,
4351                                                 const GEOM::PointStruct& loc,
4352                                                 CORBA::Double ang,
4353                                                 CORBA::Short nbtimes1,
4354                                                 CORBA::Double step,
4355                                                 CORBA::Short nbtimes2 )
4356   throw (SALOME::SALOME_Exception)
4357 {
4358   Unexpect aCatch(SALOME_SalomeException);
4359   GEOM::GEOM_Shape_var result ;
4360   TopoDS_Shape tds ;
4361   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4362   if( aShape.IsNull() ) {
4363     THROW_SALOME_CORBA_EXCEPTION("MakeMultiRotation2D aborted : null shape", SALOME::BAD_PARAM);
4364   }
4365
4366   try {
4367    
4368     int i, j ;
4369     double DX, DY, DZ ;
4370     gp_Pnt P(loc.x, loc.y, loc.z) ;
4371     gp_Dir D(dir.PS.x, dir.PS.y, dir.PS.z) ;
4372     gp_Ax1 AX1(P, D) ;
4373     gp_Trsf theTransformation1 ;
4374     gp_Trsf theTransformation2 ;
4375     gp_Pnt P1 ;
4376     GProp_GProps System ;
4377     
4378     if ( aShape.ShapeType() == TopAbs_VERTEX) {
4379       P1 = BRep_Tool::Pnt(TopoDS::Vertex( aShape ));
4380     } 
4381     else if ( aShape.ShapeType() == TopAbs_EDGE || aShape.ShapeType() == TopAbs_WIRE ) {
4382       BRepGProp::LinearProperties(aShape, System);
4383       P1 = System.CentreOfMass() ;
4384     }
4385     else if ( aShape.ShapeType() == TopAbs_FACE || aShape.ShapeType() == TopAbs_SHELL ) {
4386       BRepGProp::SurfaceProperties(aShape, System);
4387       P1 = System.CentreOfMass() ;
4388     }
4389     else {
4390       BRepGProp::VolumeProperties(aShape, System);
4391       P1 = System.CentreOfMass() ;
4392     }
4393     
4394     Handle(Geom_Line) Line = new Geom_Line(AX1);
4395     gp_Pnt P2 = GeomAPI_ProjectPointOnCurve( P1, Line ) ;
4396     
4397     if ( P1.IsEqual(P2, Precision::Confusion() ) )
4398       THROW_SALOME_CORBA_EXCEPTION("Points are confused", SALOME::BAD_PARAM);
4399     
4400     gp_Vec Vec(P1.X()-P2.X(), P1.Y()-P2.Y(), P1.Z()-P2.Z()) ;
4401     Vec.Normalize();
4402     
4403     gp_Vec myVec ;
4404     TopoDS_Compound compound;
4405     BRep_Builder B;
4406     B.MakeCompound( compound );
4407     
4408     for ( i = 0; i < nbtimes2; i++ ) {
4409       for ( j = 0; j < nbtimes1; j++ ) {
4410         DX = i * step * Vec.X() ;
4411         DY = i * step * Vec.Y() ;
4412         DZ = i * step * Vec.Z() ;
4413         myVec.SetCoord( DX, DY, DZ ) ;
4414         theTransformation1.SetTranslation(myVec) ;
4415         theTransformation2.SetRotation(AX1, j*ang*PI180) ;
4416         BRepBuilderAPI_Transform myBRepTransformation1(aShape, theTransformation1, Standard_False) ;
4417         BRepBuilderAPI_Transform myBRepTransformation2(myBRepTransformation1.Shape(), theTransformation2, Standard_False) ;
4418         B.Add( compound, myBRepTransformation2.Shape() );
4419       }
4420     }
4421     tds = compound ;
4422     result = CreateObject(tds) ;  
4423   }
4424   catch(Standard_Failure) {
4425     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeMultiRotation2D", SALOME::BAD_PARAM);
4426   }
4427   
4428   if( CORBA::is_nil(result) ) {
4429     THROW_SALOME_CORBA_EXCEPTION("MakeMultiRotation2D aborted : null result", SALOME::BAD_PARAM);
4430   }
4431   InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4432   return result;
4433 }
4434
4435
4436 //=================================================================================
4437 // function : MakeCopy()
4438 // purpose  : Copy a 3D shape
4439 //=================================================================================
4440 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeCopy( GEOM::GEOM_Shape_ptr Shape)
4441   throw (SALOME::SALOME_Exception) 
4442 {
4443   Unexpect aCatch(SALOME_SalomeException);
4444   GEOM::GEOM_Shape_var result ;
4445   TopoDS_Shape tds ;
4446   TopoDS_Shape aShape = GetTopoShape(Shape) ;
4447   if(aShape.IsNull() ) {
4448     THROW_SALOME_CORBA_EXCEPTION("Copy aborted : null shape during operation", SALOME::BAD_PARAM);
4449   }  
4450   BRepBuilderAPI_Copy Copy(aShape);
4451   if( Copy.IsDone() ) {   
4452     tds = Copy.Shape();
4453     result = CreateObject(tds);    
4454     InsertInLabelOneArgument(aShape, Shape, tds, result, myCurrentOCAFDoc) ;
4455   }
4456
4457   return result;
4458 }
4459
4460
4461 //=================================================================================
4462 // function : MakeMirrorByPlane()
4463 // purpose  : build a shape by symmetry of 'myShape' with 'shapePlane' in argument
4464 //=================================================================================
4465 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeMirrorByPlane(GEOM::GEOM_Shape_ptr myShape,
4466                                              GEOM::GEOM_Shape_ptr shapePlane) 
4467   throw (SALOME::SALOME_Exception)
4468 {
4469   Unexpect aCatch(SALOME_SalomeException);
4470   GEOM::GEOM_Shape_var result ; 
4471   TopoDS_Shape tds ;
4472   TopoDS_Shape aShape      = GetTopoShape(myShape) ;
4473   TopoDS_Shape aShapePlane = GetTopoShape(shapePlane) ;
4474   if( aShape.IsNull()  || aShapePlane.IsNull() ) {
4475     THROW_SALOME_CORBA_EXCEPTION("Mirror aborted : null shape argument", SALOME::BAD_PARAM);
4476   }  
4477   
4478   try {
4479     Handle(Geom_Surface) surf = BRep_Tool::Surface(TopoDS::Face(aShapePlane)) ; 
4480     Handle(Geom_Plane) myPlane = Handle(Geom_Plane)::DownCast(surf) ;
4481     const gp_Ax3 pos = myPlane->Position() ;
4482     const gp_Pnt loc = pos.Location() ;  /* location of the plane */
4483     const gp_Dir dir = pos.Direction() ; /* Main direction of the plane (Z axis) */  
4484     
4485     /* plane used for mirroring */
4486     gp_Ax2 pln(loc, dir) ;
4487     gp_Trsf theTransformation ;
4488     theTransformation.SetMirror(pln) ;
4489     BRepBuilderAPI_Transform myBRepTransformation(aShape, theTransformation, Standard_False) ;
4490
4491     tds = myBRepTransformation.Shape() ;
4492     if(tds.IsNull() ) {
4493       THROW_SALOME_CORBA_EXCEPTION("Mirror aborted", SALOME::BAD_PARAM);
4494     }
4495   }
4496   catch(Standard_Failure) {
4497     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeMirrorByPlane", SALOME::BAD_PARAM);    
4498   }
4499   
4500   result = CreateObject(tds) ;
4501
4502   /* Insert arguments in ocaf */
4503   GEOM::GEOM_Gen::ListOfIOR_var ListShapes = new GEOM::GEOM_Gen::ListOfIOR;
4504   ListShapes->length(2);
4505   ListShapes[0] = GetStringFromIOR(GEOM::GEOM_Shape::_duplicate(myShape)) ;
4506   ListShapes[1] = GetStringFromIOR(GEOM::GEOM_Shape::_duplicate(shapePlane)) ;
4507   InsertInLabelMoreArguments(tds, result, ListShapes, myCurrentOCAFDoc) ;
4508   return result ;
4509 }
4510
4511
4512
4513 //=================================================================================
4514 // function : MakeRotation()
4515 // purpose  : Rotation of a 3D shape around an axis
4516 //=================================================================================
4517 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeRotation( GEOM::GEOM_Shape_ptr myShape,
4518                                          const GEOM::AxisStruct& axis,
4519                                          CORBA::Double angle)
4520   throw (SALOME::SALOME_Exception)
4521 {
4522   Unexpect aCatch(SALOME_SalomeException);
4523   GEOM::GEOM_Shape_var result ;
4524   TopoDS_Shape tds ;
4525   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4526   if( aShape.IsNull() ) {
4527     THROW_SALOME_CORBA_EXCEPTION("Rotation aborted : null shape during operation", SALOME::BAD_PARAM);
4528   }
4529   
4530   try {
4531     gp_Pnt P(axis.x, axis.y, axis.z) ;
4532     gp_Dir D(axis.vx, axis.vy, axis.vz) ;
4533     gp_Ax1 AX(P, D) ;
4534     
4535     gp_Trsf theTransformation ;
4536     theTransformation.SetRotation(AX, angle) ;
4537     BRepBuilderAPI_Transform myBRepTransformation(aShape, theTransformation, Standard_False) ;
4538     tds = myBRepTransformation.Shape() ;
4539   }
4540   catch(Standard_Failure) {
4541     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeRotation", SALOME::BAD_PARAM);
4542   }
4543   
4544   if ( !tds.IsNull() ) {
4545     result = CreateObject(tds) ;
4546     InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4547   }
4548   return result ;
4549 }
4550
4551
4552 //=================================================================================
4553 // function : MakeScaleTransform()
4554 // purpose  : Make a shape multipling another by a scale factor
4555 //=================================================================================
4556 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeScaleTransform(GEOM::GEOM_Shape_ptr myShape,
4557                                               const GEOM::PointStruct& theCenterOfScale,
4558                                               CORBA::Double factor)
4559   throw (SALOME::SALOME_Exception)
4560 {
4561   Unexpect aCatch(SALOME_SalomeException);
4562   GEOM::GEOM_Shape_var result ;
4563   TopoDS_Shape tds ;
4564   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4565   if( aShape.IsNull() ) {
4566     THROW_SALOME_CORBA_EXCEPTION("Scale aborted : null shape during operation", SALOME::BAD_PARAM);
4567   }
4568   
4569   try {
4570     gp_Pnt Pcenter(theCenterOfScale.x, theCenterOfScale.y, theCenterOfScale.z) ;
4571     gp_Trsf theTransformation ;  
4572     theTransformation.SetScale(Pcenter, factor) ;
4573     BRepBuilderAPI_Transform myBRepTransformation(aShape, theTransformation, Standard_False) ;
4574     tds = myBRepTransformation.Shape() ;
4575   }
4576   catch(Standard_Failure) {
4577     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeScaleTransform", SALOME::BAD_PARAM);
4578   }
4579   
4580   if ( !tds.IsNull() ) {
4581     result = CreateObject(tds) ; 
4582     InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4583   }
4584   return result ;
4585 }
4586
4587
4588 //=================================================================================
4589 // function : MakeCompound()
4590 // purpose  : Make a compound from a list containing one or more shapes
4591 //=================================================================================
4592 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeCompound( const GEOM::GEOM_Gen::ListOfIOR& ListShapes )
4593   throw (SALOME::SALOME_Exception)
4594 {
4595   Unexpect aCatch(SALOME_SalomeException);
4596   GEOM::GEOM_Shape_var result ;
4597   TopoDS_Compound C;
4598   BRep_Builder aBuilder;
4599   aBuilder.MakeCompound(C) ;
4600
4601   for ( unsigned int i = 0; i < ListShapes.length(); i++) {
4602     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[i] );    
4603     TopoDS_Shape Shape = GetTopoShape(aShape) ;
4604     if( Shape.IsNull() ) {
4605        THROW_SALOME_CORBA_EXCEPTION("Compound aborted : null shape during operation", SALOME::BAD_PARAM);
4606     }
4607     aBuilder.Add(C, Shape) ;
4608   }
4609   
4610   if ( C.IsNull() ) {
4611     THROW_SALOME_CORBA_EXCEPTION("Null result : Compound operation aborted", SALOME::BAD_PARAM);
4612   }
4613   else {
4614     result = CreateObject(C) ;
4615     InsertInLabelMoreArguments(C, result, ListShapes, myCurrentOCAFDoc) ;
4616   }
4617   return result;
4618 }
4619
4620
4621 //================================================================================
4622 // function : MakeEdge()
4623 // purpose  : Make a linear edge with 2 points
4624 //================================================================================
4625 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeEdge(const GEOM::PointStruct& pstruct1,
4626                                     const GEOM::PointStruct& pstruct2)
4627   throw (SALOME::SALOME_Exception)
4628 {
4629   Unexpect aCatch(SALOME_SalomeException);
4630   GEOM::GEOM_Shape_var result  ;
4631   TopoDS_Shape tds ;
4632   
4633   try {
4634     gp_Pnt P1(pstruct1.x, pstruct1.y, pstruct1.z);
4635     gp_Pnt P2(pstruct2.x, pstruct2.y, pstruct2.z) ;  
4636     tds = BRepBuilderAPI_MakeEdge(P1, P2).Shape();
4637     if ( tds.IsNull() )
4638       THROW_SALOME_CORBA_EXCEPTION("MakeEdge aborted : null result", SALOME::BAD_PARAM);
4639   }
4640   catch (Standard_Failure) {
4641     THROW_SALOME_CORBA_EXCEPTION("Exception catched in MakeEdge", SALOME::BAD_PARAM);
4642   }
4643   
4644   result = CreateObject(tds) ;
4645   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
4646   result->ShapeId(entry);
4647   return result ;  
4648 }
4649
4650
4651
4652 //=================================================================================
4653 // function : MakeWire()
4654 // purpose  : Make a wire from a list containing one or more edges or wires that can
4655 // be connected
4656 //=================================================================================
4657 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeWire( const GEOM::GEOM_Gen::ListOfIOR& ListShapes )
4658   throw (SALOME::SALOME_Exception)
4659 {
4660   Unexpect aCatch(SALOME_SalomeException);
4661   GEOM::GEOM_Shape_var result ;
4662   BRepBuilderAPI_MakeWire MW ;
4663   TopoDS_Shape tds, Shape ; 
4664   
4665   try {
4666     for ( unsigned int i = 0; i < ListShapes.length(); i++) {
4667       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[i] );    
4668       Shape = GetTopoShape(aShape) ;
4669       if( Shape.IsNull() ) {
4670         THROW_SALOME_CORBA_EXCEPTION("MakeWire aborted : null shape during operation", SALOME::BAD_PARAM);
4671       }
4672       if( Shape.ShapeType() == TopAbs_EDGE )
4673         MW.Add( TopoDS::Edge(Shape) ) ;
4674       if (Shape.ShapeType() == TopAbs_WIRE ) 
4675         MW.Add( TopoDS::Wire(Shape) ) ;
4676     }    
4677     tds = MW  ;
4678
4679   }
4680   catch(Standard_Failure) {
4681     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeWire", SALOME::BAD_PARAM);
4682   }
4683   
4684   if( tds.IsNull() ) {
4685     THROW_SALOME_CORBA_EXCEPTION("Make Wire operation aborted : null result", SALOME::BAD_PARAM);
4686   }
4687   else {
4688     result = CreateObject(tds) ;
4689     InsertInLabelMoreArguments(tds, result, ListShapes, myCurrentOCAFDoc) ;   
4690   }
4691   return result;
4692 }
4693
4694
4695 //=================================================================================
4696 // function : MakeRevolution()
4697 // purpose  : 
4698 //=================================================================================
4699 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeRevolution(GEOM::GEOM_Shape_ptr myShape,
4700                                           const GEOM::AxisStruct& axis,
4701                                           double angle)
4702   throw (SALOME::SALOME_Exception)
4703
4704   Unexpect aCatch(SALOME_SalomeException);
4705   GEOM::GEOM_Shape_var result ;
4706   TopoDS_Shape tds ;
4707   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4708   if( aShape.IsNull() ) {
4709     THROW_SALOME_CORBA_EXCEPTION("Revolution aborted : null shape", SALOME::BAD_PARAM);
4710   }
4711   try {
4712     gp_Pnt P(axis.x, axis.y, axis.z) ;
4713     gp_Dir D(axis.vx, axis.vy, axis.vz);
4714     gp_Ax1 AX(P,D);
4715     tds = BRepPrimAPI_MakeRevol(aShape, AX, angle);
4716   }
4717   catch(Standard_Failure) {
4718     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeRevolution", SALOME::BAD_PARAM);
4719   }
4720   
4721   if( tds.IsNull() ) {
4722     THROW_SALOME_CORBA_EXCEPTION("Revolution aborted", SALOME::BAD_PARAM);
4723   }
4724   result = CreateObject(tds) ;
4725   InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4726   return result ;     
4727 }
4728
4729
4730 //=================================================================================
4731 // function : MakePipe()
4732 // purpose  : Create a shape by sweeping a baseShape along a pathShape
4733 //=================================================================================
4734 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakePipe( GEOM::GEOM_Shape_ptr pathShape,
4735                                      GEOM::GEOM_Shape_ptr baseShape )
4736   throw (SALOME::SALOME_Exception)
4737 {
4738   Unexpect aCatch(SALOME_SalomeException);
4739   GEOM::GEOM_Shape_var result ;
4740   TopoDS_Shape tds ;
4741   TopoDS_Wire aWire ;
4742   TopoDS_Shape pathTds = GetTopoShape(pathShape) ;
4743   TopoDS_Shape baseTds = GetTopoShape(baseShape) ;
4744
4745   if( baseTds.IsNull() || pathTds.IsNull() ) {
4746     THROW_SALOME_CORBA_EXCEPTION("MakePipe aborted : null shape argument", SALOME::BAD_PARAM);
4747   }
4748
4749   if( pathTds.ShapeType() == TopAbs_WIRE ) {
4750     aWire = TopoDS::Wire(pathTds) ;
4751   }
4752   else {
4753     if ( pathTds.ShapeType() == TopAbs_EDGE ) {
4754       TopoDS_Edge aEdge = TopoDS::Edge(pathTds) ;
4755       aWire = BRepBuilderAPI_MakeWire(aEdge);
4756     }
4757     else {
4758       THROW_SALOME_CORBA_EXCEPTION("MakePipe aborted : bad shape type", SALOME::BAD_PARAM);
4759     }
4760   }
4761
4762   try {
4763     tds = BRepOffsetAPI_MakePipe(aWire, baseTds) ;
4764   }
4765   catch(Standard_Failure) {
4766     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakePipe", SALOME::BAD_PARAM);
4767   }
4768   
4769   if (  !IsValid(tds) ) {
4770     THROW_SALOME_CORBA_EXCEPTION("MakePipe aborted : non valid shape result", SALOME::BAD_PARAM);
4771   }
4772   else {
4773     result = CreateObject(tds) ;
4774
4775     /* Insert arguments in ocaf */
4776     GEOM::GEOM_Gen::ListOfIOR_var ListShapes = new GEOM::GEOM_Gen::ListOfIOR;
4777     ListShapes->length(2);
4778     ListShapes[0] = GetStringFromIOR(GEOM::GEOM_Shape::_duplicate(pathShape)) ;
4779     ListShapes[1] = GetStringFromIOR(GEOM::GEOM_Shape::_duplicate(baseShape)) ;    
4780     InsertInLabelMoreArguments(tds, result, ListShapes, myCurrentOCAFDoc) ;
4781   }
4782   return result ;
4783 }
4784
4785
4786 //=================================================================================
4787 // function : MakePrism()
4788 // purpose  : uses myShape as base and the vector P1 to P2
4789 //=================================================================================
4790 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakePrism( GEOM::GEOM_Shape_ptr myShape,
4791                                            const GEOM::PointStruct& P1,
4792                                            const GEOM::PointStruct& P2 )
4793   throw (SALOME::SALOME_Exception)
4794 {               
4795   Unexpect aCatch(SALOME_SalomeException);
4796   GEOM::GEOM_Shape_var result ;
4797   TopoDS_Shape tds ;
4798   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4799   if( aShape.IsNull() ) {
4800     THROW_SALOME_CORBA_EXCEPTION("Prism aborted : null shape operation", SALOME::BAD_PARAM);
4801   }
4802   
4803   try {
4804     gp_Vec Vector (P2.x - P1.x, P2.y - P1.y, P2.z - P1.z) ;
4805     tds = BRepPrimAPI_MakePrism(aShape, Vector, Standard_False).Shape() ;
4806   }
4807   catch(Standard_Failure) {
4808     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakePipe", SALOME::BAD_PARAM);
4809   }
4810   
4811   if ( tds.IsNull() ) {
4812     THROW_SALOME_CORBA_EXCEPTION("Prism aborted", SALOME::BAD_PARAM);
4813   }
4814   else {
4815     result = CreateObject(tds) ;     
4816     InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4817   }
4818   return result ;
4819 }
4820
4821
4822 //=================================================================================
4823 // function : MakeCDG()
4824 // purpose  : Create a CDG topology.
4825 //=================================================================================
4826 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeCDG(GEOM::GEOM_Shape_ptr aShape) 
4827   throw (SALOME::SALOME_Exception)
4828 {
4829   Unexpect aCatch(SALOME_SalomeException);
4830   GEOM::GEOM_Shape_var result ;
4831   TopoDS_Shape tds ;
4832   TopoDS_Shape shape = GetTopoShape(aShape) ;
4833   GProp_GProps System;
4834   gp_Pnt myCenterMass ;
4835
4836   if( shape.IsNull() ) {
4837     THROW_SALOME_CORBA_EXCEPTION("MakeCDG aborted : null shape argument", SALOME::BAD_PARAM);
4838   }
4839   
4840   try {
4841     if ( shape.ShapeType() == TopAbs_VERTEX) {
4842       myCenterMass = BRep_Tool::Pnt(TopoDS::Vertex( shape ));
4843     } 
4844     else if ( shape.ShapeType() == TopAbs_EDGE || shape.ShapeType() == TopAbs_WIRE ) {
4845       BRepGProp::LinearProperties(shape, System);
4846       myCenterMass = System.CentreOfMass() ;
4847     }
4848     else if ( shape.ShapeType() == TopAbs_FACE || shape.ShapeType() == TopAbs_SHELL ) {
4849       BRepGProp::SurfaceProperties(shape, System);
4850       myCenterMass = System.CentreOfMass() ;
4851     }
4852     else {
4853       BRepGProp::VolumeProperties(shape, System);
4854       myCenterMass = System.CentreOfMass() ;
4855     }
4856
4857     tds = BRepBuilderAPI_MakeVertex(myCenterMass).Shape() ;
4858   }
4859   catch(Standard_Failure) {
4860     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeCDG", SALOME::BAD_PARAM);
4861   }
4862   
4863   if ( tds.IsNull() ) {
4864     THROW_SALOME_CORBA_EXCEPTION("Make CDG aborted : null shape result", SALOME::BAD_PARAM);
4865   }
4866   else {
4867     result = CreateObject(tds) ;     
4868     InsertInLabelOneArgument(shape, aShape, tds, result, myCurrentOCAFDoc) ;
4869   }
4870   return result ; 
4871 }
4872
4873
4874 //=================================================================================
4875 // function : Archimede()
4876 // purpose  :
4877 //=================================================================================
4878 GEOM::GEOM_Shape_ptr GEOM_Gen_i::Archimede(GEOM::GEOM_Shape_ptr aShape,
4879                                      CORBA::Double aWeight,
4880                                      CORBA::Double aWaterDensity,
4881                                      CORBA::Double aMeshingDeflection)
4882   throw (SALOME::SALOME_Exception)
4883 {
4884   Unexpect aCatch(SALOME_SalomeException);
4885   GEOM::GEOM_Shape_var result;
4886
4887   double cste = -1;
4888   if (aWaterDensity != 0.)
4889     cste = aWeight/aWaterDensity;
4890   else
4891     THROW_SALOME_CORBA_EXCEPTION("Water density is null", SALOME::BAD_PARAM);
4892
4893   TopoDS_Shape shape = GetTopoShape(aShape) ;
4894   if( shape.IsNull() ) {
4895     THROW_SALOME_CORBA_EXCEPTION("Shape is null", SALOME::BAD_PARAM);
4896   }
4897
4898   gp_Dir direct(0.0,0.0,1.0);
4899   gp_Pnt PosPlan(0.0,0.0,0.0);
4900   Geom_Plane PP (PosPlan,direct);
4901   Handle(Geom_Geometry) G = PP.Copy();
4902   Handle(Geom_Plane) P = Handle(Geom_Plane)::DownCast(G);
4903
4904   gp_Dir Zdirection(0.0,0.0,1.0);
4905   VolumeSection VOL( shape, aMeshingDeflection);
4906   VOL.SetPlane(P);
4907   Handle (Geom_RectangularTrimmedSurface) SurfaceTrimmee;
4908   
4909   if(Zdirection.IsEqual(direct,Precision::Angular()) == Standard_False) { 
4910     VOL.MakeRotation(direct);
4911   }
4912   
4913   VOL.CenterOfGravity();
4914   SurfaceTrimmee = VOL.TrimSurf();
4915   Standard_Real Cote = VOL.Archimede( cste, aMeshingDeflection );
4916   
4917   if ( Cote == -1 ) {
4918     double Zmin,Zmax;
4919     VOL.getZ(Zmin,Zmax);
4920     double volume = VOL.CalculateVolume( Zmax ) * aWaterDensity;
4921
4922     char msg[100]="";  
4923     sprintf(msg, "shape sinks to the bottom : Weigth max = %.1f", volume);
4924
4925     THROW_SALOME_CORBA_EXCEPTION(msg, SALOME::BAD_PARAM);
4926   }
4927   
4928   SurfaceTrimmee=VOL.AjustePlan(SurfaceTrimmee,Cote,PosPlan);
4929   if(Zdirection.IsEqual(direct,Precision::Angular()) == Standard_False) { 
4930     SurfaceTrimmee=VOL.InvMakeRotation(direct,SurfaceTrimmee);
4931   }
4932   
4933   Standard_Real u1,u2,v1,v2;
4934   SurfaceTrimmee->Bounds(u1,u2,v1,v2);
4935   TopoDS_Face tirant = BRepBuilderAPI_MakeFace(SurfaceTrimmee, u1, u2, v1, v2);
4936   
4937   if (tirant.IsNull()) {
4938     THROW_SALOME_CORBA_EXCEPTION("Result is null", SALOME::BAD_PARAM);
4939   }
4940
4941   result = CreateObject(tirant);
4942   InsertInLabelOneArgument(shape, aShape, tirant, result, myCurrentOCAFDoc) ;
4943
4944   return result;  
4945 }
4946
4947
4948 //================================================================================
4949 // function : MakeFillet()
4950 // purpose  : Create a cylinder topology
4951 //================================================================================
4952 GEOM::GEOM_Shape_ptr  GEOM_Gen_i::MakeFillet( GEOM::GEOM_Shape_ptr shape,
4953                                               CORBA::Double radius,
4954                                               CORBA::Short ShapeType,
4955                                               const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID ) 
4956   throw (SALOME::SALOME_Exception)
4957 {
4958   Unexpect aCatch(SALOME_SalomeException);
4959   GEOM::GEOM_Shape_var result;
4960   TopoDS_Shape tds ;
4961
4962   const TopoDS_Shape aShape = GetTopoShape(shape) ;
4963   if( aShape.IsNull() ) {
4964     THROW_SALOME_CORBA_EXCEPTION("Shape is null", SALOME::BAD_PARAM);
4965   }
4966
4967   BRepFilletAPI_MakeFillet fill(aShape);
4968
4969   try {
4970     /* case all */
4971     if(ListOfID.length() == 0) {
4972       TopExp_Explorer Exp ( aShape, TopAbs_EDGE );
4973       for (Exp; Exp.More(); Exp.Next()) {
4974         TopoDS_Edge E =TopoDS::Edge(Exp.Current());
4975         fill.Add(E);
4976       }
4977       for (int i = 1;i<=fill.NbContours();i++) {
4978 #if OCC_VERSION_MAJOR >= 5
4979         fill.SetRadius(radius,i,i);
4980 #else
4981         fill.SetRadius(radius,i);
4982 #endif
4983       }
4984       tds = fill.Shape();
4985       
4986     } else {
4987
4988       /* case selection */               
4989       for ( unsigned int ind = 0; ind < ListOfID.length(); ind++ ) {
4990         TopoDS_Shape ss ;
4991         if( GetShapeFromIndex( aShape, (TopAbs_ShapeEnum)ShapeType, ListOfID[ind], ss ) ) {
4992           TopoDS_Edge E = TopoDS::Edge(ss) ;
4993           fill.Add( E );
4994         }
4995       }
4996       for (int i = 1;i<=fill.NbContours();i++) {
4997 #if OCC_VERSION_MAJOR >= 5
4998         fill.SetRadius(radius,i,i);
4999 #else
5000         fill.SetRadius(radius,i);
5001 #endif
5002       }
5003       tds = fill.Shape();
5004     }
5005   }
5006   catch(Standard_Failure) {
5007     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeFillet", SALOME::BAD_PARAM);
5008   }
5009   
5010   if (tds.IsNull()) {
5011     THROW_SALOME_CORBA_EXCEPTION("Make Fillet aborted", SALOME::BAD_PARAM);
5012   } 
5013   result = CreateObject(tds);
5014   InsertInLabelOneArgument(aShape, shape, tds, result, myCurrentOCAFDoc) ;
5015
5016   return result ;  
5017 }
5018
5019 //================================================================================
5020 // function : MakeFilletR1R2()
5021 // purpose  : Create a cylinder topology
5022 //================================================================================
5023 GEOM::GEOM_Shape_ptr  GEOM_Gen_i::MakeFilletR1R2( GEOM::GEOM_Shape_ptr shape,
5024                                                   CORBA::Double radius1,
5025                                                   CORBA::Double radius2,
5026                                                   CORBA::Short ShapeType,
5027                                                   const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID ) 
5028   throw (SALOME::SALOME_Exception)
5029 {
5030   Unexpect aCatch(SALOME_SalomeException);
5031   GEOM::GEOM_Shape_var result;
5032   TopoDS_Shape tds ;
5033
5034   const TopoDS_Shape aShape = GetTopoShape(shape) ;
5035   if( aShape.IsNull() ) {
5036     THROW_SALOME_CORBA_EXCEPTION("Shape is null", SALOME::BAD_PARAM);
5037   }
5038
5039   BRepFilletAPI_MakeFillet fill(aShape);
5040
5041   try {
5042     /* case all */
5043     if(ListOfID.length() == 0) {
5044       TopExp_Explorer Exp ( aShape, TopAbs_EDGE );
5045       for (Exp; Exp.More(); Exp.Next()) {
5046         TopoDS_Edge E =TopoDS::Edge(Exp.Current());
5047         fill.Add(E);
5048       }
5049       for (int i = 1;i<=fill.NbContours();i++) {
5050 #if OCC_VERSION_MAJOR >= 5
5051         fill.SetRadius(radius1,radius2,i,i);
5052 #else
5053         fill.SetRadius(radius1,radius2,i);
5054 #endif
5055       }
5056       tds = fill.Shape();
5057       
5058     } else {
5059
5060       /* case selection */               
5061       for ( unsigned int ind = 0; ind < ListOfID.length(); ind++ ) {
5062         TopoDS_Shape ss ;
5063         if( GetShapeFromIndex( aShape, (TopAbs_ShapeEnum)ShapeType, ListOfID[ind], ss ) ) {
5064           TopoDS_Edge E = TopoDS::Edge(ss) ;
5065           fill.Add( E );
5066         }
5067       }
5068       for (int i = 1;i<=fill.NbContours();i++) {
5069 #if OCC_VERSION_MAJOR >= 5
5070         fill.SetRadius(radius1,radius2,i,i);
5071 #else
5072         fill.SetRadius(radius1,radius2,i);
5073 #endif
5074       }
5075       tds = fill.Shape();
5076     }
5077   }
5078   catch(Standard_Failure) {
5079     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeFilletR1R2", SALOME::BAD_PARAM);
5080   }
5081   
5082   if (tds.IsNull()) {
5083     THROW_SALOME_CORBA_EXCEPTION("Make Fillet aborted", SALOME::BAD_PARAM);
5084   } 
5085   result = CreateObject(tds);
5086   InsertInLabelOneArgument(aShape, shape, tds, result, myCurrentOCAFDoc) ;
5087
5088   return result ;  
5089 }
5090
5091 //================================================================================
5092 // function : MakeChamfer
5093 // purpose  : Create a Chamfer topology
5094 //================================================================================
5095 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeChamfer( GEOM::GEOM_Shape_ptr shape,
5096                                               CORBA::Double d1,
5097                                               CORBA::Double d2,
5098                                               CORBA::Short ShapeType,
5099                                               const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID ) 
5100   throw (SALOME::SALOME_Exception)
5101 {
5102   Unexpect aCatch(SALOME_SalomeException);
5103   GEOM::GEOM_Shape_var result;
5104   TopoDS_Shape tds ;
5105
5106   const TopoDS_Shape aShape = GetTopoShape(shape) ;
5107   if( aShape.IsNull() ) {
5108     THROW_SALOME_CORBA_EXCEPTION("Shape is null", SALOME::BAD_PARAM);
5109   }
5110   
5111   BRepFilletAPI_MakeChamfer MC(aShape);
5112
5113   try {
5114     /* case all */
5115     TopTools_IndexedDataMapOfShapeListOfShape M;
5116     TopExp::MapShapesAndAncestors(aShape,TopAbs_EDGE,TopAbs_FACE,M);
5117     if(ListOfID.length() == 0) {
5118       for (int i = 1;i<=M.Extent();i++) {
5119         TopoDS_Edge E = TopoDS::Edge(M.FindKey(i));
5120         TopoDS_Face F = TopoDS::Face(M.FindFromIndex(i).First());
5121         if (!BRepTools::IsReallyClosed(E, F) && !BRep_Tool::Degenerated(E))
5122           MC.Add(d1,d2,E,F);
5123       }
5124       tds = MC.Shape();
5125
5126     } else {
5127
5128       /* case selection */  
5129       for ( unsigned int ind = 0; ind < ListOfID.length(); ind++ ) {
5130         TopoDS_Shape ss ;
5131         if( GetShapeFromIndex( aShape, (TopAbs_ShapeEnum)ShapeType, ListOfID[ind], ss ) ) {
5132           TopoDS_Edge E = TopoDS::Edge( ss ) ;
5133           TopoDS_Face F = TopoDS::Face(M.FindFromKey(E).First());
5134           if (!BRepTools::IsReallyClosed(E, F) && !BRep_Tool::Degenerated(E))
5135             MC.Add(d1,d2,E,F);
5136         }
5137       }
5138       tds = MC.Shape();
5139     }
5140   }
5141   catch(Standard_Failure) {
5142     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeChamfer", SALOME::BAD_PARAM);
5143   }
5144   
5145   if (tds.IsNull()) {
5146     THROW_SALOME_CORBA_EXCEPTION("Make Chamfer aborted", SALOME::BAD_PARAM);
5147   } 
5148   result = CreateObject(tds);
5149   InsertInLabelOneArgument(aShape, shape, tds, result, myCurrentOCAFDoc) ;
5150
5151   return result ;
5152 }
5153
5154 //================================================================================
5155 // function : MakeChamferAD
5156 // purpose  : Create a Chamfer topology by Lenght & Angle
5157 //================================================================================
5158 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeChamferAD( GEOM::GEOM_Shape_ptr shape,
5159                                                 CORBA::Double d,
5160                                                 CORBA::Double angle,
5161                                                 CORBA::Short ShapeType,
5162                                                 const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID ) 
5163   throw (SALOME::SALOME_Exception)
5164 {
5165   Unexpect aCatch(SALOME_SalomeException);
5166   GEOM::GEOM_Shape_var result;
5167   TopoDS_Shape tds ;
5168
5169   const TopoDS_Shape aShape = GetTopoShape(shape) ;
5170   if( aShape.IsNull() ) {
5171     THROW_SALOME_CORBA_EXCEPTION("Shape is null", SALOME::BAD_PARAM);
5172   }
5173   
5174   BRepFilletAPI_MakeChamfer MC(aShape);
5175
5176   try {
5177     /* case all */
5178     TopTools_IndexedDataMapOfShapeListOfShape M;
5179     TopExp::MapShapesAndAncestors(aShape,TopAbs_EDGE,TopAbs_FACE,M);
5180     if(ListOfID.length() == 0) {
5181       for (int i = 1;i<=M.Extent();i++) {
5182         TopoDS_Edge E = TopoDS::Edge(M.FindKey(i));
5183         TopoDS_Face F = TopoDS::Face(M.FindFromIndex(i).First());
5184         if (!BRepTools::IsReallyClosed(E, F) && !BRep_Tool::Degenerated(E))
5185           MC.AddDA(d,angle,E,F);
5186       }
5187       tds = MC.Shape();
5188
5189     } else {
5190
5191       /* case selection */  
5192       for ( unsigned int ind = 0; ind < ListOfID.length(); ind++ ) {
5193         TopoDS_Shape ss ;
5194         if( GetShapeFromIndex( aShape, (TopAbs_ShapeEnum)ShapeType, ListOfID[ind], ss ) ) {
5195           TopoDS_Edge E = TopoDS::Edge( ss ) ;
5196           TopoDS_Face F = TopoDS::Face(M.FindFromKey(E).First());
5197           if (!BRepTools::IsReallyClosed(E, F) && !BRep_Tool::Degenerated(E))
5198             MC.AddDA(d,angle,E,F);
5199         }
5200       }
5201       tds = MC.Shape();
5202     }
5203   }
5204   catch(Standard_Failure) {
5205     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeChamferAD", SALOME::BAD_PARAM);
5206   }
5207   
5208   if (tds.IsNull()) {
5209     THROW_SALOME_CORBA_EXCEPTION("Make ChamferAD aborted", SALOME::BAD_PARAM);
5210   } 
5211   result = CreateObject(tds);
5212   InsertInLabelOneArgument(aShape, shape, tds, result, myCurrentOCAFDoc) ;
5213   return result ;
5214 }
5215
5216 //=================================================================================
5217 // function : CheckShape()
5218 // purpose  :
5219 //=================================================================================
5220 CORBA::Boolean GEOM_Gen_i::CheckShape(GEOM::GEOM_Shape_ptr shape) 
5221   throw (SALOME::SALOME_Exception)
5222 {
5223   Unexpect aCatch(SALOME_SalomeException);
5224   TopoDS_Shape S = GetTopoShape(shape) ;
5225   if( S.IsNull() ) {
5226     THROW_SALOME_CORBA_EXCEPTION("Shape is null", SALOME::BAD_PARAM);
5227   }
5228
5229   BRepCheck_Analyzer ana(S,false);
5230   if (ana.IsValid()) 
5231     return 1;
5232
5233   return 0;
5234 }
5235
5236 //=================================================================================
5237 // function : MakePlacedBox()
5238 // purpose  :
5239 //=================================================================================
5240 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakePlacedBox(CORBA::Double x1,  CORBA::Double y1,  CORBA::Double z1,
5241                                          CORBA::Double delta1, CORBA::Double delta2, CORBA::Double delta3)
5242   throw (SALOME::SALOME_Exception)
5243 {
5244   Unexpect aCatch(SALOME_SalomeException);
5245   GEOM::GEOM_Shape_var result ;
5246   TopoDS_Shape tds ;
5247
5248   CORBA::Double x2, y2, z2 ;
5249
5250   try {
5251     x2 = x1 + delta1 ;
5252     y2 = y1 + delta2 ;
5253     z2 = z1 + delta3 ;
5254     
5255     gp_Pnt P1(x1,y1,z1);
5256     gp_Pnt P2(x2,y2,z2);
5257     
5258     tds = BRepPrimAPI_MakeBox(P1,P2).Shape();
5259   }
5260   catch(Standard_Failure) {
5261     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeBox", SALOME::BAD_PARAM);
5262   }
5263   
5264   if (tds.IsNull()) {
5265     THROW_SALOME_CORBA_EXCEPTION("Make Box aborted : null shape", SALOME::BAD_PARAM);
5266   } 
5267   
5268   result = CreateObject(tds);
5269   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
5270   result->ShapeId(entry) ;
5271
5272   return result;  
5273 }
5274
5275 //=================================================================================
5276 // function : MakePanel()
5277 // purpose  :
5278 //=================================================================================
5279 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakePanel(GEOM::GEOM_Shape_ptr shape,
5280                                      CORBA::Short directiontype,
5281                                      CORBA::Double delta)
5282   throw (SALOME::SALOME_Exception)
5283 {
5284   Unexpect aCatch(SALOME_SalomeException);
5285   GEOM::GEOM_Shape_var result ;
5286   TopoDS_Shape tds ;
5287   TopoDS_Shape aShape = GetTopoShape(shape) ;
5288   Bnd_Box B ;
5289   Standard_Real axmin,aymin,azmin,axmax,aymax,azmax ;
5290   GEOM::PointStruct pstruct1, pstruct2, pstruct3, pstruct4 ;
5291
5292   if(aShape.IsNull() ) {
5293     THROW_SALOME_CORBA_EXCEPTION("MakePanel aborted : null shape during operation", SALOME::BAD_PARAM);
5294   }  
5295
5296   try {
5297     BRepBndLib::Add(aShape,B);
5298     B.Enlarge(10.);
5299     B.Get(axmin,aymin,azmin,axmax,aymax,azmax);
5300     
5301     switch (directiontype)
5302       {
5303       case 1 :   /* X */
5304         pstruct1 = MakePointStruct( delta, aymin, azmin ) ;
5305         pstruct2 = MakePointStruct( delta, aymin, azmax ) ;
5306         pstruct3 = MakePointStruct( delta, aymax, azmax ) ;
5307         pstruct4 = MakePointStruct( delta, aymax, azmin ) ;
5308         break ;
5309       case 2 :   /* Y */
5310         pstruct1 = MakePointStruct( axmin, delta, azmin ) ;
5311         pstruct2 = MakePointStruct( axmin, delta, azmax ) ;
5312         pstruct3 = MakePointStruct( axmax, delta, azmax ) ;
5313         pstruct4 = MakePointStruct( axmax, delta, azmin ) ;
5314         break ;
5315       case 3 :   /* Z */
5316         pstruct1 = MakePointStruct( axmin, aymin, delta ) ;
5317         pstruct2 = MakePointStruct( axmin, aymax, delta ) ;
5318         pstruct3 = MakePointStruct( axmax, aymax, delta ) ;
5319         pstruct4 = MakePointStruct( axmax, aymin, delta ) ;
5320         break ;
5321       default :
5322         return result ;
5323       }
5324     
5325     GEOM::GEOM_Shape_ptr Edge1 = MakeEdge(pstruct1, pstruct2);
5326     GEOM::GEOM_Shape_ptr Edge2 = MakeEdge(pstruct2, pstruct3);
5327     GEOM::GEOM_Shape_ptr Edge3 = MakeEdge(pstruct3, pstruct4);
5328     GEOM::GEOM_Shape_ptr Edge4 = MakeEdge(pstruct4, pstruct1);
5329     
5330     GEOM::GEOM_Gen::ListOfIOR_var aList = new GEOM::GEOM_Gen::ListOfIOR;
5331     aList->length(4);
5332     aList[0]=CORBA::string_dup(Edge1->Name());
5333     aList[1]=CORBA::string_dup(Edge2->Name());
5334     aList[2]=CORBA::string_dup(Edge3->Name());
5335     aList[3]=CORBA::string_dup(Edge4->Name());
5336     
5337     GEOM::GEOM_Shape_ptr aWire = MakeWire( aList );
5338     GEOM::GEOM_Shape_ptr aFace = MakeFace( aWire, true ) ;
5339     tds = GetTopoShape(aFace);
5340     
5341   }
5342   catch(Standard_Failure) {
5343     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakePanel", SALOME::BAD_PARAM);
5344   }
5345   
5346   if (tds.IsNull()) {
5347     THROW_SALOME_CORBA_EXCEPTION("Make PanelsPartition aborted : null shape", SALOME::BAD_PARAM);
5348   } 
5349   
5350   result = CreateObject(tds); 
5351   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
5352   result->ShapeId(entry) ;
5353   
5354   return result;
5355 }
5356
5357
5358 void GEOM_Gen_i::ExportIGES(const char* filename,GEOM::GEOM_Shape_ptr theShape) 
5359   throw (SALOME::SALOME_Exception)
5360 {
5361   Unexpect aCatch(SALOME_SalomeException);
5362   if (theShape->_is_nil()) 
5363     {
5364       THROW_SALOME_CORBA_EXCEPTION("Export IGES aborted", SALOME::BAD_PARAM);
5365     } 
5366   TopoDS_Shape tds = GetTopoShape(theShape);
5367   if (tds.IsNull()) 
5368     {
5369       THROW_SALOME_CORBA_EXCEPTION("Export IGES aborted", SALOME::BAD_PARAM);
5370     } 
5371   try 
5372     {
5373       //VRV: OCC 4.0 migration
5374       IGESControl_Controller::Init();
5375       IGESControl_Writer ICW (Interface_Static::CVal("XSTEP.iges.unit"),
5376                                    Interface_Static::IVal("XSTEP.iges.writebrep.mode"));
5377       //VRV: OCC 4.0 migration
5378         
5379       ICW.AddShape (tds);
5380       ICW.ComputeModel();
5381       char * aname = strdup(filename);
5382       Standard_Boolean result = ICW.Write( aname );
5383       free(aname);
5384     }
5385   catch(Standard_Failure) 
5386     {
5387       THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ExportIGES", SALOME::BAD_PARAM);
5388     }
5389 }
5390
5391 void GEOM_Gen_i::ExportBREP(const char* filename,GEOM::GEOM_Shape_ptr theShape)
5392   throw (SALOME::SALOME_Exception)
5393 {
5394   Unexpect aCatch(SALOME_SalomeException);
5395   if (theShape->_is_nil()) 
5396     {
5397       THROW_SALOME_CORBA_EXCEPTION("Export BRep aborted", SALOME::BAD_PARAM);
5398     } 
5399   TopoDS_Shape tds = GetTopoShape(theShape);
5400   if (tds.IsNull()) 
5401     {
5402       THROW_SALOME_CORBA_EXCEPTION("Export BRep aborted", SALOME::BAD_PARAM);
5403     } 
5404   try 
5405     {
5406       char * aname = strdup(filename);
5407       Standard_Boolean result = BRepTools::Write(tds,aname);
5408       free(aname);
5409     }
5410   catch(Standard_Failure) 
5411     {
5412       THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ExportBREP", SALOME::BAD_PARAM);
5413     }
5414 }
5415
5416 void GEOM_Gen_i::ExportSTEP(const char* filename,GEOM::GEOM_Shape_ptr theShape) 
5417   throw (SALOME::SALOME_Exception)
5418 {
5419   Unexpect aCatch(SALOME_SalomeException);
5420   if (theShape->_is_nil()) 
5421     {
5422       THROW_SALOME_CORBA_EXCEPTION("Export STEP aborted", SALOME::BAD_PARAM);
5423     } 
5424   TopoDS_Shape tds = GetTopoShape(theShape);
5425   if (tds.IsNull()) 
5426     {
5427       THROW_SALOME_CORBA_EXCEPTION("Export STEP aborted", SALOME::BAD_PARAM);
5428     } 
5429   try 
5430     {
5431       IFSelect_ReturnStatus status ;
5432       //VRV: OCC 4.0 migration
5433       STEPControl_Writer aWriter;
5434       status = aWriter.Transfer( tds, STEPControl_ManifoldSolidBrep ) ;
5435       //VRV: OCC 4.0 migration
5436       if ( status == IFSelect_RetDone ) 
5437         {
5438           char * aname = strdup(filename);
5439           status = aWriter.Write( aname ) ;
5440           free(aname);
5441         }
5442     }
5443   catch(Standard_Failure) 
5444     {
5445       THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ExportBREP", SALOME::BAD_PARAM);
5446     }
5447 }
5448
5449
5450 //=====================================================================================
5451 // EXPORTED METHODS
5452 //=====================================================================================
5453 extern "C"
5454 {
5455   PortableServer::ObjectId * GEOMEngine_factory(CORBA::ORB_ptr orb,
5456                                                 PortableServer::POA_ptr poa, 
5457                                                 PortableServer::ObjectId * contId,
5458                                                 const char *instanceName, 
5459                                                 const char * interfaceName)
5460   {
5461    GEOM_Gen_i * myGEOM_Gen_i = new GEOM_Gen_i(orb, poa, contId, instanceName, interfaceName);
5462    myGEOM_Gen_i->register_name("/myGEOM_Gen"); // NRI : 11/07/2002 : Add for Supervision example 
5463    return myGEOM_Gen_i->getId() ;
5464   }
5465 }
5466