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