1 // Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
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.
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
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_Gen_i.cxx
23 // Author : Paul RASCLE, EDF
27 #include <TopExp_Explorer.hxx>
29 #include <TopoDS_Iterator.hxx>
30 #include <TopoDS_Compound.hxx>
31 #include <TopoDS_CompSolid.hxx>
32 #include <TopoDS_Solid.hxx>
33 #include <TopoDS_Shell.hxx>
34 #include <TopoDS_Face.hxx>
35 #include <TopoDS_Wire.hxx>
36 #include <TopoDS_Edge.hxx>
37 #include <TopoDS_Vertex.hxx>
38 #include <TopoDS_Shape.hxx>
39 #include <TopTools_MapOfShape.hxx>
40 #include <TopTools_IndexedMapOfShape.hxx>
41 #include <TopTools_ListOfShape.hxx>
42 #include <TopTools_ListIteratorOfListOfShape.hxx>
44 #include <BRep_Tool.hxx>
45 #include <TCollection_AsciiString.hxx>
56 #define LibHandle HMODULE
57 #define LoadLib( name ) LoadLibrary( name )
58 #define GetProc GetProcAddress
59 #define UnLoadLib( handle ) FreeLibrary( handle );
61 #define LibHandle void*
62 #define LoadLib( name ) dlopen( name, RTLD_LAZY )
64 #define UnLoadLib( handle ) dlclose( handle );
67 #include "SMESH_Gen_i.hxx"
68 #include "SMESH_version.h"
70 #include "DriverMED_W_SMESHDS_Mesh.h"
71 #include "DriverMED_R_SMESHDS_Mesh.h"
73 #include "DriverCGNS_Read.hxx"
75 #include "MED_Factory.hxx"
76 #include "SMDS_EdgePosition.hxx"
77 #include "SMDS_FacePosition.hxx"
78 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
79 #include "SMDS_SetIterator.hxx"
80 #include "SMDS_SpacePosition.hxx"
81 #include "SMDS_VertexPosition.hxx"
82 #include "SMESHDS_Document.hxx"
83 #include "SMESHDS_Group.hxx"
84 #include "SMESHDS_GroupOnGeom.hxx"
85 #include "SMESH_Algo_i.hxx"
86 #include "SMESH_File.hxx"
87 #include "SMESH_Group.hxx"
88 #include "SMESH_Group_i.hxx"
89 #include "SMESH_Hypothesis.hxx"
90 #include "SMESH_Hypothesis_i.hxx"
91 #include "SMESH_Mesh.hxx"
92 #include "SMESH_MeshEditor.hxx"
93 #include "SMESH_Mesh_i.hxx"
94 #include "SMESH_PreMeshInfo.hxx"
95 #include "SMESH_PythonDump.hxx"
96 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
98 #include CORBA_SERVER_HEADER(SMESH_Group)
99 #include CORBA_SERVER_HEADER(SMESH_Filter)
100 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
103 #include <GEOM_Client.hxx>
105 #include <Basics_Utils.hxx>
106 #include <Basics_DirUtils.hxx>
108 #include <OpUtil.hxx>
109 #include <SALOMEDS_Tool.hxx>
110 #include <SALOME_Container_i.hxx>
111 #include <SALOME_DataContainer_i.hxx>
112 #include <SALOME_LifeCycleCORBA.hxx>
113 #include <SALOME_NamingService.hxx>
114 #include <Utils_CorbaException.hxx>
115 #include <Utils_ExceptHandlers.hxx>
116 #include <Utils_SINGLETON.hxx>
117 #include <utilities.h>
119 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
120 #include CORBA_CLIENT_HEADER(SALOME_Session)
122 // helpers about SALOME::GenericObj
123 #include <SALOMEDS_wrap.hxx>
124 #include <SALOMEDS_Attributes_wrap.hxx>
125 #include <GEOM_wrap.hxx>
133 using SMESH::TPythonDump;
136 #define NUM_TMP_FILES 2
139 static int MYDEBUG = 0;
141 static int MYDEBUG = 0;
144 // Static variables definition
145 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
146 CORBA::ORB_var SMESH_Gen_i::myOrb;
147 PortableServer::POA_var SMESH_Gen_i::myPoa;
148 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
149 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
150 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
153 const int nbElemPerDiagonal = 10;
155 //=============================================================================
157 * GetServant [ static ]
159 * Get servant of the CORBA object
161 //=============================================================================
163 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
165 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
168 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
172 INFOS( "GetServant - Unknown exception was caught!!!" );
177 //=============================================================================
179 * SObjectToObject [ static ]
181 * Get CORBA object corresponding to the SALOMEDS::SObject
183 //=============================================================================
185 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
187 SALOMEDS::GenericAttribute_wrap anAttr;
188 CORBA::Object_var anObj;
189 if ( !theSObject->_is_nil() ) {
191 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
192 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
193 CORBA::String_var aValue = anIOR->Value();
194 if( strcmp( aValue, "" ) != 0 )
195 anObj = GetORB()->string_to_object( aValue );
199 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
205 //=============================================================================
209 * Get SALOME_NamingService object
211 //=============================================================================
213 SALOME_NamingService* SMESH_Gen_i::GetNS()
215 if ( myNS == NULL ) {
216 myNS = SINGLETON_<SALOME_NamingService>::Instance();
217 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
218 myNS->init_orb( GetORB() );
223 //=============================================================================
227 * Get SALOME_LifeCycleCORBA object
229 //=============================================================================
230 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC() {
231 if ( myLCC == NULL ) {
232 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
238 //=============================================================================
240 * GetGeomEngine [ static ]
242 * Get GEOM::GEOM_Gen reference
244 //=============================================================================
245 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine() {
246 //CCRT GEOM::GEOM_Gen_var aGeomEngine =
247 //CCRT GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
248 //CCRT return aGeomEngine._retn();
249 if(CORBA::is_nil(myGeomGen))
251 Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
252 myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
257 //=============================================================================
259 * SMESH_Gen_i::SMESH_Gen_i
261 * Default constructor: not for use
263 //=============================================================================
265 SMESH_Gen_i::SMESH_Gen_i()
267 INFOS( "SMESH_Gen_i::SMESH_Gen_i : default constructor" );
270 //=============================================================================
272 * SMESH_Gen_i::SMESH_Gen_i
274 * Standard constructor, used with Container
276 //=============================================================================
278 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
279 PortableServer::POA_ptr poa,
280 PortableServer::ObjectId* contId,
281 const char* instanceName,
282 const char* interfaceName )
283 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
285 MESSAGE( "SMESH_Gen_i::SMESH_Gen_i : standard constructor" );
287 myOrb = CORBA::ORB::_duplicate(orb);
288 myPoa = PortableServer::POA::_duplicate(poa);
291 _id = myPoa->activate_object( _thisObj );
293 myIsEmbeddedMode = false;
294 myShapeReader = NULL; // shape reader
296 myIsHistoricalPythonDump = true;
297 myToForgetMeshDataOnHypModif = false;
299 myImportedStudyChanged = true;
300 myImportedStudyId = 0;
302 // set it in standalone mode only
303 //OSD::SetSignal( true );
305 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
306 // find out mode (embedded or standalone) here else
307 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
308 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
309 if ( SALOME_NamingService* ns = GetNS() )
311 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
312 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
313 if ( !session->_is_nil() )
315 CORBA::String_var str_host = session->getHostname();
316 CORBA::Long s_pid = session->getPID();
317 string my_host = Kernel_Utils::GetHostname();
319 long my_pid = (long)_getpid();
321 long my_pid = (long) getpid();
323 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
328 //=============================================================================
330 * SMESH_Gen_i::~SMESH_Gen_i
334 //=============================================================================
336 SMESH_Gen_i::~SMESH_Gen_i()
338 MESSAGE( "SMESH_Gen_i::~SMESH_Gen_i" );
340 // delete hypothesis creators
341 map<string, GenericHypothesisCreator_i*>::iterator itHyp;
342 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
344 delete (*itHyp).second;
346 myHypCreatorMap.clear();
348 // Clear study contexts data
349 map<int, StudyContext*>::iterator it;
350 for ( it = myStudyContextMap.begin(); it != myStudyContextMap.end(); ++it ) {
353 myStudyContextMap.clear();
354 // delete shape reader
356 delete myShapeReader;
358 //=============================================================================
360 * SMESH_Gen_i::getHypothesisCreator
362 * Get hypothesis creator
364 //=============================================================================
365 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
366 const char* theLibName,
367 std::string& thePlatformLibName)
368 throw (SALOME::SALOME_Exception)
370 std::string aPlatformLibName;
371 /* It's Need to tranlate lib name for WIN32 or X platform */
372 if ( theLibName && theLibName[0] != '\0' )
374 int libNameLen = strlen(theLibName);
375 //check for old format "libXXXXXXX.so"
376 if (libNameLen > 7 &&
377 !strncmp( theLibName, "lib", 3 ) &&
378 !strcmp( theLibName+libNameLen-3, ".so" ))
382 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
384 aPlatformLibName = theLibName;
389 //try to use new format
391 aPlatformLibName = theLibName;
392 aPlatformLibName += ".dll";
394 aPlatformLibName = "lib" + std::string( theLibName ) + ".so";
398 thePlatformLibName = aPlatformLibName;
400 Unexpect aCatch(SALOME_SalomeException);
401 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
403 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
404 GenericHypothesisCreator_i* aCreator;
407 // check, if creator for this hypothesis type already exists
408 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
410 // load plugin library
411 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
412 LibHandle libHandle = LoadLib( aPlatformLibName.c_str() );
415 // report any error, if occured
417 const char* anError = dlerror();
418 throw(SALOME_Exception(anError));
420 throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
424 // get method, returning hypothesis creator
425 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
426 GetHypothesisCreator procHandle =
427 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
430 throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
431 UnLoadLib(libHandle);
434 // get hypothesis creator
435 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
436 aCreator = procHandle(theHypName);
439 throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
441 // map hypothesis creator to a hypothesis name
442 myHypCreatorMap[string(theHypName)] = aCreator;
447 return myHypCreatorMap[string(theHypName)];
450 catch (SALOME_Exception& S_ex)
452 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
457 //=============================================================================
459 * SMESH_Gen_i::createHypothesis
461 * Create hypothesis of given type
463 //=============================================================================
464 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
465 const char* theLibName)
467 SMESH_Hypothesis_i* myHypothesis_i = 0;
468 SMESH::SMESH_Hypothesis_var hypothesis_i;
469 std::string aPlatformLibName;
470 GenericHypothesisCreator_i* aCreator =
471 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
473 // create a new hypothesis object, store its ref. in studyContext
474 myHypothesis_i = aCreator->Create(myPoa, GetCurrentStudyID(), &myGen);
477 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
478 CORBA::String_var hypName = myHypothesis_i->GetName();
479 myHypCreatorMap[ hypName.in() ] = aCreator;
481 // activate the CORBA servant of hypothesis
482 hypothesis_i = myHypothesis_i->_this();
483 int nextId = RegisterObject( hypothesis_i );
484 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
485 else { nextId = 0; } // avoid "unused variable" warning in release mode
487 return hypothesis_i._retn();
490 //=============================================================================
492 * SMESH_Gen_i::createMesh
494 * Create empty mesh on shape
496 //=============================================================================
497 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
498 throw ( SALOME::SALOME_Exception )
500 Unexpect aCatch(SALOME_SalomeException);
501 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
503 // Get or create the GEOM_Client instance
505 // create a new mesh object servant, store it in a map in study context
506 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this, GetCurrentStudyID() );
507 // create a new mesh object
508 MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
509 meshServant->SetImpl( myGen.CreateMesh( GetCurrentStudyID(), myIsEmbeddedMode ));
511 // activate the CORBA servant of Mesh
512 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
513 int nextId = RegisterObject( mesh );
514 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
515 else { nextId = 0; } // avoid "unused variable" warning in release mode
518 catch (SALOME_Exception& S_ex) {
519 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
521 return SMESH::SMESH_Mesh::_nil();
524 //=============================================================================
526 * SMESH_Gen_i::GetShapeReader
530 //=============================================================================
531 GEOM_Client* SMESH_Gen_i::GetShapeReader()
533 // create shape reader if necessary
534 if ( !myShapeReader )
535 myShapeReader = new GEOM_Client(GetContainerRef());
536 ASSERT( myShapeReader );
537 return myShapeReader;
540 //=============================================================================
542 * SMESH_Gen_i::SetGeomEngine
544 * Set GEOM::GEOM_Gen reference
546 //=============================================================================
547 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
548 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
550 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
551 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
552 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
556 //=============================================================================
558 * SMESH_Gen_i::SetEmbeddedMode
562 //=============================================================================
564 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
566 myIsEmbeddedMode = theMode;
567 MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
569 if ( !myIsEmbeddedMode ) {
570 //PAL10867: disable signals catching with "noexcepthandler" option
571 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
572 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
577 char* envDisableFPE = getenv("DISABLE_FPE");
578 if (envDisableFPE && atoi(envDisableFPE))
583 OSD::SetSignal( raiseFPE );
585 // else OSD::SetSignal() is called in GUI
589 //=============================================================================
591 * SMESH_Gen_i::IsEmbeddedMode
595 //=============================================================================
597 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
599 return myIsEmbeddedMode;
602 //=============================================================================
604 * SMESH_Gen_i::SetCurrentStudy
608 //=============================================================================
610 void SMESH_Gen_i::SetCurrentStudy( SALOMEDS::Study_ptr theStudy )
612 setCurrentStudy( theStudy );
615 void SMESH_Gen_i::setCurrentStudy( SALOMEDS::Study_ptr theStudy,
616 bool theStudyIsBeingClosed)
618 int curStudyId = GetCurrentStudyID();
619 myCurrentStudy = SALOMEDS::Study::_duplicate( theStudy );
620 // create study context, if it doesn't exist and set current study
621 int studyId = GetCurrentStudyID();
622 if ( myStudyContextMap.find( studyId ) == myStudyContextMap.end() )
623 myStudyContextMap[ studyId ] = new StudyContext;
625 // myCurrentStudy may be nil
626 if ( !theStudyIsBeingClosed && !CORBA::is_nil( myCurrentStudy ) ) {
627 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
628 SALOMEDS::SComponent_wrap GEOM_var = myCurrentStudy->FindComponent( "GEOM" );
629 if( !GEOM_var->_is_nil() )
630 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
631 // NPAL16168, issue 0020210
632 // Let meshes update their data depending on GEOM groups that could change
633 if ( curStudyId != studyId )
635 CORBA::String_var compDataType = ComponentDataType();
636 SALOMEDS::SComponent_wrap me = myCurrentStudy->FindComponent( compDataType.in() );
637 if ( !me->_is_nil() ) {
638 SALOMEDS::ChildIterator_wrap anIter = myCurrentStudy->NewChildIterator( me );
639 for ( ; anIter->More(); anIter->Next() ) {
640 SALOMEDS::SObject_wrap so = anIter->Value();
641 CORBA::Object_var ior = SObjectToObject( so );
642 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
643 mesh->CheckGeomModif();
650 //=============================================================================
652 * SMESH_Gen_i::GetCurrentStudy
656 //=============================================================================
658 SALOMEDS::Study_ptr SMESH_Gen_i::GetCurrentStudy()
660 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetCurrentStudy: study Id = " << GetCurrentStudyID() );
661 if ( GetCurrentStudyID() < 0 )
662 return SALOMEDS::Study::_nil();
663 return SALOMEDS::Study::_duplicate( myCurrentStudy );
666 //=============================================================================
668 * SMESH_Gen_i::GetCurrentStudyContext
670 * Get current study context
672 //=============================================================================
673 StudyContext* SMESH_Gen_i::GetCurrentStudyContext()
675 if ( !CORBA::is_nil( myCurrentStudy ) &&
676 myStudyContextMap.find( GetCurrentStudyID() ) != myStudyContextMap.end() )
677 return myStudyContextMap[ myCurrentStudy->StudyId() ];
682 //=============================================================================
684 * SMESH_Gen_i::CreateHypothesis
686 * Create hypothesis/algorothm of given type and publish it in the study
688 //=============================================================================
690 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
691 const char* theLibName )
692 throw ( SALOME::SALOME_Exception )
694 Unexpect aCatch(SALOME_SalomeException);
695 // Create hypothesis/algorithm
696 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
698 // Publish hypothesis/algorithm in the study
699 if ( CanPublishInStudy( hyp ) ) {
700 SALOMEDS::SObject_wrap aSO = PublishHypothesis( myCurrentStudy, hyp );
701 if ( !aSO->_is_nil() ) {
702 // Update Python script
703 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
704 << theHypName << "', '" << theLibName << "')";
711 //================================================================================
713 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
714 * existing on the given geometry or to size of the geometry.
715 * \param theHypType - hypothesis type name
716 * \param theLibName - plugin library name
717 * \param theMesh - The mesh of interest
718 * \param theGeom - The shape to get parameter values from
719 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
720 * in a study and used to compute the mesh, or a temporary one created just to pass
723 //================================================================================
725 SMESH::SMESH_Hypothesis_ptr
726 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
727 const char* theLibName,
728 SMESH::SMESH_Mesh_ptr theMesh,
729 GEOM::GEOM_Object_ptr theGeom,
730 CORBA::Boolean byMesh)
731 throw ( SALOME::SALOME_Exception )
733 Unexpect aCatch(SALOME_SalomeException);
734 if ( byMesh && CORBA::is_nil( theMesh ) )
735 return SMESH::SMESH_Hypothesis::_nil();
736 if ( byMesh && CORBA::is_nil( theGeom ) )
737 return SMESH::SMESH_Hypothesis::_nil();
739 // -----------------------------------------------
740 // find hypothesis used to mesh theGeom
741 // -----------------------------------------------
743 // get mesh and shape
744 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
745 TopoDS_Shape shape = GeomObjectToShape( theGeom );
746 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
747 return SMESH::SMESH_Hypothesis::_nil();
748 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
750 // create a temporary hypothesis to know its dimension
751 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
752 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
754 return SMESH::SMESH_Hypothesis::_nil();
755 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
758 // look for a hypothesis of theHypType used to mesh the shape
759 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
762 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
763 int nbLocalHyps = aHypList->length();
764 for ( int i = 0; i < nbLocalHyps; i++ ) {
765 CORBA::String_var hypName = aHypList[i]->GetName();
766 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
767 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
769 // check super shapes
770 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
771 while ( nbLocalHyps == 0 && itShape.More() ) {
772 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
773 if ( ! CORBA::is_nil( geomObj )) {
774 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
775 nbLocalHyps = aHypList->length();
776 for ( int i = 0; i < nbLocalHyps; i++ )
777 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
778 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
784 // let the temporary hypothesis find out somehow parameter values by mesh
785 if ( hyp->SetParametersByMesh( mesh, shape ))
786 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
791 diagonal = mesh->GetShapeDiagonalSize();
793 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
794 ::SMESH_Hypothesis::TDefaults dflts;
795 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
796 dflts._nbSegments = myGen.GetDefaultNbSegments();
797 dflts._shape = &shape;
798 // let the temporary hypothesis initialize it's values
799 if ( hyp->SetParametersByDefaults( dflts, mesh ))
800 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
803 return SMESH::SMESH_Hypothesis::_nil();
806 //=============================================================================
808 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
809 * \param [in] theHyp - the hypothesis of interest
810 * \param [out] theMesh - the sole mesh using \a theHyp
811 * \param [out] theShape - the sole geometry \a theHyp is assigned to
812 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
814 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
815 * considered as SAME sub-mesh => result is \c true.
816 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
817 * a shape to which an hyp being edited is assigned.
819 //=============================================================================
821 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
822 SMESH::SMESH_Mesh_out theMesh,
823 GEOM::GEOM_Object_out theShape)
825 if ( GetCurrentStudyID() < 0 || CORBA::is_nil( theHyp ))
828 // get Mesh component SO
829 CORBA::String_var compDataType = ComponentDataType();
830 SALOMEDS::SComponent_wrap comp = myCurrentStudy->FindComponent( compDataType.in() );
831 if ( CORBA::is_nil( comp ))
834 // look for child SO of meshes
835 SMESH::SMESH_Mesh_var foundMesh;
836 TopoDS_Shape foundShape;
838 SALOMEDS::ChildIterator_wrap meshIter = myCurrentStudy->NewChildIterator( comp );
839 for ( ; meshIter->More() && isSole; meshIter->Next() )
841 SALOMEDS::SObject_wrap curSO = meshIter->Value();
842 CORBA::Object_var obj = SObjectToObject( curSO );
843 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
847 // look for a sole shape where theHyp is assigned
848 bool isHypFound = false;
849 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
850 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
851 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
853 const THypList& hyps = s2hypsIt.Value();
854 THypList::const_iterator h = hyps.begin();
855 for ( ; h != hyps.end(); ++h )
856 if ( (*h)->GetID() == theHyp->GetId() )
858 if ( h != hyps.end()) // theHyp found
861 if ( ! foundShape.IsNull() &&
862 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
864 foundShape.Nullify();
868 foundShape = s2hypsIt.Key();
870 } // loop on assigned hyps
872 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
874 if ( !foundMesh->_is_nil() ) // not a sole mesh
876 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
877 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
878 if ( ! ( isSole = s1->IsSame( s2 )))
881 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
887 ! foundMesh->_is_nil() &&
888 ! foundShape.IsNull() )
890 theMesh = foundMesh._retn();
891 theShape = ShapeToGeomObject( foundShape );
892 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
897 //=============================================================================
899 * Sets number of segments per diagonal of boundary box of geometry by which
900 * default segment length of appropriate 1D hypotheses is defined
902 //=============================================================================
904 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
905 throw ( SALOME::SALOME_Exception )
907 if ( theNbSegments > 0 )
908 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
910 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
912 //=============================================================================
914 * \brief Sets default number of segments per edge
916 //=============================================================================
917 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
918 throw ( SALOME::SALOME_Exception )
920 if ( theNbSegments > 0 )
921 myGen.SetDefaultNbSegments( int(theNbSegments) );
923 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
926 //=============================================================================
930 //=============================================================================
932 void SMESH_Gen_i::SetOption(const char* name, const char* value)
934 if ( name && value && strlen( value ) > 0 )
937 if ( strcmp(name, "historical_python_dump") == 0 )
939 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
940 msgToGUI = "preferences/SMESH/historical_python_dump/";
941 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
943 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
945 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
946 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
947 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
950 // update preferences in case if SetOption() is invoked from python console
951 if ( !msgToGUI.empty() )
953 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
954 SALOME::Session_var session = SALOME::Session::_narrow( obj );
955 if ( !CORBA::is_nil( session ) )
956 session->emitMessageOneWay(msgToGUI.c_str());
961 //=============================================================================
963 Return an option value
965 //=============================================================================
967 char* SMESH_Gen_i::GetOption(const char* name)
971 if ( strcmp(name, "historical_python_dump") == 0 )
973 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
975 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
977 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
980 return CORBA::string_dup( "" );
983 //=============================================================================
985 * SMESH_Gen_i::CreateMesh
987 * Create empty mesh on a shape and publish it in the study
989 //=============================================================================
991 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
992 throw ( SALOME::SALOME_Exception )
994 Unexpect aCatch(SALOME_SalomeException);
995 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
997 SMESH::SMESH_Mesh_var mesh = this->createMesh();
999 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1000 ASSERT( meshServant );
1001 meshServant->SetShape( theShapeObject );
1003 // publish mesh in the study
1004 if ( CanPublishInStudy( mesh ) ) {
1005 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1006 aStudyBuilder->NewCommand(); // There is a transaction
1007 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1008 aStudyBuilder->CommitCommand();
1009 if ( !aSO->_is_nil() ) {
1010 // Update Python script
1011 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1015 return mesh._retn();
1018 //=============================================================================
1020 * SMESH_Gen_i::CreateEmptyMesh
1024 //=============================================================================
1026 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1027 throw ( SALOME::SALOME_Exception )
1029 Unexpect aCatch(SALOME_SalomeException);
1030 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1032 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1034 // publish mesh in the study
1035 if ( CanPublishInStudy( mesh ) ) {
1036 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1037 aStudyBuilder->NewCommand(); // There is a transaction
1038 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1039 aStudyBuilder->CommitCommand();
1040 if ( !aSO->_is_nil() ) {
1041 // Update Python script
1042 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1046 return mesh._retn();
1051 //================================================================================
1053 * \brief Throws an exception in case if the file can't be read
1055 //================================================================================
1057 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1059 SMESH_File f ( theFileName );
1062 if ( !f.error().empty() )
1063 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1065 THROW_SALOME_CORBA_EXCEPTION
1066 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1067 SALOME::BAD_PARAM );
1072 //=============================================================================
1074 * SMESH_Gen_i::CreateMeshFromUNV
1076 * Create mesh and import data from UNV file
1078 //=============================================================================
1080 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1081 throw ( SALOME::SALOME_Exception )
1083 Unexpect aCatch(SALOME_SalomeException);
1085 checkFileReadable( theFileName );
1087 SMESH::SMESH_Mesh_var aMesh = createMesh();
1089 // publish mesh in the study
1090 if ( CanPublishInStudy( aMesh ) ) {
1091 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1092 aStudyBuilder->NewCommand(); // There is a transaction
1093 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, aMesh.in(), aFileName.c_str() );
1094 aStudyBuilder->CommitCommand();
1095 if ( !aSO->_is_nil() ) {
1096 // Update Python script
1097 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1101 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1103 aServant->ImportUNVFile( theFileName );
1105 // Dump creation of groups
1106 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1108 aServant->GetImpl().GetMeshDS()->Modified();
1109 return aMesh._retn();
1112 //=============================================================================
1114 * SMESH_Gen_i::CreateMeshFromMED
1116 * Create mesh and import data from MED file
1118 //=============================================================================
1120 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1121 SMESH::DriverMED_ReadStatus& theStatus,
1122 const char* theCommandNameForPython,
1123 const char* theFileNameForPython)
1126 char bname[ _MAX_FNAME ];
1127 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1128 string aFileName = bname;
1130 string aFileName = basename( theFileNameForPython );
1132 // Retrieve mesh names from the file
1133 DriverMED_R_SMESHDS_Mesh myReader;
1134 myReader.SetFile( theFileName );
1135 myReader.SetMeshId( -1 );
1136 Driver_Mesh::Status aStatus;
1137 list<string> aNames = myReader.GetMeshNames(aStatus);
1138 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1139 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1141 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1144 TPythonDump aPythonDump;
1145 aPythonDump << "([";
1147 if (theStatus == SMESH::DRS_OK) {
1148 SALOMEDS::StudyBuilder_var aStudyBuilder;
1149 if ( GetCurrentStudyID() > -1 )
1151 aStudyBuilder = myCurrentStudy->NewBuilder();
1152 aStudyBuilder->NewCommand(); // There is a transaction
1154 aResult->length( aNames.size() );
1157 // Iterate through all meshes and create mesh objects
1158 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1161 if (i > 0) aPythonDump << ", ";
1164 SMESH::SMESH_Mesh_var mesh = createMesh();
1166 // publish mesh in the study
1167 SALOMEDS::SObject_wrap aSO;
1168 if ( CanPublishInStudy( mesh ) )
1169 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1170 // - as names of meshes are stored in MED file, we use them for data publishing
1171 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1172 aSO = PublishMesh( myCurrentStudy, mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1173 if ( !aSO->_is_nil() ) {
1178 aPythonDump << "mesh_" << i;
1181 // Read mesh data (groups are published automatically by ImportMEDFile())
1182 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1183 ASSERT( meshServant );
1184 SMESH::DriverMED_ReadStatus status1 =
1185 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1186 if (status1 > theStatus)
1187 theStatus = status1;
1189 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1190 meshServant->GetImpl().GetMeshDS()->Modified();
1192 if ( !aStudyBuilder->_is_nil() )
1193 aStudyBuilder->CommitCommand();
1196 // Update Python script
1197 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1199 // Dump creation of groups
1200 for ( int i = 0; i < aResult->length(); ++i )
1201 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1203 return aResult._retn();
1206 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1207 SMESH::DriverMED_ReadStatus& theStatus)
1208 throw ( SALOME::SALOME_Exception )
1210 Unexpect aCatch(SALOME_SalomeException);
1211 checkFileReadable( theFileName );
1213 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1217 //=============================================================================
1219 * SMESH_Gen_i::CreateMeshFromSAUV
1221 * Create mesh and import data from SAUV file
1223 //=============================================================================
1225 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1226 SMESH::DriverMED_ReadStatus& theStatus)
1227 throw ( SALOME::SALOME_Exception )
1229 Unexpect aCatch(SALOME_SalomeException);
1230 checkFileReadable( theFileName );
1232 std::string sauvfilename(theFileName);
1233 std::string medfilename(theFileName);
1234 medfilename += ".med";
1237 cmd = "%PYTHONBIN% ";
1242 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1244 system(cmd.c_str());
1245 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1247 cmd = "%PYTHONBIN% ";
1252 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1254 system(cmd.c_str());
1258 //=============================================================================
1260 * SMESH_Gen_i::CreateMeshFromSTL
1262 * Create mesh and import data from STL file
1264 //=============================================================================
1266 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1267 throw ( SALOME::SALOME_Exception )
1269 Unexpect aCatch(SALOME_SalomeException);
1270 checkFileReadable( theFileName );
1272 SMESH::SMESH_Mesh_var aMesh = createMesh();
1275 char bname[ _MAX_FNAME ];
1276 _splitpath( theFileName, NULL, NULL, bname, NULL );
1277 string aFileName = bname;
1279 string aFileName = basename( theFileName );
1281 // publish mesh in the study
1282 if ( CanPublishInStudy( aMesh ) ) {
1283 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1284 aStudyBuilder->NewCommand(); // There is a transaction
1285 SALOMEDS::SObject_wrap aSO = PublishInStudy
1286 ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1287 aStudyBuilder->CommitCommand();
1288 if ( !aSO->_is_nil() ) {
1289 // Update Python script
1290 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1294 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1296 aServant->ImportSTLFile( theFileName );
1297 aServant->GetImpl().GetMeshDS()->Modified();
1298 return aMesh._retn();
1301 //================================================================================
1303 * \brief Create meshes and import data from the CGSN file
1305 //================================================================================
1307 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1308 SMESH::DriverMED_ReadStatus& theStatus)
1309 throw ( SALOME::SALOME_Exception )
1311 Unexpect aCatch(SALOME_SalomeException);
1312 checkFileReadable( theFileName );
1314 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1317 // Retrieve nb meshes from the file
1318 DriverCGNS_Read myReader;
1319 myReader.SetFile( theFileName );
1320 Driver_Mesh::Status aStatus;
1321 int nbMeshes = myReader.GetNbMeshes(aStatus);
1322 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1324 aResult->length( nbMeshes );
1326 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1329 TPythonDump aPythonDump;
1330 aPythonDump << "([";
1332 if (theStatus == SMESH::DRS_OK)
1334 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1335 aStudyBuilder->NewCommand(); // There is a transaction
1339 // Iterate through all meshes and create mesh objects
1340 for ( ; i < nbMeshes; ++i )
1343 if (i > 0) aPythonDump << ", ";
1346 SMESH::SMESH_Mesh_var mesh = createMesh();
1347 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1349 // Read mesh data (groups are published automatically by ImportMEDFile())
1350 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1351 ASSERT( meshServant );
1353 SMESH::DriverMED_ReadStatus status1 =
1354 meshServant->ImportCGNSFile( theFileName, i, meshName );
1355 if (status1 > theStatus)
1356 theStatus = status1;
1358 meshServant->GetImpl().GetMeshDS()->Modified();
1359 // publish mesh in the study
1360 SALOMEDS::SObject_wrap aSO;
1361 if ( CanPublishInStudy( mesh ) )
1362 aSO = PublishMesh( myCurrentStudy, mesh.in(), meshName.c_str() );
1365 if ( !aSO->_is_nil() ) {
1369 aPythonDump << "mesh_" << i;
1372 aStudyBuilder->CommitCommand();
1375 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1377 // Dump creation of groups
1378 for ( int i = 0; i < aResult->length(); ++i )
1379 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1381 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1384 return aResult._retn();
1387 //================================================================================
1389 * \brief Create a mesh and import data from a GMF file
1391 //================================================================================
1393 SMESH::SMESH_Mesh_ptr
1394 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1395 CORBA::Boolean theMakeRequiredGroups,
1396 SMESH::ComputeError_out theError)
1397 throw ( SALOME::SALOME_Exception )
1399 Unexpect aCatch(SALOME_SalomeException);
1400 checkFileReadable( theFileName );
1402 SMESH::SMESH_Mesh_var aMesh = createMesh();
1404 char bname[ _MAX_FNAME ];
1405 _splitpath( theFileName, NULL, NULL, bname, NULL );
1406 string aFileName = bname;
1408 string aFileName = basename( theFileName );
1410 // publish mesh in the study
1411 if ( CanPublishInStudy( aMesh ) ) {
1412 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1413 aStudyBuilder->NewCommand(); // There is a transaction
1414 SALOMEDS::SObject_wrap aSO = PublishInStudy
1415 ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1416 aStudyBuilder->CommitCommand();
1417 if ( !aSO->_is_nil() ) {
1418 // Update Python script
1419 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1420 << theFileName << "', "
1421 << theMakeRequiredGroups << " )";
1424 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1426 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1427 aServant->GetImpl().GetMeshDS()->Modified();
1428 return aMesh._retn();
1432 //=============================================================================
1434 * SMESH_Gen_i::IsReadyToCompute
1436 * Returns true if mesh contains enough data to be computed
1438 //=============================================================================
1440 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1441 GEOM::GEOM_Object_ptr theShapeObject )
1442 throw ( SALOME::SALOME_Exception )
1444 Unexpect aCatch(SALOME_SalomeException);
1445 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1447 if ( CORBA::is_nil( theShapeObject ) )
1448 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1449 SALOME::BAD_PARAM );
1451 if ( CORBA::is_nil( theMesh ) )
1452 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1453 SALOME::BAD_PARAM );
1457 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1458 ASSERT( meshServant );
1459 if ( meshServant ) {
1460 // get local TopoDS_Shape
1461 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1462 // call implementation
1463 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1464 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1467 catch ( SALOME_Exception& S_ex ) {
1468 INFOS( "catch exception "<< S_ex.what() );
1473 //================================================================================
1475 * \brief Find SObject for an algo
1477 //================================================================================
1479 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1482 if ( !myCurrentStudy->_is_nil() ) {
1483 // find algo in the study
1484 CORBA::String_var compDataType = ComponentDataType();
1485 SALOMEDS::SComponent_wrap father = myCurrentStudy->FindComponent( compDataType.in() );
1486 if ( !father->_is_nil() ) {
1487 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( father );
1488 for ( ; itBig->More(); itBig->Next() ) {
1489 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1490 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1491 SALOMEDS::ChildIterator_wrap algoIt = myCurrentStudy->NewChildIterator( gotBranch );
1492 for ( ; algoIt->More(); algoIt->Next() ) {
1493 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1494 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1495 if ( !CORBA::is_nil( algoIOR )) {
1496 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1497 if ( impl && impl->GetImpl() == algo )
1498 return algoSO._retn();
1500 } // loop on algo SO's
1503 } // SMESH component iterator
1507 return SALOMEDS::SObject::_nil();
1510 //================================================================================
1512 * \brief Return errors of mesh computation
1514 //================================================================================
1516 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1517 GEOM::GEOM_Object_ptr theSubObject )
1518 throw ( SALOME::SALOME_Exception )
1520 Unexpect aCatch(SALOME_SalomeException);
1521 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1523 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1524 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1526 if ( CORBA::is_nil( theMesh ) )
1527 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1529 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1531 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1534 if(theMesh->HasShapeToMesh())
1535 shape = GeomObjectToShape( theSubObject );
1537 shape = SMESH_Mesh::PseudoShape();
1539 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1541 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1544 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1545 const bool includeSelf = true, complexShapeFirst = true;
1546 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1548 while ( smIt->more() )
1551 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1553 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1554 if ( error && !error->IsOK() )
1556 if ( !( error->myAlgo ) &&
1557 !( error->myAlgo = sm->GetAlgo() ))
1559 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1560 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1561 errStruct.comment = error->myComment.c_str();
1562 errStruct.subShapeID = sm->GetId();
1563 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1564 if ( !algoSO->_is_nil() ) {
1565 CORBA::String_var algoName = algoSO->GetName();
1566 errStruct.algoName = algoName;
1569 errStruct.algoName = error->myAlgo->GetName();
1571 errStruct.hasBadMesh = !error->myBadElements.empty();
1574 error_array->length( nbErr );
1577 catch ( SALOME_Exception& S_ex ) {
1578 INFOS( "catch exception "<< S_ex.what() );
1581 return error_array._retn();
1584 //================================================================================
1586 * \brief Return mesh elements preventing computation of a subshape
1588 //================================================================================
1590 SMESH::MeshPreviewStruct*
1591 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1592 CORBA::Short theSubShapeID )
1593 throw ( SALOME::SALOME_Exception )
1595 Unexpect aCatch(SALOME_SalomeException);
1596 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1598 if ( CORBA::is_nil( theMesh ) )
1599 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1601 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1604 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1606 // mesh implementation
1607 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1608 // submesh by subshape id
1609 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1612 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1613 if ( error && !error->myBadElements.empty())
1615 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1616 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1618 // get nodes of elements and count elements
1619 TNode2LocalIDMap mapNode2LocalID;
1620 list< TNodeLocalID > connectivity;
1621 int i, nbElements = 0, nbConnNodes = 0;
1623 list<const SMDS_MeshElement*>::iterator elemIt = error->myBadElements.begin();
1624 list<const SMDS_MeshElement*>::iterator elemEnd = error->myBadElements.end();
1625 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1627 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1628 while ( nIt->more() )
1629 connectivity.push_back
1630 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1632 // fill node coords and assign local ids to the nodes
1633 int nbNodes = mapNode2LocalID.size();
1634 result->nodesXYZ.length( nbNodes );
1635 TNodeLocalID node2ID = mapNode2LocalID.begin();
1636 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1637 node2ID->second = i;
1638 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1639 result->nodesXYZ[i].x = node->X();
1640 result->nodesXYZ[i].y = node->Y();
1641 result->nodesXYZ[i].z = node->Z();
1643 // fill connectivity
1644 result->elementConnectivities.length( nbConnNodes );
1645 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1646 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1647 result->elementConnectivities[i] = (*connIt)->second;
1649 // fill element types
1650 result->elementTypes.length( nbElements );
1651 for ( i = 0, elemIt = error->myBadElements.begin(); i <nbElements; ++i, ++elemIt )
1653 const SMDS_MeshElement* elem = *elemIt;
1654 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1655 result->elementTypes[i].isPoly = elem->IsPoly();
1656 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1662 catch ( SALOME_Exception& S_ex ) {
1663 INFOS( "catch exception "<< S_ex.what() );
1666 return result._retn();
1669 //================================================================================
1671 * \brief Create a group of elements preventing computation of a sub-shape
1673 //================================================================================
1675 SMESH::ListOfGroups*
1676 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1677 CORBA::Short theSubShapeID,
1678 const char* theGroupName )
1679 throw ( SALOME::SALOME_Exception )
1681 Unexpect aCatch(SALOME_SalomeException);
1683 SMESH::ListOfGroups_var groups;
1685 if ( CORBA::is_nil( theMesh ) )
1686 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1689 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1691 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1692 TPythonDump() << groups << " = " << this
1693 << ".MakeGroupsOfBadInputElements( "
1694 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1697 catch ( SALOME_Exception& S_ex ) {
1698 INFOS( "catch exception "<< S_ex.what() );
1700 return groups._retn();
1703 //================================================================================
1705 * \brief Returns errors of hypotheses definintion
1706 * \param theMesh - the mesh
1707 * \param theSubObject - the main or sub- shape
1708 * \retval SMESH::algo_error_array* - sequence of errors
1710 //================================================================================
1712 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1713 GEOM::GEOM_Object_ptr theSubObject )
1714 throw ( SALOME::SALOME_Exception )
1716 Unexpect aCatch(SALOME_SalomeException);
1717 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1719 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1720 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1722 if ( CORBA::is_nil( theMesh ) )
1723 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1725 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1727 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1728 ASSERT( meshServant );
1729 if ( meshServant ) {
1730 TopoDS_Shape myLocShape;
1731 if(theMesh->HasShapeToMesh())
1732 myLocShape = GeomObjectToShape( theSubObject );
1734 myLocShape = SMESH_Mesh::PseudoShape();
1736 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1737 list< ::SMESH_Gen::TAlgoStateError > error_list;
1738 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1739 // call ::SMESH_Gen::GetAlgoState()
1740 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1741 error_array->length( error_list.size() );
1743 for ( error = error_list.begin(); error != error_list.end(); ++error )
1745 // fill AlgoStateError structure
1746 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1747 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1748 errStruct.algoDim = error->_algoDim;
1749 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1750 errStruct.algoName = "";
1751 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1752 if ( !algoSO->_is_nil() ) {
1753 CORBA::String_var algoName = algoSO->GetName();
1754 errStruct.algoName = algoName.in();
1759 catch ( SALOME_Exception& S_ex ) {
1760 INFOS( "catch exception "<< S_ex.what() );
1762 return error_array._retn();
1765 //=============================================================================
1767 * SMESH_Gen_i::GetSubShapesId
1769 * Get sub-shapes unique ID's list
1771 //=============================================================================
1773 SMESH::long_array* SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1774 const SMESH::object_array& theListOfSubShapeObject )
1775 throw ( SALOME::SALOME_Exception )
1777 Unexpect aCatch(SALOME_SalomeException);
1778 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1780 SMESH::long_array_var shapesId = new SMESH::long_array;
1783 if ( CORBA::is_nil( theMainShapeObject ) )
1784 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1785 SALOME::BAD_PARAM );
1789 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1790 TopTools_IndexedMapOfShape myIndexToShape;
1791 TopExp::MapShapes(myMainShape,myIndexToShape);
1793 for ( int i = 0; i < theListOfSubShapeObject.length(); i++ )
1795 GEOM::GEOM_Object_var aShapeObject
1796 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1797 if ( CORBA::is_nil( aShapeObject ) )
1798 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1799 SALOME::BAD_PARAM );
1801 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1802 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1804 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1805 setId.insert(myIndexToShape.FindIndex(F));
1806 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1808 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1810 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1811 setId.insert(myIndexToShape.FindIndex(E));
1812 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1814 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1816 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1817 setId.insert(myIndexToShape.FindIndex(V));
1818 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1821 shapesId->length(setId.size());
1822 set<int>::iterator iind;
1824 for (iind = setId.begin(); iind != setId.end(); iind++)
1826 if(MYDEBUG) SCRUTE((*iind));
1827 shapesId[i] = (*iind);
1828 if(MYDEBUG) SCRUTE(shapesId[i]);
1832 catch (SALOME_Exception& S_ex)
1834 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1837 return shapesId._retn();
1840 //=============================================================================
1842 * SMESH_Gen_i::Compute
1844 * Compute mesh on a shape
1846 //=============================================================================
1848 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1849 GEOM::GEOM_Object_ptr theShapeObject )
1850 throw ( SALOME::SALOME_Exception )
1853 Unexpect aCatch(SALOME_SalomeException);
1854 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1856 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1857 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1858 SALOME::BAD_PARAM );
1860 if ( CORBA::is_nil( theMesh ) )
1861 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1862 SALOME::BAD_PARAM );
1864 // Update Python script
1865 TPythonDump() << "isDone = " << this << ".Compute( "
1866 << theMesh << ", " << theShapeObject << ")";
1870 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1871 meshServant->Load();
1872 ASSERT( meshServant );
1873 if ( meshServant ) {
1874 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1875 meshServant->CheckGeomModif();
1876 // get local TopoDS_Shape
1877 TopoDS_Shape myLocShape;
1878 if(theMesh->HasShapeToMesh())
1879 myLocShape = GeomObjectToShape( theShapeObject );
1881 myLocShape = SMESH_Mesh::PseudoShape();
1882 // call implementation compute
1883 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1884 myGen.PrepareCompute( myLocMesh, myLocShape);
1885 bool ok = myGen.Compute( myLocMesh, myLocShape);
1886 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1887 myLocMesh.GetMeshDS()->Modified();
1891 catch ( std::bad_alloc ) {
1892 INFOS( "Compute(): lack of memory" );
1894 catch ( SALOME_Exception& S_ex ) {
1895 INFOS( "Compute(): catch exception "<< S_ex.what() );
1898 INFOS( "Compute(): unknown exception " );
1903 //=============================================================================
1905 * SMESH_Gen_i::CancelCompute
1907 * Cancel Compute mesh on a shape
1909 //=============================================================================
1911 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
1912 GEOM::GEOM_Object_ptr theShapeObject )
1914 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1915 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1916 TopoDS_Shape myLocShape;
1917 if(theMesh->HasShapeToMesh())
1918 myLocShape = GeomObjectToShape( theShapeObject );
1920 myLocShape = SMESH_Mesh::PseudoShape();
1921 myGen.CancelCompute( myLocMesh, myLocShape);
1924 //=============================================================================
1926 * SMESH_Gen_i::Precompute
1928 * Compute mesh as preview till indicated dimension on shape
1930 //=============================================================================
1932 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
1933 GEOM::GEOM_Object_ptr theShapeObject,
1934 SMESH::Dimension theDimension,
1935 SMESH::long_array& theShapesId)
1936 throw ( SALOME::SALOME_Exception )
1938 Unexpect aCatch(SALOME_SalomeException);
1939 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
1941 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1942 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1943 SALOME::BAD_PARAM );
1945 if ( CORBA::is_nil( theMesh ) )
1946 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1947 SALOME::BAD_PARAM );
1949 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1952 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1953 meshServant->Load();
1954 ASSERT( meshServant );
1955 if ( meshServant ) {
1956 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1957 meshServant->CheckGeomModif();
1958 // get local TopoDS_Shape
1959 TopoDS_Shape myLocShape;
1960 if(theMesh->HasShapeToMesh())
1961 myLocShape = GeomObjectToShape( theShapeObject );
1963 return result._retn();;
1965 // call implementation compute
1966 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1968 ::MeshDimension aDim = (MeshDimension)theDimension;
1969 if ( myGen.Compute( myLocMesh, myLocShape, false, false, aDim, &shapeIds ) )
1971 int nbShapeId = shapeIds.size();
1972 theShapesId.length( nbShapeId );
1973 // iterates on shapes and collect mesh entities into mesh preview
1974 TSetOfInt::const_iterator idIt = shapeIds.begin();
1975 TSetOfInt::const_iterator idEnd = shapeIds.end();
1976 std::map< int, int > mapOfShIdNb;
1977 std::set< SMESH_TLink > setOfEdge;
1978 std::list< SMDSAbs_ElementType > listOfElemType;
1979 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1980 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1981 TNode2LocalIDMap mapNode2LocalID;
1982 list< TNodeLocalID > connectivity;
1983 int i, nbConnNodes = 0;
1984 std::set< const SMESH_subMesh* > setOfVSubMesh;
1985 // iterates on shapes
1986 for ( ; idIt != idEnd; idIt++ )
1988 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
1990 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
1991 if ( !sm || !sm->IsMeshComputed() )
1994 const TopoDS_Shape& aSh = sm->GetSubShape();
1995 const int shDim = myGen.GetShapeDim( aSh );
1996 if ( shDim < 1 || shDim > theDimension )
1999 mapOfShIdNb[ *idIt ] = 0;
2000 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2002 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2003 if ( !smDS ) continue;
2005 if ( theDimension == SMESH::DIM_2D )
2007 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2008 while ( faceIt->more() )
2010 const SMDS_MeshElement* face = faceIt->next();
2011 int aNbNode = face->NbNodes();
2013 aNbNode /= 2; // do not take into account additional middle nodes
2015 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2016 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2018 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2019 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2021 listOfElemType.push_back( SMDSAbs_Edge );
2022 connectivity.push_back
2023 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2024 connectivity.push_back
2025 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2031 else if ( theDimension == SMESH::DIM_1D )
2033 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2034 while ( nodeIt->more() )
2036 listOfElemType.push_back( SMDSAbs_Node );
2037 connectivity.push_back
2038 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2040 // add corner nodes by first vertex from edge
2041 SMESH_subMeshIteratorPtr edgeSmIt =
2042 sm->getDependsOnIterator(/*includeSelf*/false,
2043 /*complexShapeFirst*/false);
2044 while ( edgeSmIt->more() )
2046 SMESH_subMesh* vertexSM = edgeSmIt->next();
2047 // check that vertex is not already treated
2048 if ( !setOfVSubMesh.insert( vertexSM ).second )
2050 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2053 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2054 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2055 while ( nodeIt->more() )
2057 listOfElemType.push_back( SMDSAbs_Node );
2058 connectivity.push_back
2059 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2065 // fill node coords and assign local ids to the nodes
2066 int nbNodes = mapNode2LocalID.size();
2067 result->nodesXYZ.length( nbNodes );
2068 TNodeLocalID node2ID = mapNode2LocalID.begin();
2069 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2070 node2ID->second = i;
2071 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2072 result->nodesXYZ[i].x = node->X();
2073 result->nodesXYZ[i].y = node->Y();
2074 result->nodesXYZ[i].z = node->Z();
2076 // fill connectivity
2077 result->elementConnectivities.length( nbConnNodes );
2078 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2079 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2080 result->elementConnectivities[i] = (*connIt)->second;
2083 // fill element types
2084 result->elementTypes.length( listOfElemType.size() );
2085 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2086 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2087 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2089 SMDSAbs_ElementType elemType = *typeIt;
2090 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2091 result->elementTypes[i].isPoly = false;
2092 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2095 // correct number of shapes
2096 theShapesId.length( mapOfShIdNb.size() );
2100 catch ( std::bad_alloc ) {
2101 INFOS( "Precompute(): lack of memory" );
2103 catch ( SALOME_Exception& S_ex ) {
2104 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2107 INFOS( "Precompute(): unknown exception " );
2109 return result._retn();
2113 //=============================================================================
2115 * SMESH_Gen_i::Evaluate
2117 * Evaluate mesh on a shape
2119 //=============================================================================
2121 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2122 GEOM::GEOM_Object_ptr theShapeObject)
2123 // SMESH::long_array& theNbElems)
2124 throw ( SALOME::SALOME_Exception )
2126 Unexpect aCatch(SALOME_SalomeException);
2127 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2129 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2130 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2131 SALOME::BAD_PARAM );
2133 if ( CORBA::is_nil( theMesh ) )
2134 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2135 SALOME::BAD_PARAM );
2137 SMESH::long_array_var nbels = new SMESH::long_array;
2138 nbels->length(SMESH::Entity_Last);
2139 int i = SMESH::Entity_Node;
2140 for (; i < SMESH::Entity_Last; i++)
2143 // Update Python script
2144 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2145 << theMesh << ", " << theShapeObject << ")";
2149 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2150 ASSERT( meshServant );
2151 if ( meshServant ) {
2152 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
2153 meshServant->CheckGeomModif();
2154 // get local TopoDS_Shape
2155 TopoDS_Shape myLocShape;
2156 if(theMesh->HasShapeToMesh())
2157 myLocShape = GeomObjectToShape( theShapeObject );
2159 myLocShape = SMESH_Mesh::PseudoShape();
2160 // call implementation compute
2161 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2162 MapShapeNbElems aResMap;
2163 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2164 MapShapeNbElemsItr anIt = aResMap.begin();
2165 for(; anIt!=aResMap.end(); anIt++) {
2166 const vector<int>& aVec = (*anIt).second;
2167 for(i = SMESH::Entity_Node; i < aVec.size(); i++) {
2168 int nbElem = aVec[i];
2169 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2171 SMESH_subMesh* sm = anIt->first;
2172 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2173 const SMESH_Algo* algo = myGen.GetAlgo( myLocMesh, sm->GetSubShape());
2174 if ( (algo && !error.get()) || error->IsOK() )
2175 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2179 nbels[i] += aVec[i];
2183 return nbels._retn();
2186 catch ( std::bad_alloc ) {
2187 INFOS( "Evaluate(): lack of memory" );
2189 catch ( SALOME_Exception& S_ex ) {
2190 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2193 INFOS( "Evaluate(): unknown exception " );
2196 return nbels._retn();
2199 //================================================================================
2201 * \brief Return geometrical object the given element is built on
2202 * \param theMesh - the mesh the element is in
2203 * \param theElementID - the element ID
2204 * \param theGeomName - the name of the result geom object if it is not yet published
2205 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2207 //================================================================================
2209 GEOM::GEOM_Object_ptr
2210 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2211 CORBA::Long theElementID,
2212 const char* theGeomName)
2213 throw ( SALOME::SALOME_Exception )
2215 Unexpect aCatch(SALOME_SalomeException);
2217 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2218 if ( !geom->_is_nil() ) {
2219 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2220 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2222 // try to find the corresponding SObject
2223 SALOMEDS::SObject_wrap SObj = ObjectToSObject( myCurrentStudy, geom.in() );
2224 if ( SObj->_is_nil() ) // submesh can be not found even if published
2226 // try to find published submesh
2227 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2228 if ( !geom->IsMainShape() && list->length() == 1 ) {
2229 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2230 SALOMEDS::ChildIterator_wrap it;
2231 if ( !mainSO->_is_nil() ) {
2232 it = myCurrentStudy->NewChildIterator( mainSO );
2234 if ( !it->_is_nil() ) {
2235 for ( it->InitEx(true); it->More(); it->Next() ) {
2236 SALOMEDS::SObject_wrap so = it->Value();
2237 CORBA::Object_var obj = SObjectToObject( so );
2238 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2239 if ( !subGeom->_is_nil() ) {
2240 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2241 if ( subList->length() == 1 && list[0] == subList[0] ) {
2251 if ( SObj->_is_nil() ) // publish a new subshape
2252 SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
2254 // return only published geometry
2255 if ( !SObj->_is_nil() ) {
2256 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2257 CORBA::Object_var obj = SObjectToObject( SObj );
2258 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2262 return GEOM::GEOM_Object::_nil();
2265 //================================================================================
2267 * \brief Return geometrical object the given element is built on.
2268 * \param theMesh - the mesh the element is in
2269 * \param theElementID - the element ID
2270 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2272 //================================================================================
2274 GEOM::GEOM_Object_ptr
2275 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2276 CORBA::Long theElementID)
2277 throw ( SALOME::SALOME_Exception )
2279 Unexpect aCatch(SALOME_SalomeException);
2280 if ( CORBA::is_nil( theMesh ) )
2281 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2283 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2284 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2286 // get a core mesh DS
2287 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2288 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2290 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2291 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2292 // find the element in mesh
2293 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2294 // find a shape id by the element
2295 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2296 // get a geom object by the shape id
2297 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2298 if ( geom->_is_nil() ) {
2299 // try to find a published sub-shape
2300 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2301 SALOMEDS::ChildIterator_wrap it;
2302 if ( !mainSO->_is_nil() ) {
2303 it = myCurrentStudy->NewChildIterator( mainSO );
2305 if ( !it->_is_nil() ) {
2306 for ( it->InitEx(true); it->More(); it->Next() ) {
2307 SALOMEDS::SObject_wrap so = it->Value();
2308 CORBA::Object_var obj = SObjectToObject( so );
2309 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2310 if ( !subGeom->_is_nil() ) {
2311 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2312 if ( subList->length() == 1 && shapeID == subList[0] ) {
2320 if ( geom->_is_nil() ) {
2322 GEOM::GEOM_IShapesOperations_wrap op =
2323 geomGen->GetIShapesOperations( GetCurrentStudyID() );
2324 if ( !op->_is_nil() )
2325 geom = op->GetSubShape( mainShape, shapeID );
2330 if ( !geom->_is_nil() ) {
2331 GeomObjectToShape( geom ); // let geom client remember the found shape
2332 return geom._retn();
2337 return GEOM::GEOM_Object::_nil();
2340 //================================================================================
2342 * SMESH_Gen_i::Concatenate
2344 * Concatenate the given meshes into one mesh
2346 //================================================================================
2348 SMESH::SMESH_Mesh_ptr
2349 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2350 CORBA::Boolean theUniteIdenticalGroups,
2351 CORBA::Boolean theMergeNodesAndElements,
2352 CORBA::Double theMergeTolerance)
2353 throw ( SALOME::SALOME_Exception )
2355 return ConcatenateCommon(theMeshesArray,
2356 theUniteIdenticalGroups,
2357 theMergeNodesAndElements,
2362 //================================================================================
2364 * SMESH_Gen_i::ConcatenateWithGroups
2366 * Concatenate the given meshes into one mesh
2367 * Create the groups of all elements from initial meshes
2369 //================================================================================
2371 SMESH::SMESH_Mesh_ptr
2372 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2373 CORBA::Boolean theUniteIdenticalGroups,
2374 CORBA::Boolean theMergeNodesAndElements,
2375 CORBA::Double theMergeTolerance)
2376 throw ( SALOME::SALOME_Exception )
2378 return ConcatenateCommon(theMeshesArray,
2379 theUniteIdenticalGroups,
2380 theMergeNodesAndElements,
2385 //================================================================================
2387 * SMESH_Gen_i::ConcatenateCommon
2389 * Concatenate the given meshes into one mesh
2391 //================================================================================
2393 SMESH::SMESH_Mesh_ptr
2394 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2395 CORBA::Boolean theUniteIdenticalGroups,
2396 CORBA::Boolean theMergeNodesAndElements,
2397 CORBA::Double theMergeTolerance,
2398 CORBA::Boolean theCommonGroups)
2399 throw ( SALOME::SALOME_Exception )
2401 typedef list<SMESH::SMESH_Group_var> TListOfNewGroups;
2402 typedef map< pair<string, SMESH::ElementType>, TListOfNewGroups > TGroupsMap;
2404 TPythonDump* pPythonDump = new TPythonDump;
2405 TPythonDump& aPythonDump = *pPythonDump; // prevent dump of called methods
2408 SMESH::SMESH_Mesh_var aNewMesh = CreateEmptyMesh();
2410 if ( aNewMesh->_is_nil() )
2411 return aNewMesh._retn();
2413 SMESH_Mesh_i* aNewImpl = SMESH::DownCast<SMESH_Mesh_i*>( aNewMesh );
2415 return aNewMesh._retn();
2417 ::SMESH_Mesh& aLocMesh = aNewImpl->GetImpl();
2418 SMESHDS_Mesh* aNewMeshDS = aLocMesh.GetMeshDS();
2420 TGroupsMap aGroupsMap;
2421 TListOfNewGroups aListOfNewGroups;
2422 ::SMESH_MeshEditor aNewEditor(&aLocMesh);
2423 SMESH::ListOfGroups_var aListOfGroups;
2425 ::SMESH_MeshEditor::ElemFeatures elemType;
2426 std::vector<const SMDS_MeshNode*> aNodesArray;
2428 // loop on sub-meshes
2429 for ( int i = 0; i < theMeshesArray.length(); i++)
2431 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2432 SMESH::SMESH_Mesh_var anInitMesh = theMeshesArray[i]->GetMesh();
2433 if ( anInitMesh->_is_nil() ) continue;
2434 SMESH_Mesh_i* anInitImpl = SMESH::DownCast<SMESH_Mesh_i*>( anInitMesh );
2435 if ( !anInitImpl ) continue;
2438 ::SMESH_Mesh& aInitLocMesh = anInitImpl->GetImpl();
2439 SMESHDS_Mesh* anInitMeshDS = aInitLocMesh.GetMeshDS();
2441 // remember nb of elements before filling in
2442 SMESH::long_array_var prevState = aNewMesh->GetNbElementsByType();
2444 typedef std::map<const SMDS_MeshElement*, const SMDS_MeshElement*, TIDCompare > TEEMap;
2445 TEEMap elemsMap, nodesMap;
2447 // loop on elements of a sub-mesh
2448 SMDS_ElemIteratorPtr itElems = anInitImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2449 const SMDS_MeshElement* anElem;
2450 const SMDS_MeshElement* aNewElem;
2451 const SMDS_MeshNode* aNode;
2452 const SMDS_MeshNode* aNewNode;
2455 while ( itElems->more() )
2457 anElem = itElems->next();
2458 anElemNbNodes = anElem->NbNodes();
2459 aNodesArray.resize( anElemNbNodes );
2461 // loop on nodes of an element
2462 SMDS_ElemIteratorPtr itNodes = anElem->nodesIterator();
2463 for ( int k = 0; itNodes->more(); k++)
2465 aNode = static_cast<const SMDS_MeshNode*>( itNodes->next() );
2466 TEEMap::iterator n2nnIt = nodesMap.find( aNode );
2467 if ( n2nnIt == nodesMap.end() )
2469 aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2470 nodesMap.insert( make_pair( aNode, aNewNode ));
2474 aNewNode = static_cast<const SMDS_MeshNode*>( n2nnIt->second );
2476 aNodesArray[k] = aNewNode;
2479 // creates a corresponding element on existent nodes in new mesh
2480 if ( anElem->GetType() == SMDSAbs_Node )
2484 aNewEditor.AddElement( aNodesArray, elemType.Init( anElem, /*basicOnly=*/false ));
2487 elemsMap.insert( make_pair( anElem, aNewElem ));
2491 aNewEditor.ClearLastCreated(); // forget the history
2494 // create groups of just added elements
2495 SMESH::SMESH_Group_var aNewGroup;
2496 SMESH::ElementType aGroupType;
2497 if ( theCommonGroups )
2499 SMESH::long_array_var curState = aNewMesh->GetNbElementsByType();
2501 for( aGroupType = SMESH::NODE;
2502 aGroupType < SMESH::NB_ELEMENT_TYPES;
2503 aGroupType = (SMESH::ElementType)( aGroupType + 1 ))
2505 if ( curState[ aGroupType ] <= prevState[ aGroupType ])
2508 // make a group name
2509 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2510 { // check of typeNames, compilation failure mains that NB_ELEMENT_TYPES changed:
2511 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2512 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 1 : -1 ];
2514 string groupName = "Gr";
2515 SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( myCurrentStudy, theMeshesArray[i] );
2517 CORBA::String_var name = aMeshSObj->GetName();
2521 groupName += typeNames[ aGroupType ];
2523 // make and fill a group
2524 TEEMap & e2neMap = ( aGroupType == SMESH::NODE ) ? nodesMap : elemsMap;
2525 aNewGroup = aNewImpl->CreateGroup( aGroupType, groupName.c_str() );
2526 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( aNewGroup ))
2528 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2530 TEEMap::iterator e2neIt = e2neMap.begin();
2531 for ( ; e2neIt != e2neMap.end(); ++e2neIt )
2533 aNewElem = e2neIt->second;
2534 if ( aNewElem->GetType() == grpDS->GetType() )
2536 grpDS->Add( aNewElem );
2538 if ( prevState[ aGroupType ]++ >= curState[ aGroupType ] )
2544 aListOfNewGroups.clear();
2545 aListOfNewGroups.push_back(aNewGroup);
2546 aGroupsMap.insert(make_pair( make_pair(groupName, aGroupType), aListOfNewGroups ));
2550 if ( SMESH_Mesh_i* anSrcImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2552 // copy orphan nodes
2553 if ( anSrcImpl->NbNodes() > nodesMap.size() )
2555 SMDS_ElemIteratorPtr itNodes = anInitImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2556 while ( itNodes->more() )
2558 const SMDS_MeshNode* aNode = static_cast< const SMDS_MeshNode* >( itNodes->next() );
2559 if ( aNode->NbInverseElements() == 0 )
2561 aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2562 nodesMap.insert( make_pair( aNode, aNewNode ));
2569 SMESH::SMESH_GroupBase_ptr aGroup;
2570 CORBA::String_var aGroupName;
2571 SMESH::long_array_var anNewIDs = new SMESH::long_array();
2573 // loop on groups of a source mesh
2574 aListOfGroups = anSrcImpl->GetGroups();
2575 for (int iG = 0; iG < aListOfGroups->length(); iG++)
2577 aGroup = aListOfGroups[iG];
2578 aGroupType = aGroup->GetType();
2579 aGroupName = aGroup->GetName();
2581 // convert a list of IDs
2582 anNewIDs->length( aGroup->Size() );
2583 TEEMap & e2neMap = ( aGroupType == SMESH::NODE ) ? nodesMap : elemsMap;
2584 SMDS_ElemIteratorPtr itGrElems = anSrcImpl->GetElements( aGroup, SMESH::ALL );
2586 while ( itGrElems->more() )
2588 anElem = itGrElems->next();
2589 TEEMap::iterator e2neIt = e2neMap.find( anElem );
2590 if ( e2neIt != e2neMap.end() )
2591 anNewIDs[ iElem++ ] = e2neIt->second->GetID();
2593 anNewIDs->length( iElem );
2595 // check a current group name and type don't have identical ones in final mesh
2596 aListOfNewGroups.clear();
2597 TGroupsMap::iterator anIter = aGroupsMap.find( make_pair( aGroupName, aGroupType ));
2598 if ( anIter == aGroupsMap.end() ) {
2599 // add a new group in the mesh
2600 aNewGroup = aNewImpl->CreateGroup( aGroupType, aGroupName );
2601 // add elements into new group
2602 aNewGroup->Add( anNewIDs );
2604 aListOfNewGroups.push_back(aNewGroup);
2605 aGroupsMap.insert(make_pair( make_pair(aGroupName, aGroupType), aListOfNewGroups ));
2608 else if ( theUniteIdenticalGroups ) {
2609 // unite identical groups
2610 TListOfNewGroups& aNewGroups = anIter->second;
2611 aNewGroups.front()->Add( anNewIDs );
2615 // rename identical groups
2616 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
2617 aNewGroup->Add( anNewIDs );
2619 TListOfNewGroups& aNewGroups = anIter->second;
2620 string aNewGroupName;
2621 if (aNewGroups.size() == 1) {
2622 aNewGroupName = string(aGroupName) + "_1";
2623 aNewGroups.front()->SetName(aNewGroupName.c_str());
2625 char aGroupNum[128];
2626 sprintf(aGroupNum, "%u", aNewGroups.size()+1);
2627 aNewGroupName = string(aGroupName) + "_" + string(aGroupNum);
2628 aNewGroup->SetName(aNewGroupName.c_str());
2629 aNewGroups.push_back(aNewGroup);
2632 } // if an IDSource is a mesh
2635 if (theMergeNodesAndElements) // merge nodes
2637 TIDSortedNodeSet aMeshNodes; // no input nodes
2638 SMESH_MeshEditor::TListOfListOfNodes aGroupsOfNodes;
2639 aNewEditor.FindCoincidentNodes( aMeshNodes, theMergeTolerance, aGroupsOfNodes,
2640 /*SeparateCornersAndMedium=*/ false );
2641 aNewEditor.MergeNodes( aGroupsOfNodes );
2643 aNewEditor.MergeEqualElements();
2646 // Update Python script
2647 aPythonDump << aNewMesh << " = " << this << "."
2648 << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" )
2650 for ( int i = 0; i < theMeshesArray.length(); i++) {
2651 if (i > 0) aPythonDump << ", ";
2652 aPythonDump << theMeshesArray[i];
2654 aPythonDump << "], ";
2655 aPythonDump << theUniteIdenticalGroups << ", "
2656 << theMergeNodesAndElements << ", "
2657 << TVar( theMergeTolerance ) << ")";
2659 delete pPythonDump; // enable python dump from GetGroups()
2661 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2662 if ( !aNewMesh->_is_nil() )
2664 SMESH::ListOfGroups_var groups = aNewMesh->GetGroups();
2667 // IPAL21468 Change icon of compound because it need not be computed.
2668 SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( myCurrentStudy, aNewMesh );
2669 SetPixMap( aMeshSObj, "ICON_SMESH_TREE_MESH" );
2672 aNewMeshDS->Modified();
2674 return aNewMesh._retn();
2677 //================================================================================
2679 * \brief Create a mesh by copying a part of another mesh
2680 * \param meshPart - a part of mesh to copy
2681 * \param toCopyGroups - to create in the new mesh groups
2682 * the copied elements belongs to
2683 * \param toKeepIDs - to preserve IDs of the copied elements or not
2684 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2686 //================================================================================
2688 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2689 const char* meshName,
2690 CORBA::Boolean toCopyGroups,
2691 CORBA::Boolean toKeepIDs)
2693 Unexpect aCatch(SALOME_SalomeException);
2695 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2697 // 1. Get source mesh
2699 if ( CORBA::is_nil( meshPart ))
2700 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2702 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2703 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2705 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2707 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2709 // 2. Make a new mesh
2711 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2712 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2714 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2715 SALOMEDS::SObject_wrap meshSO = ObjectToSObject(myCurrentStudy, newMesh );
2716 if ( !meshSO->_is_nil() )
2718 SetName( meshSO, meshName, "Mesh" );
2719 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2721 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2722 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2723 ::SMESH_MeshEditor::ElemFeatures elemType;
2725 // 3. Get elements to copy
2727 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2728 TIDSortedElemSet srcElems;
2729 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2730 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2733 srcElemIt = srcMeshDS->elementsIterator();
2734 srcNodeIt = srcMeshDS->nodesIterator();
2738 SMESH::long_array_var ids = meshPart->GetIDs();
2739 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2741 for (int i=0; i < ids->length(); i++)
2742 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2743 srcElems.insert( elem );
2747 for (int i=0; i < ids->length(); i++)
2748 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2749 srcElems.insert( elem );
2751 if ( srcElems.empty() )
2752 return newMesh._retn();
2754 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2755 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2760 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2761 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2762 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2764 const SMDS_MeshNode *nSrc, *nTgt;
2765 vector< const SMDS_MeshNode* > nodes;
2766 while ( srcElemIt->more() )
2768 const SMDS_MeshElement * elem = srcElemIt->next();
2770 nodes.resize( elem->NbNodes());
2771 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2773 for ( iN = 0; nIt->more(); ++iN )
2775 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2776 nTgt = newMeshDS->FindNode( nSrc->GetID());
2778 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2783 for ( iN = 0; nIt->more(); ++iN )
2785 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2786 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2788 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2789 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2793 if ( elem->GetType() != SMDSAbs_Node )
2795 elemType.Init( elem, /*basicOnly=*/false );
2796 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2798 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2799 if ( toCopyGroups && !toKeepIDs )
2800 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2802 } // while ( srcElemIt->more() )
2804 // 4(b). Copy free nodes
2806 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2808 while ( srcNodeIt->more() )
2810 nSrc = srcNodeIt->next();
2811 if ( nSrc->NbInverseElements() == 0 )
2814 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2816 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2823 int nbNewGroups = 0;
2826 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2827 while ( gIt->more() )
2829 SMESH_Group* group = gIt->next();
2830 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2832 // Check group type. We copy nodal groups containing nodes of copied element
2833 SMDSAbs_ElementType groupType = groupDS->GetType();
2834 if ( groupType != SMDSAbs_Node &&
2835 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2836 continue; // group type differs from types of meshPart
2838 // Find copied elements in the group
2839 vector< const SMDS_MeshElement* > groupElems;
2840 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2843 const SMDS_MeshElement* foundElem;
2844 if ( groupType == SMDSAbs_Node )
2846 while ( eIt->more() )
2847 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2848 groupElems.push_back( foundElem );
2852 while ( eIt->more() )
2853 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2854 groupElems.push_back( foundElem );
2859 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2860 if ( e2eMap.empty() ) continue;
2861 int minID = e2eMap.begin()->first->GetID();
2862 int maxID = e2eMap.rbegin()->first->GetID();
2863 TE2EMap::iterator e2e;
2864 while ( eIt->more() && groupElems.size() < e2eMap.size())
2866 const SMDS_MeshElement* e = eIt->next();
2867 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2868 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2869 groupElems.push_back( e2e->second );
2873 if ( !groupElems.empty() )
2875 SMESH::SMESH_Group_var newGroupObj =
2876 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2877 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2879 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2880 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2881 for ( unsigned i = 0; i < groupElems.size(); ++i )
2882 smdsGroup.Add( groupElems[i] );
2890 newMeshDS->Modified();
2892 *pyDump << newMesh << " = " << this
2893 << ".CopyMesh( " << meshPart << ", "
2894 << "'" << meshName << "', "
2895 << toCopyGroups << ", "
2896 << toKeepIDs << ")";
2898 delete pyDump; pyDump = 0; // allow dump in GetGroups()
2900 if ( nbNewGroups > 0 ) // dump created groups
2901 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2903 return newMesh._retn();
2906 //================================================================================
2908 * SMESH_Gen_i::GetMEDVersion
2910 * Get MED version of the file by its name
2912 //================================================================================
2913 CORBA::Boolean SMESH_Gen_i::GetMEDVersion(const char* theFileName,
2914 SMESH::MED_VERSION& theVersion)
2916 theVersion = SMESH::MED_V2_1;
2917 MED::EVersion aVersion = MED::GetVersionId( theFileName );
2918 switch( aVersion ) {
2919 case MED::eV2_1 : theVersion = SMESH::MED_V2_1; return true;
2920 case MED::eV2_2 : theVersion = SMESH::MED_V2_2; return true;
2921 case MED::eVUnknown : return false;
2926 //================================================================================
2928 * SMESH_Gen_i::GetMeshNames
2930 * Get names of meshes defined in file with the specified name
2932 //================================================================================
2933 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
2935 SMESH::string_array_var aResult = new SMESH::string_array();
2936 MED::PWrapper aMed = MED::CrWrapper( theFileName );
2938 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
2940 aResult->length( aNbMeshes );
2941 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
2942 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
2943 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
2946 return aResult._retn();
2949 //=============================================================================
2953 * Save SMESH module's data
2955 //=============================================================================
2956 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
2960 INFOS( "SMESH_Gen_i::Save" );
2962 // ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
2963 // san -- in case <myCurrentStudy> differs from theComponent's study,
2964 // use that of the component
2965 if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
2966 SetCurrentStudy( theComponent->GetStudy() );
2968 // Store study contents as a set of python commands
2969 SavePython(myCurrentStudy);
2971 StudyContext* myStudyContext = GetCurrentStudyContext();
2973 // Declare a byte stream
2974 SALOMEDS::TMPFile_var aStreamFile;
2976 // Obtain a temporary dir
2977 TCollection_AsciiString tmpDir =
2978 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
2980 // Create a sequence of files processed
2981 SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
2982 aFileSeq->length( NUM_TMP_FILES );
2984 TCollection_AsciiString aStudyName( "" );
2986 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
2988 // Set names of temporary files
2989 TCollection_AsciiString filename =
2990 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
2991 TCollection_AsciiString meshfile =
2992 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
2993 aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
2994 aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
2995 filename = tmpDir + filename;
2996 meshfile = tmpDir + meshfile;
2999 HDFdataset* aDataset;
3000 HDFgroup* aTopGroup;
3002 HDFgroup* aSubGroup;
3003 HDFgroup* aSubSubGroup;
3004 hdf_size aSize[ 1 ];
3007 //Remove the files if they exist: BugID: 11225
3008 #ifndef WIN32 /* unix functionality */
3009 TCollection_AsciiString cmd("rm -f \"");
3011 TCollection_AsciiString cmd("del /F \"");
3018 system(cmd.ToCString());
3020 // MED writer to be used by storage process
3021 DriverMED_W_SMESHDS_Mesh myWriter;
3022 myWriter.SetFile( meshfile.ToCString() );
3025 // SetStoreName() to groups before storing hypotheses to let them refer to
3026 // groups using "store name", which is "Group <group_persistent_id>"
3028 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
3029 for ( ; itBig->More(); itBig->Next() ) {
3030 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3031 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3032 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3033 if ( !CORBA::is_nil( anObject ) ) {
3034 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3035 if ( !myMesh->_is_nil() ) {
3036 myMesh->Load(); // load from study file if not yet done
3037 TPythonDump pd; // not to dump GetGroups()
3038 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
3039 pd << ""; // to avoid optimizing pd out
3040 for ( int i = 0; i < groups->length(); ++i )
3042 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
3045 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
3046 int anId = myStudyContext->findId( string( objStr.in() ) );
3048 sprintf( grpName, "Group %d", anId );
3049 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
3050 aGrpBaseDS->SetStoreName( grpName );
3060 // ---> create HDF file
3061 aFile = new HDFfile( (char*) filename.ToCString() );
3062 aFile->CreateOnDisk();
3064 // --> iterator for top-level objects
3065 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
3066 for ( ; itBig->More(); itBig->Next() ) {
3067 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3069 // --> hypotheses root branch (only one for the study)
3070 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
3071 // create hypotheses root HDF group
3072 aTopGroup = new HDFgroup( "Hypotheses", aFile );
3073 aTopGroup->CreateOnDisk();
3075 // iterator for all hypotheses
3076 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
3077 for ( ; it->More(); it->Next() ) {
3078 SALOMEDS::SObject_wrap mySObject = it->Value();
3079 CORBA::Object_var anObject = SObjectToObject( mySObject );
3080 if ( !CORBA::is_nil( anObject ) ) {
3081 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3082 if ( !myHyp->_is_nil() ) {
3083 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3085 string hypname = string( myHyp->GetName() );
3086 string libname = string( myHyp->GetLibName() );
3088 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3089 // WIN32 and ".so" for X-system) must be deleted
3090 int libname_len = libname.length();
3092 if( libname_len > 4 )
3093 libname.resize( libname_len - 4 );
3095 // PAL17753 (Regresion: missing hypothesis in restored study)
3096 // "lib" also should be removed from the beginning
3097 //if( libname_len > 3 )
3098 //libname.resize( libname_len - 3 );
3099 if( libname_len > 6 )
3100 libname = libname.substr( 3, libname_len - 3 - 3 );
3102 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3103 int id = myStudyContext->findId( string( objStr.in() ) );
3104 string hypdata = string( myImpl->SaveTo() );
3106 // for each hypothesis create HDF group basing on its id
3107 char hypGrpName[30];
3108 sprintf( hypGrpName, "Hypothesis %d", id );
3109 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3110 aGroup->CreateOnDisk();
3111 // --> type name of hypothesis
3112 aSize[ 0 ] = hypname.length() + 1;
3113 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3114 aDataset->CreateOnDisk();
3115 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3116 aDataset->CloseOnDisk();
3117 // --> server plugin library name of hypothesis
3118 aSize[ 0 ] = libname.length() + 1;
3119 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3120 aDataset->CreateOnDisk();
3121 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3122 aDataset->CloseOnDisk();
3123 // --> persistent data of hypothesis
3124 aSize[ 0 ] = hypdata.length() + 1;
3125 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3126 aDataset->CreateOnDisk();
3127 aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
3128 aDataset->CloseOnDisk();
3129 // close hypothesis HDF group
3130 aGroup->CloseOnDisk();
3135 // close hypotheses root HDF group
3136 aTopGroup->CloseOnDisk();
3138 // --> algorithms root branch (only one for the study)
3139 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
3140 // create algorithms root HDF group
3141 aTopGroup = new HDFgroup( "Algorithms", aFile );
3142 aTopGroup->CreateOnDisk();
3144 // iterator for all algorithms
3145 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
3146 for ( ; it->More(); it->Next() ) {
3147 SALOMEDS::SObject_wrap mySObject = it->Value();
3148 CORBA::Object_var anObject = SObjectToObject( mySObject );
3149 if ( !CORBA::is_nil( anObject ) ) {
3150 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3151 if ( !myHyp->_is_nil() ) {
3152 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3154 string hypname = string( myHyp->GetName() );
3155 string libname = string( myHyp->GetLibName() );
3157 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3158 // WIN32 and ".so" for X-system) must be deleted
3159 int libname_len = libname.length();
3161 if( libname_len > 4 )
3162 libname.resize( libname_len - 4 );
3164 // PAL17753 (Regresion: missing hypothesis in restored study)
3165 // "lib" also should be removed from the beginning
3166 //if( libname_len > 3 )
3167 //libname.resize( libname_len - 3 );
3168 if( libname_len > 6 )
3169 libname = libname.substr( 3, libname_len - 3 - 3 );
3171 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3172 int id = myStudyContext->findId( string( objStr.in() ) );
3173 string hypdata = string( myImpl->SaveTo() );
3175 // for each algorithm create HDF group basing on its id
3176 char hypGrpName[30];
3177 sprintf( hypGrpName, "Algorithm %d", id );
3178 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3179 aGroup->CreateOnDisk();
3180 // --> type name of algorithm
3181 aSize[0] = hypname.length() + 1;
3182 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3183 aDataset->CreateOnDisk();
3184 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3185 aDataset->CloseOnDisk();
3186 // --> server plugin library name of hypothesis
3187 aSize[0] = libname.length() + 1;
3188 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3189 aDataset->CreateOnDisk();
3190 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3191 aDataset->CloseOnDisk();
3192 // --> persistent data of algorithm
3193 aSize[0] = hypdata.length() + 1;
3194 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3195 aDataset->CreateOnDisk();
3196 aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
3197 aDataset->CloseOnDisk();
3198 // close algorithm HDF group
3199 aGroup->CloseOnDisk();
3204 // close algorithms root HDF group
3205 aTopGroup->CloseOnDisk();
3207 // --> mesh objects roots branches
3208 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3209 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3210 if ( !CORBA::is_nil( anObject ) ) {
3211 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3212 if ( !myMesh->_is_nil() ) {
3213 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
3215 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3216 int id = myStudyContext->findId( string( objStr.in() ) );
3217 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
3218 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
3219 bool hasShape = myLocMesh.HasShapeToMesh();
3221 // for each mesh open the HDF group basing on its id
3222 char meshGrpName[ 30 ];
3223 sprintf( meshGrpName, "Mesh %d", id );
3224 aTopGroup = new HDFgroup( meshGrpName, aFile );
3225 aTopGroup->CreateOnDisk();
3227 // --> put dataset to hdf file which is a flag that mesh has data
3228 string strHasData = "0";
3229 // check if the mesh is not empty
3230 if ( mySMESHDSMesh->NbNodes() > 0 ) {
3231 // write mesh data to med file
3232 myWriter.SetMesh( mySMESHDSMesh );
3233 myWriter.SetMeshId( id );
3236 aSize[ 0 ] = strHasData.length() + 1;
3237 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
3238 aDataset->CreateOnDisk();
3239 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
3240 aDataset->CloseOnDisk();
3243 // for each mesh open the HDF group basing on its auto color parameter
3244 char meshAutoColorName[ 30 ];
3245 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
3247 anAutoColor[0] = myImpl->GetAutoColor();
3249 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
3250 aDataset->CreateOnDisk();
3251 aDataset->WriteOnDisk( anAutoColor );
3252 aDataset->CloseOnDisk();
3254 // issue 0020693. Store _isModified flag
3255 int isModified = myLocMesh.GetIsModified();
3257 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
3258 aDataset->CreateOnDisk();
3259 aDataset->WriteOnDisk( &isModified );
3260 aDataset->CloseOnDisk();
3262 // issue 20918. Store Persistent Id of SMESHDS_Mesh
3263 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
3265 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
3266 aDataset->CreateOnDisk();
3267 aDataset->WriteOnDisk( &meshPersistentId );
3268 aDataset->CloseOnDisk();
3270 // write reference on a shape if exists
3271 SALOMEDS::SObject_wrap myRef;
3272 bool shapeRefFound = false;
3273 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
3275 SALOMEDS::SObject_wrap myShape;
3276 bool ok = myRef->ReferencedObject( myShape.inout() );
3278 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
3279 string myRefOnObject = myShape->GetID();
3280 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
3281 aSize[ 0 ] = myRefOnObject.length() + 1;
3282 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
3283 aDataset->CreateOnDisk();
3284 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3285 aDataset->CloseOnDisk();
3290 // write applied hypotheses if exist
3291 SALOMEDS::SObject_wrap myHypBranch;
3292 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
3293 if ( found && !shapeRefFound && hasShape) { // remove applied hyps
3294 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
3296 if ( found && (shapeRefFound || !hasShape) ) {
3297 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
3298 aGroup->CreateOnDisk();
3300 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myHypBranch );
3302 for ( ; it->More(); it->Next() ) {
3303 SALOMEDS::SObject_wrap mySObject = it->Value();
3304 SALOMEDS::SObject_wrap myRefOnHyp;
3305 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
3307 // san - it is impossible to recover applied hypotheses
3308 // using their entries within Load() method,
3309 // for there are no AttributeIORs in the study when Load() is working.
3310 // Hence, it is better to store persistent IDs of hypotheses as references to them
3312 //string myRefOnObject = myRefOnHyp->GetID();
3313 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3314 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3315 int id = myStudyContext->findId( string( objStr.in() ) );
3316 //if ( myRefOnObject.length() > 0 ) {
3317 //aSize[ 0 ] = myRefOnObject.length() + 1;
3318 char hypName[ 30 ], hypId[ 30 ];
3319 sprintf( hypName, "Hyp %d", ++hypNb );
3320 sprintf( hypId, "%d", id );
3321 aSize[ 0 ] = strlen( hypId ) + 1;
3322 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
3323 aDataset->CreateOnDisk();
3324 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3325 aDataset->WriteOnDisk( hypId );
3326 aDataset->CloseOnDisk();
3330 aGroup->CloseOnDisk();
3333 // write applied algorithms if exist
3334 SALOMEDS::SObject_wrap myAlgoBranch;
3335 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3336 myAlgoBranch.inout() );
3337 if ( found && !shapeRefFound && hasShape) { // remove applied algos
3338 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
3340 if ( found && (shapeRefFound || !hasShape)) {
3341 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3342 aGroup->CreateOnDisk();
3344 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myAlgoBranch );
3346 for ( ; it->More(); it->Next() ) {
3347 SALOMEDS::SObject_wrap mySObject = it->Value();
3348 SALOMEDS::SObject_wrap myRefOnAlgo;
3349 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
3351 // san - it is impossible to recover applied algorithms
3352 // using their entries within Load() method,
3353 // for there are no AttributeIORs in the study when Load() is working.
3354 // Hence, it is better to store persistent IDs of algorithms as references to them
3356 //string myRefOnObject = myRefOnAlgo->GetID();
3357 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3358 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3359 int id = myStudyContext->findId( string( objStr.in() ) );
3360 //if ( myRefOnObject.length() > 0 ) {
3361 //aSize[ 0 ] = myRefOnObject.length() + 1;
3362 char algoName[ 30 ], algoId[ 30 ];
3363 sprintf( algoName, "Algo %d", ++algoNb );
3364 sprintf( algoId, "%d", id );
3365 aSize[ 0 ] = strlen( algoId ) + 1;
3366 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
3367 aDataset->CreateOnDisk();
3368 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3369 aDataset->WriteOnDisk( algoId );
3370 aDataset->CloseOnDisk();
3374 aGroup->CloseOnDisk();
3377 // --> submesh objects sub-branches
3379 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
3380 SALOMEDS::SObject_wrap mySubmeshBranch;
3381 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
3383 if ( found ) // check if there is shape reference in submeshes
3385 bool hasShapeRef = false;
3386 SALOMEDS::ChildIterator_wrap itSM =
3387 myCurrentStudy->NewChildIterator( mySubmeshBranch );
3388 for ( ; itSM->More(); itSM->Next() ) {
3389 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
3390 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3391 mySubRef->ReferencedObject( myShape.inout() );
3392 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
3395 { // remove one submesh
3396 if ( shapeRefFound )
3397 { // unassign hypothesis
3398 SMESH::SMESH_subMesh_var mySubMesh =
3399 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
3400 if ( !mySubMesh->_is_nil() ) {
3401 int shapeID = mySubMesh->GetId();
3402 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
3403 const list<const SMESHDS_Hypothesis*>& hypList =
3404 mySMESHDSMesh->GetHypothesis( S );
3405 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
3406 while ( hyp != hypList.end() ) {
3407 int hypID = (*hyp++)->GetID(); // goto next hyp here because
3408 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
3412 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
3414 } // loop on submeshes of a type
3415 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
3416 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
3419 } // end check if there is shape reference in submeshes
3421 char name_meshgroup[ 30 ];
3422 if ( i == GetSubMeshOnVertexTag() )
3423 strcpy( name_meshgroup, "SubMeshes On Vertex" );
3424 else if ( i == GetSubMeshOnEdgeTag() )
3425 strcpy( name_meshgroup, "SubMeshes On Edge" );
3426 else if ( i == GetSubMeshOnWireTag() )
3427 strcpy( name_meshgroup, "SubMeshes On Wire" );
3428 else if ( i == GetSubMeshOnFaceTag() )
3429 strcpy( name_meshgroup, "SubMeshes On Face" );
3430 else if ( i == GetSubMeshOnShellTag() )
3431 strcpy( name_meshgroup, "SubMeshes On Shell" );
3432 else if ( i == GetSubMeshOnSolidTag() )
3433 strcpy( name_meshgroup, "SubMeshes On Solid" );
3434 else if ( i == GetSubMeshOnCompoundTag() )
3435 strcpy( name_meshgroup, "SubMeshes On Compound" );
3437 // for each type of submeshes create container HDF group
3438 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
3439 aGroup->CreateOnDisk();
3441 // iterator for all submeshes of given type
3442 SALOMEDS::ChildIterator_wrap itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
3443 for ( ; itSM->More(); itSM->Next() ) {
3444 SALOMEDS::SObject_wrap mySObject = itSM->Value();
3445 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
3446 if ( !CORBA::is_nil( anSubObject ))
3448 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
3449 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
3450 int subid = myStudyContext->findId( string( objStr.in() ) );
3452 // for each mesh open the HDF group basing on its id
3453 char submeshGrpName[ 30 ];
3454 sprintf( submeshGrpName, "SubMesh %d", subid );
3455 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
3456 aSubGroup->CreateOnDisk();
3458 // write reference on a shape, already checked if it exists
3459 SALOMEDS::SObject_wrap mySubRef, myShape;
3460 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3461 mySubRef->ReferencedObject( myShape.inout() );
3462 string myRefOnObject = myShape->GetID();
3463 if ( myRefOnObject.length() > 0 ) {
3464 aSize[ 0 ] = myRefOnObject.length() + 1;
3465 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
3466 aDataset->CreateOnDisk();
3467 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3468 aDataset->CloseOnDisk();
3471 // write applied hypotheses if exist
3472 SALOMEDS::SObject_wrap mySubHypBranch;
3473 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
3474 mySubHypBranch.inout() );
3476 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
3477 aSubSubGroup->CreateOnDisk();
3479 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( mySubHypBranch );
3481 for ( ; it->More(); it->Next() ) {
3482 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3483 SALOMEDS::SObject_wrap myRefOnHyp;
3484 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
3486 //string myRefOnObject = myRefOnHyp->GetID();
3487 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3488 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3489 int id = myStudyContext->findId( string( objStr.in() ) );
3490 //if ( myRefOnObject.length() > 0 ) {
3491 //aSize[ 0 ] = myRefOnObject.length() + 1;
3492 char hypName[ 30 ], hypId[ 30 ];
3493 sprintf( hypName, "Hyp %d", ++hypNb );
3494 sprintf( hypId, "%d", id );
3495 aSize[ 0 ] = strlen( hypId ) + 1;
3496 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
3497 aDataset->CreateOnDisk();
3498 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3499 aDataset->WriteOnDisk( hypId );
3500 aDataset->CloseOnDisk();
3504 aSubSubGroup->CloseOnDisk();
3507 // write applied algorithms if exist
3508 SALOMEDS::SObject_wrap mySubAlgoBranch;
3509 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3510 mySubAlgoBranch.inout() );
3512 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3513 aSubSubGroup->CreateOnDisk();
3515 SALOMEDS::ChildIterator_wrap it =
3516 myCurrentStudy->NewChildIterator( mySubAlgoBranch );
3518 for ( ; it->More(); it->Next() ) {
3519 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3520 SALOMEDS::SObject_wrap myRefOnAlgo;
3521 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
3523 //string myRefOnObject = myRefOnAlgo->GetID();
3524 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3525 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3526 int id = myStudyContext->findId( string( objStr.in() ) );
3527 //if ( myRefOnObject.length() > 0 ) {
3528 //aSize[ 0 ] = myRefOnObject.length() + 1;
3529 char algoName[ 30 ], algoId[ 30 ];
3530 sprintf( algoName, "Algo %d", ++algoNb );
3531 sprintf( algoId, "%d", id );
3532 aSize[ 0 ] = strlen( algoId ) + 1;
3533 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
3534 aDataset->CreateOnDisk();
3535 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3536 aDataset->WriteOnDisk( algoId );
3537 aDataset->CloseOnDisk();
3541 aSubSubGroup->CloseOnDisk();
3543 // close submesh HDF group
3544 aSubGroup->CloseOnDisk();
3547 // close container of submeshes by type HDF group
3548 aGroup->CloseOnDisk();
3551 // All sub-meshes will be stored in MED file
3552 // .. will NOT (PAL 12992)
3553 //if ( shapeRefFound )
3554 //myWriter.AddAllSubMeshes();
3556 // store submesh order if any
3557 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
3558 if ( theOrderIds.size() ) {
3559 char order_list[ 30 ];
3560 strcpy( order_list, "Mesh Order" );
3561 // count number of submesh ids
3563 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
3564 for ( ; idIt != theOrderIds.end(); idIt++ )
3565 nbIDs += (*idIt).size();
3566 // number of values = number of IDs +
3567 // number of lists (for separators) - 1
3568 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
3569 idIt = theOrderIds.begin();
3570 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
3571 const TListOfInt& idList = *idIt;
3572 if (idIt != theOrderIds.begin()) // not first list
3573 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
3574 // dump submesh ids from current list
3575 TListOfInt::const_iterator id_smId = idList.begin();
3576 for( ; id_smId != idList.end(); id_smId++ )
3577 smIDs[ i++ ] = *id_smId;
3580 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
3582 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
3583 aDataset->CreateOnDisk();
3584 aDataset->WriteOnDisk( smIDs );
3585 aDataset->CloseOnDisk();
3590 // groups root sub-branch
3591 SALOMEDS::SObject_wrap myGroupsBranch;
3592 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
3593 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
3595 char name_group[ 30 ];
3596 if ( i == GetNodeGroupsTag() )
3597 strcpy( name_group, "Groups of Nodes" );
3598 else if ( i == GetEdgeGroupsTag() )
3599 strcpy( name_group, "Groups of Edges" );
3600 else if ( i == GetFaceGroupsTag() )
3601 strcpy( name_group, "Groups of Faces" );
3602 else if ( i == GetVolumeGroupsTag() )
3603 strcpy( name_group, "Groups of Volumes" );
3604 else if ( i == Get0DElementsGroupsTag() )
3605 strcpy( name_group, "Groups of 0D Elements" );
3606 else if ( i == GetBallElementsGroupsTag() )
3607 strcpy( name_group, "Groups of Balls" );
3609 aGroup = new HDFgroup( name_group, aTopGroup );
3610 aGroup->CreateOnDisk();
3612 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myGroupsBranch );
3613 for ( ; it->More(); it->Next() ) {
3614 SALOMEDS::SObject_wrap mySObject = it->Value();
3615 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
3616 if ( !CORBA::is_nil( aSubObject ) ) {
3617 SMESH_GroupBase_i* myGroupImpl =
3618 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
3621 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
3625 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
3626 int anId = myStudyContext->findId( string( objStr.in() ) );
3628 // For each group, create a dataset named "Group <group_persistent_id>"
3629 // and store the group's user name into it
3630 const char* grpName = aGrpBaseDS->GetStoreName();
3631 char* aUserName = myGroupImpl->GetName();
3632 aSize[ 0 ] = strlen( aUserName ) + 1;
3634 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
3635 aDataset->CreateOnDisk();
3636 aDataset->WriteOnDisk( aUserName );
3637 aDataset->CloseOnDisk();
3640 // For each group, create a dataset named "Group <group_persistent_id> Color"
3641 // and store the group's color into it
3642 char grpColorName[ 30 ];
3643 sprintf( grpColorName, "ColorGroup %d", anId );
3644 SALOMEDS::Color aColor = myGroupImpl->GetColor();
3646 anRGB[ 0 ] = aColor.R;
3647 anRGB[ 1 ] = aColor.G;
3648 anRGB[ 2 ] = aColor.B;
3650 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
3651 aDataset->CreateOnDisk();
3652 aDataset->WriteOnDisk( anRGB );
3653 aDataset->CloseOnDisk();
3655 // Pass SMESHDS_Group to MED writer
3656 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
3658 myWriter.AddGroup( aGrpDS );
3660 // write reference on a shape if exists
3661 SMESHDS_GroupOnGeom* aGeomGrp =
3662 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
3664 SALOMEDS::SObject_wrap mySubRef, myShape;
3665 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
3666 mySubRef->ReferencedObject( myShape.inout() ) &&
3667 !CORBA::is_nil( myShape->GetObject() ))
3669 string myRefOnObject = myShape->GetID();
3670 if ( myRefOnObject.length() > 0 ) {
3671 char aRefName[ 30 ];
3672 sprintf( aRefName, "Ref on shape %d", anId);
3673 aSize[ 0 ] = myRefOnObject.length() + 1;
3674 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
3675 aDataset->CreateOnDisk();
3676 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3677 aDataset->CloseOnDisk();
3680 else // shape ref is invalid:
3682 // save a group on geometry as ordinary group
3683 myWriter.AddGroup( aGeomGrp );
3686 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
3687 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
3689 std::string str = aFilterGrp_i->FilterToString();
3690 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
3691 aSize[ 0 ] = str.length() + 1;
3692 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
3693 aDataset->CreateOnDisk();
3694 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
3695 aDataset->CloseOnDisk();
3699 aGroup->CloseOnDisk();
3703 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
3705 // Flush current mesh information into MED file
3708 // save info on nb of elements
3709 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
3711 // maybe a shape was deleted in the study
3712 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
3713 TopoDS_Shape nullShape;
3714 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
3717 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
3722 aGroup = new HDFgroup( "Submeshes", aTopGroup );
3723 aGroup->CreateOnDisk();
3725 // each element belongs to one or none submesh,
3726 // so for each node/element, we store a submesh ID
3728 // Store submesh IDs
3729 for ( int isNode = 0; isNode < 2; ++isNode )
3731 SMDS_ElemIteratorPtr eIt =
3732 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
3733 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
3736 std::vector<int> smIDs; smIDs.reserve( nbElems );
3737 while ( eIt->more() )
3738 if ( const SMDS_MeshElement* e = eIt->next())
3739 smIDs.push_back( e->getshapeId() );
3741 aSize[ 0 ] = nbElems;
3742 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3743 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3744 aDataset->CreateOnDisk();
3745 aDataset->WriteOnDisk( & smIDs[0] );
3746 aDataset->CloseOnDisk();
3749 aGroup->CloseOnDisk();
3751 // Store node positions on sub-shapes (SMDS_Position):
3752 // ----------------------------------------------------
3754 aGroup = new HDFgroup( "Node Positions", aTopGroup );
3755 aGroup->CreateOnDisk();
3757 // in aGroup, create 5 datasets to contain:
3758 // "Nodes on Edges" - ID of node on edge
3759 // "Edge positions" - U parameter on node on edge
3760 // "Nodes on Faces" - ID of node on face
3761 // "Face U positions" - U parameter of node on face
3762 // "Face V positions" - V parameter of node on face
3764 // Find out nb of nodes on edges and faces
3765 // Collect corresponing sub-meshes
3766 int nbEdgeNodes = 0, nbFaceNodes = 0;
3767 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
3768 // loop on SMESHDS_SubMesh'es
3769 while ( smIt->more() )
3771 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
3772 if ( aSubMesh->IsComplexSubmesh() )
3773 continue; // submesh containing other submeshs
3774 int nbNodes = aSubMesh->NbNodes();
3775 if ( nbNodes == 0 ) continue;
3777 int aShapeID = aSubMesh->GetID();
3778 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
3780 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
3781 // write only SMDS_FacePosition and SMDS_EdgePosition
3782 switch ( aShapeType ) {
3784 nbFaceNodes += nbNodes;
3785 aFaceSM.push_back( aSubMesh );
3788 nbEdgeNodes += nbNodes;
3789 aEdgeSM.push_back( aSubMesh );
3795 // Treat positions on edges or faces
3796 for ( int onFace = 0; onFace < 2; onFace++ )
3798 // Create arrays to store in datasets
3799 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
3800 if (!nbNodes) continue;
3801 int* aNodeIDs = new int [ nbNodes ];
3802 double* aUPos = new double [ nbNodes ];
3803 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
3806 // loop on sub-meshes
3807 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
3808 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
3809 for ( ; itSM != pListSM->end(); itSM++ )
3811 SMESHDS_SubMesh* aSubMesh = (*itSM);
3813 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
3814 // loop on nodes in aSubMesh
3815 while ( itNode->more() )
3818 const SMDS_MeshNode* node = itNode->next();
3819 aNodeIDs [ iNode ] = node->GetID();
3822 const SMDS_PositionPtr pos = node->GetPosition();
3823 if ( onFace ) { // on FACE
3824 const SMDS_FacePosition* fPos =
3825 dynamic_cast<const SMDS_FacePosition*>( pos );
3827 aUPos[ iNode ] = fPos->GetUParameter();
3828 aVPos[ iNode ] = fPos->GetVParameter();
3835 const SMDS_EdgePosition* ePos =
3836 dynamic_cast<const SMDS_EdgePosition*>( pos );
3838 aUPos[ iNode ] = ePos->GetUParameter();
3844 } // loop on nodes in aSubMesh
3845 } // loop on sub-meshes
3850 aSize[ 0 ] = nbNodes;
3852 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
3853 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3854 aDataset->CreateOnDisk();
3855 aDataset->WriteOnDisk( aNodeIDs );
3856 aDataset->CloseOnDisk();
3859 aDSName = ( onFace ? "Face U positions" : "Edge positions");
3860 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
3861 aDataset->CreateOnDisk();
3862 aDataset->WriteOnDisk( aUPos );
3863 aDataset->CloseOnDisk();
3866 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
3867 aDataset->CreateOnDisk();
3868 aDataset->WriteOnDisk( aVPos );
3869 aDataset->CloseOnDisk();
3874 if ( aVPos ) delete [] aVPos;
3876 } // treat positions on edges or faces
3878 // close "Node Positions" group
3879 aGroup->CloseOnDisk();
3881 } // if ( there are submeshes in SMESHDS_Mesh )
3884 // close mesh HDF group
3885 aTopGroup->CloseOnDisk();
3893 aFile->CloseOnDisk();
3896 // Convert temporary files to stream
3897 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
3899 // Remove temporary files and directory
3901 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
3903 INFOS( "SMESH_Gen_i::Save() completed" );
3904 return aStreamFile._retn();
3907 //=============================================================================
3909 * SMESH_Gen_i::SaveASCII
3911 * Save SMESH module's data in ASCII format
3913 //=============================================================================
3915 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
3917 bool isMultiFile ) {
3918 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
3919 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
3920 return aStreamFile._retn();
3922 //after usual saving needs to encipher binary to text string
3923 //Any binary symbol will be represent as "|xx" () hexadecimal format number
3924 int size = aStreamFile.in().length();
3925 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
3926 for ( int i = 0; i < size; i++ )
3927 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
3929 buffer[size * 3] = '\0';
3931 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
3933 return anAsciiStreamFile._retn();
3936 //=============================================================================
3938 * SMESH_Gen_i::loadGeomData
3940 * Load GEOM module data
3942 //=============================================================================
3944 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
3946 if ( theCompRoot->_is_nil() )
3949 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
3950 if ( aStudy->_is_nil() )
3953 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
3954 aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
3957 //=============================================================================
3961 * Load SMESH module's data
3963 //=============================================================================
3965 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
3966 const SALOMEDS::TMPFile& theStream,
3970 INFOS( "SMESH_Gen_i::Load" );
3972 if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
3973 SetCurrentStudy( theComponent->GetStudy() );
3975 /* if( !theComponent->_is_nil() )
3977 //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
3978 if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
3979 loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
3982 StudyContext* myStudyContext = GetCurrentStudyContext();
3984 // Get temporary files location
3985 TCollection_AsciiString tmpDir =
3986 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
3988 INFOS( "THE URL++++++++++++++" );
3990 INFOS( "THE TMP PATH+++++++++" );
3993 // Convert the stream into sequence of files to process
3994 SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
3997 TCollection_AsciiString aStudyName( "" );
3998 if ( isMultiFile ) {
3999 CORBA::String_var url = myCurrentStudy->URL();
4000 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( url.in() ).c_str();
4002 // Set names of temporary files
4003 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
4004 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
4008 HDFdataset* aDataset;
4009 HDFgroup* aTopGroup;
4011 HDFgroup* aSubGroup;
4012 HDFgroup* aSubSubGroup;
4015 // ---> open HDF file
4016 aFile = new HDFfile( (char*) filename.ToCString() );
4018 aFile->OpenOnDisk( HDF_RDONLY );
4020 catch ( HDFexception ) {
4021 INFOS( "Load(): " << filename << " not found!" );
4025 TPythonDump pd; // prevent dump during loading
4027 // DriverMED_R_SMESHDS_Mesh myReader;
4028 // myReader.SetFile( meshfile.ToCString() );
4030 // For PAL13473 ("Repetitive mesh") implementation.
4031 // New dependencies between SMESH objects are established:
4032 // now hypotheses can refer to meshes, shapes and other hypotheses.
4033 // To keep data consistent, the following order of data restoration
4035 // 1. Create hypotheses
4036 // 2. Create all meshes
4037 // 3. Load hypotheses' data
4040 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
4041 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
4042 list< SMESH::Filter_var > filters;
4044 // get total number of top-level groups
4045 int aNbGroups = aFile->nInternalObjects();
4046 if ( aNbGroups > 0 ) {
4047 // --> in first turn we should read&create hypotheses
4048 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
4049 // open hypotheses root HDF group
4050 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4051 aTopGroup->OpenOnDisk();
4053 // get number of hypotheses
4054 int aNbObjects = aTopGroup->nInternalObjects();
4055 for ( int j = 0; j < aNbObjects; j++ ) {
4056 // try to identify hypothesis
4057 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4058 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4060 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
4061 // open hypothesis group
4062 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4063 aGroup->OpenOnDisk();
4065 // --> get hypothesis id
4066 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
4071 // get number of datasets
4072 int aNbSubObjects = aGroup->nInternalObjects();
4073 for ( int k = 0; k < aNbSubObjects; k++ ) {
4075 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4076 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4077 // --> get hypothesis name
4078 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4079 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4080 aDataset->OpenOnDisk();
4081 size = aDataset->GetSize();
4082 char* hypname_str = new char[ size ];
4083 aDataset->ReadFromDisk( hypname_str );
4084 hypname = string( hypname_str );
4085 delete [] hypname_str;
4086 aDataset->CloseOnDisk();
4088 // --> get hypothesis plugin library name
4089 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4090 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4091 aDataset->OpenOnDisk();
4092 size = aDataset->GetSize();
4093 char* libname_str = new char[ size ];
4094 aDataset->ReadFromDisk( libname_str );
4095 if(MYDEBUG) SCRUTE( libname_str );
4096 libname = string( libname_str );
4097 delete [] libname_str;
4098 aDataset->CloseOnDisk();
4100 // --> get hypothesis data
4101 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4102 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4103 aDataset->OpenOnDisk();
4104 size = aDataset->GetSize();
4105 char* hypdata_str = new char[ size ];
4106 aDataset->ReadFromDisk( hypdata_str );
4107 hypdata = string( hypdata_str );
4108 delete [] hypdata_str;
4109 aDataset->CloseOnDisk();
4112 // close hypothesis HDF group
4113 aGroup->CloseOnDisk();
4115 // --> restore hypothesis from data
4116 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4117 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
4118 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4119 SMESH::SMESH_Hypothesis_var myHyp;
4121 try { // protect persistence mechanism against exceptions
4122 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4125 INFOS( "Exception during hypothesis creation" );
4128 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4130 // myImpl->LoadFrom( hypdata.c_str() );
4131 hypDataList.push_back( make_pair( myImpl, hypdata ));
4132 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4133 int newId = myStudyContext->findId( iorString.in() );
4134 myStudyContext->mapOldToNew( id, newId );
4137 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4141 // close hypotheses root HDF group
4142 aTopGroup->CloseOnDisk();
4146 // --> then we should read&create algorithms
4147 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
4148 // open algorithms root HDF group
4149 aTopGroup = new HDFgroup( "Algorithms", aFile );
4150 aTopGroup->OpenOnDisk();
4152 // get number of algorithms
4153 int aNbObjects = aTopGroup->nInternalObjects();
4154 for ( int j = 0; j < aNbObjects; j++ ) {
4155 // try to identify algorithm
4156 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4157 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4159 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
4160 // open algorithm group
4161 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4162 aGroup->OpenOnDisk();
4164 // --> get algorithm id
4165 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
4170 // get number of datasets
4171 int aNbSubObjects = aGroup->nInternalObjects();
4172 for ( int k = 0; k < aNbSubObjects; k++ ) {
4174 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4175 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4176 // --> get algorithm name
4177 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4178 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4179 aDataset->OpenOnDisk();
4180 size = aDataset->GetSize();
4181 char* hypname_str = new char[ size ];
4182 aDataset->ReadFromDisk( hypname_str );
4183 hypname = string( hypname_str );
4184 delete [] hypname_str;
4185 aDataset->CloseOnDisk();
4187 // --> get algorithm plugin library name
4188 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4189 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4190 aDataset->OpenOnDisk();
4191 size = aDataset->GetSize();
4192 char* libname_str = new char[ size ];
4193 aDataset->ReadFromDisk( libname_str );
4194 if(MYDEBUG) SCRUTE( libname_str );
4195 libname = string( libname_str );
4196 delete [] libname_str;
4197 aDataset->CloseOnDisk();
4199 // --> get algorithm data
4200 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4201 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4202 aDataset->OpenOnDisk();
4203 size = aDataset->GetSize();
4204 char* hypdata_str = new char[ size ];
4205 aDataset->ReadFromDisk( hypdata_str );
4206 if(MYDEBUG) SCRUTE( hypdata_str );
4207 hypdata = string( hypdata_str );
4208 delete [] hypdata_str;
4209 aDataset->CloseOnDisk();
4212 // close algorithm HDF group
4213 aGroup->CloseOnDisk();
4215 // --> restore algorithm from data
4216 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4217 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
4218 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4219 SMESH::SMESH_Hypothesis_var myHyp;
4221 try { // protect persistence mechanism against exceptions
4222 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4225 INFOS( "Exception during hypothesis creation" );
4228 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4230 //myImpl->LoadFrom( hypdata.c_str() );
4231 hypDataList.push_back( make_pair( myImpl, hypdata ));
4232 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4233 int newId = myStudyContext->findId( iorString.in() );
4234 myStudyContext->mapOldToNew( id, newId );
4237 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4241 // close algorithms root HDF group
4242 aTopGroup->CloseOnDisk();
4246 // --> the rest groups should be meshes
4247 for ( int i = 0; i < aNbGroups; i++ ) {
4248 // identify next group
4249 char meshName[ HDF_NAME_MAX_LEN+1 ];
4250 aFile->InternalObjectIndentify( i, meshName );
4252 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
4254 int id = atoi( string( meshName ).substr( 4 ).c_str() );
4258 // open mesh HDF group
4259 aTopGroup = new HDFgroup( meshName, aFile );
4260 aTopGroup->OpenOnDisk();
4262 // get number of child HDF objects
4263 int aNbObjects = aTopGroup->nInternalObjects();
4264 if ( aNbObjects > 0 ) {
4266 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
4267 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
4268 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
4269 if ( !myNewMeshImpl )
4271 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
4273 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
4274 int newId = myStudyContext->findId( iorString.in() );
4275 myStudyContext->mapOldToNew( id, newId );
4278 // try to read and set auto color flag
4279 char aMeshAutoColorName[ 30 ];
4280 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
4281 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
4283 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
4284 aDataset->OpenOnDisk();
4285 size = aDataset->GetSize();
4286 int* anAutoColor = new int[ size ];
4287 aDataset->ReadFromDisk( anAutoColor );
4288 aDataset->CloseOnDisk();
4289 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
4290 delete [] anAutoColor;
4293 // try to read and set reference to shape
4294 GEOM::GEOM_Object_var aShapeObject;
4295 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
4296 // load mesh "Ref on shape" - it's an entry to SObject
4297 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
4298 aDataset->OpenOnDisk();
4299 size = aDataset->GetSize();
4300 char* refFromFile = new char[ size ];
4301 aDataset->ReadFromDisk( refFromFile );
4302 aDataset->CloseOnDisk();
4303 if ( strlen( refFromFile ) > 0 ) {
4304 SALOMEDS::SObject_wrap shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4306 // Make sure GEOM data are loaded first
4307 //loadGeomData( shapeSO->GetFatherComponent() );
4309 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4310 if ( !CORBA::is_nil( shapeObject ) ) {
4311 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4312 if ( !aShapeObject->_is_nil() )
4313 myNewMeshImpl->SetShape( aShapeObject );
4316 delete [] refFromFile;
4319 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
4320 if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
4322 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
4323 aDataset->OpenOnDisk();
4324 size = aDataset->GetSize();
4325 int* meshPersistentId = new int[ size ];
4326 aDataset->ReadFromDisk( meshPersistentId );
4327 aDataset->CloseOnDisk();
4328 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
4329 delete [] meshPersistentId;
4335 // As all object that can be referred by hypothesis are created,
4336 // we can restore hypothesis data
4338 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
4339 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4341 SMESH_Hypothesis_i* hyp = hyp_data->first;
4342 string & data = hyp_data->second;
4343 hyp->LoadFrom( data.c_str() );
4346 // Restore the rest mesh data
4348 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
4349 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4351 aTopGroup = meshi_group->second;
4352 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4353 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4354 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4356 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
4357 bool hasData = false;
4360 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
4361 int newId = myStudyContext->findId( iorString.in() );
4362 int id = myStudyContext->getOldId( newId );
4364 // try to find mesh data dataset
4365 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
4366 // load mesh "has data" flag
4367 aDataset = new HDFdataset( "Has data", aTopGroup );
4368 aDataset->OpenOnDisk();
4369 size = aDataset->GetSize();
4370 char* strHasData = new char[ size ];
4371 aDataset->ReadFromDisk( strHasData );
4372 aDataset->CloseOnDisk();
4373 if ( strcmp( strHasData, "1") == 0 ) {
4374 // read mesh data from MED file
4375 // myReader.SetMesh( mySMESHDSMesh );
4376 // myReader.SetMeshId( id );
4377 // myReader.Perform();
4380 delete [] strHasData;
4383 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
4384 // nodes and elements are not yet put into sub-meshes)
4385 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4386 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4387 aGroup->OpenOnDisk();
4388 // get number of applied algorithms
4389 int aNbSubObjects = aGroup->nInternalObjects();
4390 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
4391 for ( int j = 0; j < aNbSubObjects; j++ ) {
4392 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4393 aGroup->InternalObjectIndentify( j, name_dataset );
4394 // check if it is an algorithm
4395 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
4396 aDataset = new HDFdataset( name_dataset, aGroup );
4397 aDataset->OpenOnDisk();
4398 size = aDataset->GetSize();
4399 char* refFromFile = new char[ size ];
4400 aDataset->ReadFromDisk( refFromFile );
4401 aDataset->CloseOnDisk();
4402 // san - it is impossible to recover applied algorithms using their entries within Load() method
4403 //SALOMEDS::SObject_wrap hypSO = myCurrentStudy->FindObjectID( refFromFile );
4404 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4405 int id = atoi( refFromFile );
4406 delete [] refFromFile;
4407 string anIOR = myStudyContext->getIORbyOldId( id );
4408 if ( !anIOR.empty() ) {
4409 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4410 if ( !CORBA::is_nil( hypObject ) ) {
4411 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4412 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4413 || !myNewMeshImpl->HasShapeToMesh()) )
4414 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4419 aGroup->CloseOnDisk();
4422 // try to get applied hypotheses
4423 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4424 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4425 aGroup->OpenOnDisk();
4426 // get number of applied hypotheses
4427 int aNbSubObjects = aGroup->nInternalObjects();
4428 for ( int j = 0; j < aNbSubObjects; j++ ) {
4429 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4430 aGroup->InternalObjectIndentify( j, name_dataset );
4431 // check if it is a hypothesis
4432 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4433 aDataset = new HDFdataset( name_dataset, aGroup );
4434 aDataset->OpenOnDisk();
4435 size = aDataset->GetSize();
4436 char* refFromFile = new char[ size ];
4437 aDataset->ReadFromDisk( refFromFile );
4438 aDataset->CloseOnDisk();
4439 // san - it is impossible to recover applied hypotheses using their entries within Load() method
4440 //SALOMEDS::SObject_wrap hypSO = myCurrentStudy->FindObjectID( refFromFile );
4441 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4442 int id = atoi( refFromFile );
4443 delete [] refFromFile;
4444 string anIOR = myStudyContext->getIORbyOldId( id );
4445 if ( !anIOR.empty() ) {
4446 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4447 if ( !CORBA::is_nil( hypObject ) ) {
4448 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4449 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4450 || !myNewMeshImpl->HasShapeToMesh()) )
4451 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4456 aGroup->CloseOnDisk();
4459 // --> try to find SUB-MESHES containers for each type of submesh
4460 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
4461 const char* name_meshgroup;
4462 if ( j == GetSubMeshOnVertexTag() )
4463 name_meshgroup = "SubMeshes On Vertex";
4464 else if ( j == GetSubMeshOnEdgeTag() )
4465 name_meshgroup = "SubMeshes On Edge";
4466 else if ( j == GetSubMeshOnWireTag() )
4467 name_meshgroup = "SubMeshes On Wire";
4468 else if ( j == GetSubMeshOnFaceTag() )
4469 name_meshgroup = "SubMeshes On Face";
4470 else if ( j == GetSubMeshOnShellTag() )
4471 name_meshgroup = "SubMeshes On Shell";
4472 else if ( j == GetSubMeshOnSolidTag() )
4473 name_meshgroup = "SubMeshes On Solid";
4474 else if ( j == GetSubMeshOnCompoundTag() )
4475 name_meshgroup = "SubMeshes On Compound";
4477 // try to get submeshes container HDF group
4478 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
4479 // open submeshes containers HDF group
4480 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4481 aGroup->OpenOnDisk();
4483 // get number of submeshes
4484 int aNbSubMeshes = aGroup->nInternalObjects();
4485 for ( int k = 0; k < aNbSubMeshes; k++ ) {
4487 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
4488 aGroup->InternalObjectIndentify( k, name_submeshgroup );
4489 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
4490 // --> get submesh id
4491 int subid = atoi( name_submeshgroup + 7 );
4494 // open submesh HDF group
4495 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
4496 aSubGroup->OpenOnDisk();
4498 // try to read and set reference to subshape
4499 GEOM::GEOM_Object_var aSubShapeObject;
4500 SMESH::SMESH_subMesh_var aSubMesh;
4502 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
4503 // load submesh "Ref on shape" - it's an entry to SObject
4504 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
4505 aDataset->OpenOnDisk();
4506 size = aDataset->GetSize();
4507 char* refFromFile = new char[ size ];
4508 aDataset->ReadFromDisk( refFromFile );
4509 aDataset->CloseOnDisk();
4510 if ( strlen( refFromFile ) > 0 ) {
4511 SALOMEDS::SObject_wrap subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
4512 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
4513 if ( !CORBA::is_nil( subShapeObject ) ) {
4514 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
4515 if ( !aSubShapeObject->_is_nil() )
4516 aSubMesh = SMESH::SMESH_subMesh::_duplicate
4517 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
4518 if ( aSubMesh->_is_nil() )
4520 string iorSubString = GetORB()->object_to_string( aSubMesh );
4521 int newSubId = myStudyContext->findId( iorSubString );
4522 myStudyContext->mapOldToNew( subid, newSubId );
4527 if ( aSubMesh->_is_nil() )
4530 // try to get applied algorithms
4531 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4532 // open "applied algorithms" HDF group
4533 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4534 aSubSubGroup->OpenOnDisk();
4535 // get number of applied algorithms
4536 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4537 for ( int l = 0; l < aNbSubObjects; l++ ) {
4538 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4539 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4540 // check if it is an algorithm
4541 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
4542 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4543 aDataset->OpenOnDisk();
4544 size = aDataset->GetSize();
4545 char* refFromFile = new char[ size ];
4546 aDataset->ReadFromDisk( refFromFile );
4547 aDataset->CloseOnDisk();
4549 int id = atoi( refFromFile );
4550 string anIOR = myStudyContext->getIORbyOldId( id );
4551 if ( !anIOR.empty() ) {
4552 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4553 if ( !CORBA::is_nil( hypObject ) ) {
4554 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4555 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4556 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4561 // close "applied algorithms" HDF group
4562 aSubSubGroup->CloseOnDisk();
4565 // try to get applied hypotheses
4566 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4567 // open "applied hypotheses" HDF group
4568 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4569 aSubSubGroup->OpenOnDisk();
4570 // get number of applied hypotheses
4571 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4572 for ( int l = 0; l < aNbSubObjects; l++ ) {
4573 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4574 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4575 // check if it is a hypothesis
4576 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4577 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4578 aDataset->OpenOnDisk();
4579 size = aDataset->GetSize();
4580 char* refFromFile = new char[ size ];
4581 aDataset->ReadFromDisk( refFromFile );
4582 aDataset->CloseOnDisk();
4584 int id = atoi( refFromFile );
4585 string anIOR = myStudyContext->getIORbyOldId( id );
4586 if ( !anIOR.empty() ) {
4587 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4588 if ( !CORBA::is_nil( hypObject ) ) {
4589 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4590 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4591 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4596 // close "APPLIED HYPOTHESES" hdf group
4597 aSubSubGroup->CloseOnDisk();
4600 // close SUB-MESH hdf group
4601 aSubGroup->CloseOnDisk();
4604 // close SUB-MESHES containers hdf group
4605 aGroup->CloseOnDisk();
4609 // try to get GROUPS
4610 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
4611 char name_group[ 30 ];
4612 if ( ii == GetNodeGroupsTag() )
4613 strcpy( name_group, "Groups of Nodes" );
4614 else if ( ii == GetEdgeGroupsTag() )
4615 strcpy( name_group, "Groups of Edges" );
4616 else if ( ii == GetFaceGroupsTag() )
4617 strcpy( name_group, "Groups of Faces" );
4618 else if ( ii == GetVolumeGroupsTag() )
4619 strcpy( name_group, "Groups of Volumes" );
4620 else if ( ii == Get0DElementsGroupsTag() )
4621 strcpy( name_group, "Groups of 0D Elements" );
4622 else if ( ii == GetBallElementsGroupsTag() )
4623 strcpy( name_group, "Groups of Balls" );
4625 if ( aTopGroup->ExistInternalObject( name_group ) ) {
4626 aGroup = new HDFgroup( name_group, aTopGroup );
4627 aGroup->OpenOnDisk();
4628 // get number of groups
4629 int aNbSubObjects = aGroup->nInternalObjects();
4630 for ( int j = 0; j < aNbSubObjects; j++ ) {
4631 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4632 aGroup->InternalObjectIndentify( j, name_dataset );
4633 // check if it is an group
4634 if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
4636 int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
4639 aDataset = new HDFdataset( name_dataset, aGroup );
4640 aDataset->OpenOnDisk();
4642 // Retrieve actual group name
4643 size = aDataset->GetSize();
4644 char* nameFromFile = new char[ size ];
4645 aDataset->ReadFromDisk( nameFromFile );
4646 aDataset->CloseOnDisk();
4648 // Try to find a shape reference
4649 TopoDS_Shape aShape;
4650 char aRefName[ 30 ];
4651 sprintf( aRefName, "Ref on shape %d", subid);
4652 if ( aGroup->ExistInternalObject( aRefName ) ) {
4653 // load mesh "Ref on shape" - it's an entry to SObject
4654 aDataset = new HDFdataset( aRefName, aGroup );
4655 aDataset->OpenOnDisk();
4656 size = aDataset->GetSize();
4657 char* refFromFile = new char[ size ];
4658 aDataset->ReadFromDisk( refFromFile );
4659 aDataset->CloseOnDisk();
4660 if ( strlen( refFromFile ) > 0 ) {
4661 SALOMEDS::SObject_wrap shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4662 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4663 if ( !CORBA::is_nil( shapeObject ) ) {
4664 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4665 if ( !aShapeObject->_is_nil() )
4666 aShape = GeomObjectToShape( aShapeObject );
4670 // Try to read a filter of SMESH_GroupOnFilter
4671 SMESH::Filter_var filter;
4672 SMESH_PredicatePtr predicate;
4673 std::string hdfGrpName = "Filter " + SMESH_Comment(subid);
4674 if ( aGroup->ExistInternalObject( hdfGrpName.c_str() ))
4676 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
4677 aDataset->OpenOnDisk();
4678 size = aDataset->GetSize();
4679 char* persistStr = new char[ size ];
4680 aDataset->ReadFromDisk( persistStr );
4681 aDataset->CloseOnDisk();
4682 if ( strlen( persistStr ) > 0 ) {
4683 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
4684 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
4685 filters.push_back( filter );
4689 // Create group servant
4690 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
4691 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
4692 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape, predicate ) );
4693 // Obtain a SMESHDS_Group object
4694 if ( aNewGroup->_is_nil() )
4697 string iorSubString = GetORB()->object_to_string( aNewGroup );
4698 int newSubId = myStudyContext->findId( iorSubString );
4699 myStudyContext->mapOldToNew( subid, newSubId );
4701 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
4705 if ( SMESH_GroupOnFilter_i* aFilterGroup =
4706 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
4708 aFilterGroup->SetFilter( filter );
4709 filter->UnRegister();
4711 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
4712 if ( !aGroupBaseDS )
4715 aGroupBaseDS->SetStoreName( name_dataset );
4718 // Read color of the group
4719 char aGroupColorName[ 30 ];
4720 sprintf( aGroupColorName, "ColorGroup %d", subid);
4721 if ( aGroup->ExistInternalObject( aGroupColorName ) )
4723 aDataset = new HDFdataset( aGroupColorName, aGroup );
4724 aDataset->OpenOnDisk();
4725 size = aDataset->GetSize();
4726 double* anRGB = new double[ size ];
4727 aDataset->ReadFromDisk( anRGB );
4728 aDataset->CloseOnDisk();
4729 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
4730 aGroupBaseDS->SetColor( aColor );
4734 aGroup->CloseOnDisk();
4738 // instead of reading mesh data, we read only brief information of all
4739 // objects: mesh, groups, sub-meshes (issue 0021208 )
4742 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, id,
4743 meshfile.ToCString(), filename.ToCString(),
4747 // read Sub-Mesh ORDER if any
4748 if( aTopGroup->ExistInternalObject( "Mesh Order" ) ) {
4749 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
4750 aDataset->OpenOnDisk();
4751 size = aDataset->GetSize();
4752 int* smIDs = new int[ size ];
4753 aDataset->ReadFromDisk( smIDs );
4754 aDataset->CloseOnDisk();
4755 TListOfListOfInt anOrderIds;
4756 anOrderIds.push_back( TListOfInt() );
4757 for ( int i = 0; i < size; i++ )
4758 if ( smIDs[ i ] < 0 ) // is separator
4759 anOrderIds.push_back( TListOfInt() );
4761 anOrderIds.back().push_back(smIDs[ i ]);
4763 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
4767 // update hyps needing full mesh data restored (issue 20918)
4768 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4770 SMESH_Hypothesis_i* hyp = hyp_data->first;
4771 hyp->UpdateAsMeshesRestored();
4774 // notify algos on completed restoration to set sub-mesh event listeners
4775 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4777 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4778 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4780 TopoDS_Shape myLocShape;
4781 if(myLocMesh.HasShapeToMesh())
4782 myLocShape = myLocMesh.GetShapeToMesh();
4784 myLocShape = SMESH_Mesh::PseudoShape();
4786 myLocMesh.GetSubMesh(myLocShape)->
4787 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
4790 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
4791 list< SMESH::Filter_var >::iterator f = filters.begin();
4792 for ( ; f != filters.end(); ++f )
4793 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
4794 fi->FindBaseObjects();
4799 aTopGroup->CloseOnDisk();
4802 aFile->CloseOnDisk();
4805 // Remove temporary files created from the stream
4808 SMESH_File meshFile( meshfile.ToCString() );
4809 if ( !meshFile ) // no meshfile exists
4811 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
4815 Engines::Container_var container = GetContainerRef();
4816 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
4818 container_i->registerTemporaryFile( filename.ToCString() );
4819 container_i->registerTemporaryFile( meshfile.ToCString() );
4820 container_i->registerTemporaryFile( tmpDir.ToCString() );
4824 pd << ""; // prevent optimizing pd out
4826 // creation of tree nodes for all data objects in the study
4827 // to support tree representation customization and drag-n-drop:
4828 SALOMEDS::Study_var study = theComponent->GetStudy();
4829 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = study->GetUseCaseBuilder();
4830 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
4831 useCaseBuilder->SetRootCurrent();
4832 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
4833 SALOMEDS::ChildIterator_wrap it = study->NewChildIterator( theComponent );
4834 for (it->InitEx(true); it->More(); it->Next()) {
4835 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
4839 INFOS( "SMESH_Gen_i::Load completed" );
4843 //=============================================================================
4845 * SMESH_Gen_i::LoadASCII
4847 * Load SMESH module's data in ASCII format
4849 //=============================================================================
4851 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
4852 const SALOMEDS::TMPFile& theStream,
4854 bool isMultiFile ) {
4855 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
4856 return Load( theComponent, theStream, theURL, isMultiFile );
4858 //before call main ::Load method it's need for decipher text format to
4859 //binary ( "|xx" => x' )
4860 int size = theStream.length();
4861 if ( int((size / 3 )*3) != size ) //error size of buffer
4864 int real_size = int(size / 3);
4866 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
4870 for ( int i = 0; i < real_size; i++ )
4872 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
4873 sscanf( tmp, "%x", &c );
4874 sprintf( (char*)&(buffer[i]), "%c", (char)c );
4877 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
4879 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
4882 //=============================================================================
4884 * SMESH_Gen_i::Close
4886 * Clears study-connected data when it is closed
4888 //=============================================================================
4890 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
4892 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
4894 // set correct current study
4895 SALOMEDS::Study_var study = theComponent->GetStudy();
4896 if ( study->StudyId() != GetCurrentStudyID())
4897 setCurrentStudy( study, /*IsBeingClosed=*/true );
4899 // Clear study contexts data
4900 int studyId = GetCurrentStudyID();
4901 if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
4902 delete myStudyContextMap[ studyId ];
4903 myStudyContextMap.erase( studyId );
4906 // remove the tmp files meshes are loaded from
4907 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
4909 myCurrentStudy = SALOMEDS::Study::_nil();
4913 //=============================================================================
4915 * SMESH_Gen_i::ComponentDataType
4917 * Get component data type
4919 //=============================================================================
4921 char* SMESH_Gen_i::ComponentDataType()
4923 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
4924 return CORBA::string_dup( "SMESH" );
4928 //=============================================================================
4930 * SMESH_Gen_i::IORToLocalPersistentID
4932 * Transform data from transient form to persistent
4934 //=============================================================================
4936 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
4937 const char* IORString,
4938 CORBA::Boolean /*isMultiFile*/,
4939 CORBA::Boolean /*isASCII*/ )
4941 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
4942 StudyContext* myStudyContext = GetCurrentStudyContext();
4944 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
4945 int anId = myStudyContext->findId( IORString );
4947 if(MYDEBUG) MESSAGE( "VSR " << anId )
4949 sprintf( strId, "%d", anId );
4950 return CORBA::string_dup( strId );
4953 return CORBA::string_dup( "" );
4956 //=============================================================================
4958 * SMESH_Gen_i::LocalPersistentIDToIOR
4960 * Transform data from persistent form to transient
4962 //=============================================================================
4964 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
4965 const char* aLocalPersistentID,
4966 CORBA::Boolean /*isMultiFile*/,
4967 CORBA::Boolean /*isASCII*/ )
4969 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
4970 StudyContext* myStudyContext = GetCurrentStudyContext();
4972 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
4973 int anId = atoi( aLocalPersistentID );
4974 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
4976 return CORBA::string_dup( "" );
4979 //=======================================================================
4980 //function : RegisterObject
4982 //=======================================================================
4984 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
4986 StudyContext* myStudyContext = GetCurrentStudyContext();
4987 if ( myStudyContext && !CORBA::is_nil( theObject )) {
4988 if (GetCurrentStudyID() == myImportedStudyId)
4989 myImportedStudyChanged = true;
4990 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
4991 return myStudyContext->addObject( string( iorString.in() ) );
4996 //================================================================================
4998 * \brief Return id of registered object
4999 * \param theObject - the Object
5000 * \retval int - Object id
5002 //================================================================================
5004 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
5006 StudyContext* myStudyContext = GetCurrentStudyContext();
5007 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5008 string iorString = GetORB()->object_to_string( theObject );
5009 return myStudyContext->findId( iorString );
5014 //=============================================================================
5016 * SMESH_Gen_i::SetName
5018 * Set a new object name
5020 //=============================================================================
5021 void SMESH_Gen_i::SetName(const char* theIOR,
5022 const char* theName)
5024 if ( theIOR && strcmp( theIOR, "" ) ) {
5025 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
5026 SALOMEDS::SObject_wrap aSO = ObjectToSObject( myCurrentStudy, anObject );
5027 if ( !aSO->_is_nil() ) {
5028 SetName( aSO, theName );
5033 int SMESH_Gen_i::GetCurrentStudyID()
5035 return myCurrentStudy->_is_nil() || myCurrentStudy->_non_existent() ? -1 : myCurrentStudy->StudyId();
5038 // Version information
5039 char* SMESH_Gen_i::getVersion()
5041 #if SMESH_DEVELOPMENT
5042 return CORBA::string_dup(SMESH_VERSION_STR"dev");
5044 return CORBA::string_dup(SMESH_VERSION_STR);
5048 //=================================================================================
5049 // function : Move()
5050 // purpose : Moves objects to the specified position.
5051 // Is used in the drag-n-drop functionality.
5052 //=================================================================================
5053 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
5054 SALOMEDS::SObject_ptr where,
5057 if ( CORBA::is_nil( where ) ) return;
5059 SALOMEDS::Study_var study = where->GetStudy();
5060 SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder();
5061 SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder();
5062 SALOMEDS::SComponent_var father = where->GetFatherComponent();
5063 std::string dataType = father->ComponentDataType();
5064 if ( dataType != "SMESH" ) return; // not a SMESH component
5066 SALOMEDS::SObject_var objAfter;
5067 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
5068 // insert at given row -> find insertion position
5069 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
5071 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
5072 if ( i == row && useCaseIt->More() ) {
5073 objAfter = useCaseIt->Value();
5077 for ( int i = 0; i < what.length(); i++ ) {
5078 SALOMEDS::SObject_var sobj = what[i];
5079 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
5080 // insert the object to the use case tree
5081 if ( !CORBA::is_nil( objAfter ) )
5082 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
5084 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
5087 //================================================================================
5089 * \brief Returns true if algorithm can be used to mesh a given geometry
5090 * \param [in] theAlgoType - the algorithm type
5091 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
5092 * \param [in] theGeomObject - the geometry to mesh
5093 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
5094 * else, returns \c True if at least one shape is meshable
5095 * \return CORBA::Boolean - can or can't
5097 //================================================================================
5099 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
5100 const char* theLibName,
5101 GEOM::GEOM_Object_ptr theGeomObject,
5102 CORBA::Boolean toCheckAll)
5106 std::string aPlatformLibName;
5107 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
5108 GenericHypothesisCreator_i* aCreator =
5109 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
5112 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
5113 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll );
5120 SMESH_CATCH( SMESH::doNothing );
5123 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
5128 //=================================================================================
5129 // function : importData
5130 // purpose : imports mesh data file (the med one) into the SMESH internal data structure
5131 //=================================================================================
5132 Engines::ListOfIdentifiers* SMESH_Gen_i::importData(CORBA::Long studyId,
5133 Engines::DataContainer_ptr data,
5134 const Engines::ListOfOptions& options)
5136 Engines::ListOfIdentifiers_var aResultIds = new Engines::ListOfIdentifiers;
5137 list<string> aResultList;
5139 CORBA::Object_var aSMObject = myNS->Resolve( "/myStudyManager" );
5140 SALOMEDS::StudyManager_var aStudyManager = SALOMEDS::StudyManager::_narrow( aSMObject );
5141 SALOMEDS::Study_var aStudy = aStudyManager->GetStudyByID( studyId );
5142 SetCurrentStudy(aStudy);
5144 // load and store temporary imported file
5145 string aFileName = Kernel_Utils::GetTmpFileName();
5146 aFileName += string(".") + data->extension();
5147 Engines::TMPFile* aFileStream = data->get();
5148 const char *aBuffer = (const char*)aFileStream->NP_data();
5150 std::ofstream aFile(aFileName.c_str(), std::ios::binary);
5152 std::ofstream aFile(aFileName.c_str());
5154 aFile.write(aBuffer, aFileStream->length());
5157 // Retrieve mesh names from the file
5158 DriverMED_R_SMESHDS_Mesh aReader;
5159 aReader.SetFile( aFileName );
5160 aReader.SetMeshId(-1);
5161 Driver_Mesh::Status aStatus;
5162 list<string> aNames = aReader.GetMeshNames(aStatus);
5163 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
5164 SMESH::DriverMED_ReadStatus aStatus2 = (SMESH::DriverMED_ReadStatus)aStatus;
5165 if (aStatus2 == SMESH::DRS_OK) {
5166 // Iterate through all meshes and create mesh objects
5167 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ ) {
5169 SMESH::SMESH_Mesh_var mesh = createMesh();
5171 // publish mesh in the study
5172 SALOMEDS::SObject_var aSO;
5173 if (CanPublishInStudy(mesh)) {
5174 aSO = PublishMesh(aStudy, mesh.in(), (*it).c_str());
5175 aResultList.push_back(aSO->GetID());
5177 // Read mesh data (groups are published automatically by ImportMEDFile())
5178 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
5179 ASSERT( meshServant );
5180 meshServant->ImportMEDFile( aFileName.c_str(), (*it).c_str() );
5181 //meshServant->GetImpl().GetMeshDS()->Modified();
5184 MESSAGE("Opening MED file problems "<<aFileName.c_str())
5185 return aResultIds._retn();
5188 // remove temporary file
5190 DeleteFileA(aFileName.c_str());
5192 unlink(aFileName.c_str());
5195 if (!aResultList.empty()) {
5196 aResultIds->length(aResultList.size());
5197 list<string>::iterator aListIter = aResultList.begin();
5198 for(int a = 0; aListIter != aResultList.end(); aListIter++, a++)
5199 aResultIds[a] = aListIter->c_str();
5202 myImportedStudyId = studyId;
5203 myImportedStudyChanged = false;
5205 return aResultIds._retn();
5208 //=================================================================================
5209 // function : getModifiedData
5210 // purpose : exports all geometry of this GEOM module into one BRep file
5211 //=================================================================================
5212 Engines::ListOfData* SMESH_Gen_i::getModifiedData(CORBA::Long studyId)
5214 Engines::ListOfData_var aResult = new Engines::ListOfData;
5216 if (!myImportedStudyChanged) {
5217 INFOS("SMESH module data was not changed")
5218 return aResult._retn();
5221 CORBA::Object_var aSMObject = myNS->Resolve("/myStudyManager");
5222 SALOMEDS::StudyManager_var aStudyManager = SALOMEDS::StudyManager::_narrow(aSMObject);
5223 SALOMEDS::Study_var aStudy = aStudyManager->GetStudyByID(studyId);
5224 SetCurrentStudy(aStudy);
5225 SALOMEDS::SComponent_var aComponent = aStudy->FindComponent("SMESH");
5227 if (CORBA::is_nil(aComponent))
5228 return aResult._retn();
5230 std::string aFullPath(Kernel_Utils::GetTmpFileName());
5231 aFullPath += ".med";
5232 StudyContext* myStudyContext = GetCurrentStudyContext();
5234 SALOMEDS::ChildIterator_var anIter = aStudy->NewChildIterator(aComponent); // check only published meshes
5235 int aNumMeshes = 0; // number of meshes in result
5236 for(; anIter->More(); anIter->Next()) {
5237 SALOMEDS::SObject_var aSO = anIter->Value();
5238 CORBA::Object_var anObj = aSO->GetObject();
5239 if (!CORBA::is_nil(anObj)) {
5240 SMESH::SMESH_Mesh_var aCORBAMesh = SMESH::SMESH_Mesh::_narrow(anObj);
5241 if(!aCORBAMesh->_is_nil()) {
5242 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>(GetServant(aCORBAMesh).in());
5245 SMESH_Mesh& aMesh = myImpl->GetImpl();
5246 CORBA::String_var objName = aSO->GetName();
5247 aMesh.ExportMED(aFullPath.c_str(), objName.in(), false, MED::eV2_2, 0);
5253 if (aNumMeshes > 0) { // prepare a container to store files
5254 INFOS("Write "<<aNumMeshes<<" meshes to "<<aFullPath.c_str());
5256 Engines::DataContainer_var aData = (new Engines_DataContainer_i(
5257 aFullPath.c_str(), "", "", true))->_this();
5260 return aResult._retn();
5263 //=============================================================================
5265 * SMESHEngine_factory
5267 * C factory, accessible with dlsym, after dlopen
5269 //=============================================================================
5273 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
5274 PortableServer::POA_ptr poa,
5275 PortableServer::ObjectId* contId,
5276 const char* instanceName,
5277 const char* interfaceName )
5279 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
5280 if(MYDEBUG) SCRUTE(interfaceName);
5281 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
5282 return aSMESHGen->getId() ;