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