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