1 // Copyright (C) 2007-2016 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
26 #include <BRepPrimAPI_MakeBox.hxx>
27 #include <BRepPrimAPI_MakeCylinder.hxx>
28 #include <BRepPrimAPI_MakeSphere.hxx>
29 #include <BRep_Tool.hxx>
31 #include <TColStd_MapOfAsciiString.hxx>
32 #include <TCollection_AsciiString.hxx>
34 #include <TopExp_Explorer.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopTools_ListIteratorOfListOfShape.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <TopTools_MapOfShape.hxx>
40 #include <TopoDS_CompSolid.hxx>
41 #include <TopoDS_Compound.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS_Face.hxx>
44 #include <TopoDS_Iterator.hxx>
45 #include <TopoDS_Shape.hxx>
46 #include <TopoDS_Shell.hxx>
47 #include <TopoDS_Solid.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopoDS_Wire.hxx>
58 #include <libgen.h> // for basename function
62 #define LibHandle HMODULE
63 #define LoadLib( name ) LoadLibrary( name )
64 #define GetProc GetProcAddress
65 #define UnLoadLib( handle ) FreeLibrary( handle );
67 #define LibHandle void*
69 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
70 #else // DYNLOAD_LOCAL
71 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
72 #endif // DYNLOAD_LOCAL
74 #define UnLoadLib( handle ) dlclose( handle );
77 #include "SMESH_Gen_i.hxx"
78 #include "SMESH_version.h"
80 #include "DriverMED_W_SMESHDS_Mesh.h"
81 #include "DriverMED_R_SMESHDS_Mesh.h"
83 #include "DriverCGNS_Read.hxx"
85 #include "MED_Factory.hxx"
86 #include "SMDS_EdgePosition.hxx"
87 #include "SMDS_FacePosition.hxx"
88 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
89 #include "SMDS_SetIterator.hxx"
90 #include "SMDS_SpacePosition.hxx"
91 #include "SMDS_VertexPosition.hxx"
92 #include "SMESHDS_Document.hxx"
93 #include "SMESHDS_Group.hxx"
94 #include "SMESHDS_GroupOnGeom.hxx"
95 #include "SMESH_Algo_i.hxx"
96 #include "SMESH_File.hxx"
97 #include "SMESH_Group.hxx"
98 #include "SMESH_Group_i.hxx"
99 #include "SMESH_Hypothesis.hxx"
100 #include "SMESH_Hypothesis_i.hxx"
101 #include "SMESH_Mesh.hxx"
102 #include "SMESH_MeshEditor.hxx"
103 #include "SMESH_Mesh_i.hxx"
104 #include "SMESH_PreMeshInfo.hxx"
105 #include "SMESH_PythonDump.hxx"
106 #include "SMESH_ControlsDef.hxx"
107 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
109 #include CORBA_SERVER_HEADER(SMESH_Group)
110 #include CORBA_SERVER_HEADER(SMESH_Filter)
111 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
114 #include <GEOM_Client.hxx>
116 #include <Basics_Utils.hxx>
117 #include <Basics_DirUtils.hxx>
119 #include <OpUtil.hxx>
120 #include <SALOMEDS_Tool.hxx>
121 #include <SALOME_Container_i.hxx>
122 #include <SALOME_LifeCycleCORBA.hxx>
123 #include <SALOME_NamingService.hxx>
124 #include <Utils_CorbaException.hxx>
125 #include <Utils_ExceptHandlers.hxx>
126 #include <Utils_SINGLETON.hxx>
127 #include <utilities.h>
129 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
130 #include CORBA_CLIENT_HEADER(SALOME_Session)
132 // helpers about SALOME::GenericObj
133 #include <SALOMEDS_wrap.hxx>
134 #include <SALOMEDS_Attributes_wrap.hxx>
135 #include <GEOM_wrap.hxx>
143 using SMESH::TPythonDump;
146 #define NUM_TMP_FILES 2
149 static int MYDEBUG = 0;
151 static int MYDEBUG = 0;
154 // Static variables definition
155 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
156 CORBA::ORB_var SMESH_Gen_i::myOrb;
157 PortableServer::POA_var SMESH_Gen_i::myPoa;
158 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
159 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
160 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
163 const int nbElemPerDiagonal = 10;
165 //=============================================================================
167 * GetServant [ static ]
169 * Get servant of the CORBA object
171 //=============================================================================
173 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
175 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
178 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
182 INFOS( "GetServant - Unknown exception was caught!!!" );
187 //=============================================================================
189 * SObjectToObject [ static ]
191 * Get CORBA object corresponding to the SALOMEDS::SObject
193 //=============================================================================
195 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
197 SALOMEDS::GenericAttribute_wrap anAttr;
198 CORBA::Object_var anObj;
199 if ( !theSObject->_is_nil() ) {
201 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
202 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
203 CORBA::String_var aValue = anIOR->Value();
204 if( strcmp( aValue, "" ) != 0 )
205 anObj = GetORB()->string_to_object( aValue );
209 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
215 //=============================================================================
219 * Get SALOME_NamingService object
221 //=============================================================================
223 SALOME_NamingService* SMESH_Gen_i::GetNS()
225 if ( myNS == NULL ) {
226 myNS = SINGLETON_<SALOME_NamingService>::Instance();
227 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
228 myNS->init_orb( GetORB() );
233 //=============================================================================
237 * Get SALOME_LifeCycleCORBA object
239 //=============================================================================
240 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC() {
241 if ( myLCC == NULL ) {
242 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
248 //=============================================================================
250 * GetGeomEngine [ static ]
252 * Get GEOM::GEOM_Gen reference
254 //=============================================================================
255 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine() {
256 //CCRT GEOM::GEOM_Gen_var aGeomEngine =
257 //CCRT GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
258 //CCRT return aGeomEngine._retn();
259 if(CORBA::is_nil(myGeomGen))
261 Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
262 myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
267 //=============================================================================
269 * SMESH_Gen_i::SMESH_Gen_i
271 * Default constructor: not for use
273 //=============================================================================
275 SMESH_Gen_i::SMESH_Gen_i()
279 //=============================================================================
281 * SMESH_Gen_i::SMESH_Gen_i
283 * Standard constructor, used with Container
285 //=============================================================================
287 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
288 PortableServer::POA_ptr poa,
289 PortableServer::ObjectId* contId,
290 const char* instanceName,
291 const char* interfaceName )
292 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
295 myOrb = CORBA::ORB::_duplicate(orb);
296 myPoa = PortableServer::POA::_duplicate(poa);
299 _id = myPoa->activate_object( _thisObj );
301 myIsEmbeddedMode = false;
302 myShapeReader = NULL; // shape reader
304 myIsHistoricalPythonDump = true;
305 myToForgetMeshDataOnHypModif = false;
307 // set it in standalone mode only
308 //OSD::SetSignal( true );
310 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
311 // find out mode (embedded or standalone) here else
312 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
313 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
314 if ( SALOME_NamingService* ns = GetNS() )
316 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
317 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
318 if ( !session->_is_nil() )
320 CORBA::String_var str_host = session->getHostname();
321 CORBA::Long s_pid = session->getPID();
322 string my_host = Kernel_Utils::GetHostname();
324 long my_pid = (long)_getpid();
326 long my_pid = (long) getpid();
328 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
333 //=============================================================================
335 * SMESH_Gen_i::~SMESH_Gen_i
339 //=============================================================================
341 SMESH_Gen_i::~SMESH_Gen_i()
343 // delete hypothesis creators
344 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
345 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
347 // same creator can be mapped under different names
348 GenericHypothesisCreator_i* creator = (*itHyp).second;
352 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
353 if ( creator == (*itHyp2).second )
354 (*itHyp2).second = 0;
356 myHypCreatorMap.clear();
358 // Clear study contexts data
359 map<int, StudyContext*>::iterator it;
360 for ( it = myStudyContextMap.begin(); it != myStudyContextMap.end(); ++it ) {
363 myStudyContextMap.clear();
364 // delete shape reader
366 delete myShapeReader;
368 //=============================================================================
370 * SMESH_Gen_i::getHypothesisCreator
372 * Get hypothesis creator
374 //=============================================================================
375 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
376 const char* theLibName,
377 std::string& thePlatformLibName)
378 throw (SALOME::SALOME_Exception)
380 std::string aPlatformLibName;
381 /* It's Need to translate lib name for WIN32 or X platform */
382 if ( theLibName && theLibName[0] != '\0' )
384 int libNameLen = strlen(theLibName);
385 //check for old format "libXXXXXXX.so"
386 if (libNameLen > 7 &&
387 !strncmp( theLibName, "lib", 3 ) &&
388 !strcmp( theLibName+libNameLen-3, ".so" ))
392 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
393 #elif defined(__APPLE__)
394 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
396 aPlatformLibName = theLibName;
401 //try to use new format
403 aPlatformLibName = theLibName;
404 aPlatformLibName += ".dll";
405 #elif defined(__APPLE__)
406 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
408 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
412 thePlatformLibName = aPlatformLibName;
414 Unexpect aCatch(SALOME_SalomeException);
415 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
417 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
418 GenericHypothesisCreator_i* aCreator;
421 // check, if creator for this hypothesis type already exists
422 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
424 // load plugin library
425 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
426 LibHandle libHandle = LoadLib( aPlatformLibName.c_str() );
429 // report any error, if occurred
431 const char* anError = dlerror();
432 throw(SALOME_Exception(anError));
434 throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
438 // get method, returning hypothesis creator
439 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
440 GetHypothesisCreator procHandle =
441 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
444 throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
445 UnLoadLib(libHandle);
448 // get hypothesis creator
449 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
450 aCreator = procHandle(theHypName);
453 throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
455 // map hypothesis creator to a hypothesis name
456 myHypCreatorMap[string(theHypName)] = aCreator;
461 return myHypCreatorMap[string(theHypName)];
464 catch (SALOME_Exception& S_ex)
466 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
471 //=============================================================================
473 * SMESH_Gen_i::createHypothesis
475 * Create hypothesis of given type
477 //=============================================================================
478 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
479 const char* theLibName)
481 SMESH_Hypothesis_i* myHypothesis_i = 0;
482 SMESH::SMESH_Hypothesis_var hypothesis_i;
483 std::string aPlatformLibName;
484 GenericHypothesisCreator_i* aCreator =
485 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
487 // create a new hypothesis object, store its ref. in studyContext
488 myHypothesis_i = aCreator->Create(myPoa, GetCurrentStudyID(), &myGen);
491 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
492 CORBA::String_var hypName = myHypothesis_i->GetName();
493 myHypCreatorMap[ hypName.in() ] = aCreator;
495 // activate the CORBA servant of hypothesis
496 hypothesis_i = myHypothesis_i->_this();
497 int nextId = RegisterObject( hypothesis_i );
498 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
499 else { nextId = 0; } // avoid "unused variable" warning in release mode
501 return hypothesis_i._retn();
504 //=============================================================================
506 * SMESH_Gen_i::createMesh
508 * Create empty mesh on shape
510 //=============================================================================
511 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
512 throw ( SALOME::SALOME_Exception )
514 Unexpect aCatch(SALOME_SalomeException);
515 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
517 // Get or create the GEOM_Client instance
519 // create a new mesh object servant, store it in a map in study context
520 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this, GetCurrentStudyID() );
521 // create a new mesh object
522 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
523 meshServant->SetImpl( myGen.CreateMesh( GetCurrentStudyID(), myIsEmbeddedMode ));
525 // activate the CORBA servant of Mesh
526 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
527 int nextId = RegisterObject( mesh );
528 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
529 else { nextId = 0; } // avoid "unused variable" warning in release mode
532 catch (SALOME_Exception& S_ex) {
533 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
535 return SMESH::SMESH_Mesh::_nil();
538 //=============================================================================
540 * SMESH_Gen_i::GetShapeReader
544 //=============================================================================
545 GEOM_Client* SMESH_Gen_i::GetShapeReader()
547 // create shape reader if necessary
548 if ( !myShapeReader )
549 myShapeReader = new GEOM_Client(GetContainerRef());
550 ASSERT( myShapeReader );
551 return myShapeReader;
554 //=============================================================================
556 * SMESH_Gen_i::SetGeomEngine
558 * Set GEOM::GEOM_Gen reference
560 //=============================================================================
561 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
562 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
564 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
565 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
566 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
570 //=============================================================================
572 * SMESH_Gen_i::SetEmbeddedMode
576 //=============================================================================
578 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
580 myIsEmbeddedMode = theMode;
582 if ( !myIsEmbeddedMode ) {
583 //PAL10867: disable signals catching with "noexcepthandler" option
584 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
585 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
590 char* envDisableFPE = getenv("DISABLE_FPE");
591 if (envDisableFPE && atoi(envDisableFPE))
596 OSD::SetSignal( raiseFPE );
598 // else OSD::SetSignal() is called in GUI
602 //=============================================================================
604 * SMESH_Gen_i::IsEmbeddedMode
608 //=============================================================================
610 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
612 return myIsEmbeddedMode;
615 //=============================================================================
617 * SMESH_Gen_i::SetCurrentStudy
621 //=============================================================================
623 void SMESH_Gen_i::SetCurrentStudy( SALOMEDS::Study_ptr theStudy )
625 setCurrentStudy( theStudy );
628 void SMESH_Gen_i::setCurrentStudy( SALOMEDS::Study_ptr theStudy,
629 bool theStudyIsBeingClosed)
631 int curStudyId = GetCurrentStudyID();
632 myCurrentStudy = SALOMEDS::Study::_duplicate( theStudy );
633 // create study context, if it doesn't exist and set current study
634 int studyId = GetCurrentStudyID();
635 if ( myStudyContextMap.find( studyId ) == myStudyContextMap.end() )
636 myStudyContextMap[ studyId ] = new StudyContext;
638 // myCurrentStudy may be nil
639 if ( !theStudyIsBeingClosed && !CORBA::is_nil( myCurrentStudy ) ) {
640 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
641 SALOMEDS::SComponent_wrap GEOM_var = myCurrentStudy->FindComponent( "GEOM" );
642 if( !GEOM_var->_is_nil() )
643 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
644 // NPAL16168, issue 0020210
645 // Let meshes update their data depending on GEOM groups that could change
646 if ( curStudyId != studyId )
648 CORBA::String_var compDataType = ComponentDataType();
649 SALOMEDS::SComponent_wrap me = myCurrentStudy->FindComponent( compDataType.in() );
650 if ( !me->_is_nil() ) {
651 SALOMEDS::ChildIterator_wrap anIter = myCurrentStudy->NewChildIterator( me );
652 for ( ; anIter->More(); anIter->Next() ) {
653 SALOMEDS::SObject_wrap so = anIter->Value();
654 CORBA::Object_var ior = SObjectToObject( so );
655 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
656 mesh->CheckGeomModif();
663 //=============================================================================
665 * SMESH_Gen_i::GetCurrentStudy
669 //=============================================================================
671 SALOMEDS::Study_ptr SMESH_Gen_i::GetCurrentStudy()
673 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetCurrentStudy: study Id = " << GetCurrentStudyID() );
674 if ( GetCurrentStudyID() < 0 )
675 return SALOMEDS::Study::_nil();
676 return SALOMEDS::Study::_duplicate( myCurrentStudy );
679 //=============================================================================
681 * SMESH_Gen_i::GetCurrentStudyContext
683 * Get current study context
685 //=============================================================================
686 StudyContext* SMESH_Gen_i::GetCurrentStudyContext()
688 if ( !CORBA::is_nil( myCurrentStudy ) &&
689 myStudyContextMap.find( GetCurrentStudyID() ) != myStudyContextMap.end() )
690 return myStudyContextMap[ myCurrentStudy->StudyId() ];
695 //=============================================================================
697 * SMESH_Gen_i::CreateHypothesis
699 * Create hypothesis/algorothm of given type and publish it in the study
701 //=============================================================================
703 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
704 const char* theLibName )
705 throw ( SALOME::SALOME_Exception )
707 Unexpect aCatch(SALOME_SalomeException);
708 // Create hypothesis/algorithm
709 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
711 // Publish hypothesis/algorithm in the study
712 if ( CanPublishInStudy( hyp ) ) {
713 SALOMEDS::SObject_wrap aSO = PublishHypothesis( myCurrentStudy, hyp );
714 if ( !aSO->_is_nil() ) {
715 // Update Python script
716 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
717 << theHypName << "', '" << theLibName << "')";
724 //================================================================================
726 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
727 * existing on the given geometry or to size of the geometry.
728 * \param theHypType - hypothesis type name
729 * \param theLibName - plugin library name
730 * \param theMesh - The mesh of interest
731 * \param theGeom - The shape to get parameter values from
732 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
733 * in a study and used to compute the mesh, or a temporary one created just to pass
736 //================================================================================
738 SMESH::SMESH_Hypothesis_ptr
739 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
740 const char* theLibName,
741 SMESH::SMESH_Mesh_ptr theMesh,
742 GEOM::GEOM_Object_ptr theGeom,
743 CORBA::Boolean byMesh)
744 throw ( SALOME::SALOME_Exception )
746 Unexpect aCatch(SALOME_SalomeException);
747 if ( byMesh && CORBA::is_nil( theMesh ) )
748 return SMESH::SMESH_Hypothesis::_nil();
749 if ( byMesh && CORBA::is_nil( theGeom ) )
750 return SMESH::SMESH_Hypothesis::_nil();
752 // -----------------------------------------------
753 // find hypothesis used to mesh theGeom
754 // -----------------------------------------------
756 // get mesh and shape
757 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
758 TopoDS_Shape shape = GeomObjectToShape( theGeom );
759 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
760 return SMESH::SMESH_Hypothesis::_nil();
761 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
763 // create a temporary hypothesis to know its dimension
764 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
765 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
767 return SMESH::SMESH_Hypothesis::_nil();
768 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
771 // look for a hypothesis of theHypType used to mesh the shape
772 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
775 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
776 int nbLocalHyps = aHypList->length();
777 for ( int i = 0; i < nbLocalHyps; i++ ) {
778 CORBA::String_var hypName = aHypList[i]->GetName();
779 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
780 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
782 // check super shapes
783 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
784 while ( nbLocalHyps == 0 && itShape.More() ) {
785 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
786 if ( ! CORBA::is_nil( geomObj )) {
787 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
788 nbLocalHyps = aHypList->length();
789 for ( int i = 0; i < nbLocalHyps; i++ )
790 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
791 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
797 // let the temporary hypothesis find out somehow parameter values by mesh
798 if ( hyp->SetParametersByMesh( mesh, shape ))
799 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
804 diagonal = mesh->GetShapeDiagonalSize();
806 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
807 ::SMESH_Hypothesis::TDefaults dflts;
808 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
809 dflts._nbSegments = myGen.GetDefaultNbSegments();
810 dflts._shape = &shape;
811 // let the temporary hypothesis initialize it's values
812 if ( hyp->SetParametersByDefaults( dflts, mesh ))
813 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
816 return SMESH::SMESH_Hypothesis::_nil();
819 //=============================================================================
821 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
822 * \param [in] theHyp - the hypothesis of interest
823 * \param [out] theMesh - the sole mesh using \a theHyp
824 * \param [out] theShape - the sole geometry \a theHyp is assigned to
825 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
827 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
828 * considered as SAME sub-mesh => result is \c true.
829 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
830 * a shape to which an hyp being edited is assigned.
832 //=============================================================================
834 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
835 SMESH::SMESH_Mesh_out theMesh,
836 GEOM::GEOM_Object_out theShape)
838 if ( GetCurrentStudyID() < 0 || CORBA::is_nil( theHyp ))
841 // get Mesh component SO
842 CORBA::String_var compDataType = ComponentDataType();
843 SALOMEDS::SComponent_wrap comp = myCurrentStudy->FindComponent( compDataType.in() );
844 if ( CORBA::is_nil( comp ))
847 // look for child SO of meshes
848 SMESH::SMESH_Mesh_var foundMesh;
849 TopoDS_Shape foundShape;
851 SALOMEDS::ChildIterator_wrap meshIter = myCurrentStudy->NewChildIterator( comp );
852 for ( ; meshIter->More() && isSole; meshIter->Next() )
854 SALOMEDS::SObject_wrap curSO = meshIter->Value();
855 CORBA::Object_var obj = SObjectToObject( curSO );
856 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
860 // look for a sole shape where theHyp is assigned
861 bool isHypFound = false;
862 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
863 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
864 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
866 const THypList& hyps = s2hypsIt.Value();
867 THypList::const_iterator h = hyps.begin();
868 for ( ; h != hyps.end(); ++h )
869 if ( (*h)->GetID() == theHyp->GetId() )
871 if ( h != hyps.end()) // theHyp found
874 if ( ! foundShape.IsNull() &&
875 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
877 foundShape.Nullify();
881 foundShape = s2hypsIt.Key();
883 } // loop on assigned hyps
885 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
887 if ( !foundMesh->_is_nil() ) // not a sole mesh
889 if ( !foundMesh->HasShapeToMesh() ||
890 !mesh_i ->HasShapeToMesh() )
892 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
896 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
897 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
898 isSole = s1->IsSame( s2 );
901 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
907 ! foundMesh->_is_nil() &&
908 ! foundShape.IsNull() )
910 theMesh = foundMesh._retn();
911 theShape = ShapeToGeomObject( foundShape );
912 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
917 //=============================================================================
919 * Sets number of segments per diagonal of boundary box of geometry by which
920 * default segment length of appropriate 1D hypotheses is defined
922 //=============================================================================
924 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
925 throw ( SALOME::SALOME_Exception )
927 if ( theNbSegments > 0 )
928 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
930 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
932 //=============================================================================
934 * \brief Sets default number of segments per edge
936 //=============================================================================
937 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
938 throw ( SALOME::SALOME_Exception )
940 if ( theNbSegments > 0 )
941 myGen.SetDefaultNbSegments( int(theNbSegments) );
943 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
946 //=============================================================================
950 //=============================================================================
952 void SMESH_Gen_i::SetOption(const char* name, const char* value)
954 if ( name && value && strlen( value ) > 0 )
957 if ( strcmp(name, "historical_python_dump") == 0 )
959 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
960 msgToGUI = "preferences/SMESH/historical_python_dump/";
961 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
963 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
965 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
966 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
967 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
969 else if ( strcmp(name, "default_grp_color") == 0 )
973 // color must be presented as a string of following form:
974 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
976 for ( size_t i = 0; i < str.length()/2; i++ )
977 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
978 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
980 else if ( value ) { // rgb color ("255,170,0", for example)
981 string tempValue( value );
982 char* colorValue = strtok( &tempValue[0], "," );
983 while ( colorValue != NULL ) {
984 int c_value = atoi( colorValue );
985 if ( c_value >= 0 && c_value <= 255 )
986 color.push_back( c_value );
987 colorValue = strtok( NULL, "," );
990 if ( color.size() == 3 ) { // color must have three valid component
991 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
992 myDefaultGroupColor = value;
993 msgToGUI = "preferences/SMESH/default_grp_color/";
998 // update preferences in case if SetOption() is invoked from python console
999 if ( !msgToGUI.empty() )
1001 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1002 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1003 if ( !CORBA::is_nil( session ) )
1004 session->emitMessageOneWay(msgToGUI.c_str());
1009 //=============================================================================
1011 Return an option value
1013 //=============================================================================
1015 char* SMESH_Gen_i::GetOption(const char* name)
1019 if ( strcmp(name, "historical_python_dump") == 0 )
1021 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1023 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1025 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1027 if ( strcmp(name, "default_grp_color") == 0 )
1029 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1032 return CORBA::string_dup( "" );
1035 //=============================================================================
1037 * SMESH_Gen_i::CreateMesh
1039 * Create empty mesh on a shape and publish it in the study
1041 //=============================================================================
1043 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1044 throw ( SALOME::SALOME_Exception )
1046 Unexpect aCatch(SALOME_SalomeException);
1047 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1049 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1051 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1052 ASSERT( meshServant );
1053 meshServant->SetShape( theShapeObject );
1055 // publish mesh in the study
1056 if ( CanPublishInStudy( mesh ) ) {
1057 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1058 aStudyBuilder->NewCommand(); // There is a transaction
1059 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1060 aStudyBuilder->CommitCommand();
1061 if ( !aSO->_is_nil() ) {
1062 // Update Python script
1063 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1067 return mesh._retn();
1070 //=============================================================================
1072 * SMESH_Gen_i::CreateEmptyMesh
1076 //=============================================================================
1078 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1079 throw ( SALOME::SALOME_Exception )
1081 Unexpect aCatch(SALOME_SalomeException);
1082 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1084 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1086 // publish mesh in the study
1087 if ( CanPublishInStudy( mesh ) ) {
1088 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1089 aStudyBuilder->NewCommand(); // There is a transaction
1090 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1091 aStudyBuilder->CommitCommand();
1092 if ( !aSO->_is_nil() ) {
1093 // Update Python script
1094 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1098 return mesh._retn();
1103 //================================================================================
1105 * \brief Throws an exception in case if the file can't be read
1107 //================================================================================
1109 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1111 SMESH_File f ( theFileName );
1114 if ( !f.error().empty() )
1115 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1117 THROW_SALOME_CORBA_EXCEPTION
1118 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1119 SALOME::BAD_PARAM );
1124 //=============================================================================
1126 * SMESH_Gen_i::CreateMeshFromUNV
1128 * Create mesh and import data from UNV file
1130 //=============================================================================
1132 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1133 throw ( SALOME::SALOME_Exception )
1135 Unexpect aCatch(SALOME_SalomeException);
1137 checkFileReadable( theFileName );
1139 SMESH::SMESH_Mesh_var aMesh = createMesh();
1141 // publish mesh in the study
1142 if ( CanPublishInStudy( aMesh ) ) {
1143 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1144 aStudyBuilder->NewCommand(); // There is a transaction
1145 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, aMesh.in(), aFileName.c_str() );
1146 aStudyBuilder->CommitCommand();
1147 if ( !aSO->_is_nil() ) {
1148 // Update Python script
1149 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1153 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1155 aServant->ImportUNVFile( theFileName );
1157 // Dump creation of groups
1158 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1160 aServant->GetImpl().GetMeshDS()->Modified();
1161 return aMesh._retn();
1164 //=============================================================================
1166 * SMESH_Gen_i::CreateMeshFromMED
1168 * Create mesh and import data from MED file
1170 //=============================================================================
1172 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1173 SMESH::DriverMED_ReadStatus& theStatus,
1174 const char* theCommandNameForPython,
1175 const char* theFileNameForPython)
1178 char bname[ _MAX_FNAME ];
1179 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1180 string aFileName = bname;
1182 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1184 // Retrieve mesh names from the file
1185 DriverMED_R_SMESHDS_Mesh myReader;
1186 myReader.SetFile( theFileName );
1187 myReader.SetMeshId( -1 );
1188 Driver_Mesh::Status aStatus;
1189 list<string> aNames = myReader.GetMeshNames(aStatus);
1190 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1191 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1193 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1196 TPythonDump aPythonDump;
1197 aPythonDump << "([";
1199 if (theStatus == SMESH::DRS_OK) {
1200 SALOMEDS::StudyBuilder_var aStudyBuilder;
1201 if ( GetCurrentStudyID() > -1 )
1203 aStudyBuilder = myCurrentStudy->NewBuilder();
1204 aStudyBuilder->NewCommand(); // There is a transaction
1206 aResult->length( aNames.size() );
1209 // Iterate through all meshes and create mesh objects
1210 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1213 if (i > 0) aPythonDump << ", ";
1216 SMESH::SMESH_Mesh_var mesh = createMesh();
1218 // publish mesh in the study
1219 SALOMEDS::SObject_wrap aSO;
1220 if ( CanPublishInStudy( mesh ) )
1221 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1222 // - as names of meshes are stored in MED file, we use them for data publishing
1223 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1224 aSO = PublishMesh( myCurrentStudy, mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1227 if ( !aSO->_is_nil() ) {
1230 aPythonDump << "mesh_" << i;
1233 // Read mesh data (groups are published automatically by ImportMEDFile())
1234 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1235 ASSERT( meshServant );
1236 SMESH::DriverMED_ReadStatus status1 =
1237 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1238 if (status1 > theStatus)
1239 theStatus = status1;
1241 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1242 meshServant->GetImpl().GetMeshDS()->Modified();
1244 if ( !aStudyBuilder->_is_nil() )
1245 aStudyBuilder->CommitCommand();
1248 // Update Python script
1249 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1251 // Dump creation of groups
1252 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1253 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1255 return aResult._retn();
1258 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1259 SMESH::DriverMED_ReadStatus& theStatus)
1260 throw ( SALOME::SALOME_Exception )
1262 Unexpect aCatch(SALOME_SalomeException);
1263 checkFileReadable( theFileName );
1265 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1269 //=============================================================================
1271 * SMESH_Gen_i::CreateMeshFromSAUV
1273 * Create mesh and import data from SAUV file
1275 //=============================================================================
1277 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1278 SMESH::DriverMED_ReadStatus& theStatus)
1279 throw ( SALOME::SALOME_Exception )
1281 Unexpect aCatch(SALOME_SalomeException);
1282 checkFileReadable( theFileName );
1284 std::string sauvfilename(theFileName);
1285 std::string medfilename(theFileName);
1286 medfilename += ".med";
1289 cmd = "%PYTHONBIN% ";
1294 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1296 system(cmd.c_str());
1297 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1299 cmd = "%PYTHONBIN% ";
1304 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1306 system(cmd.c_str());
1310 //=============================================================================
1312 * SMESH_Gen_i::CreateMeshFromSTL
1314 * Create mesh and import data from STL file
1316 //=============================================================================
1318 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1319 throw ( SALOME::SALOME_Exception )
1321 Unexpect aCatch(SALOME_SalomeException);
1322 checkFileReadable( theFileName );
1324 SMESH::SMESH_Mesh_var aMesh = createMesh();
1327 char bname[ _MAX_FNAME ];
1328 _splitpath( theFileName, NULL, NULL, bname, NULL );
1329 string aFileName = bname;
1331 string aFileName = basename( const_cast<char *>(theFileName) );
1333 // publish mesh in the study
1334 if ( CanPublishInStudy( aMesh ) ) {
1335 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1336 aStudyBuilder->NewCommand(); // There is a transaction
1337 SALOMEDS::SObject_wrap aSO = PublishInStudy
1338 ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1339 aStudyBuilder->CommitCommand();
1340 if ( !aSO->_is_nil() ) {
1341 // Update Python script
1342 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1346 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1348 aServant->ImportSTLFile( theFileName );
1349 aServant->GetImpl().GetMeshDS()->Modified();
1350 return aMesh._retn();
1353 //================================================================================
1355 * \brief Create meshes and import data from the CGSN file
1357 //================================================================================
1359 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1360 SMESH::DriverMED_ReadStatus& theStatus)
1361 throw ( SALOME::SALOME_Exception )
1363 Unexpect aCatch(SALOME_SalomeException);
1364 checkFileReadable( theFileName );
1366 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1369 // Retrieve nb meshes from the file
1370 DriverCGNS_Read myReader;
1371 myReader.SetFile( theFileName );
1372 Driver_Mesh::Status aStatus;
1373 int nbMeshes = myReader.GetNbMeshes(aStatus);
1374 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1376 aResult->length( nbMeshes );
1378 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1381 TPythonDump aPythonDump;
1382 aPythonDump << "([";
1384 if (theStatus == SMESH::DRS_OK)
1386 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1387 aStudyBuilder->NewCommand(); // There is a transaction
1391 // Iterate through all meshes and create mesh objects
1392 for ( ; i < nbMeshes; ++i )
1395 if (i > 0) aPythonDump << ", ";
1398 SMESH::SMESH_Mesh_var mesh = createMesh();
1399 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1401 // Read mesh data (groups are published automatically by ImportMEDFile())
1402 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1403 ASSERT( meshServant );
1405 SMESH::DriverMED_ReadStatus status1 =
1406 meshServant->ImportCGNSFile( theFileName, i, meshName );
1407 if (status1 > theStatus)
1408 theStatus = status1;
1410 meshServant->GetImpl().GetMeshDS()->Modified();
1411 // publish mesh in the study
1412 SALOMEDS::SObject_wrap aSO;
1413 if ( CanPublishInStudy( mesh ) )
1414 aSO = PublishMesh( myCurrentStudy, mesh.in(), meshName.c_str() );
1417 if ( !aSO->_is_nil() ) {
1421 aPythonDump << "mesh_" << i;
1424 aStudyBuilder->CommitCommand();
1427 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1429 // Dump creation of groups
1430 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1431 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1433 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1436 return aResult._retn();
1439 //================================================================================
1441 * \brief Create a mesh and import data from a GMF file
1443 //================================================================================
1445 SMESH::SMESH_Mesh_ptr
1446 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1447 CORBA::Boolean theMakeRequiredGroups,
1448 SMESH::ComputeError_out theError)
1449 throw ( SALOME::SALOME_Exception )
1451 Unexpect aCatch(SALOME_SalomeException);
1452 checkFileReadable( theFileName );
1454 SMESH::SMESH_Mesh_var aMesh = createMesh();
1456 char bname[ _MAX_FNAME ];
1457 _splitpath( theFileName, NULL, NULL, bname, NULL );
1458 string aFileName = bname;
1460 string aFileName = basename( const_cast<char *>(theFileName) );
1462 // publish mesh in the study
1463 if ( CanPublishInStudy( aMesh ) ) {
1464 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1465 aStudyBuilder->NewCommand(); // There is a transaction
1466 SALOMEDS::SObject_wrap aSO = PublishInStudy
1467 ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1468 aStudyBuilder->CommitCommand();
1469 if ( !aSO->_is_nil() ) {
1470 // Update Python script
1471 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1472 << theFileName << "', "
1473 << theMakeRequiredGroups << " )";
1476 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1478 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1479 aServant->GetImpl().GetMeshDS()->Modified();
1480 return aMesh._retn();
1484 //=============================================================================
1486 * SMESH_Gen_i::IsReadyToCompute
1488 * Returns true if mesh contains enough data to be computed
1490 //=============================================================================
1492 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1493 GEOM::GEOM_Object_ptr theShapeObject )
1494 throw ( SALOME::SALOME_Exception )
1496 Unexpect aCatch(SALOME_SalomeException);
1497 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1499 if ( CORBA::is_nil( theShapeObject ) )
1500 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1501 SALOME::BAD_PARAM );
1503 if ( CORBA::is_nil( theMesh ) )
1504 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1505 SALOME::BAD_PARAM );
1509 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1510 ASSERT( meshServant );
1511 if ( meshServant ) {
1512 // get local TopoDS_Shape
1513 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1514 // call implementation
1515 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1516 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1519 catch ( SALOME_Exception& S_ex ) {
1520 INFOS( "catch exception "<< S_ex.what() );
1525 //================================================================================
1527 * \brief Find SObject for an algo
1529 //================================================================================
1531 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1534 if ( !myCurrentStudy->_is_nil() ) {
1535 // find algo in the study
1536 CORBA::String_var compDataType = ComponentDataType();
1537 SALOMEDS::SComponent_wrap father = myCurrentStudy->FindComponent( compDataType.in() );
1538 if ( !father->_is_nil() ) {
1539 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( father );
1540 for ( ; itBig->More(); itBig->Next() ) {
1541 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1542 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1543 SALOMEDS::ChildIterator_wrap algoIt = myCurrentStudy->NewChildIterator( gotBranch );
1544 for ( ; algoIt->More(); algoIt->Next() ) {
1545 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1546 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1547 if ( !CORBA::is_nil( algoIOR )) {
1548 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1549 if ( impl && impl->GetImpl() == algo )
1550 return algoSO._retn();
1552 } // loop on algo SO's
1555 } // SMESH component iterator
1559 return SALOMEDS::SObject::_nil();
1562 //================================================================================
1564 * \brief Return errors of mesh computation
1566 //================================================================================
1568 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1569 GEOM::GEOM_Object_ptr theSubObject )
1570 throw ( SALOME::SALOME_Exception )
1572 Unexpect aCatch(SALOME_SalomeException);
1573 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1575 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1576 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1578 if ( CORBA::is_nil( theMesh ) )
1579 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1581 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1583 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1586 if(theMesh->HasShapeToMesh())
1587 shape = GeomObjectToShape( theSubObject );
1589 shape = SMESH_Mesh::PseudoShape();
1591 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1593 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1596 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1597 const bool includeSelf = true, complexShapeFirst = true;
1598 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1600 while ( smIt->more() )
1603 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1605 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1606 if ( error && !error->IsOK() )
1608 if ( !( error->myAlgo ) &&
1609 !( error->myAlgo = sm->GetAlgo() ))
1611 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1612 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1613 errStruct.comment = error->myComment.c_str();
1614 errStruct.subShapeID = sm->GetId();
1615 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1616 if ( !algoSO->_is_nil() ) {
1617 CORBA::String_var algoName = algoSO->GetName();
1618 errStruct.algoName = algoName;
1621 errStruct.algoName = error->myAlgo->GetName();
1623 errStruct.hasBadMesh = !error->myBadElements.empty();
1626 error_array->length( nbErr );
1629 catch ( SALOME_Exception& S_ex ) {
1630 INFOS( "catch exception "<< S_ex.what() );
1633 return error_array._retn();
1636 //================================================================================
1638 * \brief Return mesh elements preventing computation of a subshape
1640 //================================================================================
1642 SMESH::MeshPreviewStruct*
1643 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1644 CORBA::Short theSubShapeID )
1645 throw ( SALOME::SALOME_Exception )
1647 Unexpect aCatch(SALOME_SalomeException);
1648 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1650 if ( CORBA::is_nil( theMesh ) )
1651 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1653 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1656 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1658 // mesh implementation
1659 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1660 // submesh by subshape id
1661 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1664 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1665 if ( error && !error->myBadElements.empty())
1667 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1668 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1670 // get nodes of elements and count elements
1671 TNode2LocalIDMap mapNode2LocalID;
1672 list< TNodeLocalID > connectivity;
1673 int i, nbElements = 0, nbConnNodes = 0;
1675 list<const SMDS_MeshElement*>::iterator elemIt = error->myBadElements.begin();
1676 list<const SMDS_MeshElement*>::iterator elemEnd = error->myBadElements.end();
1677 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1679 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1680 while ( nIt->more() )
1681 connectivity.push_back
1682 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1684 // fill node coords and assign local ids to the nodes
1685 int nbNodes = mapNode2LocalID.size();
1686 result->nodesXYZ.length( nbNodes );
1687 TNodeLocalID node2ID = mapNode2LocalID.begin();
1688 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1689 node2ID->second = i;
1690 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1691 result->nodesXYZ[i].x = node->X();
1692 result->nodesXYZ[i].y = node->Y();
1693 result->nodesXYZ[i].z = node->Z();
1695 // fill connectivity
1696 result->elementConnectivities.length( nbConnNodes );
1697 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1698 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1699 result->elementConnectivities[i] = (*connIt)->second;
1701 // fill element types
1702 result->elementTypes.length( nbElements );
1703 for ( i = 0, elemIt = error->myBadElements.begin(); i <nbElements; ++i, ++elemIt )
1705 const SMDS_MeshElement* elem = *elemIt;
1706 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1707 result->elementTypes[i].isPoly = elem->IsPoly();
1708 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1714 catch ( SALOME_Exception& S_ex ) {
1715 INFOS( "catch exception "<< S_ex.what() );
1718 return result._retn();
1721 //================================================================================
1723 * \brief Create a group of elements preventing computation of a sub-shape
1725 //================================================================================
1727 SMESH::ListOfGroups*
1728 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1729 CORBA::Short theSubShapeID,
1730 const char* theGroupName )
1731 throw ( SALOME::SALOME_Exception )
1733 Unexpect aCatch(SALOME_SalomeException);
1735 SMESH::ListOfGroups_var groups;
1737 if ( CORBA::is_nil( theMesh ) )
1738 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1741 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1743 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1744 TPythonDump() << groups << " = " << this
1745 << ".MakeGroupsOfBadInputElements( "
1746 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1749 catch ( SALOME_Exception& S_ex ) {
1750 INFOS( "catch exception "<< S_ex.what() );
1752 return groups._retn();
1755 //================================================================================
1757 * \brief Returns errors of hypotheses definition
1758 * \param theMesh - the mesh
1759 * \param theSubObject - the main or sub- shape
1760 * \retval SMESH::algo_error_array* - sequence of errors
1762 //================================================================================
1764 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1765 GEOM::GEOM_Object_ptr theSubObject )
1766 throw ( SALOME::SALOME_Exception )
1768 Unexpect aCatch(SALOME_SalomeException);
1769 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1771 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1772 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1774 if ( CORBA::is_nil( theMesh ) )
1775 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1777 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1779 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1780 ASSERT( meshServant );
1781 if ( meshServant ) {
1782 TopoDS_Shape myLocShape;
1783 if(theMesh->HasShapeToMesh())
1784 myLocShape = GeomObjectToShape( theSubObject );
1786 myLocShape = SMESH_Mesh::PseudoShape();
1788 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1789 list< ::SMESH_Gen::TAlgoStateError > error_list;
1790 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1791 // call ::SMESH_Gen::GetAlgoState()
1792 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1793 error_array->length( error_list.size() );
1795 for ( error = error_list.begin(); error != error_list.end(); ++error )
1797 // fill AlgoStateError structure
1798 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1799 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1800 errStruct.algoDim = error->_algoDim;
1801 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1802 errStruct.algoName = "";
1803 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1804 if ( !algoSO->_is_nil() ) {
1805 CORBA::String_var algoName = algoSO->GetName();
1806 errStruct.algoName = algoName.in();
1811 catch ( SALOME_Exception& S_ex ) {
1812 INFOS( "catch exception "<< S_ex.what() );
1814 return error_array._retn();
1817 //=============================================================================
1819 * SMESH_Gen_i::GetSubShapesId
1821 * Get sub-shapes unique ID's list
1823 //=============================================================================
1826 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1827 const SMESH::object_array& theListOfSubShapeObject )
1828 throw ( SALOME::SALOME_Exception )
1830 Unexpect aCatch(SALOME_SalomeException);
1831 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1833 SMESH::long_array_var shapesId = new SMESH::long_array;
1836 if ( CORBA::is_nil( theMainShapeObject ) )
1837 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1841 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1842 TopTools_IndexedMapOfShape myIndexToShape;
1843 TopExp::MapShapes(myMainShape,myIndexToShape);
1845 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1847 GEOM::GEOM_Object_var aShapeObject
1848 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1849 if ( CORBA::is_nil( aShapeObject ) )
1850 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1851 SALOME::BAD_PARAM );
1853 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1854 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1856 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1857 setId.insert(myIndexToShape.FindIndex(F));
1858 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1860 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1862 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1863 setId.insert(myIndexToShape.FindIndex(E));
1864 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1866 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1868 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1869 setId.insert(myIndexToShape.FindIndex(V));
1870 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1873 shapesId->length(setId.size());
1874 set<int>::iterator iind;
1876 for (iind = setId.begin(); iind != setId.end(); iind++)
1878 if(MYDEBUG) SCRUTE((*iind));
1879 shapesId[i] = (*iind);
1880 if(MYDEBUG) SCRUTE(shapesId[i]);
1884 catch (SALOME_Exception& S_ex)
1886 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1889 return shapesId._retn();
1892 //=============================================================================
1894 * SMESH_Gen_i::Compute
1896 * Compute mesh on a shape
1898 //=============================================================================
1900 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1901 GEOM::GEOM_Object_ptr theShapeObject )
1902 throw ( SALOME::SALOME_Exception )
1905 Unexpect aCatch(SALOME_SalomeException);
1906 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1908 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1909 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1910 SALOME::BAD_PARAM );
1912 if ( CORBA::is_nil( theMesh ) )
1913 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1914 SALOME::BAD_PARAM );
1916 // Update Python script
1917 TPythonDump() << "isDone = " << this << ".Compute( "
1918 << theMesh << ", " << theShapeObject << ")";
1922 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1923 ASSERT( meshServant );
1924 if ( meshServant ) {
1925 meshServant->Load();
1926 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1927 meshServant->CheckGeomModif();
1928 // get local TopoDS_Shape
1929 TopoDS_Shape myLocShape;
1930 if(theMesh->HasShapeToMesh())
1931 myLocShape = GeomObjectToShape( theShapeObject );
1933 myLocShape = SMESH_Mesh::PseudoShape();
1934 // call implementation compute
1935 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1936 myGen.PrepareCompute( myLocMesh, myLocShape );
1937 int how = ::SMESH_Gen::COMPACT_MESH;
1938 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
1939 how |= ::SMESH_Gen::SHAPE_ONLY;
1940 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
1941 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1942 myLocMesh.GetMeshDS()->Modified();
1946 catch ( std::bad_alloc ) {
1947 INFOS( "Compute(): lack of memory" );
1949 catch ( SALOME_Exception& S_ex ) {
1950 INFOS( "Compute(): catch exception "<< S_ex.what() );
1953 INFOS( "Compute(): unknown exception " );
1958 //=============================================================================
1960 * SMESH_Gen_i::CancelCompute
1962 * Cancel Compute mesh on a shape
1964 //=============================================================================
1966 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
1967 GEOM::GEOM_Object_ptr theShapeObject )
1969 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1970 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1971 TopoDS_Shape myLocShape;
1972 if(theMesh->HasShapeToMesh())
1973 myLocShape = GeomObjectToShape( theShapeObject );
1975 myLocShape = SMESH_Mesh::PseudoShape();
1976 myGen.CancelCompute( myLocMesh, myLocShape);
1979 //=============================================================================
1981 * SMESH_Gen_i::Precompute
1983 * Compute mesh as preview till indicated dimension on shape
1985 //=============================================================================
1987 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
1988 GEOM::GEOM_Object_ptr theShapeObject,
1989 SMESH::Dimension theDimension,
1990 SMESH::long_array& theShapesId)
1991 throw ( SALOME::SALOME_Exception )
1993 Unexpect aCatch(SALOME_SalomeException);
1994 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
1996 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1997 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1998 SALOME::BAD_PARAM );
2000 if ( CORBA::is_nil( theMesh ) )
2001 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2002 SALOME::BAD_PARAM );
2004 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2007 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2008 meshServant->Load();
2009 ASSERT( meshServant );
2010 if ( meshServant ) {
2011 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
2012 meshServant->CheckGeomModif();
2013 // get local TopoDS_Shape
2014 TopoDS_Shape myLocShape;
2015 if(theMesh->HasShapeToMesh())
2016 myLocShape = GeomObjectToShape( theShapeObject );
2018 return result._retn();;
2020 // call implementation compute
2021 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2023 ::MeshDimension aDim = (MeshDimension)theDimension;
2024 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2026 int nbShapeId = shapeIds.size();
2027 theShapesId.length( nbShapeId );
2028 // iterates on shapes and collect mesh entities into mesh preview
2029 TSetOfInt::const_iterator idIt = shapeIds.begin();
2030 TSetOfInt::const_iterator idEnd = shapeIds.end();
2031 std::map< int, int > mapOfShIdNb;
2032 std::set< SMESH_TLink > setOfEdge;
2033 std::list< SMDSAbs_ElementType > listOfElemType;
2034 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2035 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2036 TNode2LocalIDMap mapNode2LocalID;
2037 list< TNodeLocalID > connectivity;
2038 int i, nbConnNodes = 0;
2039 std::set< const SMESH_subMesh* > setOfVSubMesh;
2040 // iterates on shapes
2041 for ( ; idIt != idEnd; idIt++ )
2043 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2045 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2046 if ( !sm || !sm->IsMeshComputed() )
2049 const TopoDS_Shape& aSh = sm->GetSubShape();
2050 const int shDim = myGen.GetShapeDim( aSh );
2051 if ( shDim < 1 || shDim > theDimension )
2054 mapOfShIdNb[ *idIt ] = 0;
2055 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2057 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2058 if ( !smDS ) continue;
2060 if ( theDimension == SMESH::DIM_2D )
2062 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2063 while ( faceIt->more() )
2065 const SMDS_MeshElement* face = faceIt->next();
2066 int aNbNode = face->NbNodes();
2068 aNbNode /= 2; // do not take into account additional middle nodes
2070 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2071 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2073 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2074 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2076 listOfElemType.push_back( SMDSAbs_Edge );
2077 connectivity.push_back
2078 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2079 connectivity.push_back
2080 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2086 else if ( theDimension == SMESH::DIM_1D )
2088 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2089 while ( nodeIt->more() )
2091 listOfElemType.push_back( SMDSAbs_Node );
2092 connectivity.push_back
2093 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2095 // add corner nodes by first vertex from edge
2096 SMESH_subMeshIteratorPtr edgeSmIt =
2097 sm->getDependsOnIterator(/*includeSelf*/false,
2098 /*complexShapeFirst*/false);
2099 while ( edgeSmIt->more() )
2101 SMESH_subMesh* vertexSM = edgeSmIt->next();
2102 // check that vertex is not already treated
2103 if ( !setOfVSubMesh.insert( vertexSM ).second )
2105 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2108 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2109 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2110 while ( nodeIt->more() )
2112 listOfElemType.push_back( SMDSAbs_Node );
2113 connectivity.push_back
2114 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2120 // fill node coords and assign local ids to the nodes
2121 int nbNodes = mapNode2LocalID.size();
2122 result->nodesXYZ.length( nbNodes );
2123 TNodeLocalID node2ID = mapNode2LocalID.begin();
2124 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2125 node2ID->second = i;
2126 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2127 result->nodesXYZ[i].x = node->X();
2128 result->nodesXYZ[i].y = node->Y();
2129 result->nodesXYZ[i].z = node->Z();
2131 // fill connectivity
2132 result->elementConnectivities.length( nbConnNodes );
2133 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2134 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2135 result->elementConnectivities[i] = (*connIt)->second;
2138 // fill element types
2139 result->elementTypes.length( listOfElemType.size() );
2140 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2141 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2142 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2144 SMDSAbs_ElementType elemType = *typeIt;
2145 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2146 result->elementTypes[i].isPoly = false;
2147 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2150 // correct number of shapes
2151 theShapesId.length( mapOfShIdNb.size() );
2155 catch ( std::bad_alloc ) {
2156 INFOS( "Precompute(): lack of memory" );
2158 catch ( SALOME_Exception& S_ex ) {
2159 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2162 INFOS( "Precompute(): unknown exception " );
2164 return result._retn();
2168 //=============================================================================
2170 * SMESH_Gen_i::Evaluate
2172 * Evaluate mesh on a shape
2174 //=============================================================================
2176 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2177 GEOM::GEOM_Object_ptr theShapeObject)
2178 // SMESH::long_array& theNbElems)
2179 throw ( SALOME::SALOME_Exception )
2181 Unexpect aCatch(SALOME_SalomeException);
2182 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2184 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2185 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2186 SALOME::BAD_PARAM );
2188 if ( CORBA::is_nil( theMesh ) )
2189 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2190 SALOME::BAD_PARAM );
2192 SMESH::long_array_var nbels = new SMESH::long_array;
2193 nbels->length(SMESH::Entity_Last);
2194 int i = SMESH::Entity_Node;
2195 for (; i < SMESH::Entity_Last; i++)
2198 // Update Python script
2199 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2200 << theMesh << ", " << theShapeObject << ")";
2204 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2205 ASSERT( meshServant );
2206 if ( meshServant ) {
2207 meshServant->Load();
2208 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
2209 meshServant->CheckGeomModif();
2210 // get local TopoDS_Shape
2211 TopoDS_Shape myLocShape;
2212 if(theMesh->HasShapeToMesh())
2213 myLocShape = GeomObjectToShape( theShapeObject );
2215 myLocShape = SMESH_Mesh::PseudoShape();
2216 // call implementation compute
2217 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2218 MapShapeNbElems aResMap;
2219 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2220 MapShapeNbElemsItr anIt = aResMap.begin();
2221 for(; anIt!=aResMap.end(); anIt++) {
2222 const vector<int>& aVec = (*anIt).second;
2223 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2224 int nbElem = aVec[i];
2225 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2227 SMESH_subMesh* sm = anIt->first;
2228 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2229 const SMESH_Algo* algo = sm->GetAlgo();
2230 if ( (algo && !error.get()) || error->IsOK() )
2231 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2235 nbels[i] += aVec[i];
2239 return nbels._retn();
2242 catch ( std::bad_alloc ) {
2243 INFOS( "Evaluate(): lack of memory" );
2245 catch ( SALOME_Exception& S_ex ) {
2246 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2249 INFOS( "Evaluate(): unknown exception " );
2252 return nbels._retn();
2255 //================================================================================
2257 * \brief Return geometrical object the given element is built on
2258 * \param theMesh - the mesh the element is in
2259 * \param theElementID - the element ID
2260 * \param theGeomName - the name of the result geom object if it is not yet published
2261 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2263 //================================================================================
2265 GEOM::GEOM_Object_ptr
2266 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2267 CORBA::Long theElementID,
2268 const char* theGeomName)
2269 throw ( SALOME::SALOME_Exception )
2271 Unexpect aCatch(SALOME_SalomeException);
2273 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2274 if ( !geom->_is_nil() ) {
2275 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2276 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2278 // try to find the corresponding SObject
2279 SALOMEDS::SObject_wrap SObj = ObjectToSObject( myCurrentStudy, geom.in() );
2280 if ( SObj->_is_nil() ) // submesh can be not found even if published
2282 // try to find published submesh
2283 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2284 if ( !geom->IsMainShape() && list->length() == 1 ) {
2285 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2286 SALOMEDS::ChildIterator_wrap it;
2287 if ( !mainSO->_is_nil() ) {
2288 it = myCurrentStudy->NewChildIterator( mainSO );
2290 if ( !it->_is_nil() ) {
2291 for ( it->InitEx(true); it->More(); it->Next() ) {
2292 SALOMEDS::SObject_wrap so = it->Value();
2293 CORBA::Object_var obj = SObjectToObject( so );
2294 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2295 if ( !subGeom->_is_nil() ) {
2296 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2297 if ( subList->length() == 1 && list[0] == subList[0] ) {
2307 if ( SObj->_is_nil() ) // publish a new subshape
2308 SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
2310 // return only published geometry
2311 if ( !SObj->_is_nil() ) {
2312 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2313 CORBA::Object_var obj = SObjectToObject( SObj );
2314 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2318 return GEOM::GEOM_Object::_nil();
2321 //================================================================================
2323 * \brief Return geometrical object the given element is built on.
2324 * \param theMesh - the mesh the element is in
2325 * \param theElementID - the element ID
2326 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2328 //================================================================================
2330 GEOM::GEOM_Object_ptr
2331 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2332 CORBA::Long theElementID)
2333 throw ( SALOME::SALOME_Exception )
2335 Unexpect aCatch(SALOME_SalomeException);
2336 if ( CORBA::is_nil( theMesh ) )
2337 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2339 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2340 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2342 // get a core mesh DS
2343 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2344 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2346 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2347 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2348 // find the element in mesh
2349 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2350 // find a shape id by the element
2351 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2352 // get a geom object by the shape id
2353 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2354 if ( geom->_is_nil() ) {
2355 // try to find a published sub-shape
2356 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2357 SALOMEDS::ChildIterator_wrap it;
2358 if ( !mainSO->_is_nil() ) {
2359 it = myCurrentStudy->NewChildIterator( mainSO );
2361 if ( !it->_is_nil() ) {
2362 for ( it->InitEx(true); it->More(); it->Next() ) {
2363 SALOMEDS::SObject_wrap so = it->Value();
2364 CORBA::Object_var obj = SObjectToObject( so );
2365 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2366 if ( !subGeom->_is_nil() ) {
2367 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2368 if ( subList->length() == 1 && shapeID == subList[0] ) {
2376 if ( geom->_is_nil() ) {
2378 GEOM::GEOM_IShapesOperations_wrap op =
2379 geomGen->GetIShapesOperations( GetCurrentStudyID() );
2380 if ( !op->_is_nil() )
2381 geom = op->GetSubShape( mainShape, shapeID );
2386 if ( !geom->_is_nil() ) {
2387 GeomObjectToShape( geom ); // let geom client remember the found shape
2388 return geom._retn();
2393 return GEOM::GEOM_Object::_nil();
2396 //================================================================================
2398 * SMESH_Gen_i::Concatenate
2400 * Concatenate the given meshes into one mesh
2402 //================================================================================
2404 SMESH::SMESH_Mesh_ptr
2405 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2406 CORBA::Boolean theUniteIdenticalGroups,
2407 CORBA::Boolean theMergeNodesAndElements,
2408 CORBA::Double theMergeTolerance)
2409 throw ( SALOME::SALOME_Exception )
2411 return ConcatenateCommon(theMeshesArray,
2412 theUniteIdenticalGroups,
2413 theMergeNodesAndElements,
2418 //================================================================================
2420 * SMESH_Gen_i::ConcatenateWithGroups
2422 * Concatenate the given meshes into one mesh
2423 * Create the groups of all elements from initial meshes
2425 //================================================================================
2427 SMESH::SMESH_Mesh_ptr
2428 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2429 CORBA::Boolean theUniteIdenticalGroups,
2430 CORBA::Boolean theMergeNodesAndElements,
2431 CORBA::Double theMergeTolerance)
2432 throw ( SALOME::SALOME_Exception )
2434 return ConcatenateCommon(theMeshesArray,
2435 theUniteIdenticalGroups,
2436 theMergeNodesAndElements,
2441 //================================================================================
2443 * SMESH_Gen_i::ConcatenateCommon
2445 * Concatenate the given meshes into one mesh
2447 //================================================================================
2449 SMESH::SMESH_Mesh_ptr
2450 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2451 CORBA::Boolean theUniteIdenticalGroups,
2452 CORBA::Boolean theMergeNodesAndElements,
2453 CORBA::Double theMergeTolerance,
2454 CORBA::Boolean theCommonGroups)
2455 throw ( SALOME::SALOME_Exception )
2457 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2458 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2461 SMESH::SMESH_Mesh_var newMesh = CreateEmptyMesh();
2462 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2463 if ( !newImpl ) return newMesh._retn();
2465 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2466 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2468 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2469 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2470 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2471 TGroupsMap groupsMap;
2472 TListOfNewGroups listOfNewGroups;
2474 ::SMESH_MeshEditor newEditor( &locMesh );
2475 ::SMESH_MeshEditor::ElemFeatures elemType;
2477 // loop on sub-meshes
2478 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2480 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2481 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2482 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2483 if ( !initImpl ) continue;
2486 // assure that IDs increments by one during iteration
2487 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2488 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2489 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2490 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2492 initMeshDS->Modified();
2493 initMeshDS->CompactMesh();
2496 // remember nb of elements before filling in
2497 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2501 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2502 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2503 while ( elemIt->more() )
2505 SMESH_NodeXYZ node = elemIt->next();
2506 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2511 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2512 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2513 while ( elemIt->more() )
2515 const SMDS_MeshElement* elem = elemIt->next();
2516 elemType.myNodes.resize( elem->NbNodes() );
2518 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2519 for ( int k = 0; itNodes->more(); k++)
2521 const SMDS_MeshNode* node = itNodes->next();
2522 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2525 // creates a corresponding element on existent nodes in new mesh
2526 newElems[ elem->GetID() ] =
2527 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2529 newEditor.ClearLastCreated(); // forget the history
2532 // create groups of just added elements
2533 SMESH::SMESH_Group_var newGroup;
2534 SMESH::ElementType groupType;
2535 if ( theCommonGroups )
2538 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2539 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2540 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2541 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2544 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2546 for( groupType = SMESH::NODE;
2547 groupType < SMESH::NB_ELEMENT_TYPES;
2548 groupType = (SMESH::ElementType)( groupType + 1 ))
2550 if ( curState[ groupType ] <= prevState[ groupType ])
2551 continue; // no elements of groupType added from the i-th mesh
2553 // make a group name
2554 std::string groupName = "Gr";
2555 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( myCurrentStudy, theMeshesArray[i] );
2557 CORBA::String_var name = meshSO->GetName();
2561 groupName += typeNames[ groupType ];
2563 // make and fill a group
2564 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2565 std::vector< const SMDS_MeshElement* > & elemVec =
2566 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2567 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2569 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2571 for ( size_t j = 0; j < elemVec.size(); ++j )
2573 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2574 grpDS->Add( elemVec[j] );
2578 listOfNewGroups.clear();
2579 listOfNewGroups.push_back( newGroup );
2580 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2585 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2589 SMESH::SMESH_GroupBase_ptr group;
2590 CORBA::String_var groupName;
2591 SMESH::long_array_var newIDs = new SMESH::long_array();
2593 // loop on groups of a source mesh
2594 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2595 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2597 group = listOfGroups[iG];
2598 groupType = group->GetType();
2599 groupName = group->GetName();
2600 std::string name = groupName.in();
2602 // convert a list of IDs
2603 newIDs->length( group->Size() );
2604 std::vector< const SMDS_MeshElement* > & elemVec =
2605 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2606 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2608 while ( itGrElems->more() )
2610 const SMDS_MeshElement* elem = itGrElems->next();
2611 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2613 newIDs[ nbElems++ ] = newElem->GetID();
2615 newIDs->length( nbElems );
2617 // check that a current group name and type don't have identical ones in final mesh
2618 listOfNewGroups.clear();
2619 TNameAndType nameAndType( name, groupType );
2620 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2621 if ( anIter == groupsMap.end() )
2623 // add a new group in the mesh
2624 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2625 newGroup->Add( newIDs );
2627 listOfNewGroups.push_back( newGroup );
2628 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2630 else if ( theUniteIdenticalGroups )
2632 // unite identical groups
2633 TListOfNewGroups& aNewGroups = anIter->second;
2634 aNewGroups.front()->Add( newIDs );
2638 // rename identical groups
2639 newGroup = newImpl->CreateGroup( groupType, groupName );
2640 newGroup->Add( newIDs );
2642 TListOfNewGroups& newGroups = anIter->second;
2643 std::string newGroupName;
2644 if ( newGroups.size() == 1 )
2646 newGroupName = name + "_1";
2647 newGroups.front()->SetName( newGroupName.c_str() );
2649 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2650 newGroup->SetName( newGroupName.c_str() );
2651 newGroups.push_back( newGroup );
2654 } // if an IDSource is a mesh
2657 if ( theMergeNodesAndElements ) // merge nodes
2659 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2660 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2661 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2662 /*SeparateCornersAndMedium=*/ false );
2663 newEditor.MergeNodes( groupsOfNodes );
2665 newEditor.MergeEqualElements();
2668 // Update Python script
2669 pythonDump << newMesh << " = " << this
2670 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "("
2671 << theMeshesArray << ", "
2672 << theUniteIdenticalGroups << ", "
2673 << theMergeNodesAndElements << ", "
2674 << TVar( theMergeTolerance ) << ")";
2676 pPythonDump.reset(); // enable python dump from GetGroups()
2678 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2679 if ( !newMesh->_is_nil() )
2681 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2684 // IPAL21468 Change icon of compound because it need not be computed.
2685 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( myCurrentStudy, newMesh );
2686 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2688 newMeshDS->Modified();
2690 return newMesh._retn();
2693 //================================================================================
2695 * \brief Create a mesh by copying a part of another mesh
2696 * \param meshPart - a part of mesh to copy
2697 * \param toCopyGroups - to create in the new mesh groups
2698 * the copied elements belongs to
2699 * \param toKeepIDs - to preserve IDs of the copied elements or not
2700 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2702 //================================================================================
2704 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2705 const char* meshName,
2706 CORBA::Boolean toCopyGroups,
2707 CORBA::Boolean toKeepIDs)
2709 Unexpect aCatch(SALOME_SalomeException);
2711 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2713 // 1. Get source mesh
2715 if ( CORBA::is_nil( meshPart ))
2716 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2718 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2719 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2721 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2723 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2725 // 2. Make a new mesh
2727 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2728 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2730 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2731 SALOMEDS::SObject_wrap meshSO = ObjectToSObject(myCurrentStudy, newMesh );
2732 if ( !meshSO->_is_nil() )
2734 SetName( meshSO, meshName, "Mesh" );
2735 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2737 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2738 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2739 ::SMESH_MeshEditor::ElemFeatures elemType;
2741 // 3. Get elements to copy
2743 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2744 TIDSortedElemSet srcElems;
2745 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2746 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2749 srcElemIt = srcMeshDS->elementsIterator();
2750 srcNodeIt = srcMeshDS->nodesIterator();
2754 SMESH::long_array_var ids = meshPart->GetIDs();
2755 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2757 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2758 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2759 srcElems.insert( elem );
2763 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2764 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2765 srcElems.insert( elem );
2767 if ( srcElems.empty() )
2768 return newMesh._retn();
2770 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2771 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2776 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2777 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2778 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2780 const SMDS_MeshNode *nSrc, *nTgt;
2781 vector< const SMDS_MeshNode* > nodes;
2782 while ( srcElemIt->more() )
2784 const SMDS_MeshElement * elem = srcElemIt->next();
2786 nodes.resize( elem->NbNodes());
2787 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2789 for ( iN = 0; nIt->more(); ++iN )
2791 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2792 nTgt = newMeshDS->FindNode( nSrc->GetID());
2794 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2799 for ( iN = 0; nIt->more(); ++iN )
2801 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2802 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2804 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2805 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2809 if ( elem->GetType() != SMDSAbs_Node )
2811 elemType.Init( elem, /*basicOnly=*/false );
2812 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2814 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2815 if ( toCopyGroups && !toKeepIDs )
2816 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2818 } // while ( srcElemIt->more() )
2820 // 4(b). Copy free nodes
2822 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2824 while ( srcNodeIt->more() )
2826 nSrc = srcNodeIt->next();
2827 if ( nSrc->NbInverseElements() == 0 )
2830 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2832 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2839 int nbNewGroups = 0;
2842 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2843 while ( gIt->more() )
2845 SMESH_Group* group = gIt->next();
2846 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2848 // Check group type. We copy nodal groups containing nodes of copied element
2849 SMDSAbs_ElementType groupType = groupDS->GetType();
2850 if ( groupType != SMDSAbs_Node &&
2851 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2852 continue; // group type differs from types of meshPart
2854 // Find copied elements in the group
2855 vector< const SMDS_MeshElement* > groupElems;
2856 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2859 const SMDS_MeshElement* foundElem;
2860 if ( groupType == SMDSAbs_Node )
2862 while ( eIt->more() )
2863 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2864 groupElems.push_back( foundElem );
2868 while ( eIt->more() )
2869 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2870 groupElems.push_back( foundElem );
2875 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2876 if ( e2eMap.empty() ) continue;
2877 int minID = e2eMap.begin()->first->GetID();
2878 int maxID = e2eMap.rbegin()->first->GetID();
2879 TE2EMap::iterator e2e;
2880 while ( eIt->more() && groupElems.size() < e2eMap.size())
2882 const SMDS_MeshElement* e = eIt->next();
2883 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2884 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2885 groupElems.push_back( e2e->second );
2889 if ( !groupElems.empty() )
2891 SMESH::SMESH_Group_var newGroupObj =
2892 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2893 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2895 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2896 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2897 for ( unsigned i = 0; i < groupElems.size(); ++i )
2898 smdsGroup.Add( groupElems[i] );
2906 newMeshDS->Modified();
2908 *pyDump << newMesh << " = " << this
2909 << ".CopyMesh( " << meshPart << ", "
2910 << "'" << meshName << "', "
2911 << toCopyGroups << ", "
2912 << toKeepIDs << ")";
2914 delete pyDump; pyDump = 0; // allow dump in GetGroups()
2916 if ( nbNewGroups > 0 ) // dump created groups
2917 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2919 return newMesh._retn();
2922 //================================================================================
2924 * SMESH_Gen_i::GetMEDVersion
2926 * Get MED version of the file by its name
2928 //================================================================================
2929 CORBA::Boolean SMESH_Gen_i::GetMEDVersion(const char* theFileName,
2930 SMESH::MED_VERSION& theVersion)
2932 theVersion = SMESH::MED_V2_1;
2933 MED::EVersion aVersion = MED::GetVersionId( theFileName );
2934 switch( aVersion ) {
2935 case MED::eV2_1 : theVersion = SMESH::MED_V2_1; return true;
2936 case MED::eV2_2 : theVersion = SMESH::MED_V2_2; return true;
2937 case MED::eLATEST : theVersion = SMESH::MED_LATEST; return true;
2938 case MED::eMINOR_0 : theVersion = SMESH::MED_MINOR_0; return true;
2939 case MED::eMINOR_1 : theVersion = SMESH::MED_MINOR_1; return true;
2940 case MED::eMINOR_2 : theVersion = SMESH::MED_MINOR_2; return true;
2941 case MED::eMINOR_3 : theVersion = SMESH::MED_MINOR_3; return true;
2942 case MED::eMINOR_4 : theVersion = SMESH::MED_MINOR_4; return true;
2943 case MED::eMINOR_5 : theVersion = SMESH::MED_MINOR_5; return true;
2944 case MED::eMINOR_6 : theVersion = SMESH::MED_MINOR_6; return true;
2945 case MED::eMINOR_7 : theVersion = SMESH::MED_MINOR_7; return true;
2946 case MED::eMINOR_8 : theVersion = SMESH::MED_MINOR_8; return true;
2947 case MED::eMINOR_9 : theVersion = SMESH::MED_MINOR_9; return true;
2948 case MED::eVUnknown : return false;
2953 //================================================================================
2955 * SMESH_Gen_i::GetMeshNames
2957 * Get names of meshes defined in file with the specified name
2959 //================================================================================
2960 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
2962 SMESH::string_array_var aResult = new SMESH::string_array();
2963 MED::PWrapper aMed = MED::CrWrapper( theFileName );
2965 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
2967 aResult->length( aNbMeshes );
2968 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
2969 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
2970 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
2973 return aResult._retn();
2976 //=============================================================================
2980 * Save SMESH module's data
2982 //=============================================================================
2983 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
2987 // ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
2988 // san -- in case <myCurrentStudy> differs from theComponent's study,
2989 // use that of the component
2990 if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
2991 SetCurrentStudy( theComponent->GetStudy() );
2993 // Store study contents as a set of python commands
2994 SavePython(myCurrentStudy);
2996 StudyContext* myStudyContext = GetCurrentStudyContext();
2998 // Declare a byte stream
2999 SALOMEDS::TMPFile_var aStreamFile;
3001 // Obtain a temporary dir
3002 TCollection_AsciiString tmpDir =
3003 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
3005 // Create a sequence of files processed
3006 SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
3007 aFileSeq->length( NUM_TMP_FILES );
3009 TCollection_AsciiString aStudyName( "" );
3011 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
3013 // Set names of temporary files
3014 TCollection_AsciiString filename =
3015 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
3016 TCollection_AsciiString meshfile =
3017 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
3018 aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
3019 aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
3020 filename = tmpDir + filename;
3021 meshfile = tmpDir + meshfile;
3024 HDFdataset* aDataset;
3025 HDFgroup* aTopGroup;
3027 HDFgroup* aSubGroup;
3028 HDFgroup* aSubSubGroup;
3029 hdf_size aSize[ 1 ];
3032 //Remove the files if they exist: BugID: 11225
3033 #ifndef WIN32 /* unix functionality */
3034 TCollection_AsciiString cmd("rm -f \"");
3036 TCollection_AsciiString cmd("del /F \"");
3043 system(cmd.ToCString());
3045 // MED writer to be used by storage process
3046 DriverMED_W_SMESHDS_Mesh myWriter;
3047 myWriter.SetFile( meshfile.ToCString() );
3050 // SetStoreName() to groups before storing hypotheses to let them refer to
3051 // groups using "store name", which is "Group <group_persistent_id>"
3053 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
3054 for ( ; itBig->More(); itBig->Next() ) {
3055 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3056 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3057 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3058 if ( !CORBA::is_nil( anObject ) ) {
3059 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3060 if ( !myMesh->_is_nil() ) {
3061 myMesh->Load(); // load from study file if not yet done
3062 TPythonDump pd; // not to dump GetGroups()
3063 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
3064 pd << ""; // to avoid optimizing pd out
3065 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
3067 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
3070 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
3071 int anId = myStudyContext->findId( string( objStr.in() ) );
3073 sprintf( grpName, "Group %d", anId );
3074 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
3075 aGrpBaseDS->SetStoreName( grpName );
3085 // ---> create HDF file
3086 aFile = new HDFfile( (char*) filename.ToCString() );
3087 aFile->CreateOnDisk();
3089 // --> iterator for top-level objects
3090 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
3091 for ( ; itBig->More(); itBig->Next() ) {
3092 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3094 // --> hypotheses root branch (only one for the study)
3095 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
3096 // create hypotheses root HDF group
3097 aTopGroup = new HDFgroup( "Hypotheses", aFile );
3098 aTopGroup->CreateOnDisk();
3100 // iterator for all hypotheses
3101 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
3102 for ( ; it->More(); it->Next() ) {
3103 SALOMEDS::SObject_wrap mySObject = it->Value();
3104 CORBA::Object_var anObject = SObjectToObject( mySObject );
3105 if ( !CORBA::is_nil( anObject ) ) {
3106 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3107 if ( !myHyp->_is_nil() ) {
3108 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3110 string hypname = string( myHyp->GetName() );
3111 string libname = string( myHyp->GetLibName() );
3113 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3114 // WIN32 and ".so" for X-system) must be deleted
3115 int libname_len = libname.length();
3117 if( libname_len > 4 )
3118 libname.resize( libname_len - 4 );
3120 // PAL17753 (Regression: missing hypothesis in restored study)
3121 // "lib" also should be removed from the beginning
3122 //if( libname_len > 3 )
3123 //libname.resize( libname_len - 3 );
3124 if( libname_len > 6 )
3125 libname = libname.substr( 3, libname_len - 3 - 3 );
3127 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3128 int id = myStudyContext->findId( string( objStr.in() ) );
3129 string hypdata = string( myImpl->SaveTo() );
3131 // for each hypothesis create HDF group basing on its id
3132 char hypGrpName[30];
3133 sprintf( hypGrpName, "Hypothesis %d", id );
3134 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3135 aGroup->CreateOnDisk();
3136 // --> type name of hypothesis
3137 aSize[ 0 ] = hypname.length() + 1;
3138 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3139 aDataset->CreateOnDisk();
3140 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3141 aDataset->CloseOnDisk();
3142 // --> server plugin library name of hypothesis
3143 aSize[ 0 ] = libname.length() + 1;
3144 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3145 aDataset->CreateOnDisk();
3146 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3147 aDataset->CloseOnDisk();
3148 // --> persistent data of hypothesis
3149 aSize[ 0 ] = hypdata.length() + 1;
3150 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3151 aDataset->CreateOnDisk();
3152 aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
3153 aDataset->CloseOnDisk();
3154 // close hypothesis HDF group
3155 aGroup->CloseOnDisk();
3160 // close hypotheses root HDF group
3161 aTopGroup->CloseOnDisk();
3163 // --> algorithms root branch (only one for the study)
3164 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
3165 // create algorithms root HDF group
3166 aTopGroup = new HDFgroup( "Algorithms", aFile );
3167 aTopGroup->CreateOnDisk();
3169 // iterator for all algorithms
3170 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
3171 for ( ; it->More(); it->Next() ) {
3172 SALOMEDS::SObject_wrap mySObject = it->Value();
3173 CORBA::Object_var anObject = SObjectToObject( mySObject );
3174 if ( !CORBA::is_nil( anObject ) ) {
3175 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3176 if ( !myHyp->_is_nil() ) {
3177 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3179 string hypname = string( myHyp->GetName() );
3180 string libname = string( myHyp->GetLibName() );
3182 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3183 // WIN32 and ".so" for X-system) must be deleted
3184 int libname_len = libname.length();
3186 if( libname_len > 4 )
3187 libname.resize( libname_len - 4 );
3189 // PAL17753 (Regression: missing hypothesis in restored study)
3190 // "lib" also should be removed from the beginning
3191 //if( libname_len > 3 )
3192 //libname.resize( libname_len - 3 );
3193 if( libname_len > 6 )
3194 libname = libname.substr( 3, libname_len - 3 - 3 );
3196 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3197 int id = myStudyContext->findId( string( objStr.in() ) );
3198 string hypdata = string( myImpl->SaveTo() );
3200 // for each algorithm create HDF group basing on its id
3201 char hypGrpName[30];
3202 sprintf( hypGrpName, "Algorithm %d", id );
3203 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3204 aGroup->CreateOnDisk();
3205 // --> type name of algorithm
3206 aSize[0] = hypname.length() + 1;
3207 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3208 aDataset->CreateOnDisk();
3209 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3210 aDataset->CloseOnDisk();
3211 // --> server plugin library name of hypothesis
3212 aSize[0] = libname.length() + 1;
3213 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3214 aDataset->CreateOnDisk();
3215 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3216 aDataset->CloseOnDisk();
3217 // --> persistent data of algorithm
3218 aSize[0] = hypdata.length() + 1;
3219 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3220 aDataset->CreateOnDisk();
3221 aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
3222 aDataset->CloseOnDisk();
3223 // close algorithm HDF group
3224 aGroup->CloseOnDisk();
3229 // close algorithms root HDF group
3230 aTopGroup->CloseOnDisk();
3232 // --> mesh objects roots branches
3233 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3234 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3235 if ( !CORBA::is_nil( anObject ) ) {
3236 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3237 if ( !myMesh->_is_nil() ) {
3238 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
3240 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3241 int id = myStudyContext->findId( string( objStr.in() ) );
3242 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
3243 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
3244 bool hasShape = myLocMesh.HasShapeToMesh();
3246 // for each mesh open the HDF group basing on its id
3247 char meshGrpName[ 30 ];
3248 sprintf( meshGrpName, "Mesh %d", id );
3249 aTopGroup = new HDFgroup( meshGrpName, aFile );
3250 aTopGroup->CreateOnDisk();
3252 // --> put dataset to hdf file which is a flag that mesh has data
3253 string strHasData = "0";
3254 // check if the mesh is not empty
3255 if ( mySMESHDSMesh->NbNodes() > 0 ) {
3256 // write mesh data to med file
3257 myWriter.SetMesh( mySMESHDSMesh );
3258 myWriter.SetMeshId( id );
3261 aSize[ 0 ] = strHasData.length() + 1;
3262 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
3263 aDataset->CreateOnDisk();
3264 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
3265 aDataset->CloseOnDisk();
3268 // for each mesh open the HDF group basing on its auto color parameter
3269 char meshAutoColorName[ 30 ];
3270 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
3272 anAutoColor[0] = myImpl->GetAutoColor();
3274 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
3275 aDataset->CreateOnDisk();
3276 aDataset->WriteOnDisk( anAutoColor );
3277 aDataset->CloseOnDisk();
3279 // issue 0020693. Store _isModified flag
3280 int isModified = myLocMesh.GetIsModified();
3282 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
3283 aDataset->CreateOnDisk();
3284 aDataset->WriteOnDisk( &isModified );
3285 aDataset->CloseOnDisk();
3287 // issue 20918. Store Persistent Id of SMESHDS_Mesh
3288 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
3290 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
3291 aDataset->CreateOnDisk();
3292 aDataset->WriteOnDisk( &meshPersistentId );
3293 aDataset->CloseOnDisk();
3295 // write reference on a shape if exists
3296 SALOMEDS::SObject_wrap myRef;
3297 bool shapeRefFound = false;
3298 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
3300 SALOMEDS::SObject_wrap myShape;
3301 bool ok = myRef->ReferencedObject( myShape.inout() );
3303 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
3304 string myRefOnObject = myShape->GetID();
3305 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
3306 aSize[ 0 ] = myRefOnObject.length() + 1;
3307 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
3308 aDataset->CreateOnDisk();
3309 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3310 aDataset->CloseOnDisk();
3315 // write applied hypotheses if exist
3316 SALOMEDS::SObject_wrap myHypBranch;
3317 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
3318 if ( found && !shapeRefFound && hasShape) { // remove applied hyps
3319 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
3321 if ( found && (shapeRefFound || !hasShape) ) {
3322 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
3323 aGroup->CreateOnDisk();
3325 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myHypBranch );
3327 for ( ; it->More(); it->Next() ) {
3328 SALOMEDS::SObject_wrap mySObject = it->Value();
3329 SALOMEDS::SObject_wrap myRefOnHyp;
3330 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
3332 // san - it is impossible to recover applied hypotheses
3333 // using their entries within Load() method,
3334 // for there are no AttributeIORs in the study when Load() is working.
3335 // Hence, it is better to store persistent IDs of hypotheses as references to them
3337 //string myRefOnObject = myRefOnHyp->GetID();
3338 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3339 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3340 int id = myStudyContext->findId( string( objStr.in() ) );
3341 //if ( myRefOnObject.length() > 0 ) {
3342 //aSize[ 0 ] = myRefOnObject.length() + 1;
3343 char hypName[ 30 ], hypId[ 30 ];
3344 sprintf( hypName, "Hyp %d", ++hypNb );
3345 sprintf( hypId, "%d", id );
3346 aSize[ 0 ] = strlen( hypId ) + 1;
3347 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
3348 aDataset->CreateOnDisk();
3349 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3350 aDataset->WriteOnDisk( hypId );
3351 aDataset->CloseOnDisk();
3355 aGroup->CloseOnDisk();
3358 // write applied algorithms if exist
3359 SALOMEDS::SObject_wrap myAlgoBranch;
3360 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3361 myAlgoBranch.inout() );
3362 if ( found && !shapeRefFound && hasShape) { // remove applied algos
3363 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
3365 if ( found && (shapeRefFound || !hasShape)) {
3366 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3367 aGroup->CreateOnDisk();
3369 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myAlgoBranch );
3371 for ( ; it->More(); it->Next() ) {
3372 SALOMEDS::SObject_wrap mySObject = it->Value();
3373 SALOMEDS::SObject_wrap myRefOnAlgo;
3374 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
3376 // san - it is impossible to recover applied algorithms
3377 // using their entries within Load() method,
3378 // for there are no AttributeIORs in the study when Load() is working.
3379 // Hence, it is better to store persistent IDs of algorithms as references to them
3381 //string myRefOnObject = myRefOnAlgo->GetID();
3382 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3383 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3384 int id = myStudyContext->findId( string( objStr.in() ) );
3385 //if ( myRefOnObject.length() > 0 ) {
3386 //aSize[ 0 ] = myRefOnObject.length() + 1;
3387 char algoName[ 30 ], algoId[ 30 ];
3388 sprintf( algoName, "Algo %d", ++algoNb );
3389 sprintf( algoId, "%d", id );
3390 aSize[ 0 ] = strlen( algoId ) + 1;
3391 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
3392 aDataset->CreateOnDisk();
3393 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3394 aDataset->WriteOnDisk( algoId );
3395 aDataset->CloseOnDisk();
3399 aGroup->CloseOnDisk();
3402 // --> submesh objects sub-branches
3404 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
3405 SALOMEDS::SObject_wrap mySubmeshBranch;
3406 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
3408 if ( found ) // check if there is shape reference in submeshes
3410 bool hasShapeRef = false;
3411 SALOMEDS::ChildIterator_wrap itSM =
3412 myCurrentStudy->NewChildIterator( mySubmeshBranch );
3413 for ( ; itSM->More(); itSM->Next() ) {
3414 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
3415 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3416 mySubRef->ReferencedObject( myShape.inout() );
3417 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
3420 { // remove one submesh
3421 if ( shapeRefFound )
3422 { // unassign hypothesis
3423 SMESH::SMESH_subMesh_var mySubMesh =
3424 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
3425 if ( !mySubMesh->_is_nil() ) {
3426 int shapeID = mySubMesh->GetId();
3427 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
3428 const list<const SMESHDS_Hypothesis*>& hypList =
3429 mySMESHDSMesh->GetHypothesis( S );
3430 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
3431 while ( hyp != hypList.end() ) {
3432 int hypID = (*hyp++)->GetID(); // goto next hyp here because
3433 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
3437 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
3439 } // loop on submeshes of a type
3440 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
3441 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
3444 } // end check if there is shape reference in submeshes
3446 char name_meshgroup[ 30 ];
3447 if ( i == GetSubMeshOnVertexTag() )
3448 strcpy( name_meshgroup, "SubMeshes On Vertex" );
3449 else if ( i == GetSubMeshOnEdgeTag() )
3450 strcpy( name_meshgroup, "SubMeshes On Edge" );
3451 else if ( i == GetSubMeshOnWireTag() )
3452 strcpy( name_meshgroup, "SubMeshes On Wire" );
3453 else if ( i == GetSubMeshOnFaceTag() )
3454 strcpy( name_meshgroup, "SubMeshes On Face" );
3455 else if ( i == GetSubMeshOnShellTag() )
3456 strcpy( name_meshgroup, "SubMeshes On Shell" );
3457 else if ( i == GetSubMeshOnSolidTag() )
3458 strcpy( name_meshgroup, "SubMeshes On Solid" );
3459 else if ( i == GetSubMeshOnCompoundTag() )
3460 strcpy( name_meshgroup, "SubMeshes On Compound" );
3462 // for each type of submeshes create container HDF group
3463 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
3464 aGroup->CreateOnDisk();
3466 // iterator for all submeshes of given type
3467 SALOMEDS::ChildIterator_wrap itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
3468 for ( ; itSM->More(); itSM->Next() ) {
3469 SALOMEDS::SObject_wrap mySObject = itSM->Value();
3470 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
3471 if ( !CORBA::is_nil( anSubObject ))
3473 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
3474 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
3475 int subid = myStudyContext->findId( string( objStr.in() ) );
3477 // for each mesh open the HDF group basing on its id
3478 char submeshGrpName[ 30 ];
3479 sprintf( submeshGrpName, "SubMesh %d", subid );
3480 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
3481 aSubGroup->CreateOnDisk();
3483 // write reference on a shape, already checked if it exists
3484 SALOMEDS::SObject_wrap mySubRef, myShape;
3485 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3486 mySubRef->ReferencedObject( myShape.inout() );
3487 string myRefOnObject = myShape->GetID();
3488 if ( myRefOnObject.length() > 0 ) {
3489 aSize[ 0 ] = myRefOnObject.length() + 1;
3490 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
3491 aDataset->CreateOnDisk();
3492 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3493 aDataset->CloseOnDisk();
3496 // write applied hypotheses if exist
3497 SALOMEDS::SObject_wrap mySubHypBranch;
3498 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
3499 mySubHypBranch.inout() );
3501 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
3502 aSubSubGroup->CreateOnDisk();
3504 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( mySubHypBranch );
3506 for ( ; it->More(); it->Next() ) {
3507 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3508 SALOMEDS::SObject_wrap myRefOnHyp;
3509 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
3511 //string myRefOnObject = myRefOnHyp->GetID();
3512 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3513 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3514 int id = myStudyContext->findId( string( objStr.in() ) );
3515 //if ( myRefOnObject.length() > 0 ) {
3516 //aSize[ 0 ] = myRefOnObject.length() + 1;
3517 char hypName[ 30 ], hypId[ 30 ];
3518 sprintf( hypName, "Hyp %d", ++hypNb );
3519 sprintf( hypId, "%d", id );
3520 aSize[ 0 ] = strlen( hypId ) + 1;
3521 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
3522 aDataset->CreateOnDisk();
3523 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3524 aDataset->WriteOnDisk( hypId );
3525 aDataset->CloseOnDisk();
3529 aSubSubGroup->CloseOnDisk();
3532 // write applied algorithms if exist
3533 SALOMEDS::SObject_wrap mySubAlgoBranch;
3534 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3535 mySubAlgoBranch.inout() );
3537 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3538 aSubSubGroup->CreateOnDisk();
3540 SALOMEDS::ChildIterator_wrap it =
3541 myCurrentStudy->NewChildIterator( mySubAlgoBranch );
3543 for ( ; it->More(); it->Next() ) {
3544 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3545 SALOMEDS::SObject_wrap myRefOnAlgo;
3546 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
3548 //string myRefOnObject = myRefOnAlgo->GetID();
3549 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3550 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3551 int id = myStudyContext->findId( string( objStr.in() ) );
3552 //if ( myRefOnObject.length() > 0 ) {
3553 //aSize[ 0 ] = myRefOnObject.length() + 1;
3554 char algoName[ 30 ], algoId[ 30 ];
3555 sprintf( algoName, "Algo %d", ++algoNb );
3556 sprintf( algoId, "%d", id );
3557 aSize[ 0 ] = strlen( algoId ) + 1;
3558 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
3559 aDataset->CreateOnDisk();
3560 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3561 aDataset->WriteOnDisk( algoId );
3562 aDataset->CloseOnDisk();
3566 aSubSubGroup->CloseOnDisk();
3568 // close submesh HDF group
3569 aSubGroup->CloseOnDisk();
3572 // close container of submeshes by type HDF group
3573 aGroup->CloseOnDisk();
3576 // All sub-meshes will be stored in MED file
3577 // .. will NOT (PAL 12992)
3578 //if ( shapeRefFound )
3579 //myWriter.AddAllSubMeshes();
3581 // store submesh order if any
3582 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
3583 if ( theOrderIds.size() ) {
3584 char order_list[ 30 ];
3585 strcpy( order_list, "Mesh Order" );
3586 // count number of submesh ids
3588 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
3589 for ( ; idIt != theOrderIds.end(); idIt++ )
3590 nbIDs += (*idIt).size();
3591 // number of values = number of IDs +
3592 // number of lists (for separators) - 1
3593 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
3594 idIt = theOrderIds.begin();
3595 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
3596 const TListOfInt& idList = *idIt;
3597 if (idIt != theOrderIds.begin()) // not first list
3598 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
3599 // dump submesh ids from current list
3600 TListOfInt::const_iterator id_smId = idList.begin();
3601 for( ; id_smId != idList.end(); id_smId++ )
3602 smIDs[ i++ ] = *id_smId;
3605 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
3607 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
3608 aDataset->CreateOnDisk();
3609 aDataset->WriteOnDisk( smIDs );
3610 aDataset->CloseOnDisk();
3615 // groups root sub-branch
3616 SALOMEDS::SObject_wrap myGroupsBranch;
3617 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
3618 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
3620 char name_group[ 30 ];
3621 if ( i == GetNodeGroupsTag() )
3622 strcpy( name_group, "Groups of Nodes" );
3623 else if ( i == GetEdgeGroupsTag() )
3624 strcpy( name_group, "Groups of Edges" );
3625 else if ( i == GetFaceGroupsTag() )
3626 strcpy( name_group, "Groups of Faces" );
3627 else if ( i == GetVolumeGroupsTag() )
3628 strcpy( name_group, "Groups of Volumes" );
3629 else if ( i == Get0DElementsGroupsTag() )
3630 strcpy( name_group, "Groups of 0D Elements" );
3631 else if ( i == GetBallElementsGroupsTag() )
3632 strcpy( name_group, "Groups of Balls" );
3634 aGroup = new HDFgroup( name_group, aTopGroup );
3635 aGroup->CreateOnDisk();
3637 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myGroupsBranch );
3638 for ( ; it->More(); it->Next() ) {
3639 SALOMEDS::SObject_wrap mySObject = it->Value();
3640 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
3641 if ( !CORBA::is_nil( aSubObject ) ) {
3642 SMESH_GroupBase_i* myGroupImpl =
3643 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
3646 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
3650 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
3651 int anId = myStudyContext->findId( string( objStr.in() ) );
3653 // For each group, create a dataset named "Group <group_persistent_id>"
3654 // and store the group's user name into it
3655 const char* grpName = aGrpBaseDS->GetStoreName();
3656 char* aUserName = myGroupImpl->GetName();
3657 aSize[ 0 ] = strlen( aUserName ) + 1;
3659 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
3660 aDataset->CreateOnDisk();
3661 aDataset->WriteOnDisk( aUserName );
3662 aDataset->CloseOnDisk();
3665 // For each group, create a dataset named "Group <group_persistent_id> Color"
3666 // and store the group's color into it
3667 char grpColorName[ 30 ];
3668 sprintf( grpColorName, "ColorGroup %d", anId );
3669 SALOMEDS::Color aColor = myGroupImpl->GetColor();
3671 anRGB[ 0 ] = aColor.R;
3672 anRGB[ 1 ] = aColor.G;
3673 anRGB[ 2 ] = aColor.B;
3675 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
3676 aDataset->CreateOnDisk();
3677 aDataset->WriteOnDisk( anRGB );
3678 aDataset->CloseOnDisk();
3680 // Pass SMESHDS_Group to MED writer
3681 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
3683 myWriter.AddGroup( aGrpDS );
3685 // write reference on a shape if exists
3686 SMESHDS_GroupOnGeom* aGeomGrp =
3687 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
3689 SALOMEDS::SObject_wrap mySubRef, myShape;
3690 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
3691 mySubRef->ReferencedObject( myShape.inout() ) &&
3692 !CORBA::is_nil( myShape->GetObject() ))
3694 string myRefOnObject = myShape->GetID();
3695 if ( myRefOnObject.length() > 0 ) {
3696 char aRefName[ 30 ];
3697 sprintf( aRefName, "Ref on shape %d", anId);
3698 aSize[ 0 ] = myRefOnObject.length() + 1;
3699 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
3700 aDataset->CreateOnDisk();
3701 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3702 aDataset->CloseOnDisk();
3705 else // shape ref is invalid:
3707 // save a group on geometry as ordinary group
3708 myWriter.AddGroup( aGeomGrp );
3711 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
3712 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
3714 std::string str = aFilterGrp_i->FilterToString();
3715 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
3716 aSize[ 0 ] = str.length() + 1;
3717 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
3718 aDataset->CreateOnDisk();
3719 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
3720 aDataset->CloseOnDisk();
3724 aGroup->CloseOnDisk();
3728 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
3730 // Flush current mesh information into MED file
3733 // save info on nb of elements
3734 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
3736 // maybe a shape was deleted in the study
3737 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
3738 TopoDS_Shape nullShape;
3739 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
3742 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
3747 aGroup = new HDFgroup( "Submeshes", aTopGroup );
3748 aGroup->CreateOnDisk();
3750 // each element belongs to one or none submesh,
3751 // so for each node/element, we store a submesh ID
3753 // Store submesh IDs
3754 for ( int isNode = 0; isNode < 2; ++isNode )
3756 SMDS_ElemIteratorPtr eIt =
3757 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
3758 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
3761 std::vector<int> smIDs; smIDs.reserve( nbElems );
3762 while ( eIt->more() )
3763 if ( const SMDS_MeshElement* e = eIt->next())
3764 smIDs.push_back( e->getshapeId() );
3766 aSize[ 0 ] = nbElems;
3767 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3768 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3769 aDataset->CreateOnDisk();
3770 aDataset->WriteOnDisk( & smIDs[0] );
3771 aDataset->CloseOnDisk();
3774 aGroup->CloseOnDisk();
3776 // Store node positions on sub-shapes (SMDS_Position):
3777 // ----------------------------------------------------
3779 aGroup = new HDFgroup( "Node Positions", aTopGroup );
3780 aGroup->CreateOnDisk();
3782 // in aGroup, create 5 datasets to contain:
3783 // "Nodes on Edges" - ID of node on edge
3784 // "Edge positions" - U parameter on node on edge
3785 // "Nodes on Faces" - ID of node on face
3786 // "Face U positions" - U parameter of node on face
3787 // "Face V positions" - V parameter of node on face
3789 // Find out nb of nodes on edges and faces
3790 // Collect corresponding sub-meshes
3791 int nbEdgeNodes = 0, nbFaceNodes = 0;
3792 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
3793 // loop on SMESHDS_SubMesh'es
3794 while ( smIt->more() )
3796 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
3797 if ( aSubMesh->IsComplexSubmesh() )
3798 continue; // submesh containing other submeshs
3799 int nbNodes = aSubMesh->NbNodes();
3800 if ( nbNodes == 0 ) continue;
3802 int aShapeID = aSubMesh->GetID();
3803 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
3805 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
3806 // write only SMDS_FacePosition and SMDS_EdgePosition
3807 switch ( aShapeType ) {
3809 nbFaceNodes += nbNodes;
3810 aFaceSM.push_back( aSubMesh );
3813 nbEdgeNodes += nbNodes;
3814 aEdgeSM.push_back( aSubMesh );
3820 // Treat positions on edges or faces
3821 for ( int onFace = 0; onFace < 2; onFace++ )
3823 // Create arrays to store in datasets
3824 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
3825 if (!nbNodes) continue;
3826 int* aNodeIDs = new int [ nbNodes ];
3827 double* aUPos = new double [ nbNodes ];
3828 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
3831 // loop on sub-meshes
3832 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
3833 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
3834 for ( ; itSM != pListSM->end(); itSM++ )
3836 SMESHDS_SubMesh* aSubMesh = (*itSM);
3838 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
3839 // loop on nodes in aSubMesh
3840 while ( itNode->more() )
3843 const SMDS_MeshNode* node = itNode->next();
3844 aNodeIDs [ iNode ] = node->GetID();
3847 const SMDS_PositionPtr pos = node->GetPosition();
3848 if ( onFace ) { // on FACE
3849 const SMDS_FacePosition* fPos =
3850 dynamic_cast<const SMDS_FacePosition*>( pos );
3852 aUPos[ iNode ] = fPos->GetUParameter();
3853 aVPos[ iNode ] = fPos->GetVParameter();
3860 const SMDS_EdgePosition* ePos =
3861 dynamic_cast<const SMDS_EdgePosition*>( pos );
3863 aUPos[ iNode ] = ePos->GetUParameter();
3869 } // loop on nodes in aSubMesh
3870 } // loop on sub-meshes
3875 aSize[ 0 ] = nbNodes;
3877 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
3878 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3879 aDataset->CreateOnDisk();
3880 aDataset->WriteOnDisk( aNodeIDs );
3881 aDataset->CloseOnDisk();
3884 aDSName = ( onFace ? "Face U positions" : "Edge positions");
3885 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
3886 aDataset->CreateOnDisk();
3887 aDataset->WriteOnDisk( aUPos );
3888 aDataset->CloseOnDisk();
3891 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
3892 aDataset->CreateOnDisk();
3893 aDataset->WriteOnDisk( aVPos );
3894 aDataset->CloseOnDisk();
3899 if ( aVPos ) delete [] aVPos;
3901 } // treat positions on edges or faces
3903 // close "Node Positions" group
3904 aGroup->CloseOnDisk();
3906 } // if ( there are submeshes in SMESHDS_Mesh )
3909 // close mesh HDF group
3910 aTopGroup->CloseOnDisk();
3918 aFile->CloseOnDisk();
3921 // Convert temporary files to stream
3922 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
3924 // Remove temporary files and directory
3926 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
3928 return aStreamFile._retn();
3931 //=============================================================================
3933 * SMESH_Gen_i::SaveASCII
3935 * Save SMESH module's data in ASCII format
3937 //=============================================================================
3939 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
3941 bool isMultiFile ) {
3942 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
3943 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
3944 return aStreamFile._retn();
3946 //after usual saving needs to encipher binary to text string
3947 //Any binary symbol will be represent as "|xx" () hexadecimal format number
3948 int size = aStreamFile.in().length();
3949 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
3950 for ( int i = 0; i < size; i++ )
3951 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
3953 buffer[size * 3] = '\0';
3955 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
3957 return anAsciiStreamFile._retn();
3960 //=============================================================================
3962 * SMESH_Gen_i::loadGeomData
3964 * Load GEOM module data
3966 //=============================================================================
3968 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
3970 if ( theCompRoot->_is_nil() )
3973 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
3974 if ( aStudy->_is_nil() )
3977 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
3978 aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
3981 //=============================================================================
3985 * Load SMESH module's data
3987 //=============================================================================
3989 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
3990 const SALOMEDS::TMPFile& theStream,
3994 if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
3995 SetCurrentStudy( theComponent->GetStudy() );
3997 /* if( !theComponent->_is_nil() )
3999 //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
4000 if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
4001 loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
4004 StudyContext* myStudyContext = GetCurrentStudyContext();
4006 // Get temporary files location
4007 TCollection_AsciiString tmpDir =
4008 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
4010 // Convert the stream into sequence of files to process
4011 SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
4014 TCollection_AsciiString aStudyName( "" );
4015 if ( isMultiFile ) {
4016 CORBA::String_var url = myCurrentStudy->URL();
4017 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( url.in() ).c_str();
4019 // Set names of temporary files
4020 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
4021 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
4025 HDFdataset* aDataset;
4026 HDFgroup* aTopGroup;
4028 HDFgroup* aSubGroup;
4029 HDFgroup* aSubSubGroup;
4032 // ---> open HDF file
4033 aFile = new HDFfile( (char*) filename.ToCString() );
4035 aFile->OpenOnDisk( HDF_RDONLY );
4037 catch ( HDFexception ) {
4038 INFOS( "Load(): " << filename << " not found!" );
4042 TPythonDump pd; // prevent dump during loading
4044 // DriverMED_R_SMESHDS_Mesh myReader;
4045 // myReader.SetFile( meshfile.ToCString() );
4047 // For PAL13473 ("Repetitive mesh") implementation.
4048 // New dependencies between SMESH objects are established:
4049 // now hypotheses can refer to meshes, shapes and other hypotheses.
4050 // To keep data consistent, the following order of data restoration
4052 // 1. Create hypotheses
4053 // 2. Create all meshes
4054 // 3. Load hypotheses' data
4057 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
4058 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
4059 list< SMESH::Filter_var > filters;
4061 // get total number of top-level groups
4062 int aNbGroups = aFile->nInternalObjects();
4063 if ( aNbGroups > 0 ) {
4064 // --> in first turn we should read&create hypotheses
4065 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
4066 // open hypotheses root HDF group
4067 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4068 aTopGroup->OpenOnDisk();
4070 // get number of hypotheses
4071 int aNbObjects = aTopGroup->nInternalObjects();
4072 for ( int j = 0; j < aNbObjects; j++ ) {
4073 // try to identify hypothesis
4074 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4075 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4077 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
4078 // open hypothesis group
4079 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4080 aGroup->OpenOnDisk();
4082 // --> get hypothesis id
4083 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
4088 // get number of datasets
4089 int aNbSubObjects = aGroup->nInternalObjects();
4090 for ( int k = 0; k < aNbSubObjects; k++ ) {
4092 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4093 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4094 // --> get hypothesis name
4095 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4096 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4097 aDataset->OpenOnDisk();
4098 size = aDataset->GetSize();
4099 char* hypname_str = new char[ size ];
4100 aDataset->ReadFromDisk( hypname_str );
4101 hypname = string( hypname_str );
4102 delete [] hypname_str;
4103 aDataset->CloseOnDisk();
4105 // --> get hypothesis plugin library name
4106 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4107 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4108 aDataset->OpenOnDisk();
4109 size = aDataset->GetSize();
4110 char* libname_str = new char[ size ];
4111 aDataset->ReadFromDisk( libname_str );
4112 if(MYDEBUG) SCRUTE( libname_str );
4113 libname = string( libname_str );
4114 delete [] libname_str;
4115 aDataset->CloseOnDisk();
4117 // --> get hypothesis data
4118 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4119 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4120 aDataset->OpenOnDisk();
4121 size = aDataset->GetSize();
4122 char* hypdata_str = new char[ size ];
4123 aDataset->ReadFromDisk( hypdata_str );
4124 hypdata = string( hypdata_str );
4125 delete [] hypdata_str;
4126 aDataset->CloseOnDisk();
4129 // close hypothesis HDF group
4130 aGroup->CloseOnDisk();
4132 // --> restore hypothesis from data
4133 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4134 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
4135 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4136 SMESH::SMESH_Hypothesis_var myHyp;
4138 try { // protect persistence mechanism against exceptions
4139 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4142 INFOS( "Exception during hypothesis creation" );
4145 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4147 // myImpl->LoadFrom( hypdata.c_str() );
4148 hypDataList.push_back( make_pair( myImpl, hypdata ));
4149 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4150 int newId = myStudyContext->findId( iorString.in() );
4151 myStudyContext->mapOldToNew( id, newId );
4154 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4158 // close hypotheses root HDF group
4159 aTopGroup->CloseOnDisk();
4163 // --> then we should read&create algorithms
4164 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
4165 // open algorithms root HDF group
4166 aTopGroup = new HDFgroup( "Algorithms", aFile );
4167 aTopGroup->OpenOnDisk();
4169 // get number of algorithms
4170 int aNbObjects = aTopGroup->nInternalObjects();
4171 for ( int j = 0; j < aNbObjects; j++ ) {
4172 // try to identify algorithm
4173 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4174 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4176 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
4177 // open algorithm group
4178 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4179 aGroup->OpenOnDisk();
4181 // --> get algorithm id
4182 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
4187 // get number of datasets
4188 int aNbSubObjects = aGroup->nInternalObjects();
4189 for ( int k = 0; k < aNbSubObjects; k++ ) {
4191 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4192 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4193 // --> get algorithm name
4194 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4195 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4196 aDataset->OpenOnDisk();
4197 size = aDataset->GetSize();
4198 char* hypname_str = new char[ size ];
4199 aDataset->ReadFromDisk( hypname_str );
4200 hypname = string( hypname_str );
4201 delete [] hypname_str;
4202 aDataset->CloseOnDisk();
4204 // --> get algorithm plugin library name
4205 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4206 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4207 aDataset->OpenOnDisk();
4208 size = aDataset->GetSize();
4209 char* libname_str = new char[ size ];
4210 aDataset->ReadFromDisk( libname_str );
4211 if(MYDEBUG) SCRUTE( libname_str );
4212 libname = string( libname_str );
4213 delete [] libname_str;
4214 aDataset->CloseOnDisk();
4216 // --> get algorithm data
4217 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4218 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4219 aDataset->OpenOnDisk();
4220 size = aDataset->GetSize();
4221 char* hypdata_str = new char[ size ];
4222 aDataset->ReadFromDisk( hypdata_str );
4223 if(MYDEBUG) SCRUTE( hypdata_str );
4224 hypdata = string( hypdata_str );
4225 delete [] hypdata_str;
4226 aDataset->CloseOnDisk();
4229 // close algorithm HDF group
4230 aGroup->CloseOnDisk();
4232 // --> restore algorithm from data
4233 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4234 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
4235 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4236 SMESH::SMESH_Hypothesis_var myHyp;
4238 try { // protect persistence mechanism against exceptions
4239 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4242 INFOS( "Exception during hypothesis creation" );
4245 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4247 //myImpl->LoadFrom( hypdata.c_str() );
4248 hypDataList.push_back( make_pair( myImpl, hypdata ));
4249 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4250 int newId = myStudyContext->findId( iorString.in() );
4251 myStudyContext->mapOldToNew( id, newId );
4254 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4258 // close algorithms root HDF group
4259 aTopGroup->CloseOnDisk();
4263 // --> the rest groups should be meshes
4264 for ( int i = 0; i < aNbGroups; i++ ) {
4265 // identify next group
4266 char meshName[ HDF_NAME_MAX_LEN+1 ];
4267 aFile->InternalObjectIndentify( i, meshName );
4269 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
4271 int id = atoi( string( meshName ).substr( 4 ).c_str() );
4275 // open mesh HDF group
4276 aTopGroup = new HDFgroup( meshName, aFile );
4277 aTopGroup->OpenOnDisk();
4279 // get number of child HDF objects
4280 int aNbObjects = aTopGroup->nInternalObjects();
4281 if ( aNbObjects > 0 ) {
4283 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
4284 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
4285 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
4286 if ( !myNewMeshImpl )
4288 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
4290 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
4291 int newId = myStudyContext->findId( iorString.in() );
4292 myStudyContext->mapOldToNew( id, newId );
4295 // try to read and set auto color flag
4296 char aMeshAutoColorName[ 30 ];
4297 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
4298 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
4300 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
4301 aDataset->OpenOnDisk();
4302 size = aDataset->GetSize();
4303 int* anAutoColor = new int[ size ];
4304 aDataset->ReadFromDisk( anAutoColor );
4305 aDataset->CloseOnDisk();
4306 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
4307 delete [] anAutoColor;
4310 // try to read and set reference to shape
4311 GEOM::GEOM_Object_var aShapeObject;
4312 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
4313 // load mesh "Ref on shape" - it's an entry to SObject
4314 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
4315 aDataset->OpenOnDisk();
4316 size = aDataset->GetSize();
4317 char* refFromFile = new char[ size ];
4318 aDataset->ReadFromDisk( refFromFile );
4319 aDataset->CloseOnDisk();
4320 if ( strlen( refFromFile ) > 0 ) {
4321 SALOMEDS::SObject_wrap shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4323 // Make sure GEOM data are loaded first
4324 //loadGeomData( shapeSO->GetFatherComponent() );
4326 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4327 if ( !CORBA::is_nil( shapeObject ) ) {
4328 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4329 if ( !aShapeObject->_is_nil() )
4330 myNewMeshImpl->SetShape( aShapeObject );
4333 delete [] refFromFile;
4336 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
4337 if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
4339 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
4340 aDataset->OpenOnDisk();
4341 size = aDataset->GetSize();
4342 int* meshPersistentId = new int[ size ];
4343 aDataset->ReadFromDisk( meshPersistentId );
4344 aDataset->CloseOnDisk();
4345 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
4346 delete [] meshPersistentId;
4352 // As all object that can be referred by hypothesis are created,
4353 // we can restore hypothesis data
4355 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
4356 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4358 SMESH_Hypothesis_i* hyp = hyp_data->first;
4359 string & data = hyp_data->second;
4360 hyp->LoadFrom( data.c_str() );
4363 // Restore the rest mesh data
4365 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
4366 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4368 aTopGroup = meshi_group->second;
4369 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4370 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4371 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4373 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
4374 bool hasData = false;
4377 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
4378 int newId = myStudyContext->findId( iorString.in() );
4379 int id = myStudyContext->getOldId( newId );
4381 // try to find mesh data dataset
4382 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
4383 // load mesh "has data" flag
4384 aDataset = new HDFdataset( "Has data", aTopGroup );
4385 aDataset->OpenOnDisk();
4386 size = aDataset->GetSize();
4387 char* strHasData = new char[ size ];
4388 aDataset->ReadFromDisk( strHasData );
4389 aDataset->CloseOnDisk();
4390 if ( strcmp( strHasData, "1") == 0 ) {
4391 // read mesh data from MED file
4392 // myReader.SetMesh( mySMESHDSMesh );
4393 // myReader.SetMeshId( id );
4394 // myReader.Perform();
4397 delete [] strHasData;
4400 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
4401 // nodes and elements are not yet put into sub-meshes)
4402 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4403 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4404 aGroup->OpenOnDisk();
4405 // get number of applied algorithms
4406 int aNbSubObjects = aGroup->nInternalObjects();
4407 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
4408 for ( int j = 0; j < aNbSubObjects; j++ ) {
4409 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4410 aGroup->InternalObjectIndentify( j, name_dataset );
4411 // check if it is an algorithm
4412 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
4413 aDataset = new HDFdataset( name_dataset, aGroup );
4414 aDataset->OpenOnDisk();
4415 size = aDataset->GetSize();
4416 char* refFromFile = new char[ size ];
4417 aDataset->ReadFromDisk( refFromFile );
4418 aDataset->CloseOnDisk();
4419 // san - it is impossible to recover applied algorithms using their entries within Load() method
4420 //SALOMEDS::SObject_wrap hypSO = myCurrentStudy->FindObjectID( refFromFile );
4421 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4422 int id = atoi( refFromFile );
4423 delete [] refFromFile;
4424 string anIOR = myStudyContext->getIORbyOldId( id );
4425 if ( !anIOR.empty() ) {
4426 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4427 if ( !CORBA::is_nil( hypObject ) ) {
4428 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4429 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4430 || !myNewMeshImpl->HasShapeToMesh()) )
4431 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4436 aGroup->CloseOnDisk();
4439 // try to get applied hypotheses
4440 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4441 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4442 aGroup->OpenOnDisk();
4443 // get number of applied hypotheses
4444 int aNbSubObjects = aGroup->nInternalObjects();
4445 for ( int j = 0; j < aNbSubObjects; j++ ) {
4446 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4447 aGroup->InternalObjectIndentify( j, name_dataset );
4448 // check if it is a hypothesis
4449 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4450 aDataset = new HDFdataset( name_dataset, aGroup );
4451 aDataset->OpenOnDisk();
4452 size = aDataset->GetSize();
4453 char* refFromFile = new char[ size ];
4454 aDataset->ReadFromDisk( refFromFile );
4455 aDataset->CloseOnDisk();
4456 // san - it is impossible to recover applied hypotheses using their entries within Load() method
4457 //SALOMEDS::SObject_wrap hypSO = myCurrentStudy->FindObjectID( refFromFile );
4458 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4459 int id = atoi( refFromFile );
4460 delete [] refFromFile;
4461 string anIOR = myStudyContext->getIORbyOldId( id );
4462 if ( !anIOR.empty() ) {
4463 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4464 if ( !CORBA::is_nil( hypObject ) ) {
4465 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4466 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4467 || !myNewMeshImpl->HasShapeToMesh()) )
4468 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4473 aGroup->CloseOnDisk();
4476 // --> try to find SUB-MESHES containers for each type of submesh
4477 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
4478 const char* name_meshgroup = 0;
4479 if ( j == GetSubMeshOnVertexTag() )
4480 name_meshgroup = "SubMeshes On Vertex";
4481 else if ( j == GetSubMeshOnEdgeTag() )
4482 name_meshgroup = "SubMeshes On Edge";
4483 else if ( j == GetSubMeshOnWireTag() )
4484 name_meshgroup = "SubMeshes On Wire";
4485 else if ( j == GetSubMeshOnFaceTag() )
4486 name_meshgroup = "SubMeshes On Face";
4487 else if ( j == GetSubMeshOnShellTag() )
4488 name_meshgroup = "SubMeshes On Shell";
4489 else if ( j == GetSubMeshOnSolidTag() )
4490 name_meshgroup = "SubMeshes On Solid";
4491 else if ( j == GetSubMeshOnCompoundTag() )
4492 name_meshgroup = "SubMeshes On Compound";
4494 // try to get submeshes container HDF group
4495 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
4496 // open submeshes containers HDF group
4497 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4498 aGroup->OpenOnDisk();
4500 // get number of submeshes
4501 int aNbSubMeshes = aGroup->nInternalObjects();
4502 for ( int k = 0; k < aNbSubMeshes; k++ ) {
4504 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
4505 aGroup->InternalObjectIndentify( k, name_submeshgroup );
4506 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
4507 // --> get submesh id
4508 int subid = atoi( name_submeshgroup + 7 );
4511 // open submesh HDF group
4512 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
4513 aSubGroup->OpenOnDisk();
4515 // try to read and set reference to subshape
4516 GEOM::GEOM_Object_var aSubShapeObject;
4517 SMESH::SMESH_subMesh_var aSubMesh;
4519 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
4520 // load submesh "Ref on shape" - it's an entry to SObject
4521 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
4522 aDataset->OpenOnDisk();
4523 size = aDataset->GetSize();
4524 char* refFromFile = new char[ size ];
4525 aDataset->ReadFromDisk( refFromFile );
4526 aDataset->CloseOnDisk();
4527 if ( strlen( refFromFile ) > 0 ) {
4528 SALOMEDS::SObject_wrap subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
4529 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
4530 if ( !CORBA::is_nil( subShapeObject ) ) {
4531 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
4532 if ( !aSubShapeObject->_is_nil() )
4533 aSubMesh = SMESH::SMESH_subMesh::_duplicate
4534 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
4535 if ( aSubMesh->_is_nil() )
4537 string iorSubString = GetORB()->object_to_string( aSubMesh );
4538 int newSubId = myStudyContext->findId( iorSubString );
4539 myStudyContext->mapOldToNew( subid, newSubId );
4544 if ( aSubMesh->_is_nil() )
4547 // try to get applied algorithms
4548 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4549 // open "applied algorithms" HDF group
4550 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4551 aSubSubGroup->OpenOnDisk();
4552 // get number of applied algorithms
4553 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4554 for ( int l = 0; l < aNbSubObjects; l++ ) {
4555 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4556 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4557 // check if it is an algorithm
4558 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
4559 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4560 aDataset->OpenOnDisk();
4561 size = aDataset->GetSize();
4562 char* refFromFile = new char[ size ];
4563 aDataset->ReadFromDisk( refFromFile );
4564 aDataset->CloseOnDisk();
4566 int id = atoi( refFromFile );
4567 string anIOR = myStudyContext->getIORbyOldId( id );
4568 if ( !anIOR.empty() ) {
4569 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4570 if ( !CORBA::is_nil( hypObject ) ) {
4571 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4572 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4573 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4578 // close "applied algorithms" HDF group
4579 aSubSubGroup->CloseOnDisk();
4582 // try to get applied hypotheses
4583 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4584 // open "applied hypotheses" HDF group
4585 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4586 aSubSubGroup->OpenOnDisk();
4587 // get number of applied hypotheses
4588 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4589 for ( int l = 0; l < aNbSubObjects; l++ ) {
4590 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4591 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4592 // check if it is a hypothesis
4593 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4594 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4595 aDataset->OpenOnDisk();
4596 size = aDataset->GetSize();
4597 char* refFromFile = new char[ size ];
4598 aDataset->ReadFromDisk( refFromFile );
4599 aDataset->CloseOnDisk();
4601 int id = atoi( refFromFile );
4602 string anIOR = myStudyContext->getIORbyOldId( id );
4603 if ( !anIOR.empty() ) {
4604 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4605 if ( !CORBA::is_nil( hypObject ) ) {
4606 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4607 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4608 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4613 // close "APPLIED HYPOTHESES" hdf group
4614 aSubSubGroup->CloseOnDisk();
4617 // close SUB-MESH hdf group
4618 aSubGroup->CloseOnDisk();
4621 // close SUB-MESHES containers hdf group
4622 aGroup->CloseOnDisk();
4626 // try to get GROUPS
4627 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
4628 char name_group[ 30 ];
4629 if ( ii == GetNodeGroupsTag() )
4630 strcpy( name_group, "Groups of Nodes" );
4631 else if ( ii == GetEdgeGroupsTag() )
4632 strcpy( name_group, "Groups of Edges" );
4633 else if ( ii == GetFaceGroupsTag() )
4634 strcpy( name_group, "Groups of Faces" );
4635 else if ( ii == GetVolumeGroupsTag() )
4636 strcpy( name_group, "Groups of Volumes" );
4637 else if ( ii == Get0DElementsGroupsTag() )
4638 strcpy( name_group, "Groups of 0D Elements" );
4639 else if ( ii == GetBallElementsGroupsTag() )
4640 strcpy( name_group, "Groups of Balls" );
4642 if ( aTopGroup->ExistInternalObject( name_group ) ) {
4643 aGroup = new HDFgroup( name_group, aTopGroup );
4644 aGroup->OpenOnDisk();
4645 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
4646 // within aGroup->ExistInternalObject( name )
4647 std::vector< std::string > subNames;
4648 TColStd_MapOfAsciiString mapOfNames;
4649 aGroup->GetAllObjects( subNames );
4650 for ( size_t iN = 0; iN < subNames.size(); ++iN )
4651 mapOfNames.Add( subNames[ iN ].c_str() );
4653 for ( size_t j = 0; j < subNames.size(); j++ ) {
4654 const std::string& name_dataset = subNames[ j ];
4655 // check if it is a group
4656 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
4658 int subid = atoi( name_dataset.substr( 5 ).c_str() );
4661 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
4662 aDataset->OpenOnDisk();
4664 // Retrieve actual group name
4665 size = aDataset->GetSize();
4666 char* nameFromFile = new char[ size ];
4667 aDataset->ReadFromDisk( nameFromFile );
4668 aDataset->CloseOnDisk();
4670 // Try to find a shape reference
4671 TopoDS_Shape aShape;
4672 char aRefName[ 30 ];
4673 sprintf( aRefName, "Ref on shape %d", subid);
4674 if ( mapOfNames.Contains( aRefName ))
4676 // load mesh "Ref on shape" - it's an entry to SObject
4677 aDataset = new HDFdataset( aRefName, aGroup );
4678 aDataset->OpenOnDisk();
4679 size = aDataset->GetSize();
4680 char* refFromFile = new char[ size ];
4681 aDataset->ReadFromDisk( refFromFile );
4682 aDataset->CloseOnDisk();
4683 if ( strlen( refFromFile ) > 0 ) {
4684 SALOMEDS::SObject_wrap shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4685 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4686 if ( !CORBA::is_nil( shapeObject ) ) {
4687 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4688 if ( !aShapeObject->_is_nil() )
4689 aShape = GeomObjectToShape( aShapeObject );
4693 // Try to read a filter of SMESH_GroupOnFilter
4694 SMESH::Filter_var filter;
4695 SMESH_PredicatePtr predicate;
4696 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
4697 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
4699 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
4700 aDataset->OpenOnDisk();
4701 size = aDataset->GetSize();
4702 char* persistStr = new char[ size ];
4703 aDataset->ReadFromDisk( persistStr );
4704 aDataset->CloseOnDisk();
4705 if ( strlen( persistStr ) > 0 ) {
4706 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
4707 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
4708 filters.push_back( filter );
4712 // Create group servant
4713 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
4714 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
4715 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape, predicate ) );
4716 // Obtain a SMESHDS_Group object
4717 if ( aNewGroup->_is_nil() )
4720 string iorSubString = GetORB()->object_to_string( aNewGroup );
4721 int newSubId = myStudyContext->findId( iorSubString );
4722 myStudyContext->mapOldToNew( subid, newSubId );
4724 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
4728 if ( SMESH_GroupOnFilter_i* aFilterGroup =
4729 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
4731 aFilterGroup->SetFilter( filter );
4732 filter->UnRegister();
4734 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
4735 if ( !aGroupBaseDS )
4738 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
4741 // Read color of the group
4742 char aGroupColorName[ 30 ];
4743 sprintf( aGroupColorName, "ColorGroup %d", subid);
4744 if ( mapOfNames.Contains( aGroupColorName ))
4746 aDataset = new HDFdataset( aGroupColorName, aGroup );
4747 aDataset->OpenOnDisk();
4748 size = aDataset->GetSize();
4749 double* anRGB = new double[ size ];
4750 aDataset->ReadFromDisk( anRGB );
4751 aDataset->CloseOnDisk();
4752 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
4753 aGroupBaseDS->SetColor( aColor );
4757 aGroup->CloseOnDisk();
4761 // instead of reading mesh data, we read only brief information of all
4762 // objects: mesh, groups, sub-meshes (issue 0021208 )
4765 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, id,
4766 meshfile.ToCString(), filename.ToCString(),
4770 // read Sub-Mesh ORDER if any
4771 if( aTopGroup->ExistInternalObject( "Mesh Order" ) ) {
4772 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
4773 aDataset->OpenOnDisk();
4774 size = aDataset->GetSize();
4775 int* smIDs = new int[ size ];
4776 aDataset->ReadFromDisk( smIDs );
4777 aDataset->CloseOnDisk();
4778 TListOfListOfInt anOrderIds;
4779 anOrderIds.push_back( TListOfInt() );
4780 for ( int i = 0; i < size; i++ )
4781 if ( smIDs[ i ] < 0 ) // is separator
4782 anOrderIds.push_back( TListOfInt() );
4784 anOrderIds.back().push_back(smIDs[ i ]);
4786 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
4790 // update hyps needing full mesh data restored (issue 20918)
4791 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4793 SMESH_Hypothesis_i* hyp = hyp_data->first;
4794 hyp->UpdateAsMeshesRestored();
4797 // notify algos on completed restoration to set sub-mesh event listeners
4798 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4800 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4801 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4803 TopoDS_Shape myLocShape;
4804 if(myLocMesh.HasShapeToMesh())
4805 myLocShape = myLocMesh.GetShapeToMesh();
4807 myLocShape = SMESH_Mesh::PseudoShape();
4809 myLocMesh.GetSubMesh(myLocShape)->
4810 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
4813 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
4814 list< SMESH::Filter_var >::iterator f = filters.begin();
4815 for ( ; f != filters.end(); ++f )
4816 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
4817 fi->FindBaseObjects();
4822 aTopGroup->CloseOnDisk();
4825 aFile->CloseOnDisk();
4828 // Remove temporary files created from the stream
4831 SMESH_File meshFile( meshfile.ToCString() );
4832 if ( !meshFile ) // no meshfile exists
4834 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
4838 Engines::Container_var container = GetContainerRef();
4839 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
4841 container_i->registerTemporaryFile( filename.ToCString() );
4842 container_i->registerTemporaryFile( meshfile.ToCString() );
4843 container_i->registerTemporaryFile( tmpDir.ToCString() );
4847 pd << ""; // prevent optimizing pd out
4849 // creation of tree nodes for all data objects in the study
4850 // to support tree representation customization and drag-n-drop:
4851 SALOMEDS::Study_var study = theComponent->GetStudy();
4852 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = study->GetUseCaseBuilder();
4853 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
4854 useCaseBuilder->SetRootCurrent();
4855 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
4856 SALOMEDS::ChildIterator_wrap it = study->NewChildIterator( theComponent );
4857 for (it->InitEx(true); it->More(); it->Next()) {
4858 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
4865 //=============================================================================
4867 * SMESH_Gen_i::LoadASCII
4869 * Load SMESH module's data in ASCII format
4871 //=============================================================================
4873 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
4874 const SALOMEDS::TMPFile& theStream,
4876 bool isMultiFile ) {
4877 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
4878 return Load( theComponent, theStream, theURL, isMultiFile );
4880 //before call main ::Load method it's need for decipher text format to
4881 //binary ( "|xx" => x' )
4882 int size = theStream.length();
4883 if ( int((size / 3 )*3) != size ) //error size of buffer
4886 int real_size = int(size / 3);
4888 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
4891 unsigned int c = -1;
4892 for ( int i = 0; i < real_size; i++ )
4894 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
4895 sscanf( tmp, "%x", &c );
4896 sprintf( (char*)&(buffer[i]), "%c", (char)c );
4899 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
4901 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
4904 //=============================================================================
4906 * SMESH_Gen_i::Close
4908 * Clears study-connected data when it is closed
4910 //=============================================================================
4912 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
4914 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
4916 // set correct current study
4917 SALOMEDS::Study_var study = theComponent->GetStudy();
4918 if ( study->StudyId() != GetCurrentStudyID())
4919 setCurrentStudy( study, /*IsBeingClosed=*/true );
4921 // Clear study contexts data
4922 int studyId = GetCurrentStudyID();
4923 if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
4924 delete myStudyContextMap[ studyId ];
4925 myStudyContextMap.erase( studyId );
4928 // remove the tmp files meshes are loaded from
4929 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
4931 myCurrentStudy = SALOMEDS::Study::_nil();
4935 //=============================================================================
4937 * SMESH_Gen_i::ComponentDataType
4939 * Get component data type
4941 //=============================================================================
4943 char* SMESH_Gen_i::ComponentDataType()
4945 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
4946 return CORBA::string_dup( "SMESH" );
4950 //=============================================================================
4952 * SMESH_Gen_i::IORToLocalPersistentID
4954 * Transform data from transient form to persistent
4956 //=============================================================================
4958 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
4959 const char* IORString,
4960 CORBA::Boolean /*isMultiFile*/,
4961 CORBA::Boolean /*isASCII*/ )
4963 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
4964 StudyContext* myStudyContext = GetCurrentStudyContext();
4966 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
4967 int anId = myStudyContext->findId( IORString );
4969 if(MYDEBUG) MESSAGE( "VSR " << anId )
4971 sprintf( strId, "%d", anId );
4972 return CORBA::string_dup( strId );
4975 return CORBA::string_dup( "" );
4978 //=============================================================================
4980 * SMESH_Gen_i::LocalPersistentIDToIOR
4982 * Transform data from persistent form to transient
4984 //=============================================================================
4986 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
4987 const char* aLocalPersistentID,
4988 CORBA::Boolean /*isMultiFile*/,
4989 CORBA::Boolean /*isASCII*/ )
4991 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
4992 StudyContext* myStudyContext = GetCurrentStudyContext();
4994 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
4995 int anId = atoi( aLocalPersistentID );
4996 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
4998 return CORBA::string_dup( "" );
5001 //=======================================================================
5002 //function : RegisterObject
5004 //=======================================================================
5006 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
5008 StudyContext* myStudyContext = GetCurrentStudyContext();
5009 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5010 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
5011 return myStudyContext->addObject( string( iorString.in() ) );
5016 //================================================================================
5018 * \brief Return id of registered object
5019 * \param theObject - the Object
5020 * \retval int - Object id
5022 //================================================================================
5024 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
5026 StudyContext* myStudyContext = GetCurrentStudyContext();
5027 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5028 string iorString = GetORB()->object_to_string( theObject );
5029 return myStudyContext->findId( iorString );
5034 //=============================================================================
5036 * SMESH_Gen_i::SetName
5038 * Set a new object name
5040 //=============================================================================
5041 void SMESH_Gen_i::SetName(const char* theIOR,
5042 const char* theName)
5044 if ( theIOR && strcmp( theIOR, "" ) ) {
5045 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
5046 SALOMEDS::SObject_wrap aSO = ObjectToSObject( myCurrentStudy, anObject );
5047 if ( !aSO->_is_nil() ) {
5048 SetName( aSO, theName );
5053 int SMESH_Gen_i::GetCurrentStudyID()
5055 return myCurrentStudy->_is_nil() || myCurrentStudy->_non_existent() ? -1 : myCurrentStudy->StudyId();
5058 // Version information
5059 char* SMESH_Gen_i::getVersion()
5061 #if SMESH_DEVELOPMENT
5062 return CORBA::string_dup(SMESH_VERSION_STR"dev");
5064 return CORBA::string_dup(SMESH_VERSION_STR);
5068 //=================================================================================
5069 // function : Move()
5070 // purpose : Moves objects to the specified position.
5071 // Is used in the drag-n-drop functionality.
5072 //=================================================================================
5073 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
5074 SALOMEDS::SObject_ptr where,
5077 if ( CORBA::is_nil( where ) ) return;
5079 SALOMEDS::Study_var study = where->GetStudy();
5080 SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder();
5081 SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder();
5082 SALOMEDS::SComponent_var father = where->GetFatherComponent();
5083 std::string dataType = father->ComponentDataType();
5084 if ( dataType != "SMESH" ) return; // not a SMESH component
5086 SALOMEDS::SObject_var objAfter;
5087 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
5088 // insert at given row -> find insertion position
5089 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
5091 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
5092 if ( i == row && useCaseIt->More() ) {
5093 objAfter = useCaseIt->Value();
5097 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
5098 SALOMEDS::SObject_var sobj = what[i];
5099 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
5100 // insert the object to the use case tree
5101 if ( !CORBA::is_nil( objAfter ) )
5102 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
5104 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
5107 //================================================================================
5109 * \brief Returns true if algorithm can be used to mesh a given geometry
5110 * \param [in] theAlgoType - the algorithm type
5111 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
5112 * \param [in] theGeomObject - the geometry to mesh
5113 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
5114 * else, returns \c True if at least one shape is meshable
5115 * \return CORBA::Boolean - can or can't
5117 //================================================================================
5119 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
5120 const char* theLibName,
5121 GEOM::GEOM_Object_ptr theGeomObject,
5122 CORBA::Boolean toCheckAll)
5126 std::string aPlatformLibName;
5127 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
5128 GenericHypothesisCreator_i* aCreator =
5129 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
5132 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
5133 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll );
5140 SMESH_CATCH( SMESH::doNothing );
5143 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
5148 //=================================================================================
5149 // function : GetInsideSphere
5150 // purpose : Collect indices of elements, which are located inside the sphere
5151 //=================================================================================
5152 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
5153 SMESH::ElementType theElemType,
5159 SMESH::long_array_var aResult = new SMESH::long_array();
5160 if ( meshPart->_is_nil() )
5161 return aResult._retn();
5163 // 1. Create geometrical object
5164 gp_Pnt aP( theX, theY, theZ );
5165 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
5167 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5169 if ( lst.size() > 0 ) {
5170 aResult->length( lst.size() );
5171 for ( size_t i = 0; i < lst.size(); i++ ) {
5172 aResult[i] = lst[i];
5175 return aResult._retn();
5178 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
5179 SMESH::ElementType theElemType,
5180 CORBA::Double theX1,
5181 CORBA::Double theY1,
5182 CORBA::Double theZ1,
5183 CORBA::Double theX2,
5184 CORBA::Double theY2,
5185 CORBA::Double theZ2) {
5186 SMESH::long_array_var aResult = new SMESH::long_array();
5187 if( meshPart->_is_nil() )
5188 return aResult._retn();
5190 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
5192 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5194 if( lst.size() > 0 ) {
5195 aResult->length( lst.size() );
5196 for ( size_t i = 0; i < lst.size(); i++ ) {
5197 aResult[i] = lst[i];
5200 return aResult._retn();
5203 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
5204 SMESH::ElementType theElemType,
5208 CORBA::Double theDX,
5209 CORBA::Double theDY,
5210 CORBA::Double theDZ,
5212 CORBA::Double theR ){
5213 SMESH::long_array_var aResult = new SMESH::long_array();
5214 if( meshPart->_is_nil() )
5215 return aResult._retn();
5217 gp_Pnt aP( theX, theY, theZ );
5218 gp_Vec aV( theDX, theDY, theDZ );
5219 gp_Ax2 anAxes (aP, aV);
5221 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
5223 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5225 if( lst.size() > 0 ) {
5226 aResult->length( lst.size() );
5227 for ( size_t i = 0; i < lst.size(); i++ ) {
5228 aResult[i] = lst[i];
5231 return aResult._retn();
5234 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5235 SMESH::ElementType theElemType,
5236 GEOM::GEOM_Object_ptr theGeom,
5237 CORBA::Double theTolerance ) {
5238 SMESH::long_array_var aResult = new SMESH::long_array();
5239 if( meshPart->_is_nil() || theGeom->_is_nil() )
5240 return aResult._retn();
5242 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
5244 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
5246 if( lst.size() > 0 ) {
5247 aResult->length( lst.size() );
5248 for ( size_t i = 0; i < lst.size(); i++ ) {
5249 aResult[i] = lst[i];
5252 return aResult._retn();
5257 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5258 SMESH::ElementType theElemType,
5259 TopoDS_Shape& aShape,
5260 double* theTolerance) {
5262 std::vector<long> res;
5263 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
5265 if ( mesh->_is_nil() )
5268 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
5272 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
5277 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
5278 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
5279 anElementsOnShape->SetAllNodes( true );
5280 anElementsOnShape->SetMesh( meshDS );
5281 anElementsOnShape->SetShape( aShape, aType );
5284 anElementsOnShape->SetTolerance(*theTolerance);
5286 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
5287 if ( !msource->_is_nil() ) { // Mesh case
5288 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
5290 while ( elemIt->more() ) {
5291 const SMDS_MeshElement* anElem = elemIt->next();
5292 long anId = anElem->GetID();
5293 if ( anElementsOnShape->IsSatisfy( anId ) )
5294 res.push_back( anId );
5298 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
5299 if ( !gsource->_is_nil() ) {
5300 if(theElemType == SMESH::NODE) {
5301 SMESH::long_array_var nodes = gsource->GetNodeIDs();
5302 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
5303 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
5304 long anId = node->GetID();
5305 if ( anElementsOnShape->IsSatisfy( anId ) )
5306 res.push_back( anId );
5309 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
5310 SMESH::long_array_var elems = gsource->GetListOfID();
5311 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
5312 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
5313 long anId = elem->GetID();
5314 if ( anElementsOnShape->IsSatisfy( anId ) )
5315 res.push_back( anId );
5320 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
5321 if ( !smsource->_is_nil() ) {
5322 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
5323 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
5324 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
5326 long anId = elem->GetID();
5327 if ( anElementsOnShape->IsSatisfy( anId ) )
5328 res.push_back( anId );
5336 //=============================================================================
5338 * SMESHEngine_factory
5340 * C factory, accessible with dlsym, after dlopen
5342 //=============================================================================
5346 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
5347 PortableServer::POA_ptr poa,
5348 PortableServer::ObjectId* contId,
5349 const char* instanceName,
5350 const char* interfaceName )
5352 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
5353 if(MYDEBUG) SCRUTE(interfaceName);
5354 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
5355 return aSMESHGen->getId() ;