1 // Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_Gen_i.cxx
23 // Author : Paul RASCLE, EDF
27 #include <TopExp_Explorer.hxx>
29 #include <TopoDS_Iterator.hxx>
30 #include <TopoDS_Compound.hxx>
31 #include <TopoDS_CompSolid.hxx>
32 #include <TopoDS_Solid.hxx>
33 #include <TopoDS_Shell.hxx>
34 #include <TopoDS_Face.hxx>
35 #include <TopoDS_Wire.hxx>
36 #include <TopoDS_Edge.hxx>
37 #include <TopoDS_Vertex.hxx>
38 #include <TopoDS_Shape.hxx>
39 #include <TopTools_MapOfShape.hxx>
40 #include <TopTools_IndexedMapOfShape.hxx>
41 #include <TopTools_ListOfShape.hxx>
42 #include <TopTools_ListIteratorOfListOfShape.hxx>
44 #include <BRep_Tool.hxx>
45 #include <TCollection_AsciiString.hxx>
47 #include <BRepPrimAPI_MakeSphere.hxx>
48 #include <BRepPrimAPI_MakeCylinder.hxx>
49 #include <BRepPrimAPI_MakeBox.hxx>
60 #define LibHandle HMODULE
61 #define LoadLib( name ) LoadLibrary( name )
62 #define GetProc GetProcAddress
63 #define UnLoadLib( handle ) FreeLibrary( handle );
65 #define LibHandle void*
66 #define LoadLib( name ) dlopen( name, RTLD_LAZY )
68 #define UnLoadLib( handle ) dlclose( handle );
71 #include "SMESH_Gen_i.hxx"
72 #include "SMESH_version.h"
74 #include "DriverMED_W_SMESHDS_Mesh.h"
75 #include "DriverMED_R_SMESHDS_Mesh.h"
77 #include "DriverCGNS_Read.hxx"
79 #include "MED_Factory.hxx"
80 #include "SMDS_EdgePosition.hxx"
81 #include "SMDS_FacePosition.hxx"
82 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
83 #include "SMDS_SetIterator.hxx"
84 #include "SMDS_SpacePosition.hxx"
85 #include "SMDS_VertexPosition.hxx"
86 #include "SMESHDS_Document.hxx"
87 #include "SMESHDS_Group.hxx"
88 #include "SMESHDS_GroupOnGeom.hxx"
89 #include "SMESH_Algo_i.hxx"
90 #include "SMESH_File.hxx"
91 #include "SMESH_Group.hxx"
92 #include "SMESH_Group_i.hxx"
93 #include "SMESH_Hypothesis.hxx"
94 #include "SMESH_Hypothesis_i.hxx"
95 #include "SMESH_Mesh.hxx"
96 #include "SMESH_MeshEditor.hxx"
97 #include "SMESH_Mesh_i.hxx"
98 #include "SMESH_PreMeshInfo.hxx"
99 #include "SMESH_PythonDump.hxx"
100 #include "SMESH_ControlsDef.hxx"
101 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
103 #include CORBA_SERVER_HEADER(SMESH_Group)
104 #include CORBA_SERVER_HEADER(SMESH_Filter)
105 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
108 #include <GEOM_Client.hxx>
110 #include <Basics_Utils.hxx>
111 #include <Basics_DirUtils.hxx>
113 #include <OpUtil.hxx>
114 #include <SALOMEDS_Tool.hxx>
115 #include <SALOME_Container_i.hxx>
116 #include <SALOME_LifeCycleCORBA.hxx>
117 #include <SALOME_NamingService.hxx>
118 #include <Utils_CorbaException.hxx>
119 #include <Utils_ExceptHandlers.hxx>
120 #include <Utils_SINGLETON.hxx>
121 #include <utilities.h>
123 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
124 #include CORBA_CLIENT_HEADER(SALOME_Session)
126 // helpers about SALOME::GenericObj
127 #include <SALOMEDS_wrap.hxx>
128 #include <SALOMEDS_Attributes_wrap.hxx>
129 #include <GEOM_wrap.hxx>
137 using SMESH::TPythonDump;
140 #define NUM_TMP_FILES 2
143 static int MYDEBUG = 0;
145 static int MYDEBUG = 0;
148 // Static variables definition
149 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
150 CORBA::ORB_var SMESH_Gen_i::myOrb;
151 PortableServer::POA_var SMESH_Gen_i::myPoa;
152 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
153 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
154 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
157 const int nbElemPerDiagonal = 10;
159 //=============================================================================
161 * GetServant [ static ]
163 * Get servant of the CORBA object
165 //=============================================================================
167 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
169 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
172 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
176 INFOS( "GetServant - Unknown exception was caught!!!" );
181 //=============================================================================
183 * SObjectToObject [ static ]
185 * Get CORBA object corresponding to the SALOMEDS::SObject
187 //=============================================================================
189 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
191 SALOMEDS::GenericAttribute_wrap anAttr;
192 CORBA::Object_var anObj;
193 if ( !theSObject->_is_nil() ) {
195 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
196 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
197 CORBA::String_var aValue = anIOR->Value();
198 if( strcmp( aValue, "" ) != 0 )
199 anObj = GetORB()->string_to_object( aValue );
203 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
209 //=============================================================================
213 * Get SALOME_NamingService object
215 //=============================================================================
217 SALOME_NamingService* SMESH_Gen_i::GetNS()
219 if ( myNS == NULL ) {
220 myNS = SINGLETON_<SALOME_NamingService>::Instance();
221 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
222 myNS->init_orb( GetORB() );
227 //=============================================================================
231 * Get SALOME_LifeCycleCORBA object
233 //=============================================================================
234 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC() {
235 if ( myLCC == NULL ) {
236 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
242 //=============================================================================
244 * GetGeomEngine [ static ]
246 * Get GEOM::GEOM_Gen reference
248 //=============================================================================
249 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine() {
250 //CCRT GEOM::GEOM_Gen_var aGeomEngine =
251 //CCRT GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
252 //CCRT return aGeomEngine._retn();
253 if(CORBA::is_nil(myGeomGen))
255 Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
256 myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
261 //=============================================================================
263 * SMESH_Gen_i::SMESH_Gen_i
265 * Default constructor: not for use
267 //=============================================================================
269 SMESH_Gen_i::SMESH_Gen_i()
273 //=============================================================================
275 * SMESH_Gen_i::SMESH_Gen_i
277 * Standard constructor, used with Container
279 //=============================================================================
281 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
282 PortableServer::POA_ptr poa,
283 PortableServer::ObjectId* contId,
284 const char* instanceName,
285 const char* interfaceName )
286 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
288 MESSAGE( "SMESH_Gen_i::SMESH_Gen_i : standard constructor" );
290 myOrb = CORBA::ORB::_duplicate(orb);
291 myPoa = PortableServer::POA::_duplicate(poa);
294 _id = myPoa->activate_object( _thisObj );
296 myIsEmbeddedMode = false;
297 myShapeReader = NULL; // shape reader
299 myIsHistoricalPythonDump = true;
300 myToForgetMeshDataOnHypModif = false;
302 // set it in standalone mode only
303 //OSD::SetSignal( true );
305 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
306 // find out mode (embedded or standalone) here else
307 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
308 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
309 if ( SALOME_NamingService* ns = GetNS() )
311 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
312 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
313 if ( !session->_is_nil() )
315 CORBA::String_var str_host = session->getHostname();
316 CORBA::Long s_pid = session->getPID();
317 string my_host = Kernel_Utils::GetHostname();
319 long my_pid = (long)_getpid();
321 long my_pid = (long) getpid();
323 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
328 //=============================================================================
330 * SMESH_Gen_i::~SMESH_Gen_i
334 //=============================================================================
336 SMESH_Gen_i::~SMESH_Gen_i()
338 MESSAGE( "SMESH_Gen_i::~SMESH_Gen_i" );
340 // delete hypothesis creators
341 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
342 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
344 // same creator can be mapped under different names
345 GenericHypothesisCreator_i* creator = (*itHyp).second;
349 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
350 if ( creator == (*itHyp2).second )
351 (*itHyp2).second = 0;
353 myHypCreatorMap.clear();
355 // Clear study contexts data
356 map<int, StudyContext*>::iterator it;
357 for ( it = myStudyContextMap.begin(); it != myStudyContextMap.end(); ++it ) {
360 myStudyContextMap.clear();
361 // delete shape reader
363 delete myShapeReader;
365 //=============================================================================
367 * SMESH_Gen_i::getHypothesisCreator
369 * Get hypothesis creator
371 //=============================================================================
372 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
373 const char* theLibName,
374 std::string& thePlatformLibName)
375 throw (SALOME::SALOME_Exception)
377 std::string aPlatformLibName;
378 /* It's Need to tranlate lib name for WIN32 or X platform */
379 if ( theLibName && theLibName[0] != '\0' )
381 int libNameLen = strlen(theLibName);
382 //check for old format "libXXXXXXX.so"
383 if (libNameLen > 7 &&
384 !strncmp( theLibName, "lib", 3 ) &&
385 !strcmp( theLibName+libNameLen-3, ".so" ))
389 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
391 aPlatformLibName = theLibName;
396 //try to use new format
398 aPlatformLibName = theLibName;
399 aPlatformLibName += ".dll";
401 aPlatformLibName = "lib" + std::string( theLibName ) + ".so";
405 thePlatformLibName = aPlatformLibName;
407 Unexpect aCatch(SALOME_SalomeException);
408 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
410 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
411 GenericHypothesisCreator_i* aCreator;
414 // check, if creator for this hypothesis type already exists
415 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
417 // load plugin library
418 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
419 LibHandle libHandle = LoadLib( aPlatformLibName.c_str() );
422 // report any error, if occured
424 const char* anError = dlerror();
425 throw(SALOME_Exception(anError));
427 throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
431 // get method, returning hypothesis creator
432 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
433 GetHypothesisCreator procHandle =
434 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
437 throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
438 UnLoadLib(libHandle);
441 // get hypothesis creator
442 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
443 aCreator = procHandle(theHypName);
446 throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
448 // map hypothesis creator to a hypothesis name
449 myHypCreatorMap[string(theHypName)] = aCreator;
454 return myHypCreatorMap[string(theHypName)];
457 catch (SALOME_Exception& S_ex)
459 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
464 //=============================================================================
466 * SMESH_Gen_i::createHypothesis
468 * Create hypothesis of given type
470 //=============================================================================
471 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
472 const char* theLibName)
474 SMESH_Hypothesis_i* myHypothesis_i = 0;
475 SMESH::SMESH_Hypothesis_var hypothesis_i;
476 std::string aPlatformLibName;
477 GenericHypothesisCreator_i* aCreator =
478 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
480 // create a new hypothesis object, store its ref. in studyContext
481 myHypothesis_i = aCreator->Create(myPoa, GetCurrentStudyID(), &myGen);
484 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
485 CORBA::String_var hypName = myHypothesis_i->GetName();
486 myHypCreatorMap[ hypName.in() ] = aCreator;
488 // activate the CORBA servant of hypothesis
489 hypothesis_i = myHypothesis_i->_this();
490 int nextId = RegisterObject( hypothesis_i );
491 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
492 else { nextId = 0; } // avoid "unused variable" warning in release mode
494 return hypothesis_i._retn();
497 //=============================================================================
499 * SMESH_Gen_i::createMesh
501 * Create empty mesh on shape
503 //=============================================================================
504 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
505 throw ( SALOME::SALOME_Exception )
507 Unexpect aCatch(SALOME_SalomeException);
508 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
510 // Get or create the GEOM_Client instance
512 // create a new mesh object servant, store it in a map in study context
513 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this, GetCurrentStudyID() );
514 // create a new mesh object
515 MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
516 meshServant->SetImpl( myGen.CreateMesh( GetCurrentStudyID(), myIsEmbeddedMode ));
518 // activate the CORBA servant of Mesh
519 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
520 int nextId = RegisterObject( mesh );
521 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
522 else { nextId = 0; } // avoid "unused variable" warning in release mode
525 catch (SALOME_Exception& S_ex) {
526 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
528 return SMESH::SMESH_Mesh::_nil();
531 //=============================================================================
533 * SMESH_Gen_i::GetShapeReader
537 //=============================================================================
538 GEOM_Client* SMESH_Gen_i::GetShapeReader()
540 // create shape reader if necessary
541 if ( !myShapeReader )
542 myShapeReader = new GEOM_Client(GetContainerRef());
543 ASSERT( myShapeReader );
544 return myShapeReader;
547 //=============================================================================
549 * SMESH_Gen_i::SetGeomEngine
551 * Set GEOM::GEOM_Gen reference
553 //=============================================================================
554 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
555 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
557 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
558 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
559 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
563 //=============================================================================
565 * SMESH_Gen_i::SetEmbeddedMode
569 //=============================================================================
571 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
573 myIsEmbeddedMode = theMode;
574 MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
576 if ( !myIsEmbeddedMode ) {
577 //PAL10867: disable signals catching with "noexcepthandler" option
578 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
579 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
584 char* envDisableFPE = getenv("DISABLE_FPE");
585 if (envDisableFPE && atoi(envDisableFPE))
590 OSD::SetSignal( raiseFPE );
592 // else OSD::SetSignal() is called in GUI
596 //=============================================================================
598 * SMESH_Gen_i::IsEmbeddedMode
602 //=============================================================================
604 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
606 return myIsEmbeddedMode;
609 //=============================================================================
611 * SMESH_Gen_i::SetCurrentStudy
615 //=============================================================================
617 void SMESH_Gen_i::SetCurrentStudy( SALOMEDS::Study_ptr theStudy )
619 setCurrentStudy( theStudy );
622 void SMESH_Gen_i::setCurrentStudy( SALOMEDS::Study_ptr theStudy,
623 bool theStudyIsBeingClosed)
625 int curStudyId = GetCurrentStudyID();
626 myCurrentStudy = SALOMEDS::Study::_duplicate( theStudy );
627 // create study context, if it doesn't exist and set current study
628 int studyId = GetCurrentStudyID();
629 if ( myStudyContextMap.find( studyId ) == myStudyContextMap.end() )
630 myStudyContextMap[ studyId ] = new StudyContext;
632 // myCurrentStudy may be nil
633 if ( !theStudyIsBeingClosed && !CORBA::is_nil( myCurrentStudy ) ) {
634 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
635 SALOMEDS::SComponent_wrap GEOM_var = myCurrentStudy->FindComponent( "GEOM" );
636 if( !GEOM_var->_is_nil() )
637 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
638 // NPAL16168, issue 0020210
639 // Let meshes update their data depending on GEOM groups that could change
640 if ( curStudyId != studyId )
642 CORBA::String_var compDataType = ComponentDataType();
643 SALOMEDS::SComponent_wrap me = myCurrentStudy->FindComponent( compDataType.in() );
644 if ( !me->_is_nil() ) {
645 SALOMEDS::ChildIterator_wrap anIter = myCurrentStudy->NewChildIterator( me );
646 for ( ; anIter->More(); anIter->Next() ) {
647 SALOMEDS::SObject_wrap so = anIter->Value();
648 CORBA::Object_var ior = SObjectToObject( so );
649 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
650 mesh->CheckGeomModif();
657 //=============================================================================
659 * SMESH_Gen_i::GetCurrentStudy
663 //=============================================================================
665 SALOMEDS::Study_ptr SMESH_Gen_i::GetCurrentStudy()
667 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetCurrentStudy: study Id = " << GetCurrentStudyID() );
668 if ( GetCurrentStudyID() < 0 )
669 return SALOMEDS::Study::_nil();
670 return SALOMEDS::Study::_duplicate( myCurrentStudy );
673 //=============================================================================
675 * SMESH_Gen_i::GetCurrentStudyContext
677 * Get current study context
679 //=============================================================================
680 StudyContext* SMESH_Gen_i::GetCurrentStudyContext()
682 if ( !CORBA::is_nil( myCurrentStudy ) &&
683 myStudyContextMap.find( GetCurrentStudyID() ) != myStudyContextMap.end() )
684 return myStudyContextMap[ myCurrentStudy->StudyId() ];
689 //=============================================================================
691 * SMESH_Gen_i::CreateHypothesis
693 * Create hypothesis/algorothm of given type and publish it in the study
695 //=============================================================================
697 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
698 const char* theLibName )
699 throw ( SALOME::SALOME_Exception )
701 Unexpect aCatch(SALOME_SalomeException);
702 // Create hypothesis/algorithm
703 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
705 // Publish hypothesis/algorithm in the study
706 if ( CanPublishInStudy( hyp ) ) {
707 SALOMEDS::SObject_wrap aSO = PublishHypothesis( myCurrentStudy, hyp );
708 if ( !aSO->_is_nil() ) {
709 // Update Python script
710 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
711 << theHypName << "', '" << theLibName << "')";
718 //================================================================================
720 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
721 * existing on the given geometry or to size of the geometry.
722 * \param theHypType - hypothesis type name
723 * \param theLibName - plugin library name
724 * \param theMesh - The mesh of interest
725 * \param theGeom - The shape to get parameter values from
726 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
727 * in a study and used to compute the mesh, or a temporary one created just to pass
730 //================================================================================
732 SMESH::SMESH_Hypothesis_ptr
733 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
734 const char* theLibName,
735 SMESH::SMESH_Mesh_ptr theMesh,
736 GEOM::GEOM_Object_ptr theGeom,
737 CORBA::Boolean byMesh)
738 throw ( SALOME::SALOME_Exception )
740 Unexpect aCatch(SALOME_SalomeException);
741 if ( byMesh && CORBA::is_nil( theMesh ) )
742 return SMESH::SMESH_Hypothesis::_nil();
743 if ( byMesh && CORBA::is_nil( theGeom ) )
744 return SMESH::SMESH_Hypothesis::_nil();
746 // -----------------------------------------------
747 // find hypothesis used to mesh theGeom
748 // -----------------------------------------------
750 // get mesh and shape
751 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
752 TopoDS_Shape shape = GeomObjectToShape( theGeom );
753 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
754 return SMESH::SMESH_Hypothesis::_nil();
755 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
757 // create a temporary hypothesis to know its dimension
758 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
759 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
761 return SMESH::SMESH_Hypothesis::_nil();
762 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
765 // look for a hypothesis of theHypType used to mesh the shape
766 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
769 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
770 int nbLocalHyps = aHypList->length();
771 for ( int i = 0; i < nbLocalHyps; i++ ) {
772 CORBA::String_var hypName = aHypList[i]->GetName();
773 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
774 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
776 // check super shapes
777 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
778 while ( nbLocalHyps == 0 && itShape.More() ) {
779 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
780 if ( ! CORBA::is_nil( geomObj )) {
781 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
782 nbLocalHyps = aHypList->length();
783 for ( int i = 0; i < nbLocalHyps; i++ )
784 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
785 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
791 // let the temporary hypothesis find out somehow parameter values by mesh
792 if ( hyp->SetParametersByMesh( mesh, shape ))
793 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
798 diagonal = mesh->GetShapeDiagonalSize();
800 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
801 ::SMESH_Hypothesis::TDefaults dflts;
802 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
803 dflts._nbSegments = myGen.GetDefaultNbSegments();
804 dflts._shape = &shape;
805 // let the temporary hypothesis initialize it's values
806 if ( hyp->SetParametersByDefaults( dflts, mesh ))
807 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
810 return SMESH::SMESH_Hypothesis::_nil();
813 //=============================================================================
815 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
816 * \param [in] theHyp - the hypothesis of interest
817 * \param [out] theMesh - the sole mesh using \a theHyp
818 * \param [out] theShape - the sole geometry \a theHyp is assigned to
819 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
821 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
822 * considered as SAME sub-mesh => result is \c true.
823 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
824 * a shape to which an hyp being edited is assigned.
826 //=============================================================================
828 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
829 SMESH::SMESH_Mesh_out theMesh,
830 GEOM::GEOM_Object_out theShape)
832 if ( GetCurrentStudyID() < 0 || CORBA::is_nil( theHyp ))
835 // get Mesh component SO
836 CORBA::String_var compDataType = ComponentDataType();
837 SALOMEDS::SComponent_wrap comp = myCurrentStudy->FindComponent( compDataType.in() );
838 if ( CORBA::is_nil( comp ))
841 // look for child SO of meshes
842 SMESH::SMESH_Mesh_var foundMesh;
843 TopoDS_Shape foundShape;
845 SALOMEDS::ChildIterator_wrap meshIter = myCurrentStudy->NewChildIterator( comp );
846 for ( ; meshIter->More() && isSole; meshIter->Next() )
848 SALOMEDS::SObject_wrap curSO = meshIter->Value();
849 CORBA::Object_var obj = SObjectToObject( curSO );
850 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
854 // look for a sole shape where theHyp is assigned
855 bool isHypFound = false;
856 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
857 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
858 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
860 const THypList& hyps = s2hypsIt.Value();
861 THypList::const_iterator h = hyps.begin();
862 for ( ; h != hyps.end(); ++h )
863 if ( (*h)->GetID() == theHyp->GetId() )
865 if ( h != hyps.end()) // theHyp found
868 if ( ! foundShape.IsNull() &&
869 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
871 foundShape.Nullify();
875 foundShape = s2hypsIt.Key();
877 } // loop on assigned hyps
879 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
881 if ( !foundMesh->_is_nil() ) // not a sole mesh
883 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
884 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
885 if ( ! ( isSole = s1->IsSame( s2 )))
888 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
894 ! foundMesh->_is_nil() &&
895 ! foundShape.IsNull() )
897 theMesh = foundMesh._retn();
898 theShape = ShapeToGeomObject( foundShape );
899 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
904 //=============================================================================
906 * Sets number of segments per diagonal of boundary box of geometry by which
907 * default segment length of appropriate 1D hypotheses is defined
909 //=============================================================================
911 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
912 throw ( SALOME::SALOME_Exception )
914 if ( theNbSegments > 0 )
915 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
917 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
919 //=============================================================================
921 * \brief Sets default number of segments per edge
923 //=============================================================================
924 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
925 throw ( SALOME::SALOME_Exception )
927 if ( theNbSegments > 0 )
928 myGen.SetDefaultNbSegments( int(theNbSegments) );
930 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
933 //=============================================================================
937 //=============================================================================
939 void SMESH_Gen_i::SetOption(const char* name, const char* value)
941 if ( name && value && strlen( value ) > 0 )
944 if ( strcmp(name, "historical_python_dump") == 0 )
946 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
947 msgToGUI = "preferences/SMESH/historical_python_dump/";
948 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
950 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
952 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
953 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
954 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
957 // update preferences in case if SetOption() is invoked from python console
958 if ( !msgToGUI.empty() )
960 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
961 SALOME::Session_var session = SALOME::Session::_narrow( obj );
962 if ( !CORBA::is_nil( session ) )
963 session->emitMessageOneWay(msgToGUI.c_str());
968 //=============================================================================
970 Return an option value
972 //=============================================================================
974 char* SMESH_Gen_i::GetOption(const char* name)
978 if ( strcmp(name, "historical_python_dump") == 0 )
980 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
982 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
984 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
987 return CORBA::string_dup( "" );
990 //=============================================================================
992 * SMESH_Gen_i::CreateMesh
994 * Create empty mesh on a shape and publish it in the study
996 //=============================================================================
998 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
999 throw ( SALOME::SALOME_Exception )
1001 Unexpect aCatch(SALOME_SalomeException);
1002 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1004 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1006 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1007 ASSERT( meshServant );
1008 meshServant->SetShape( theShapeObject );
1010 // publish mesh in the study
1011 if ( CanPublishInStudy( mesh ) ) {
1012 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1013 aStudyBuilder->NewCommand(); // There is a transaction
1014 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1015 aStudyBuilder->CommitCommand();
1016 if ( !aSO->_is_nil() ) {
1017 // Update Python script
1018 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1022 return mesh._retn();
1025 //=============================================================================
1027 * SMESH_Gen_i::CreateEmptyMesh
1031 //=============================================================================
1033 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1034 throw ( SALOME::SALOME_Exception )
1036 Unexpect aCatch(SALOME_SalomeException);
1037 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1039 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1041 // publish mesh in the study
1042 if ( CanPublishInStudy( mesh ) ) {
1043 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1044 aStudyBuilder->NewCommand(); // There is a transaction
1045 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1046 aStudyBuilder->CommitCommand();
1047 if ( !aSO->_is_nil() ) {
1048 // Update Python script
1049 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1053 return mesh._retn();
1058 //================================================================================
1060 * \brief Throws an exception in case if the file can't be read
1062 //================================================================================
1064 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1066 SMESH_File f ( theFileName );
1069 if ( !f.error().empty() )
1070 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1072 THROW_SALOME_CORBA_EXCEPTION
1073 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1074 SALOME::BAD_PARAM );
1079 //=============================================================================
1081 * SMESH_Gen_i::CreateMeshFromUNV
1083 * Create mesh and import data from UNV file
1085 //=============================================================================
1087 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1088 throw ( SALOME::SALOME_Exception )
1090 Unexpect aCatch(SALOME_SalomeException);
1092 checkFileReadable( theFileName );
1094 SMESH::SMESH_Mesh_var aMesh = createMesh();
1096 // publish mesh in the study
1097 if ( CanPublishInStudy( aMesh ) ) {
1098 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1099 aStudyBuilder->NewCommand(); // There is a transaction
1100 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, aMesh.in(), aFileName.c_str() );
1101 aStudyBuilder->CommitCommand();
1102 if ( !aSO->_is_nil() ) {
1103 // Update Python script
1104 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1108 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1110 aServant->ImportUNVFile( theFileName );
1112 // Dump creation of groups
1113 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1115 aServant->GetImpl().GetMeshDS()->Modified();
1116 return aMesh._retn();
1119 //=============================================================================
1121 * SMESH_Gen_i::CreateMeshFromMED
1123 * Create mesh and import data from MED file
1125 //=============================================================================
1127 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1128 SMESH::DriverMED_ReadStatus& theStatus,
1129 const char* theCommandNameForPython,
1130 const char* theFileNameForPython)
1133 char bname[ _MAX_FNAME ];
1134 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1135 string aFileName = bname;
1137 string aFileName = basename( theFileNameForPython );
1139 // Retrieve mesh names from the file
1140 DriverMED_R_SMESHDS_Mesh myReader;
1141 myReader.SetFile( theFileName );
1142 myReader.SetMeshId( -1 );
1143 Driver_Mesh::Status aStatus;
1144 list<string> aNames = myReader.GetMeshNames(aStatus);
1145 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1146 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1148 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1151 TPythonDump aPythonDump;
1152 aPythonDump << "([";
1154 if (theStatus == SMESH::DRS_OK) {
1155 SALOMEDS::StudyBuilder_var aStudyBuilder;
1156 if ( GetCurrentStudyID() > -1 )
1158 aStudyBuilder = myCurrentStudy->NewBuilder();
1159 aStudyBuilder->NewCommand(); // There is a transaction
1161 aResult->length( aNames.size() );
1164 // Iterate through all meshes and create mesh objects
1165 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1168 if (i > 0) aPythonDump << ", ";
1171 SMESH::SMESH_Mesh_var mesh = createMesh();
1173 // publish mesh in the study
1174 SALOMEDS::SObject_wrap aSO;
1175 if ( CanPublishInStudy( mesh ) )
1176 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1177 // - as names of meshes are stored in MED file, we use them for data publishing
1178 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1179 aSO = PublishMesh( myCurrentStudy, mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1180 if ( !aSO->_is_nil() ) {
1185 aPythonDump << "mesh_" << i;
1188 // Read mesh data (groups are published automatically by ImportMEDFile())
1189 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1190 ASSERT( meshServant );
1191 SMESH::DriverMED_ReadStatus status1 =
1192 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1193 if (status1 > theStatus)
1194 theStatus = status1;
1196 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1197 meshServant->GetImpl().GetMeshDS()->Modified();
1199 if ( !aStudyBuilder->_is_nil() )
1200 aStudyBuilder->CommitCommand();
1203 // Update Python script
1204 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1206 // Dump creation of groups
1207 for ( int i = 0; i < aResult->length(); ++i )
1208 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1210 return aResult._retn();
1213 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1214 SMESH::DriverMED_ReadStatus& theStatus)
1215 throw ( SALOME::SALOME_Exception )
1217 Unexpect aCatch(SALOME_SalomeException);
1218 checkFileReadable( theFileName );
1220 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1224 //=============================================================================
1226 * SMESH_Gen_i::CreateMeshFromSAUV
1228 * Create mesh and import data from SAUV file
1230 //=============================================================================
1232 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1233 SMESH::DriverMED_ReadStatus& theStatus)
1234 throw ( SALOME::SALOME_Exception )
1236 Unexpect aCatch(SALOME_SalomeException);
1237 checkFileReadable( theFileName );
1239 std::string sauvfilename(theFileName);
1240 std::string medfilename(theFileName);
1241 medfilename += ".med";
1244 cmd = "%PYTHONBIN% ";
1249 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1251 system(cmd.c_str());
1252 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1254 cmd = "%PYTHONBIN% ";
1259 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1261 system(cmd.c_str());
1265 //=============================================================================
1267 * SMESH_Gen_i::CreateMeshFromSTL
1269 * Create mesh and import data from STL file
1271 //=============================================================================
1273 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1274 throw ( SALOME::SALOME_Exception )
1276 Unexpect aCatch(SALOME_SalomeException);
1277 checkFileReadable( theFileName );
1279 SMESH::SMESH_Mesh_var aMesh = createMesh();
1282 char bname[ _MAX_FNAME ];
1283 _splitpath( theFileName, NULL, NULL, bname, NULL );
1284 string aFileName = bname;
1286 string aFileName = basename( theFileName );
1288 // publish mesh in the study
1289 if ( CanPublishInStudy( aMesh ) ) {
1290 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1291 aStudyBuilder->NewCommand(); // There is a transaction
1292 SALOMEDS::SObject_wrap aSO = PublishInStudy
1293 ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1294 aStudyBuilder->CommitCommand();
1295 if ( !aSO->_is_nil() ) {
1296 // Update Python script
1297 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1301 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1303 aServant->ImportSTLFile( theFileName );
1304 aServant->GetImpl().GetMeshDS()->Modified();
1305 return aMesh._retn();
1308 //================================================================================
1310 * \brief Create meshes and import data from the CGSN file
1312 //================================================================================
1314 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1315 SMESH::DriverMED_ReadStatus& theStatus)
1316 throw ( SALOME::SALOME_Exception )
1318 Unexpect aCatch(SALOME_SalomeException);
1319 checkFileReadable( theFileName );
1321 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1324 // Retrieve nb meshes from the file
1325 DriverCGNS_Read myReader;
1326 myReader.SetFile( theFileName );
1327 Driver_Mesh::Status aStatus;
1328 int nbMeshes = myReader.GetNbMeshes(aStatus);
1329 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1331 aResult->length( nbMeshes );
1333 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1336 TPythonDump aPythonDump;
1337 aPythonDump << "([";
1339 if (theStatus == SMESH::DRS_OK)
1341 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1342 aStudyBuilder->NewCommand(); // There is a transaction
1346 // Iterate through all meshes and create mesh objects
1347 for ( ; i < nbMeshes; ++i )
1350 if (i > 0) aPythonDump << ", ";
1353 SMESH::SMESH_Mesh_var mesh = createMesh();
1354 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1356 // Read mesh data (groups are published automatically by ImportMEDFile())
1357 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1358 ASSERT( meshServant );
1360 SMESH::DriverMED_ReadStatus status1 =
1361 meshServant->ImportCGNSFile( theFileName, i, meshName );
1362 if (status1 > theStatus)
1363 theStatus = status1;
1365 meshServant->GetImpl().GetMeshDS()->Modified();
1366 // publish mesh in the study
1367 SALOMEDS::SObject_wrap aSO;
1368 if ( CanPublishInStudy( mesh ) )
1369 aSO = PublishMesh( myCurrentStudy, mesh.in(), meshName.c_str() );
1372 if ( !aSO->_is_nil() ) {
1376 aPythonDump << "mesh_" << i;
1379 aStudyBuilder->CommitCommand();
1382 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1384 // Dump creation of groups
1385 for ( int i = 0; i < aResult->length(); ++i )
1386 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1388 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1391 return aResult._retn();
1394 //================================================================================
1396 * \brief Create a mesh and import data from a GMF file
1398 //================================================================================
1400 SMESH::SMESH_Mesh_ptr
1401 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1402 CORBA::Boolean theMakeRequiredGroups,
1403 SMESH::ComputeError_out theError)
1404 throw ( SALOME::SALOME_Exception )
1406 Unexpect aCatch(SALOME_SalomeException);
1407 checkFileReadable( theFileName );
1409 SMESH::SMESH_Mesh_var aMesh = createMesh();
1411 char bname[ _MAX_FNAME ];
1412 _splitpath( theFileName, NULL, NULL, bname, NULL );
1413 string aFileName = bname;
1415 string aFileName = basename( theFileName );
1417 // publish mesh in the study
1418 if ( CanPublishInStudy( aMesh ) ) {
1419 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1420 aStudyBuilder->NewCommand(); // There is a transaction
1421 SALOMEDS::SObject_wrap aSO = PublishInStudy
1422 ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1423 aStudyBuilder->CommitCommand();
1424 if ( !aSO->_is_nil() ) {
1425 // Update Python script
1426 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1427 << theFileName << "', "
1428 << theMakeRequiredGroups << " )";
1431 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1433 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1434 aServant->GetImpl().GetMeshDS()->Modified();
1435 return aMesh._retn();
1439 //=============================================================================
1441 * SMESH_Gen_i::IsReadyToCompute
1443 * Returns true if mesh contains enough data to be computed
1445 //=============================================================================
1447 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1448 GEOM::GEOM_Object_ptr theShapeObject )
1449 throw ( SALOME::SALOME_Exception )
1451 Unexpect aCatch(SALOME_SalomeException);
1452 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1454 if ( CORBA::is_nil( theShapeObject ) )
1455 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1456 SALOME::BAD_PARAM );
1458 if ( CORBA::is_nil( theMesh ) )
1459 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1460 SALOME::BAD_PARAM );
1464 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1465 ASSERT( meshServant );
1466 if ( meshServant ) {
1467 // get local TopoDS_Shape
1468 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1469 // call implementation
1470 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1471 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1474 catch ( SALOME_Exception& S_ex ) {
1475 INFOS( "catch exception "<< S_ex.what() );
1480 //================================================================================
1482 * \brief Find SObject for an algo
1484 //================================================================================
1486 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1489 if ( !myCurrentStudy->_is_nil() ) {
1490 // find algo in the study
1491 CORBA::String_var compDataType = ComponentDataType();
1492 SALOMEDS::SComponent_wrap father = myCurrentStudy->FindComponent( compDataType.in() );
1493 if ( !father->_is_nil() ) {
1494 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( father );
1495 for ( ; itBig->More(); itBig->Next() ) {
1496 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1497 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1498 SALOMEDS::ChildIterator_wrap algoIt = myCurrentStudy->NewChildIterator( gotBranch );
1499 for ( ; algoIt->More(); algoIt->Next() ) {
1500 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1501 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1502 if ( !CORBA::is_nil( algoIOR )) {
1503 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1504 if ( impl && impl->GetImpl() == algo )
1505 return algoSO._retn();
1507 } // loop on algo SO's
1510 } // SMESH component iterator
1514 return SALOMEDS::SObject::_nil();
1517 //================================================================================
1519 * \brief Return errors of mesh computation
1521 //================================================================================
1523 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1524 GEOM::GEOM_Object_ptr theSubObject )
1525 throw ( SALOME::SALOME_Exception )
1527 Unexpect aCatch(SALOME_SalomeException);
1528 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1530 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1531 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1533 if ( CORBA::is_nil( theMesh ) )
1534 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1536 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1538 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1541 if(theMesh->HasShapeToMesh())
1542 shape = GeomObjectToShape( theSubObject );
1544 shape = SMESH_Mesh::PseudoShape();
1546 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1548 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1551 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1552 const bool includeSelf = true, complexShapeFirst = true;
1553 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1555 while ( smIt->more() )
1558 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1560 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1561 if ( error && !error->IsOK() )
1563 if ( !( error->myAlgo ) &&
1564 !( error->myAlgo = sm->GetAlgo() ))
1566 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1567 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1568 errStruct.comment = error->myComment.c_str();
1569 errStruct.subShapeID = sm->GetId();
1570 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1571 if ( !algoSO->_is_nil() ) {
1572 CORBA::String_var algoName = algoSO->GetName();
1573 errStruct.algoName = algoName;
1576 errStruct.algoName = error->myAlgo->GetName();
1578 errStruct.hasBadMesh = !error->myBadElements.empty();
1581 error_array->length( nbErr );
1584 catch ( SALOME_Exception& S_ex ) {
1585 INFOS( "catch exception "<< S_ex.what() );
1588 return error_array._retn();
1591 //================================================================================
1593 * \brief Return mesh elements preventing computation of a subshape
1595 //================================================================================
1597 SMESH::MeshPreviewStruct*
1598 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1599 CORBA::Short theSubShapeID )
1600 throw ( SALOME::SALOME_Exception )
1602 Unexpect aCatch(SALOME_SalomeException);
1603 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1605 if ( CORBA::is_nil( theMesh ) )
1606 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1608 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1611 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1613 // mesh implementation
1614 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1615 // submesh by subshape id
1616 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1619 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1620 if ( error && !error->myBadElements.empty())
1622 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1623 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1625 // get nodes of elements and count elements
1626 TNode2LocalIDMap mapNode2LocalID;
1627 list< TNodeLocalID > connectivity;
1628 int i, nbElements = 0, nbConnNodes = 0;
1630 list<const SMDS_MeshElement*>::iterator elemIt = error->myBadElements.begin();
1631 list<const SMDS_MeshElement*>::iterator elemEnd = error->myBadElements.end();
1632 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1634 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1635 while ( nIt->more() )
1636 connectivity.push_back
1637 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1639 // fill node coords and assign local ids to the nodes
1640 int nbNodes = mapNode2LocalID.size();
1641 result->nodesXYZ.length( nbNodes );
1642 TNodeLocalID node2ID = mapNode2LocalID.begin();
1643 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1644 node2ID->second = i;
1645 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1646 result->nodesXYZ[i].x = node->X();
1647 result->nodesXYZ[i].y = node->Y();
1648 result->nodesXYZ[i].z = node->Z();
1650 // fill connectivity
1651 result->elementConnectivities.length( nbConnNodes );
1652 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1653 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1654 result->elementConnectivities[i] = (*connIt)->second;
1656 // fill element types
1657 result->elementTypes.length( nbElements );
1658 for ( i = 0, elemIt = error->myBadElements.begin(); i <nbElements; ++i, ++elemIt )
1660 const SMDS_MeshElement* elem = *elemIt;
1661 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1662 result->elementTypes[i].isPoly = elem->IsPoly();
1663 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1669 catch ( SALOME_Exception& S_ex ) {
1670 INFOS( "catch exception "<< S_ex.what() );
1673 return result._retn();
1676 //================================================================================
1678 * \brief Create a group of elements preventing computation of a sub-shape
1680 //================================================================================
1682 SMESH::ListOfGroups*
1683 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1684 CORBA::Short theSubShapeID,
1685 const char* theGroupName )
1686 throw ( SALOME::SALOME_Exception )
1688 Unexpect aCatch(SALOME_SalomeException);
1690 SMESH::ListOfGroups_var groups;
1692 if ( CORBA::is_nil( theMesh ) )
1693 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1696 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1698 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1699 TPythonDump() << groups << " = " << this
1700 << ".MakeGroupsOfBadInputElements( "
1701 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1704 catch ( SALOME_Exception& S_ex ) {
1705 INFOS( "catch exception "<< S_ex.what() );
1707 return groups._retn();
1710 //================================================================================
1712 * \brief Returns errors of hypotheses definintion
1713 * \param theMesh - the mesh
1714 * \param theSubObject - the main or sub- shape
1715 * \retval SMESH::algo_error_array* - sequence of errors
1717 //================================================================================
1719 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1720 GEOM::GEOM_Object_ptr theSubObject )
1721 throw ( SALOME::SALOME_Exception )
1723 Unexpect aCatch(SALOME_SalomeException);
1724 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1726 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1727 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1729 if ( CORBA::is_nil( theMesh ) )
1730 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1732 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1734 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1735 ASSERT( meshServant );
1736 if ( meshServant ) {
1737 TopoDS_Shape myLocShape;
1738 if(theMesh->HasShapeToMesh())
1739 myLocShape = GeomObjectToShape( theSubObject );
1741 myLocShape = SMESH_Mesh::PseudoShape();
1743 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1744 list< ::SMESH_Gen::TAlgoStateError > error_list;
1745 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1746 // call ::SMESH_Gen::GetAlgoState()
1747 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1748 error_array->length( error_list.size() );
1750 for ( error = error_list.begin(); error != error_list.end(); ++error )
1752 // fill AlgoStateError structure
1753 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1754 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1755 errStruct.algoDim = error->_algoDim;
1756 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1757 errStruct.algoName = "";
1758 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1759 if ( !algoSO->_is_nil() ) {
1760 CORBA::String_var algoName = algoSO->GetName();
1761 errStruct.algoName = algoName.in();
1766 catch ( SALOME_Exception& S_ex ) {
1767 INFOS( "catch exception "<< S_ex.what() );
1769 return error_array._retn();
1772 //=============================================================================
1774 * SMESH_Gen_i::GetSubShapesId
1776 * Get sub-shapes unique ID's list
1778 //=============================================================================
1780 SMESH::long_array* SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1781 const SMESH::object_array& theListOfSubShapeObject )
1782 throw ( SALOME::SALOME_Exception )
1784 Unexpect aCatch(SALOME_SalomeException);
1785 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1787 SMESH::long_array_var shapesId = new SMESH::long_array;
1790 if ( CORBA::is_nil( theMainShapeObject ) )
1791 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1792 SALOME::BAD_PARAM );
1796 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1797 TopTools_IndexedMapOfShape myIndexToShape;
1798 TopExp::MapShapes(myMainShape,myIndexToShape);
1800 for ( int i = 0; i < theListOfSubShapeObject.length(); i++ )
1802 GEOM::GEOM_Object_var aShapeObject
1803 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1804 if ( CORBA::is_nil( aShapeObject ) )
1805 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1806 SALOME::BAD_PARAM );
1808 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1809 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1811 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1812 setId.insert(myIndexToShape.FindIndex(F));
1813 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1815 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1817 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1818 setId.insert(myIndexToShape.FindIndex(E));
1819 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1821 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1823 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1824 setId.insert(myIndexToShape.FindIndex(V));
1825 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1828 shapesId->length(setId.size());
1829 set<int>::iterator iind;
1831 for (iind = setId.begin(); iind != setId.end(); iind++)
1833 if(MYDEBUG) SCRUTE((*iind));
1834 shapesId[i] = (*iind);
1835 if(MYDEBUG) SCRUTE(shapesId[i]);
1839 catch (SALOME_Exception& S_ex)
1841 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1844 return shapesId._retn();
1847 //=============================================================================
1849 * SMESH_Gen_i::Compute
1851 * Compute mesh on a shape
1853 //=============================================================================
1855 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1856 GEOM::GEOM_Object_ptr theShapeObject )
1857 throw ( SALOME::SALOME_Exception )
1860 Unexpect aCatch(SALOME_SalomeException);
1861 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1863 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1864 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1865 SALOME::BAD_PARAM );
1867 if ( CORBA::is_nil( theMesh ) )
1868 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1869 SALOME::BAD_PARAM );
1871 // Update Python script
1872 TPythonDump() << "isDone = " << this << ".Compute( "
1873 << theMesh << ", " << theShapeObject << ")";
1877 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1878 ASSERT( meshServant );
1879 if ( meshServant ) {
1880 meshServant->Load();
1881 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1882 meshServant->CheckGeomModif();
1883 // get local TopoDS_Shape
1884 TopoDS_Shape myLocShape;
1885 if(theMesh->HasShapeToMesh())
1886 myLocShape = GeomObjectToShape( theShapeObject );
1888 myLocShape = SMESH_Mesh::PseudoShape();
1889 // call implementation compute
1890 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1891 myGen.PrepareCompute( myLocMesh, myLocShape);
1892 bool ok = myGen.Compute( myLocMesh, myLocShape);
1893 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1894 myLocMesh.GetMeshDS()->Modified();
1898 catch ( std::bad_alloc ) {
1899 INFOS( "Compute(): lack of memory" );
1901 catch ( SALOME_Exception& S_ex ) {
1902 INFOS( "Compute(): catch exception "<< S_ex.what() );
1905 INFOS( "Compute(): unknown exception " );
1910 //=============================================================================
1912 * SMESH_Gen_i::CancelCompute
1914 * Cancel Compute mesh on a shape
1916 //=============================================================================
1918 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
1919 GEOM::GEOM_Object_ptr theShapeObject )
1921 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1922 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1923 TopoDS_Shape myLocShape;
1924 if(theMesh->HasShapeToMesh())
1925 myLocShape = GeomObjectToShape( theShapeObject );
1927 myLocShape = SMESH_Mesh::PseudoShape();
1928 myGen.CancelCompute( myLocMesh, myLocShape);
1931 //=============================================================================
1933 * SMESH_Gen_i::Precompute
1935 * Compute mesh as preview till indicated dimension on shape
1937 //=============================================================================
1939 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
1940 GEOM::GEOM_Object_ptr theShapeObject,
1941 SMESH::Dimension theDimension,
1942 SMESH::long_array& theShapesId)
1943 throw ( SALOME::SALOME_Exception )
1945 Unexpect aCatch(SALOME_SalomeException);
1946 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
1948 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1949 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1950 SALOME::BAD_PARAM );
1952 if ( CORBA::is_nil( theMesh ) )
1953 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1954 SALOME::BAD_PARAM );
1956 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1959 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1960 meshServant->Load();
1961 ASSERT( meshServant );
1962 if ( meshServant ) {
1963 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1964 meshServant->CheckGeomModif();
1965 // get local TopoDS_Shape
1966 TopoDS_Shape myLocShape;
1967 if(theMesh->HasShapeToMesh())
1968 myLocShape = GeomObjectToShape( theShapeObject );
1970 return result._retn();;
1972 // call implementation compute
1973 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1975 ::MeshDimension aDim = (MeshDimension)theDimension;
1976 if ( myGen.Compute( myLocMesh, myLocShape, false, false, aDim, &shapeIds ) )
1978 int nbShapeId = shapeIds.size();
1979 theShapesId.length( nbShapeId );
1980 // iterates on shapes and collect mesh entities into mesh preview
1981 TSetOfInt::const_iterator idIt = shapeIds.begin();
1982 TSetOfInt::const_iterator idEnd = shapeIds.end();
1983 std::map< int, int > mapOfShIdNb;
1984 std::set< SMESH_TLink > setOfEdge;
1985 std::list< SMDSAbs_ElementType > listOfElemType;
1986 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1987 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1988 TNode2LocalIDMap mapNode2LocalID;
1989 list< TNodeLocalID > connectivity;
1990 int i, nbConnNodes = 0;
1991 std::set< const SMESH_subMesh* > setOfVSubMesh;
1992 // iterates on shapes
1993 for ( ; idIt != idEnd; idIt++ )
1995 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
1997 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
1998 if ( !sm || !sm->IsMeshComputed() )
2001 const TopoDS_Shape& aSh = sm->GetSubShape();
2002 const int shDim = myGen.GetShapeDim( aSh );
2003 if ( shDim < 1 || shDim > theDimension )
2006 mapOfShIdNb[ *idIt ] = 0;
2007 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2009 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2010 if ( !smDS ) continue;
2012 if ( theDimension == SMESH::DIM_2D )
2014 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2015 while ( faceIt->more() )
2017 const SMDS_MeshElement* face = faceIt->next();
2018 int aNbNode = face->NbNodes();
2020 aNbNode /= 2; // do not take into account additional middle nodes
2022 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2023 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2025 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2026 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2028 listOfElemType.push_back( SMDSAbs_Edge );
2029 connectivity.push_back
2030 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2031 connectivity.push_back
2032 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2038 else if ( theDimension == SMESH::DIM_1D )
2040 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2041 while ( nodeIt->more() )
2043 listOfElemType.push_back( SMDSAbs_Node );
2044 connectivity.push_back
2045 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2047 // add corner nodes by first vertex from edge
2048 SMESH_subMeshIteratorPtr edgeSmIt =
2049 sm->getDependsOnIterator(/*includeSelf*/false,
2050 /*complexShapeFirst*/false);
2051 while ( edgeSmIt->more() )
2053 SMESH_subMesh* vertexSM = edgeSmIt->next();
2054 // check that vertex is not already treated
2055 if ( !setOfVSubMesh.insert( vertexSM ).second )
2057 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2060 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2061 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2062 while ( nodeIt->more() )
2064 listOfElemType.push_back( SMDSAbs_Node );
2065 connectivity.push_back
2066 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2072 // fill node coords and assign local ids to the nodes
2073 int nbNodes = mapNode2LocalID.size();
2074 result->nodesXYZ.length( nbNodes );
2075 TNodeLocalID node2ID = mapNode2LocalID.begin();
2076 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2077 node2ID->second = i;
2078 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2079 result->nodesXYZ[i].x = node->X();
2080 result->nodesXYZ[i].y = node->Y();
2081 result->nodesXYZ[i].z = node->Z();
2083 // fill connectivity
2084 result->elementConnectivities.length( nbConnNodes );
2085 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2086 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2087 result->elementConnectivities[i] = (*connIt)->second;
2090 // fill element types
2091 result->elementTypes.length( listOfElemType.size() );
2092 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2093 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2094 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2096 SMDSAbs_ElementType elemType = *typeIt;
2097 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2098 result->elementTypes[i].isPoly = false;
2099 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2102 // correct number of shapes
2103 theShapesId.length( mapOfShIdNb.size() );
2107 catch ( std::bad_alloc ) {
2108 INFOS( "Precompute(): lack of memory" );
2110 catch ( SALOME_Exception& S_ex ) {
2111 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2114 INFOS( "Precompute(): unknown exception " );
2116 return result._retn();
2120 //=============================================================================
2122 * SMESH_Gen_i::Evaluate
2124 * Evaluate mesh on a shape
2126 //=============================================================================
2128 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2129 GEOM::GEOM_Object_ptr theShapeObject)
2130 // SMESH::long_array& theNbElems)
2131 throw ( SALOME::SALOME_Exception )
2133 Unexpect aCatch(SALOME_SalomeException);
2134 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2136 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2137 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2138 SALOME::BAD_PARAM );
2140 if ( CORBA::is_nil( theMesh ) )
2141 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2142 SALOME::BAD_PARAM );
2144 SMESH::long_array_var nbels = new SMESH::long_array;
2145 nbels->length(SMESH::Entity_Last);
2146 int i = SMESH::Entity_Node;
2147 for (; i < SMESH::Entity_Last; i++)
2150 // Update Python script
2151 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2152 << theMesh << ", " << theShapeObject << ")";
2156 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2157 ASSERT( meshServant );
2158 if ( meshServant ) {
2159 meshServant->Load();
2160 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
2161 meshServant->CheckGeomModif();
2162 // get local TopoDS_Shape
2163 TopoDS_Shape myLocShape;
2164 if(theMesh->HasShapeToMesh())
2165 myLocShape = GeomObjectToShape( theShapeObject );
2167 myLocShape = SMESH_Mesh::PseudoShape();
2168 // call implementation compute
2169 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2170 MapShapeNbElems aResMap;
2171 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2172 MapShapeNbElemsItr anIt = aResMap.begin();
2173 for(; anIt!=aResMap.end(); anIt++) {
2174 const vector<int>& aVec = (*anIt).second;
2175 for(i = SMESH::Entity_Node; i < aVec.size(); i++) {
2176 int nbElem = aVec[i];
2177 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2179 SMESH_subMesh* sm = anIt->first;
2180 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2181 const SMESH_Algo* algo = sm->GetAlgo();
2182 if ( (algo && !error.get()) || error->IsOK() )
2183 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2187 nbels[i] += aVec[i];
2191 return nbels._retn();
2194 catch ( std::bad_alloc ) {
2195 INFOS( "Evaluate(): lack of memory" );
2197 catch ( SALOME_Exception& S_ex ) {
2198 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2201 INFOS( "Evaluate(): unknown exception " );
2204 return nbels._retn();
2207 //================================================================================
2209 * \brief Return geometrical object the given element is built on
2210 * \param theMesh - the mesh the element is in
2211 * \param theElementID - the element ID
2212 * \param theGeomName - the name of the result geom object if it is not yet published
2213 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2215 //================================================================================
2217 GEOM::GEOM_Object_ptr
2218 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2219 CORBA::Long theElementID,
2220 const char* theGeomName)
2221 throw ( SALOME::SALOME_Exception )
2223 Unexpect aCatch(SALOME_SalomeException);
2225 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2226 if ( !geom->_is_nil() ) {
2227 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2228 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2230 // try to find the corresponding SObject
2231 SALOMEDS::SObject_wrap SObj = ObjectToSObject( myCurrentStudy, geom.in() );
2232 if ( SObj->_is_nil() ) // submesh can be not found even if published
2234 // try to find published submesh
2235 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2236 if ( !geom->IsMainShape() && list->length() == 1 ) {
2237 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2238 SALOMEDS::ChildIterator_wrap it;
2239 if ( !mainSO->_is_nil() ) {
2240 it = myCurrentStudy->NewChildIterator( mainSO );
2242 if ( !it->_is_nil() ) {
2243 for ( it->InitEx(true); it->More(); it->Next() ) {
2244 SALOMEDS::SObject_wrap so = it->Value();
2245 CORBA::Object_var obj = SObjectToObject( so );
2246 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2247 if ( !subGeom->_is_nil() ) {
2248 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2249 if ( subList->length() == 1 && list[0] == subList[0] ) {
2259 if ( SObj->_is_nil() ) // publish a new subshape
2260 SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
2262 // return only published geometry
2263 if ( !SObj->_is_nil() ) {
2264 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2265 CORBA::Object_var obj = SObjectToObject( SObj );
2266 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2270 return GEOM::GEOM_Object::_nil();
2273 //================================================================================
2275 * \brief Return geometrical object the given element is built on.
2276 * \param theMesh - the mesh the element is in
2277 * \param theElementID - the element ID
2278 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2280 //================================================================================
2282 GEOM::GEOM_Object_ptr
2283 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2284 CORBA::Long theElementID)
2285 throw ( SALOME::SALOME_Exception )
2287 Unexpect aCatch(SALOME_SalomeException);
2288 if ( CORBA::is_nil( theMesh ) )
2289 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2291 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2292 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2294 // get a core mesh DS
2295 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2296 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2298 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2299 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2300 // find the element in mesh
2301 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2302 // find a shape id by the element
2303 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2304 // get a geom object by the shape id
2305 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2306 if ( geom->_is_nil() ) {
2307 // try to find a published sub-shape
2308 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2309 SALOMEDS::ChildIterator_wrap it;
2310 if ( !mainSO->_is_nil() ) {
2311 it = myCurrentStudy->NewChildIterator( mainSO );
2313 if ( !it->_is_nil() ) {
2314 for ( it->InitEx(true); it->More(); it->Next() ) {
2315 SALOMEDS::SObject_wrap so = it->Value();
2316 CORBA::Object_var obj = SObjectToObject( so );
2317 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2318 if ( !subGeom->_is_nil() ) {
2319 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2320 if ( subList->length() == 1 && shapeID == subList[0] ) {
2328 if ( geom->_is_nil() ) {
2330 GEOM::GEOM_IShapesOperations_wrap op =
2331 geomGen->GetIShapesOperations( GetCurrentStudyID() );
2332 if ( !op->_is_nil() )
2333 geom = op->GetSubShape( mainShape, shapeID );
2338 if ( !geom->_is_nil() ) {
2339 GeomObjectToShape( geom ); // let geom client remember the found shape
2340 return geom._retn();
2345 return GEOM::GEOM_Object::_nil();
2348 //================================================================================
2350 * SMESH_Gen_i::Concatenate
2352 * Concatenate the given meshes into one mesh
2354 //================================================================================
2356 SMESH::SMESH_Mesh_ptr
2357 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2358 CORBA::Boolean theUniteIdenticalGroups,
2359 CORBA::Boolean theMergeNodesAndElements,
2360 CORBA::Double theMergeTolerance)
2361 throw ( SALOME::SALOME_Exception )
2363 return ConcatenateCommon(theMeshesArray,
2364 theUniteIdenticalGroups,
2365 theMergeNodesAndElements,
2370 //================================================================================
2372 * SMESH_Gen_i::ConcatenateWithGroups
2374 * Concatenate the given meshes into one mesh
2375 * Create the groups of all elements from initial meshes
2377 //================================================================================
2379 SMESH::SMESH_Mesh_ptr
2380 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2381 CORBA::Boolean theUniteIdenticalGroups,
2382 CORBA::Boolean theMergeNodesAndElements,
2383 CORBA::Double theMergeTolerance)
2384 throw ( SALOME::SALOME_Exception )
2386 return ConcatenateCommon(theMeshesArray,
2387 theUniteIdenticalGroups,
2388 theMergeNodesAndElements,
2393 //================================================================================
2395 * SMESH_Gen_i::ConcatenateCommon
2397 * Concatenate the given meshes into one mesh
2399 //================================================================================
2401 SMESH::SMESH_Mesh_ptr
2402 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2403 CORBA::Boolean theUniteIdenticalGroups,
2404 CORBA::Boolean theMergeNodesAndElements,
2405 CORBA::Double theMergeTolerance,
2406 CORBA::Boolean theCommonGroups)
2407 throw ( SALOME::SALOME_Exception )
2409 typedef list<SMESH::SMESH_Group_var> TListOfNewGroups;
2410 typedef map< pair<string, SMESH::ElementType>, TListOfNewGroups > TGroupsMap;
2412 TPythonDump* pPythonDump = new TPythonDump;
2413 TPythonDump& aPythonDump = *pPythonDump; // prevent dump of called methods
2416 SMESH::SMESH_Mesh_var aNewMesh = CreateEmptyMesh();
2418 if ( aNewMesh->_is_nil() )
2419 return aNewMesh._retn();
2421 SMESH_Mesh_i* aNewImpl = SMESH::DownCast<SMESH_Mesh_i*>( aNewMesh );
2423 return aNewMesh._retn();
2425 ::SMESH_Mesh& aLocMesh = aNewImpl->GetImpl();
2426 SMESHDS_Mesh* aNewMeshDS = aLocMesh.GetMeshDS();
2428 TGroupsMap aGroupsMap;
2429 TListOfNewGroups aListOfNewGroups;
2430 ::SMESH_MeshEditor aNewEditor(&aLocMesh);
2431 SMESH::ListOfGroups_var aListOfGroups;
2433 ::SMESH_MeshEditor::ElemFeatures elemType;
2434 std::vector<const SMDS_MeshNode*> aNodesArray;
2436 // loop on sub-meshes
2437 for ( int i = 0; i < theMeshesArray.length(); i++)
2439 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2440 SMESH::SMESH_Mesh_var anInitMesh = theMeshesArray[i]->GetMesh();
2441 if ( anInitMesh->_is_nil() ) continue;
2442 SMESH_Mesh_i* anInitImpl = SMESH::DownCast<SMESH_Mesh_i*>( anInitMesh );
2443 if ( !anInitImpl ) continue;
2446 ::SMESH_Mesh& aInitLocMesh = anInitImpl->GetImpl();
2447 SMESHDS_Mesh* anInitMeshDS = aInitLocMesh.GetMeshDS();
2449 // remember nb of elements before filling in
2450 SMESH::long_array_var prevState = aNewMesh->GetNbElementsByType();
2452 typedef std::map<const SMDS_MeshElement*, const SMDS_MeshElement*, TIDCompare > TEEMap;
2453 TEEMap elemsMap, nodesMap;
2455 // loop on elements of a sub-mesh
2456 SMDS_ElemIteratorPtr itElems = anInitImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2457 const SMDS_MeshElement* anElem;
2458 const SMDS_MeshElement* aNewElem;
2459 const SMDS_MeshNode* aNode;
2460 const SMDS_MeshNode* aNewNode;
2463 while ( itElems->more() )
2465 anElem = itElems->next();
2466 anElemNbNodes = anElem->NbNodes();
2467 aNodesArray.resize( anElemNbNodes );
2469 // loop on nodes of an element
2470 SMDS_ElemIteratorPtr itNodes = anElem->nodesIterator();
2471 for ( int k = 0; itNodes->more(); k++)
2473 aNode = static_cast<const SMDS_MeshNode*>( itNodes->next() );
2474 TEEMap::iterator n2nnIt = nodesMap.find( aNode );
2475 if ( n2nnIt == nodesMap.end() )
2477 aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2478 nodesMap.insert( make_pair( aNode, aNewNode ));
2482 aNewNode = static_cast<const SMDS_MeshNode*>( n2nnIt->second );
2484 aNodesArray[k] = aNewNode;
2487 // creates a corresponding element on existent nodes in new mesh
2488 if ( anElem->GetType() == SMDSAbs_Node )
2492 aNewEditor.AddElement( aNodesArray, elemType.Init( anElem, /*basicOnly=*/false ));
2495 elemsMap.insert( make_pair( anElem, aNewElem ));
2499 aNewEditor.ClearLastCreated(); // forget the history
2502 // create groups of just added elements
2503 SMESH::SMESH_Group_var aNewGroup;
2504 SMESH::ElementType aGroupType;
2505 if ( theCommonGroups )
2507 SMESH::long_array_var curState = aNewMesh->GetNbElementsByType();
2509 for( aGroupType = SMESH::NODE;
2510 aGroupType < SMESH::NB_ELEMENT_TYPES;
2511 aGroupType = (SMESH::ElementType)( aGroupType + 1 ))
2513 if ( curState[ aGroupType ] <= prevState[ aGroupType ])
2516 // make a group name
2517 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2518 { // check of typeNames, compilation failure mains that NB_ELEMENT_TYPES changed:
2519 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2520 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 1 : -1 ];
2522 string groupName = "Gr";
2523 SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( myCurrentStudy, theMeshesArray[i] );
2525 CORBA::String_var name = aMeshSObj->GetName();
2529 groupName += typeNames[ aGroupType ];
2531 // make and fill a group
2532 TEEMap & e2neMap = ( aGroupType == SMESH::NODE ) ? nodesMap : elemsMap;
2533 aNewGroup = aNewImpl->CreateGroup( aGroupType, groupName.c_str() );
2534 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( aNewGroup ))
2536 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2538 TEEMap::iterator e2neIt = e2neMap.begin();
2539 for ( ; e2neIt != e2neMap.end(); ++e2neIt )
2541 aNewElem = e2neIt->second;
2542 if ( aNewElem->GetType() == grpDS->GetType() )
2544 grpDS->Add( aNewElem );
2546 if ( prevState[ aGroupType ]++ >= curState[ aGroupType ] )
2552 aListOfNewGroups.clear();
2553 aListOfNewGroups.push_back(aNewGroup);
2554 aGroupsMap.insert(make_pair( make_pair(groupName, aGroupType), aListOfNewGroups ));
2558 if ( SMESH_Mesh_i* anSrcImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2560 // copy orphan nodes
2561 if ( anSrcImpl->NbNodes() > nodesMap.size() )
2563 SMDS_ElemIteratorPtr itNodes = anInitImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2564 while ( itNodes->more() )
2566 const SMDS_MeshNode* aNode = static_cast< const SMDS_MeshNode* >( itNodes->next() );
2567 if ( aNode->NbInverseElements() == 0 )
2569 aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2570 nodesMap.insert( make_pair( aNode, aNewNode ));
2577 SMESH::SMESH_GroupBase_ptr aGroup;
2578 CORBA::String_var aGroupName;
2579 SMESH::long_array_var anNewIDs = new SMESH::long_array();
2581 // loop on groups of a source mesh
2582 aListOfGroups = anSrcImpl->GetGroups();
2583 for (int iG = 0; iG < aListOfGroups->length(); iG++)
2585 aGroup = aListOfGroups[iG];
2586 aGroupType = aGroup->GetType();
2587 aGroupName = aGroup->GetName();
2589 // convert a list of IDs
2590 anNewIDs->length( aGroup->Size() );
2591 TEEMap & e2neMap = ( aGroupType == SMESH::NODE ) ? nodesMap : elemsMap;
2592 SMDS_ElemIteratorPtr itGrElems = anSrcImpl->GetElements( aGroup, SMESH::ALL );
2594 while ( itGrElems->more() )
2596 anElem = itGrElems->next();
2597 TEEMap::iterator e2neIt = e2neMap.find( anElem );
2598 if ( e2neIt != e2neMap.end() )
2599 anNewIDs[ iElem++ ] = e2neIt->second->GetID();
2601 anNewIDs->length( iElem );
2603 // check a current group name and type don't have identical ones in final mesh
2604 aListOfNewGroups.clear();
2605 TGroupsMap::iterator anIter = aGroupsMap.find( make_pair( aGroupName, aGroupType ));
2606 if ( anIter == aGroupsMap.end() ) {
2607 // add a new group in the mesh
2608 aNewGroup = aNewImpl->CreateGroup( aGroupType, aGroupName );
2609 // add elements into new group
2610 aNewGroup->Add( anNewIDs );
2612 aListOfNewGroups.push_back(aNewGroup);
2613 aGroupsMap.insert(make_pair( make_pair(aGroupName, aGroupType), aListOfNewGroups ));
2616 else if ( theUniteIdenticalGroups ) {
2617 // unite identical groups
2618 TListOfNewGroups& aNewGroups = anIter->second;
2619 aNewGroups.front()->Add( anNewIDs );
2623 // rename identical groups
2624 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
2625 aNewGroup->Add( anNewIDs );
2627 TListOfNewGroups& aNewGroups = anIter->second;
2628 string aNewGroupName;
2629 if (aNewGroups.size() == 1) {
2630 aNewGroupName = string(aGroupName) + "_1";
2631 aNewGroups.front()->SetName(aNewGroupName.c_str());
2633 char aGroupNum[128];
2634 sprintf(aGroupNum, "%u", aNewGroups.size()+1);
2635 aNewGroupName = string(aGroupName) + "_" + string(aGroupNum);
2636 aNewGroup->SetName(aNewGroupName.c_str());
2637 aNewGroups.push_back(aNewGroup);
2640 } // if an IDSource is a mesh
2643 if (theMergeNodesAndElements) // merge nodes
2645 TIDSortedNodeSet aMeshNodes; // no input nodes
2646 SMESH_MeshEditor::TListOfListOfNodes aGroupsOfNodes;
2647 aNewEditor.FindCoincidentNodes( aMeshNodes, theMergeTolerance, aGroupsOfNodes,
2648 /*SeparateCornersAndMedium=*/ false );
2649 aNewEditor.MergeNodes( aGroupsOfNodes );
2651 aNewEditor.MergeEqualElements();
2654 // Update Python script
2655 aPythonDump << aNewMesh << " = " << this << "."
2656 << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" )
2658 for ( int i = 0; i < theMeshesArray.length(); i++) {
2659 if (i > 0) aPythonDump << ", ";
2660 aPythonDump << theMeshesArray[i];
2662 aPythonDump << "], ";
2663 aPythonDump << theUniteIdenticalGroups << ", "
2664 << theMergeNodesAndElements << ", "
2665 << TVar( theMergeTolerance ) << ")";
2667 delete pPythonDump; // enable python dump from GetGroups()
2669 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2670 if ( !aNewMesh->_is_nil() )
2672 SMESH::ListOfGroups_var groups = aNewMesh->GetGroups();
2675 // IPAL21468 Change icon of compound because it need not be computed.
2676 SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( myCurrentStudy, aNewMesh );
2677 SetPixMap( aMeshSObj, "ICON_SMESH_TREE_MESH" );
2680 aNewMeshDS->Modified();
2682 return aNewMesh._retn();
2685 //================================================================================
2687 * \brief Create a mesh by copying a part of another mesh
2688 * \param meshPart - a part of mesh to copy
2689 * \param toCopyGroups - to create in the new mesh groups
2690 * the copied elements belongs to
2691 * \param toKeepIDs - to preserve IDs of the copied elements or not
2692 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2694 //================================================================================
2696 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2697 const char* meshName,
2698 CORBA::Boolean toCopyGroups,
2699 CORBA::Boolean toKeepIDs)
2701 Unexpect aCatch(SALOME_SalomeException);
2703 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2705 // 1. Get source mesh
2707 if ( CORBA::is_nil( meshPart ))
2708 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2710 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2711 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2713 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2715 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2717 // 2. Make a new mesh
2719 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2720 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2722 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2723 SALOMEDS::SObject_wrap meshSO = ObjectToSObject(myCurrentStudy, newMesh );
2724 if ( !meshSO->_is_nil() )
2726 SetName( meshSO, meshName, "Mesh" );
2727 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2729 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2730 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2731 ::SMESH_MeshEditor::ElemFeatures elemType;
2733 // 3. Get elements to copy
2735 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2736 TIDSortedElemSet srcElems;
2737 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2738 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2741 srcElemIt = srcMeshDS->elementsIterator();
2742 srcNodeIt = srcMeshDS->nodesIterator();
2746 SMESH::long_array_var ids = meshPart->GetIDs();
2747 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2749 for (int i=0; i < ids->length(); i++)
2750 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2751 srcElems.insert( elem );
2755 for (int i=0; i < ids->length(); i++)
2756 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2757 srcElems.insert( elem );
2759 if ( srcElems.empty() )
2760 return newMesh._retn();
2762 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2763 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2768 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2769 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2770 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2772 const SMDS_MeshNode *nSrc, *nTgt;
2773 vector< const SMDS_MeshNode* > nodes;
2774 while ( srcElemIt->more() )
2776 const SMDS_MeshElement * elem = srcElemIt->next();
2778 nodes.resize( elem->NbNodes());
2779 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2781 for ( iN = 0; nIt->more(); ++iN )
2783 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2784 nTgt = newMeshDS->FindNode( nSrc->GetID());
2786 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2791 for ( iN = 0; nIt->more(); ++iN )
2793 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2794 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2796 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2797 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2801 if ( elem->GetType() != SMDSAbs_Node )
2803 elemType.Init( elem, /*basicOnly=*/false );
2804 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2806 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2807 if ( toCopyGroups && !toKeepIDs )
2808 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2810 } // while ( srcElemIt->more() )
2812 // 4(b). Copy free nodes
2814 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2816 while ( srcNodeIt->more() )
2818 nSrc = srcNodeIt->next();
2819 if ( nSrc->NbInverseElements() == 0 )
2822 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2824 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2831 int nbNewGroups = 0;
2834 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2835 while ( gIt->more() )
2837 SMESH_Group* group = gIt->next();
2838 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2840 // Check group type. We copy nodal groups containing nodes of copied element
2841 SMDSAbs_ElementType groupType = groupDS->GetType();
2842 if ( groupType != SMDSAbs_Node &&
2843 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2844 continue; // group type differs from types of meshPart
2846 // Find copied elements in the group
2847 vector< const SMDS_MeshElement* > groupElems;
2848 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2851 const SMDS_MeshElement* foundElem;
2852 if ( groupType == SMDSAbs_Node )
2854 while ( eIt->more() )
2855 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2856 groupElems.push_back( foundElem );
2860 while ( eIt->more() )
2861 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2862 groupElems.push_back( foundElem );
2867 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2868 if ( e2eMap.empty() ) continue;
2869 int minID = e2eMap.begin()->first->GetID();
2870 int maxID = e2eMap.rbegin()->first->GetID();
2871 TE2EMap::iterator e2e;
2872 while ( eIt->more() && groupElems.size() < e2eMap.size())
2874 const SMDS_MeshElement* e = eIt->next();
2875 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2876 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2877 groupElems.push_back( e2e->second );
2881 if ( !groupElems.empty() )
2883 SMESH::SMESH_Group_var newGroupObj =
2884 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2885 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2887 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2888 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2889 for ( unsigned i = 0; i < groupElems.size(); ++i )
2890 smdsGroup.Add( groupElems[i] );
2898 newMeshDS->Modified();
2900 *pyDump << newMesh << " = " << this
2901 << ".CopyMesh( " << meshPart << ", "
2902 << "'" << meshName << "', "
2903 << toCopyGroups << ", "
2904 << toKeepIDs << ")";
2906 delete pyDump; pyDump = 0; // allow dump in GetGroups()
2908 if ( nbNewGroups > 0 ) // dump created groups
2909 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2911 return newMesh._retn();
2914 //================================================================================
2916 * SMESH_Gen_i::GetMEDVersion
2918 * Get MED version of the file by its name
2920 //================================================================================
2921 CORBA::Boolean SMESH_Gen_i::GetMEDVersion(const char* theFileName,
2922 SMESH::MED_VERSION& theVersion)
2924 theVersion = SMESH::MED_V2_1;
2925 MED::EVersion aVersion = MED::GetVersionId( theFileName );
2926 switch( aVersion ) {
2927 case MED::eV2_1 : theVersion = SMESH::MED_V2_1; return true;
2928 case MED::eV2_2 : theVersion = SMESH::MED_V2_2; return true;
2929 case MED::eVUnknown : return false;
2934 //================================================================================
2936 * SMESH_Gen_i::GetMeshNames
2938 * Get names of meshes defined in file with the specified name
2940 //================================================================================
2941 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
2943 SMESH::string_array_var aResult = new SMESH::string_array();
2944 MED::PWrapper aMed = MED::CrWrapper( theFileName );
2946 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
2948 aResult->length( aNbMeshes );
2949 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
2950 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
2951 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
2954 return aResult._retn();
2957 //=============================================================================
2961 * Save SMESH module's data
2963 //=============================================================================
2964 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
2968 // ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
2969 // san -- in case <myCurrentStudy> differs from theComponent's study,
2970 // use that of the component
2971 if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
2972 SetCurrentStudy( theComponent->GetStudy() );
2974 // Store study contents as a set of python commands
2975 SavePython(myCurrentStudy);
2977 StudyContext* myStudyContext = GetCurrentStudyContext();
2979 // Declare a byte stream
2980 SALOMEDS::TMPFile_var aStreamFile;
2982 // Obtain a temporary dir
2983 TCollection_AsciiString tmpDir =
2984 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
2986 // Create a sequence of files processed
2987 SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
2988 aFileSeq->length( NUM_TMP_FILES );
2990 TCollection_AsciiString aStudyName( "" );
2992 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
2994 // Set names of temporary files
2995 TCollection_AsciiString filename =
2996 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
2997 TCollection_AsciiString meshfile =
2998 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
2999 aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
3000 aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
3001 filename = tmpDir + filename;
3002 meshfile = tmpDir + meshfile;
3005 HDFdataset* aDataset;
3006 HDFgroup* aTopGroup;
3008 HDFgroup* aSubGroup;
3009 HDFgroup* aSubSubGroup;
3010 hdf_size aSize[ 1 ];
3013 //Remove the files if they exist: BugID: 11225
3014 #ifndef WIN32 /* unix functionality */
3015 TCollection_AsciiString cmd("rm -f \"");
3017 TCollection_AsciiString cmd("del /F \"");
3024 system(cmd.ToCString());
3026 // MED writer to be used by storage process
3027 DriverMED_W_SMESHDS_Mesh myWriter;
3028 myWriter.SetFile( meshfile.ToCString() );
3031 // SetStoreName() to groups before storing hypotheses to let them refer to
3032 // groups using "store name", which is "Group <group_persistent_id>"
3034 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
3035 for ( ; itBig->More(); itBig->Next() ) {
3036 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3037 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3038 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3039 if ( !CORBA::is_nil( anObject ) ) {
3040 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3041 if ( !myMesh->_is_nil() ) {
3042 myMesh->Load(); // load from study file if not yet done
3043 TPythonDump pd; // not to dump GetGroups()
3044 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
3045 pd << ""; // to avoid optimizing pd out
3046 for ( int i = 0; i < groups->length(); ++i )
3048 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
3051 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
3052 int anId = myStudyContext->findId( string( objStr.in() ) );
3054 sprintf( grpName, "Group %d", anId );
3055 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
3056 aGrpBaseDS->SetStoreName( grpName );
3066 // ---> create HDF file
3067 aFile = new HDFfile( (char*) filename.ToCString() );
3068 aFile->CreateOnDisk();
3070 // --> iterator for top-level objects
3071 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
3072 for ( ; itBig->More(); itBig->Next() ) {
3073 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3075 // --> hypotheses root branch (only one for the study)
3076 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
3077 // create hypotheses root HDF group
3078 aTopGroup = new HDFgroup( "Hypotheses", aFile );
3079 aTopGroup->CreateOnDisk();
3081 // iterator for all hypotheses
3082 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
3083 for ( ; it->More(); it->Next() ) {
3084 SALOMEDS::SObject_wrap mySObject = it->Value();
3085 CORBA::Object_var anObject = SObjectToObject( mySObject );
3086 if ( !CORBA::is_nil( anObject ) ) {
3087 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3088 if ( !myHyp->_is_nil() ) {
3089 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3091 string hypname = string( myHyp->GetName() );
3092 string libname = string( myHyp->GetLibName() );
3094 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3095 // WIN32 and ".so" for X-system) must be deleted
3096 int libname_len = libname.length();
3098 if( libname_len > 4 )
3099 libname.resize( libname_len - 4 );
3101 // PAL17753 (Regresion: missing hypothesis in restored study)
3102 // "lib" also should be removed from the beginning
3103 //if( libname_len > 3 )
3104 //libname.resize( libname_len - 3 );
3105 if( libname_len > 6 )
3106 libname = libname.substr( 3, libname_len - 3 - 3 );
3108 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3109 int id = myStudyContext->findId( string( objStr.in() ) );
3110 string hypdata = string( myImpl->SaveTo() );
3112 // for each hypothesis create HDF group basing on its id
3113 char hypGrpName[30];
3114 sprintf( hypGrpName, "Hypothesis %d", id );
3115 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3116 aGroup->CreateOnDisk();
3117 // --> type name of hypothesis
3118 aSize[ 0 ] = hypname.length() + 1;
3119 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3120 aDataset->CreateOnDisk();
3121 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3122 aDataset->CloseOnDisk();
3123 // --> server plugin library name of hypothesis
3124 aSize[ 0 ] = libname.length() + 1;
3125 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3126 aDataset->CreateOnDisk();
3127 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3128 aDataset->CloseOnDisk();
3129 // --> persistent data of hypothesis
3130 aSize[ 0 ] = hypdata.length() + 1;
3131 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3132 aDataset->CreateOnDisk();
3133 aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
3134 aDataset->CloseOnDisk();
3135 // close hypothesis HDF group
3136 aGroup->CloseOnDisk();
3141 // close hypotheses root HDF group
3142 aTopGroup->CloseOnDisk();
3144 // --> algorithms root branch (only one for the study)
3145 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
3146 // create algorithms root HDF group
3147 aTopGroup = new HDFgroup( "Algorithms", aFile );
3148 aTopGroup->CreateOnDisk();
3150 // iterator for all algorithms
3151 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
3152 for ( ; it->More(); it->Next() ) {
3153 SALOMEDS::SObject_wrap mySObject = it->Value();
3154 CORBA::Object_var anObject = SObjectToObject( mySObject );
3155 if ( !CORBA::is_nil( anObject ) ) {
3156 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3157 if ( !myHyp->_is_nil() ) {
3158 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3160 string hypname = string( myHyp->GetName() );
3161 string libname = string( myHyp->GetLibName() );
3163 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3164 // WIN32 and ".so" for X-system) must be deleted
3165 int libname_len = libname.length();
3167 if( libname_len > 4 )
3168 libname.resize( libname_len - 4 );
3170 // PAL17753 (Regresion: missing hypothesis in restored study)
3171 // "lib" also should be removed from the beginning
3172 //if( libname_len > 3 )
3173 //libname.resize( libname_len - 3 );
3174 if( libname_len > 6 )
3175 libname = libname.substr( 3, libname_len - 3 - 3 );
3177 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3178 int id = myStudyContext->findId( string( objStr.in() ) );
3179 string hypdata = string( myImpl->SaveTo() );
3181 // for each algorithm create HDF group basing on its id
3182 char hypGrpName[30];
3183 sprintf( hypGrpName, "Algorithm %d", id );
3184 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3185 aGroup->CreateOnDisk();
3186 // --> type name of algorithm
3187 aSize[0] = hypname.length() + 1;
3188 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3189 aDataset->CreateOnDisk();
3190 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3191 aDataset->CloseOnDisk();
3192 // --> server plugin library name of hypothesis
3193 aSize[0] = libname.length() + 1;
3194 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3195 aDataset->CreateOnDisk();
3196 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3197 aDataset->CloseOnDisk();
3198 // --> persistent data of algorithm
3199 aSize[0] = hypdata.length() + 1;
3200 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3201 aDataset->CreateOnDisk();
3202 aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
3203 aDataset->CloseOnDisk();
3204 // close algorithm HDF group
3205 aGroup->CloseOnDisk();
3210 // close algorithms root HDF group
3211 aTopGroup->CloseOnDisk();
3213 // --> mesh objects roots branches
3214 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3215 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3216 if ( !CORBA::is_nil( anObject ) ) {
3217 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3218 if ( !myMesh->_is_nil() ) {
3219 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
3221 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3222 int id = myStudyContext->findId( string( objStr.in() ) );
3223 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
3224 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
3225 bool hasShape = myLocMesh.HasShapeToMesh();
3227 // for each mesh open the HDF group basing on its id
3228 char meshGrpName[ 30 ];
3229 sprintf( meshGrpName, "Mesh %d", id );
3230 aTopGroup = new HDFgroup( meshGrpName, aFile );
3231 aTopGroup->CreateOnDisk();
3233 // --> put dataset to hdf file which is a flag that mesh has data
3234 string strHasData = "0";
3235 // check if the mesh is not empty
3236 if ( mySMESHDSMesh->NbNodes() > 0 ) {
3237 // write mesh data to med file
3238 myWriter.SetMesh( mySMESHDSMesh );
3239 myWriter.SetMeshId( id );
3242 aSize[ 0 ] = strHasData.length() + 1;
3243 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
3244 aDataset->CreateOnDisk();
3245 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
3246 aDataset->CloseOnDisk();
3249 // for each mesh open the HDF group basing on its auto color parameter
3250 char meshAutoColorName[ 30 ];
3251 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
3253 anAutoColor[0] = myImpl->GetAutoColor();
3255 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
3256 aDataset->CreateOnDisk();
3257 aDataset->WriteOnDisk( anAutoColor );
3258 aDataset->CloseOnDisk();
3260 // issue 0020693. Store _isModified flag
3261 int isModified = myLocMesh.GetIsModified();
3263 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
3264 aDataset->CreateOnDisk();
3265 aDataset->WriteOnDisk( &isModified );
3266 aDataset->CloseOnDisk();
3268 // issue 20918. Store Persistent Id of SMESHDS_Mesh
3269 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
3271 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
3272 aDataset->CreateOnDisk();
3273 aDataset->WriteOnDisk( &meshPersistentId );
3274 aDataset->CloseOnDisk();
3276 // write reference on a shape if exists
3277 SALOMEDS::SObject_wrap myRef;
3278 bool shapeRefFound = false;
3279 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
3281 SALOMEDS::SObject_wrap myShape;
3282 bool ok = myRef->ReferencedObject( myShape.inout() );
3284 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
3285 string myRefOnObject = myShape->GetID();
3286 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
3287 aSize[ 0 ] = myRefOnObject.length() + 1;
3288 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
3289 aDataset->CreateOnDisk();
3290 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3291 aDataset->CloseOnDisk();
3296 // write applied hypotheses if exist
3297 SALOMEDS::SObject_wrap myHypBranch;
3298 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
3299 if ( found && !shapeRefFound && hasShape) { // remove applied hyps
3300 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
3302 if ( found && (shapeRefFound || !hasShape) ) {
3303 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
3304 aGroup->CreateOnDisk();
3306 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myHypBranch );
3308 for ( ; it->More(); it->Next() ) {
3309 SALOMEDS::SObject_wrap mySObject = it->Value();
3310 SALOMEDS::SObject_wrap myRefOnHyp;
3311 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
3313 // san - it is impossible to recover applied hypotheses
3314 // using their entries within Load() method,
3315 // for there are no AttributeIORs in the study when Load() is working.
3316 // Hence, it is better to store persistent IDs of hypotheses as references to them
3318 //string myRefOnObject = myRefOnHyp->GetID();
3319 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3320 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3321 int id = myStudyContext->findId( string( objStr.in() ) );
3322 //if ( myRefOnObject.length() > 0 ) {
3323 //aSize[ 0 ] = myRefOnObject.length() + 1;
3324 char hypName[ 30 ], hypId[ 30 ];
3325 sprintf( hypName, "Hyp %d", ++hypNb );
3326 sprintf( hypId, "%d", id );
3327 aSize[ 0 ] = strlen( hypId ) + 1;
3328 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
3329 aDataset->CreateOnDisk();
3330 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3331 aDataset->WriteOnDisk( hypId );
3332 aDataset->CloseOnDisk();
3336 aGroup->CloseOnDisk();
3339 // write applied algorithms if exist
3340 SALOMEDS::SObject_wrap myAlgoBranch;
3341 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3342 myAlgoBranch.inout() );
3343 if ( found && !shapeRefFound && hasShape) { // remove applied algos
3344 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
3346 if ( found && (shapeRefFound || !hasShape)) {
3347 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3348 aGroup->CreateOnDisk();
3350 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myAlgoBranch );
3352 for ( ; it->More(); it->Next() ) {
3353 SALOMEDS::SObject_wrap mySObject = it->Value();
3354 SALOMEDS::SObject_wrap myRefOnAlgo;
3355 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
3357 // san - it is impossible to recover applied algorithms
3358 // using their entries within Load() method,
3359 // for there are no AttributeIORs in the study when Load() is working.
3360 // Hence, it is better to store persistent IDs of algorithms as references to them
3362 //string myRefOnObject = myRefOnAlgo->GetID();
3363 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3364 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3365 int id = myStudyContext->findId( string( objStr.in() ) );
3366 //if ( myRefOnObject.length() > 0 ) {
3367 //aSize[ 0 ] = myRefOnObject.length() + 1;
3368 char algoName[ 30 ], algoId[ 30 ];
3369 sprintf( algoName, "Algo %d", ++algoNb );
3370 sprintf( algoId, "%d", id );
3371 aSize[ 0 ] = strlen( algoId ) + 1;
3372 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
3373 aDataset->CreateOnDisk();
3374 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3375 aDataset->WriteOnDisk( algoId );
3376 aDataset->CloseOnDisk();
3380 aGroup->CloseOnDisk();
3383 // --> submesh objects sub-branches
3385 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
3386 SALOMEDS::SObject_wrap mySubmeshBranch;
3387 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
3389 if ( found ) // check if there is shape reference in submeshes
3391 bool hasShapeRef = false;
3392 SALOMEDS::ChildIterator_wrap itSM =
3393 myCurrentStudy->NewChildIterator( mySubmeshBranch );
3394 for ( ; itSM->More(); itSM->Next() ) {
3395 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
3396 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3397 mySubRef->ReferencedObject( myShape.inout() );
3398 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
3401 { // remove one submesh
3402 if ( shapeRefFound )
3403 { // unassign hypothesis
3404 SMESH::SMESH_subMesh_var mySubMesh =
3405 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
3406 if ( !mySubMesh->_is_nil() ) {
3407 int shapeID = mySubMesh->GetId();
3408 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
3409 const list<const SMESHDS_Hypothesis*>& hypList =
3410 mySMESHDSMesh->GetHypothesis( S );
3411 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
3412 while ( hyp != hypList.end() ) {
3413 int hypID = (*hyp++)->GetID(); // goto next hyp here because
3414 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
3418 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
3420 } // loop on submeshes of a type
3421 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
3422 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
3425 } // end check if there is shape reference in submeshes
3427 char name_meshgroup[ 30 ];
3428 if ( i == GetSubMeshOnVertexTag() )
3429 strcpy( name_meshgroup, "SubMeshes On Vertex" );
3430 else if ( i == GetSubMeshOnEdgeTag() )
3431 strcpy( name_meshgroup, "SubMeshes On Edge" );
3432 else if ( i == GetSubMeshOnWireTag() )
3433 strcpy( name_meshgroup, "SubMeshes On Wire" );
3434 else if ( i == GetSubMeshOnFaceTag() )
3435 strcpy( name_meshgroup, "SubMeshes On Face" );
3436 else if ( i == GetSubMeshOnShellTag() )
3437 strcpy( name_meshgroup, "SubMeshes On Shell" );
3438 else if ( i == GetSubMeshOnSolidTag() )
3439 strcpy( name_meshgroup, "SubMeshes On Solid" );
3440 else if ( i == GetSubMeshOnCompoundTag() )
3441 strcpy( name_meshgroup, "SubMeshes On Compound" );
3443 // for each type of submeshes create container HDF group
3444 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
3445 aGroup->CreateOnDisk();
3447 // iterator for all submeshes of given type
3448 SALOMEDS::ChildIterator_wrap itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
3449 for ( ; itSM->More(); itSM->Next() ) {
3450 SALOMEDS::SObject_wrap mySObject = itSM->Value();
3451 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
3452 if ( !CORBA::is_nil( anSubObject ))
3454 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
3455 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
3456 int subid = myStudyContext->findId( string( objStr.in() ) );
3458 // for each mesh open the HDF group basing on its id
3459 char submeshGrpName[ 30 ];
3460 sprintf( submeshGrpName, "SubMesh %d", subid );
3461 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
3462 aSubGroup->CreateOnDisk();
3464 // write reference on a shape, already checked if it exists
3465 SALOMEDS::SObject_wrap mySubRef, myShape;
3466 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3467 mySubRef->ReferencedObject( myShape.inout() );
3468 string myRefOnObject = myShape->GetID();
3469 if ( myRefOnObject.length() > 0 ) {
3470 aSize[ 0 ] = myRefOnObject.length() + 1;
3471 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
3472 aDataset->CreateOnDisk();
3473 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3474 aDataset->CloseOnDisk();
3477 // write applied hypotheses if exist
3478 SALOMEDS::SObject_wrap mySubHypBranch;
3479 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
3480 mySubHypBranch.inout() );
3482 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
3483 aSubSubGroup->CreateOnDisk();
3485 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( mySubHypBranch );
3487 for ( ; it->More(); it->Next() ) {
3488 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3489 SALOMEDS::SObject_wrap myRefOnHyp;
3490 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
3492 //string myRefOnObject = myRefOnHyp->GetID();
3493 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3494 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3495 int id = myStudyContext->findId( string( objStr.in() ) );
3496 //if ( myRefOnObject.length() > 0 ) {
3497 //aSize[ 0 ] = myRefOnObject.length() + 1;
3498 char hypName[ 30 ], hypId[ 30 ];
3499 sprintf( hypName, "Hyp %d", ++hypNb );
3500 sprintf( hypId, "%d", id );
3501 aSize[ 0 ] = strlen( hypId ) + 1;
3502 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
3503 aDataset->CreateOnDisk();
3504 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3505 aDataset->WriteOnDisk( hypId );
3506 aDataset->CloseOnDisk();
3510 aSubSubGroup->CloseOnDisk();
3513 // write applied algorithms if exist
3514 SALOMEDS::SObject_wrap mySubAlgoBranch;
3515 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3516 mySubAlgoBranch.inout() );
3518 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3519 aSubSubGroup->CreateOnDisk();
3521 SALOMEDS::ChildIterator_wrap it =
3522 myCurrentStudy->NewChildIterator( mySubAlgoBranch );
3524 for ( ; it->More(); it->Next() ) {
3525 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3526 SALOMEDS::SObject_wrap myRefOnAlgo;
3527 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
3529 //string myRefOnObject = myRefOnAlgo->GetID();
3530 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3531 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3532 int id = myStudyContext->findId( string( objStr.in() ) );
3533 //if ( myRefOnObject.length() > 0 ) {
3534 //aSize[ 0 ] = myRefOnObject.length() + 1;
3535 char algoName[ 30 ], algoId[ 30 ];
3536 sprintf( algoName, "Algo %d", ++algoNb );
3537 sprintf( algoId, "%d", id );
3538 aSize[ 0 ] = strlen( algoId ) + 1;
3539 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
3540 aDataset->CreateOnDisk();
3541 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3542 aDataset->WriteOnDisk( algoId );
3543 aDataset->CloseOnDisk();
3547 aSubSubGroup->CloseOnDisk();
3549 // close submesh HDF group
3550 aSubGroup->CloseOnDisk();
3553 // close container of submeshes by type HDF group
3554 aGroup->CloseOnDisk();
3557 // All sub-meshes will be stored in MED file
3558 // .. will NOT (PAL 12992)
3559 //if ( shapeRefFound )
3560 //myWriter.AddAllSubMeshes();
3562 // store submesh order if any
3563 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
3564 if ( theOrderIds.size() ) {
3565 char order_list[ 30 ];
3566 strcpy( order_list, "Mesh Order" );
3567 // count number of submesh ids
3569 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
3570 for ( ; idIt != theOrderIds.end(); idIt++ )
3571 nbIDs += (*idIt).size();
3572 // number of values = number of IDs +
3573 // number of lists (for separators) - 1
3574 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
3575 idIt = theOrderIds.begin();
3576 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
3577 const TListOfInt& idList = *idIt;
3578 if (idIt != theOrderIds.begin()) // not first list
3579 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
3580 // dump submesh ids from current list
3581 TListOfInt::const_iterator id_smId = idList.begin();
3582 for( ; id_smId != idList.end(); id_smId++ )
3583 smIDs[ i++ ] = *id_smId;
3586 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
3588 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
3589 aDataset->CreateOnDisk();
3590 aDataset->WriteOnDisk( smIDs );
3591 aDataset->CloseOnDisk();
3596 // groups root sub-branch
3597 SALOMEDS::SObject_wrap myGroupsBranch;
3598 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
3599 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
3601 char name_group[ 30 ];
3602 if ( i == GetNodeGroupsTag() )
3603 strcpy( name_group, "Groups of Nodes" );
3604 else if ( i == GetEdgeGroupsTag() )
3605 strcpy( name_group, "Groups of Edges" );
3606 else if ( i == GetFaceGroupsTag() )
3607 strcpy( name_group, "Groups of Faces" );
3608 else if ( i == GetVolumeGroupsTag() )
3609 strcpy( name_group, "Groups of Volumes" );
3610 else if ( i == Get0DElementsGroupsTag() )
3611 strcpy( name_group, "Groups of 0D Elements" );
3612 else if ( i == GetBallElementsGroupsTag() )
3613 strcpy( name_group, "Groups of Balls" );
3615 aGroup = new HDFgroup( name_group, aTopGroup );
3616 aGroup->CreateOnDisk();
3618 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myGroupsBranch );
3619 for ( ; it->More(); it->Next() ) {
3620 SALOMEDS::SObject_wrap mySObject = it->Value();
3621 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
3622 if ( !CORBA::is_nil( aSubObject ) ) {
3623 SMESH_GroupBase_i* myGroupImpl =
3624 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
3627 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
3631 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
3632 int anId = myStudyContext->findId( string( objStr.in() ) );
3634 // For each group, create a dataset named "Group <group_persistent_id>"
3635 // and store the group's user name into it
3636 const char* grpName = aGrpBaseDS->GetStoreName();
3637 char* aUserName = myGroupImpl->GetName();
3638 aSize[ 0 ] = strlen( aUserName ) + 1;
3640 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
3641 aDataset->CreateOnDisk();
3642 aDataset->WriteOnDisk( aUserName );
3643 aDataset->CloseOnDisk();
3646 // For each group, create a dataset named "Group <group_persistent_id> Color"
3647 // and store the group's color into it
3648 char grpColorName[ 30 ];
3649 sprintf( grpColorName, "ColorGroup %d", anId );
3650 SALOMEDS::Color aColor = myGroupImpl->GetColor();
3652 anRGB[ 0 ] = aColor.R;
3653 anRGB[ 1 ] = aColor.G;
3654 anRGB[ 2 ] = aColor.B;
3656 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
3657 aDataset->CreateOnDisk();
3658 aDataset->WriteOnDisk( anRGB );
3659 aDataset->CloseOnDisk();
3661 // Pass SMESHDS_Group to MED writer
3662 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
3664 myWriter.AddGroup( aGrpDS );
3666 // write reference on a shape if exists
3667 SMESHDS_GroupOnGeom* aGeomGrp =
3668 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
3670 SALOMEDS::SObject_wrap mySubRef, myShape;
3671 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
3672 mySubRef->ReferencedObject( myShape.inout() ) &&
3673 !CORBA::is_nil( myShape->GetObject() ))
3675 string myRefOnObject = myShape->GetID();
3676 if ( myRefOnObject.length() > 0 ) {
3677 char aRefName[ 30 ];
3678 sprintf( aRefName, "Ref on shape %d", anId);
3679 aSize[ 0 ] = myRefOnObject.length() + 1;
3680 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
3681 aDataset->CreateOnDisk();
3682 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3683 aDataset->CloseOnDisk();
3686 else // shape ref is invalid:
3688 // save a group on geometry as ordinary group
3689 myWriter.AddGroup( aGeomGrp );
3692 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
3693 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
3695 std::string str = aFilterGrp_i->FilterToString();
3696 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
3697 aSize[ 0 ] = str.length() + 1;
3698 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
3699 aDataset->CreateOnDisk();
3700 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
3701 aDataset->CloseOnDisk();
3705 aGroup->CloseOnDisk();
3709 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
3711 // Flush current mesh information into MED file
3714 // save info on nb of elements
3715 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
3717 // maybe a shape was deleted in the study
3718 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
3719 TopoDS_Shape nullShape;
3720 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
3723 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
3728 aGroup = new HDFgroup( "Submeshes", aTopGroup );
3729 aGroup->CreateOnDisk();
3731 // each element belongs to one or none submesh,
3732 // so for each node/element, we store a submesh ID
3734 // Store submesh IDs
3735 for ( int isNode = 0; isNode < 2; ++isNode )
3737 SMDS_ElemIteratorPtr eIt =
3738 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
3739 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
3742 std::vector<int> smIDs; smIDs.reserve( nbElems );
3743 while ( eIt->more() )
3744 if ( const SMDS_MeshElement* e = eIt->next())
3745 smIDs.push_back( e->getshapeId() );
3747 aSize[ 0 ] = nbElems;
3748 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3749 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3750 aDataset->CreateOnDisk();
3751 aDataset->WriteOnDisk( & smIDs[0] );
3752 aDataset->CloseOnDisk();
3755 aGroup->CloseOnDisk();
3757 // Store node positions on sub-shapes (SMDS_Position):
3758 // ----------------------------------------------------
3760 aGroup = new HDFgroup( "Node Positions", aTopGroup );
3761 aGroup->CreateOnDisk();
3763 // in aGroup, create 5 datasets to contain:
3764 // "Nodes on Edges" - ID of node on edge
3765 // "Edge positions" - U parameter on node on edge
3766 // "Nodes on Faces" - ID of node on face
3767 // "Face U positions" - U parameter of node on face
3768 // "Face V positions" - V parameter of node on face
3770 // Find out nb of nodes on edges and faces
3771 // Collect corresponing sub-meshes
3772 int nbEdgeNodes = 0, nbFaceNodes = 0;
3773 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
3774 // loop on SMESHDS_SubMesh'es
3775 while ( smIt->more() )
3777 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
3778 if ( aSubMesh->IsComplexSubmesh() )
3779 continue; // submesh containing other submeshs
3780 int nbNodes = aSubMesh->NbNodes();
3781 if ( nbNodes == 0 ) continue;
3783 int aShapeID = aSubMesh->GetID();
3784 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
3786 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
3787 // write only SMDS_FacePosition and SMDS_EdgePosition
3788 switch ( aShapeType ) {
3790 nbFaceNodes += nbNodes;
3791 aFaceSM.push_back( aSubMesh );
3794 nbEdgeNodes += nbNodes;
3795 aEdgeSM.push_back( aSubMesh );
3801 // Treat positions on edges or faces
3802 for ( int onFace = 0; onFace < 2; onFace++ )
3804 // Create arrays to store in datasets
3805 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
3806 if (!nbNodes) continue;
3807 int* aNodeIDs = new int [ nbNodes ];
3808 double* aUPos = new double [ nbNodes ];
3809 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
3812 // loop on sub-meshes
3813 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
3814 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
3815 for ( ; itSM != pListSM->end(); itSM++ )
3817 SMESHDS_SubMesh* aSubMesh = (*itSM);
3819 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
3820 // loop on nodes in aSubMesh
3821 while ( itNode->more() )
3824 const SMDS_MeshNode* node = itNode->next();
3825 aNodeIDs [ iNode ] = node->GetID();
3828 const SMDS_PositionPtr pos = node->GetPosition();
3829 if ( onFace ) { // on FACE
3830 const SMDS_FacePosition* fPos =
3831 dynamic_cast<const SMDS_FacePosition*>( pos );
3833 aUPos[ iNode ] = fPos->GetUParameter();
3834 aVPos[ iNode ] = fPos->GetVParameter();
3841 const SMDS_EdgePosition* ePos =
3842 dynamic_cast<const SMDS_EdgePosition*>( pos );
3844 aUPos[ iNode ] = ePos->GetUParameter();
3850 } // loop on nodes in aSubMesh
3851 } // loop on sub-meshes
3856 aSize[ 0 ] = nbNodes;
3858 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
3859 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3860 aDataset->CreateOnDisk();
3861 aDataset->WriteOnDisk( aNodeIDs );
3862 aDataset->CloseOnDisk();
3865 aDSName = ( onFace ? "Face U positions" : "Edge positions");
3866 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
3867 aDataset->CreateOnDisk();
3868 aDataset->WriteOnDisk( aUPos );
3869 aDataset->CloseOnDisk();
3872 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
3873 aDataset->CreateOnDisk();
3874 aDataset->WriteOnDisk( aVPos );
3875 aDataset->CloseOnDisk();
3880 if ( aVPos ) delete [] aVPos;
3882 } // treat positions on edges or faces
3884 // close "Node Positions" group
3885 aGroup->CloseOnDisk();
3887 } // if ( there are submeshes in SMESHDS_Mesh )
3890 // close mesh HDF group
3891 aTopGroup->CloseOnDisk();
3899 aFile->CloseOnDisk();
3902 // Convert temporary files to stream
3903 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
3905 // Remove temporary files and directory
3907 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
3909 return aStreamFile._retn();
3912 //=============================================================================
3914 * SMESH_Gen_i::SaveASCII
3916 * Save SMESH module's data in ASCII format
3918 //=============================================================================
3920 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
3922 bool isMultiFile ) {
3923 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
3924 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
3925 return aStreamFile._retn();
3927 //after usual saving needs to encipher binary to text string
3928 //Any binary symbol will be represent as "|xx" () hexadecimal format number
3929 int size = aStreamFile.in().length();
3930 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
3931 for ( int i = 0; i < size; i++ )
3932 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
3934 buffer[size * 3] = '\0';
3936 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
3938 return anAsciiStreamFile._retn();
3941 //=============================================================================
3943 * SMESH_Gen_i::loadGeomData
3945 * Load GEOM module data
3947 //=============================================================================
3949 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
3951 if ( theCompRoot->_is_nil() )
3954 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
3955 if ( aStudy->_is_nil() )
3958 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
3959 aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
3962 //=============================================================================
3966 * Load SMESH module's data
3968 //=============================================================================
3970 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
3971 const SALOMEDS::TMPFile& theStream,
3975 if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
3976 SetCurrentStudy( theComponent->GetStudy() );
3978 /* if( !theComponent->_is_nil() )
3980 //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
3981 if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
3982 loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
3985 StudyContext* myStudyContext = GetCurrentStudyContext();
3987 // Get temporary files location
3988 TCollection_AsciiString tmpDir =
3989 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
3991 // Convert the stream into sequence of files to process
3992 SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
3995 TCollection_AsciiString aStudyName( "" );
3996 if ( isMultiFile ) {
3997 CORBA::String_var url = myCurrentStudy->URL();
3998 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( url.in() ).c_str();
4000 // Set names of temporary files
4001 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
4002 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
4006 HDFdataset* aDataset;
4007 HDFgroup* aTopGroup;
4009 HDFgroup* aSubGroup;
4010 HDFgroup* aSubSubGroup;
4013 // ---> open HDF file
4014 aFile = new HDFfile( (char*) filename.ToCString() );
4016 aFile->OpenOnDisk( HDF_RDONLY );
4018 catch ( HDFexception ) {
4019 INFOS( "Load(): " << filename << " not found!" );
4023 TPythonDump pd; // prevent dump during loading
4025 // DriverMED_R_SMESHDS_Mesh myReader;
4026 // myReader.SetFile( meshfile.ToCString() );
4028 // For PAL13473 ("Repetitive mesh") implementation.
4029 // New dependencies between SMESH objects are established:
4030 // now hypotheses can refer to meshes, shapes and other hypotheses.
4031 // To keep data consistent, the following order of data restoration
4033 // 1. Create hypotheses
4034 // 2. Create all meshes
4035 // 3. Load hypotheses' data
4038 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
4039 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
4040 list< SMESH::Filter_var > filters;
4042 // get total number of top-level groups
4043 int aNbGroups = aFile->nInternalObjects();
4044 if ( aNbGroups > 0 ) {
4045 // --> in first turn we should read&create hypotheses
4046 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
4047 // open hypotheses root HDF group
4048 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4049 aTopGroup->OpenOnDisk();
4051 // get number of hypotheses
4052 int aNbObjects = aTopGroup->nInternalObjects();
4053 for ( int j = 0; j < aNbObjects; j++ ) {
4054 // try to identify hypothesis
4055 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4056 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4058 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
4059 // open hypothesis group
4060 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4061 aGroup->OpenOnDisk();
4063 // --> get hypothesis id
4064 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
4069 // get number of datasets
4070 int aNbSubObjects = aGroup->nInternalObjects();
4071 for ( int k = 0; k < aNbSubObjects; k++ ) {
4073 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4074 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4075 // --> get hypothesis name
4076 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4077 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4078 aDataset->OpenOnDisk();
4079 size = aDataset->GetSize();
4080 char* hypname_str = new char[ size ];
4081 aDataset->ReadFromDisk( hypname_str );
4082 hypname = string( hypname_str );
4083 delete [] hypname_str;
4084 aDataset->CloseOnDisk();
4086 // --> get hypothesis plugin library name
4087 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4088 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4089 aDataset->OpenOnDisk();
4090 size = aDataset->GetSize();
4091 char* libname_str = new char[ size ];
4092 aDataset->ReadFromDisk( libname_str );
4093 if(MYDEBUG) SCRUTE( libname_str );
4094 libname = string( libname_str );
4095 delete [] libname_str;
4096 aDataset->CloseOnDisk();
4098 // --> get hypothesis data
4099 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4100 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4101 aDataset->OpenOnDisk();
4102 size = aDataset->GetSize();
4103 char* hypdata_str = new char[ size ];
4104 aDataset->ReadFromDisk( hypdata_str );
4105 hypdata = string( hypdata_str );
4106 delete [] hypdata_str;
4107 aDataset->CloseOnDisk();
4110 // close hypothesis HDF group
4111 aGroup->CloseOnDisk();
4113 // --> restore hypothesis from data
4114 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4115 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
4116 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4117 SMESH::SMESH_Hypothesis_var myHyp;
4119 try { // protect persistence mechanism against exceptions
4120 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4123 INFOS( "Exception during hypothesis creation" );
4126 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4128 // myImpl->LoadFrom( hypdata.c_str() );
4129 hypDataList.push_back( make_pair( myImpl, hypdata ));
4130 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4131 int newId = myStudyContext->findId( iorString.in() );
4132 myStudyContext->mapOldToNew( id, newId );
4135 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4139 // close hypotheses root HDF group
4140 aTopGroup->CloseOnDisk();
4144 // --> then we should read&create algorithms
4145 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
4146 // open algorithms root HDF group
4147 aTopGroup = new HDFgroup( "Algorithms", aFile );
4148 aTopGroup->OpenOnDisk();
4150 // get number of algorithms
4151 int aNbObjects = aTopGroup->nInternalObjects();
4152 for ( int j = 0; j < aNbObjects; j++ ) {
4153 // try to identify algorithm
4154 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4155 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4157 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
4158 // open algorithm group
4159 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4160 aGroup->OpenOnDisk();
4162 // --> get algorithm id
4163 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
4168 // get number of datasets
4169 int aNbSubObjects = aGroup->nInternalObjects();
4170 for ( int k = 0; k < aNbSubObjects; k++ ) {
4172 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4173 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4174 // --> get algorithm name
4175 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4176 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4177 aDataset->OpenOnDisk();
4178 size = aDataset->GetSize();
4179 char* hypname_str = new char[ size ];
4180 aDataset->ReadFromDisk( hypname_str );
4181 hypname = string( hypname_str );
4182 delete [] hypname_str;
4183 aDataset->CloseOnDisk();
4185 // --> get algorithm plugin library name
4186 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4187 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4188 aDataset->OpenOnDisk();
4189 size = aDataset->GetSize();
4190 char* libname_str = new char[ size ];
4191 aDataset->ReadFromDisk( libname_str );
4192 if(MYDEBUG) SCRUTE( libname_str );
4193 libname = string( libname_str );
4194 delete [] libname_str;
4195 aDataset->CloseOnDisk();
4197 // --> get algorithm data
4198 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4199 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4200 aDataset->OpenOnDisk();
4201 size = aDataset->GetSize();
4202 char* hypdata_str = new char[ size ];
4203 aDataset->ReadFromDisk( hypdata_str );
4204 if(MYDEBUG) SCRUTE( hypdata_str );
4205 hypdata = string( hypdata_str );
4206 delete [] hypdata_str;
4207 aDataset->CloseOnDisk();
4210 // close algorithm HDF group
4211 aGroup->CloseOnDisk();
4213 // --> restore algorithm from data
4214 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4215 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
4216 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4217 SMESH::SMESH_Hypothesis_var myHyp;
4219 try { // protect persistence mechanism against exceptions
4220 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4223 INFOS( "Exception during hypothesis creation" );
4226 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4228 //myImpl->LoadFrom( hypdata.c_str() );
4229 hypDataList.push_back( make_pair( myImpl, hypdata ));
4230 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4231 int newId = myStudyContext->findId( iorString.in() );
4232 myStudyContext->mapOldToNew( id, newId );
4235 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4239 // close algorithms root HDF group
4240 aTopGroup->CloseOnDisk();
4244 // --> the rest groups should be meshes
4245 for ( int i = 0; i < aNbGroups; i++ ) {
4246 // identify next group
4247 char meshName[ HDF_NAME_MAX_LEN+1 ];
4248 aFile->InternalObjectIndentify( i, meshName );
4250 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
4252 int id = atoi( string( meshName ).substr( 4 ).c_str() );
4256 // open mesh HDF group
4257 aTopGroup = new HDFgroup( meshName, aFile );
4258 aTopGroup->OpenOnDisk();
4260 // get number of child HDF objects
4261 int aNbObjects = aTopGroup->nInternalObjects();
4262 if ( aNbObjects > 0 ) {
4264 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
4265 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
4266 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
4267 if ( !myNewMeshImpl )
4269 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
4271 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
4272 int newId = myStudyContext->findId( iorString.in() );
4273 myStudyContext->mapOldToNew( id, newId );
4276 // try to read and set auto color flag
4277 char aMeshAutoColorName[ 30 ];
4278 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
4279 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
4281 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
4282 aDataset->OpenOnDisk();
4283 size = aDataset->GetSize();
4284 int* anAutoColor = new int[ size ];
4285 aDataset->ReadFromDisk( anAutoColor );
4286 aDataset->CloseOnDisk();
4287 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
4288 delete [] anAutoColor;
4291 // try to read and set reference to shape
4292 GEOM::GEOM_Object_var aShapeObject;
4293 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
4294 // load mesh "Ref on shape" - it's an entry to SObject
4295 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
4296 aDataset->OpenOnDisk();
4297 size = aDataset->GetSize();
4298 char* refFromFile = new char[ size ];
4299 aDataset->ReadFromDisk( refFromFile );
4300 aDataset->CloseOnDisk();
4301 if ( strlen( refFromFile ) > 0 ) {
4302 SALOMEDS::SObject_wrap shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4304 // Make sure GEOM data are loaded first
4305 //loadGeomData( shapeSO->GetFatherComponent() );
4307 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4308 if ( !CORBA::is_nil( shapeObject ) ) {
4309 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4310 if ( !aShapeObject->_is_nil() )
4311 myNewMeshImpl->SetShape( aShapeObject );
4314 delete [] refFromFile;
4317 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
4318 if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
4320 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
4321 aDataset->OpenOnDisk();
4322 size = aDataset->GetSize();
4323 int* meshPersistentId = new int[ size ];
4324 aDataset->ReadFromDisk( meshPersistentId );
4325 aDataset->CloseOnDisk();
4326 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
4327 delete [] meshPersistentId;
4333 // As all object that can be referred by hypothesis are created,
4334 // we can restore hypothesis data
4336 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
4337 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4339 SMESH_Hypothesis_i* hyp = hyp_data->first;
4340 string & data = hyp_data->second;
4341 hyp->LoadFrom( data.c_str() );
4344 // Restore the rest mesh data
4346 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
4347 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4349 aTopGroup = meshi_group->second;
4350 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4351 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4352 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4354 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
4355 bool hasData = false;
4358 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
4359 int newId = myStudyContext->findId( iorString.in() );
4360 int id = myStudyContext->getOldId( newId );
4362 // try to find mesh data dataset
4363 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
4364 // load mesh "has data" flag
4365 aDataset = new HDFdataset( "Has data", aTopGroup );
4366 aDataset->OpenOnDisk();
4367 size = aDataset->GetSize();
4368 char* strHasData = new char[ size ];
4369 aDataset->ReadFromDisk( strHasData );
4370 aDataset->CloseOnDisk();
4371 if ( strcmp( strHasData, "1") == 0 ) {
4372 // read mesh data from MED file
4373 // myReader.SetMesh( mySMESHDSMesh );
4374 // myReader.SetMeshId( id );
4375 // myReader.Perform();
4378 delete [] strHasData;
4381 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
4382 // nodes and elements are not yet put into sub-meshes)
4383 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4384 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4385 aGroup->OpenOnDisk();
4386 // get number of applied algorithms
4387 int aNbSubObjects = aGroup->nInternalObjects();
4388 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
4389 for ( int j = 0; j < aNbSubObjects; j++ ) {
4390 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4391 aGroup->InternalObjectIndentify( j, name_dataset );
4392 // check if it is an algorithm
4393 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
4394 aDataset = new HDFdataset( name_dataset, aGroup );
4395 aDataset->OpenOnDisk();
4396 size = aDataset->GetSize();
4397 char* refFromFile = new char[ size ];
4398 aDataset->ReadFromDisk( refFromFile );
4399 aDataset->CloseOnDisk();
4400 // san - it is impossible to recover applied algorithms using their entries within Load() method
4401 //SALOMEDS::SObject_wrap hypSO = myCurrentStudy->FindObjectID( refFromFile );
4402 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4403 int id = atoi( refFromFile );
4404 delete [] refFromFile;
4405 string anIOR = myStudyContext->getIORbyOldId( id );
4406 if ( !anIOR.empty() ) {
4407 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4408 if ( !CORBA::is_nil( hypObject ) ) {
4409 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4410 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4411 || !myNewMeshImpl->HasShapeToMesh()) )
4412 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4417 aGroup->CloseOnDisk();
4420 // try to get applied hypotheses
4421 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4422 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4423 aGroup->OpenOnDisk();
4424 // get number of applied hypotheses
4425 int aNbSubObjects = aGroup->nInternalObjects();
4426 for ( int j = 0; j < aNbSubObjects; j++ ) {
4427 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4428 aGroup->InternalObjectIndentify( j, name_dataset );
4429 // check if it is a hypothesis
4430 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4431 aDataset = new HDFdataset( name_dataset, aGroup );
4432 aDataset->OpenOnDisk();
4433 size = aDataset->GetSize();
4434 char* refFromFile = new char[ size ];
4435 aDataset->ReadFromDisk( refFromFile );
4436 aDataset->CloseOnDisk();
4437 // san - it is impossible to recover applied hypotheses using their entries within Load() method
4438 //SALOMEDS::SObject_wrap hypSO = myCurrentStudy->FindObjectID( refFromFile );
4439 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4440 int id = atoi( refFromFile );
4441 delete [] refFromFile;
4442 string anIOR = myStudyContext->getIORbyOldId( id );
4443 if ( !anIOR.empty() ) {
4444 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4445 if ( !CORBA::is_nil( hypObject ) ) {
4446 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4447 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4448 || !myNewMeshImpl->HasShapeToMesh()) )
4449 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4454 aGroup->CloseOnDisk();
4457 // --> try to find SUB-MESHES containers for each type of submesh
4458 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
4459 const char* name_meshgroup;
4460 if ( j == GetSubMeshOnVertexTag() )
4461 name_meshgroup = "SubMeshes On Vertex";
4462 else if ( j == GetSubMeshOnEdgeTag() )
4463 name_meshgroup = "SubMeshes On Edge";
4464 else if ( j == GetSubMeshOnWireTag() )
4465 name_meshgroup = "SubMeshes On Wire";
4466 else if ( j == GetSubMeshOnFaceTag() )
4467 name_meshgroup = "SubMeshes On Face";
4468 else if ( j == GetSubMeshOnShellTag() )
4469 name_meshgroup = "SubMeshes On Shell";
4470 else if ( j == GetSubMeshOnSolidTag() )
4471 name_meshgroup = "SubMeshes On Solid";
4472 else if ( j == GetSubMeshOnCompoundTag() )
4473 name_meshgroup = "SubMeshes On Compound";
4475 // try to get submeshes container HDF group
4476 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
4477 // open submeshes containers HDF group
4478 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4479 aGroup->OpenOnDisk();
4481 // get number of submeshes
4482 int aNbSubMeshes = aGroup->nInternalObjects();
4483 for ( int k = 0; k < aNbSubMeshes; k++ ) {
4485 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
4486 aGroup->InternalObjectIndentify( k, name_submeshgroup );
4487 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
4488 // --> get submesh id
4489 int subid = atoi( name_submeshgroup + 7 );
4492 // open submesh HDF group
4493 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
4494 aSubGroup->OpenOnDisk();
4496 // try to read and set reference to subshape
4497 GEOM::GEOM_Object_var aSubShapeObject;
4498 SMESH::SMESH_subMesh_var aSubMesh;
4500 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
4501 // load submesh "Ref on shape" - it's an entry to SObject
4502 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
4503 aDataset->OpenOnDisk();
4504 size = aDataset->GetSize();
4505 char* refFromFile = new char[ size ];
4506 aDataset->ReadFromDisk( refFromFile );
4507 aDataset->CloseOnDisk();
4508 if ( strlen( refFromFile ) > 0 ) {
4509 SALOMEDS::SObject_wrap subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
4510 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
4511 if ( !CORBA::is_nil( subShapeObject ) ) {
4512 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
4513 if ( !aSubShapeObject->_is_nil() )
4514 aSubMesh = SMESH::SMESH_subMesh::_duplicate
4515 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
4516 if ( aSubMesh->_is_nil() )
4518 string iorSubString = GetORB()->object_to_string( aSubMesh );
4519 int newSubId = myStudyContext->findId( iorSubString );
4520 myStudyContext->mapOldToNew( subid, newSubId );
4525 if ( aSubMesh->_is_nil() )
4528 // try to get applied algorithms
4529 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4530 // open "applied algorithms" HDF group
4531 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4532 aSubSubGroup->OpenOnDisk();
4533 // get number of applied algorithms
4534 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4535 for ( int l = 0; l < aNbSubObjects; l++ ) {
4536 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4537 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4538 // check if it is an algorithm
4539 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
4540 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4541 aDataset->OpenOnDisk();
4542 size = aDataset->GetSize();
4543 char* refFromFile = new char[ size ];
4544 aDataset->ReadFromDisk( refFromFile );
4545 aDataset->CloseOnDisk();
4547 int id = atoi( refFromFile );
4548 string anIOR = myStudyContext->getIORbyOldId( id );
4549 if ( !anIOR.empty() ) {
4550 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4551 if ( !CORBA::is_nil( hypObject ) ) {
4552 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4553 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4554 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4559 // close "applied algorithms" HDF group
4560 aSubSubGroup->CloseOnDisk();
4563 // try to get applied hypotheses
4564 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4565 // open "applied hypotheses" HDF group
4566 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4567 aSubSubGroup->OpenOnDisk();
4568 // get number of applied hypotheses
4569 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4570 for ( int l = 0; l < aNbSubObjects; l++ ) {
4571 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4572 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4573 // check if it is a hypothesis
4574 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4575 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4576 aDataset->OpenOnDisk();
4577 size = aDataset->GetSize();
4578 char* refFromFile = new char[ size ];
4579 aDataset->ReadFromDisk( refFromFile );
4580 aDataset->CloseOnDisk();
4582 int id = atoi( refFromFile );
4583 string anIOR = myStudyContext->getIORbyOldId( id );
4584 if ( !anIOR.empty() ) {
4585 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4586 if ( !CORBA::is_nil( hypObject ) ) {
4587 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4588 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4589 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4594 // close "APPLIED HYPOTHESES" hdf group
4595 aSubSubGroup->CloseOnDisk();
4598 // close SUB-MESH hdf group
4599 aSubGroup->CloseOnDisk();
4602 // close SUB-MESHES containers hdf group
4603 aGroup->CloseOnDisk();
4607 // try to get GROUPS
4608 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
4609 char name_group[ 30 ];
4610 if ( ii == GetNodeGroupsTag() )
4611 strcpy( name_group, "Groups of Nodes" );
4612 else if ( ii == GetEdgeGroupsTag() )
4613 strcpy( name_group, "Groups of Edges" );
4614 else if ( ii == GetFaceGroupsTag() )
4615 strcpy( name_group, "Groups of Faces" );
4616 else if ( ii == GetVolumeGroupsTag() )
4617 strcpy( name_group, "Groups of Volumes" );
4618 else if ( ii == Get0DElementsGroupsTag() )
4619 strcpy( name_group, "Groups of 0D Elements" );
4620 else if ( ii == GetBallElementsGroupsTag() )
4621 strcpy( name_group, "Groups of Balls" );
4623 if ( aTopGroup->ExistInternalObject( name_group ) ) {
4624 aGroup = new HDFgroup( name_group, aTopGroup );
4625 aGroup->OpenOnDisk();
4626 // get number of groups
4627 int aNbSubObjects = aGroup->nInternalObjects();
4628 for ( int j = 0; j < aNbSubObjects; j++ ) {
4629 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4630 aGroup->InternalObjectIndentify( j, name_dataset );
4631 // check if it is an group
4632 if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
4634 int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
4637 aDataset = new HDFdataset( name_dataset, aGroup );
4638 aDataset->OpenOnDisk();
4640 // Retrieve actual group name
4641 size = aDataset->GetSize();
4642 char* nameFromFile = new char[ size ];
4643 aDataset->ReadFromDisk( nameFromFile );
4644 aDataset->CloseOnDisk();
4646 // Try to find a shape reference
4647 TopoDS_Shape aShape;
4648 char aRefName[ 30 ];
4649 sprintf( aRefName, "Ref on shape %d", subid);
4650 if ( aGroup->ExistInternalObject( aRefName ) ) {
4651 // load mesh "Ref on shape" - it's an entry to SObject
4652 aDataset = new HDFdataset( aRefName, aGroup );
4653 aDataset->OpenOnDisk();
4654 size = aDataset->GetSize();
4655 char* refFromFile = new char[ size ];
4656 aDataset->ReadFromDisk( refFromFile );
4657 aDataset->CloseOnDisk();
4658 if ( strlen( refFromFile ) > 0 ) {
4659 SALOMEDS::SObject_wrap shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4660 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4661 if ( !CORBA::is_nil( shapeObject ) ) {
4662 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4663 if ( !aShapeObject->_is_nil() )
4664 aShape = GeomObjectToShape( aShapeObject );
4668 // Try to read a filter of SMESH_GroupOnFilter
4669 SMESH::Filter_var filter;
4670 SMESH_PredicatePtr predicate;
4671 std::string hdfGrpName = "Filter " + SMESH_Comment(subid);
4672 if ( aGroup->ExistInternalObject( hdfGrpName.c_str() ))
4674 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
4675 aDataset->OpenOnDisk();
4676 size = aDataset->GetSize();
4677 char* persistStr = new char[ size ];
4678 aDataset->ReadFromDisk( persistStr );
4679 aDataset->CloseOnDisk();
4680 if ( strlen( persistStr ) > 0 ) {
4681 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
4682 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
4683 filters.push_back( filter );
4687 // Create group servant
4688 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
4689 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
4690 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape, predicate ) );
4691 // Obtain a SMESHDS_Group object
4692 if ( aNewGroup->_is_nil() )
4695 string iorSubString = GetORB()->object_to_string( aNewGroup );
4696 int newSubId = myStudyContext->findId( iorSubString );
4697 myStudyContext->mapOldToNew( subid, newSubId );
4699 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
4703 if ( SMESH_GroupOnFilter_i* aFilterGroup =
4704 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
4706 aFilterGroup->SetFilter( filter );
4707 filter->UnRegister();
4709 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
4710 if ( !aGroupBaseDS )
4713 aGroupBaseDS->SetStoreName( name_dataset );
4716 // Read color of the group
4717 char aGroupColorName[ 30 ];
4718 sprintf( aGroupColorName, "ColorGroup %d", subid);
4719 if ( aGroup->ExistInternalObject( aGroupColorName ) )
4721 aDataset = new HDFdataset( aGroupColorName, aGroup );
4722 aDataset->OpenOnDisk();
4723 size = aDataset->GetSize();
4724 double* anRGB = new double[ size ];
4725 aDataset->ReadFromDisk( anRGB );
4726 aDataset->CloseOnDisk();
4727 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
4728 aGroupBaseDS->SetColor( aColor );
4732 aGroup->CloseOnDisk();
4736 // instead of reading mesh data, we read only brief information of all
4737 // objects: mesh, groups, sub-meshes (issue 0021208 )
4740 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, id,
4741 meshfile.ToCString(), filename.ToCString(),
4745 // read Sub-Mesh ORDER if any
4746 if( aTopGroup->ExistInternalObject( "Mesh Order" ) ) {
4747 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
4748 aDataset->OpenOnDisk();
4749 size = aDataset->GetSize();
4750 int* smIDs = new int[ size ];
4751 aDataset->ReadFromDisk( smIDs );
4752 aDataset->CloseOnDisk();
4753 TListOfListOfInt anOrderIds;
4754 anOrderIds.push_back( TListOfInt() );
4755 for ( int i = 0; i < size; i++ )
4756 if ( smIDs[ i ] < 0 ) // is separator
4757 anOrderIds.push_back( TListOfInt() );
4759 anOrderIds.back().push_back(smIDs[ i ]);
4761 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
4765 // update hyps needing full mesh data restored (issue 20918)
4766 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4768 SMESH_Hypothesis_i* hyp = hyp_data->first;
4769 hyp->UpdateAsMeshesRestored();
4772 // notify algos on completed restoration to set sub-mesh event listeners
4773 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4775 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4776 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4778 TopoDS_Shape myLocShape;
4779 if(myLocMesh.HasShapeToMesh())
4780 myLocShape = myLocMesh.GetShapeToMesh();
4782 myLocShape = SMESH_Mesh::PseudoShape();
4784 myLocMesh.GetSubMesh(myLocShape)->
4785 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
4788 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
4789 list< SMESH::Filter_var >::iterator f = filters.begin();
4790 for ( ; f != filters.end(); ++f )
4791 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
4792 fi->FindBaseObjects();
4797 aTopGroup->CloseOnDisk();
4800 aFile->CloseOnDisk();
4803 // Remove temporary files created from the stream
4806 SMESH_File meshFile( meshfile.ToCString() );
4807 if ( !meshFile ) // no meshfile exists
4809 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
4813 Engines::Container_var container = GetContainerRef();
4814 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
4816 container_i->registerTemporaryFile( filename.ToCString() );
4817 container_i->registerTemporaryFile( meshfile.ToCString() );
4818 container_i->registerTemporaryFile( tmpDir.ToCString() );
4822 pd << ""; // prevent optimizing pd out
4824 // creation of tree nodes for all data objects in the study
4825 // to support tree representation customization and drag-n-drop:
4826 SALOMEDS::Study_var study = theComponent->GetStudy();
4827 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = study->GetUseCaseBuilder();
4828 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
4829 useCaseBuilder->SetRootCurrent();
4830 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
4831 SALOMEDS::ChildIterator_wrap it = study->NewChildIterator( theComponent );
4832 for (it->InitEx(true); it->More(); it->Next()) {
4833 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
4840 //=============================================================================
4842 * SMESH_Gen_i::LoadASCII
4844 * Load SMESH module's data in ASCII format
4846 //=============================================================================
4848 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
4849 const SALOMEDS::TMPFile& theStream,
4851 bool isMultiFile ) {
4852 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
4853 return Load( theComponent, theStream, theURL, isMultiFile );
4855 //before call main ::Load method it's need for decipher text format to
4856 //binary ( "|xx" => x' )
4857 int size = theStream.length();
4858 if ( int((size / 3 )*3) != size ) //error size of buffer
4861 int real_size = int(size / 3);
4863 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
4867 for ( int i = 0; i < real_size; i++ )
4869 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
4870 sscanf( tmp, "%x", &c );
4871 sprintf( (char*)&(buffer[i]), "%c", (char)c );
4874 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
4876 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
4879 //=============================================================================
4881 * SMESH_Gen_i::Close
4883 * Clears study-connected data when it is closed
4885 //=============================================================================
4887 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
4889 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
4891 // set correct current study
4892 SALOMEDS::Study_var study = theComponent->GetStudy();
4893 if ( study->StudyId() != GetCurrentStudyID())
4894 setCurrentStudy( study, /*IsBeingClosed=*/true );
4896 // Clear study contexts data
4897 int studyId = GetCurrentStudyID();
4898 if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
4899 delete myStudyContextMap[ studyId ];
4900 myStudyContextMap.erase( studyId );
4903 // remove the tmp files meshes are loaded from
4904 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
4906 myCurrentStudy = SALOMEDS::Study::_nil();
4910 //=============================================================================
4912 * SMESH_Gen_i::ComponentDataType
4914 * Get component data type
4916 //=============================================================================
4918 char* SMESH_Gen_i::ComponentDataType()
4920 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
4921 return CORBA::string_dup( "SMESH" );
4925 //=============================================================================
4927 * SMESH_Gen_i::IORToLocalPersistentID
4929 * Transform data from transient form to persistent
4931 //=============================================================================
4933 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
4934 const char* IORString,
4935 CORBA::Boolean /*isMultiFile*/,
4936 CORBA::Boolean /*isASCII*/ )
4938 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
4939 StudyContext* myStudyContext = GetCurrentStudyContext();
4941 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
4942 int anId = myStudyContext->findId( IORString );
4944 if(MYDEBUG) MESSAGE( "VSR " << anId )
4946 sprintf( strId, "%d", anId );
4947 return CORBA::string_dup( strId );
4950 return CORBA::string_dup( "" );
4953 //=============================================================================
4955 * SMESH_Gen_i::LocalPersistentIDToIOR
4957 * Transform data from persistent form to transient
4959 //=============================================================================
4961 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
4962 const char* aLocalPersistentID,
4963 CORBA::Boolean /*isMultiFile*/,
4964 CORBA::Boolean /*isASCII*/ )
4966 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
4967 StudyContext* myStudyContext = GetCurrentStudyContext();
4969 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
4970 int anId = atoi( aLocalPersistentID );
4971 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
4973 return CORBA::string_dup( "" );
4976 //=======================================================================
4977 //function : RegisterObject
4979 //=======================================================================
4981 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
4983 StudyContext* myStudyContext = GetCurrentStudyContext();
4984 if ( myStudyContext && !CORBA::is_nil( theObject )) {
4985 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
4986 return myStudyContext->addObject( string( iorString.in() ) );
4991 //================================================================================
4993 * \brief Return id of registered object
4994 * \param theObject - the Object
4995 * \retval int - Object id
4997 //================================================================================
4999 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
5001 StudyContext* myStudyContext = GetCurrentStudyContext();
5002 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5003 string iorString = GetORB()->object_to_string( theObject );
5004 return myStudyContext->findId( iorString );
5009 //=============================================================================
5011 * SMESH_Gen_i::SetName
5013 * Set a new object name
5015 //=============================================================================
5016 void SMESH_Gen_i::SetName(const char* theIOR,
5017 const char* theName)
5019 if ( theIOR && strcmp( theIOR, "" ) ) {
5020 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
5021 SALOMEDS::SObject_wrap aSO = ObjectToSObject( myCurrentStudy, anObject );
5022 if ( !aSO->_is_nil() ) {
5023 SetName( aSO, theName );
5028 int SMESH_Gen_i::GetCurrentStudyID()
5030 return myCurrentStudy->_is_nil() || myCurrentStudy->_non_existent() ? -1 : myCurrentStudy->StudyId();
5033 // Version information
5034 char* SMESH_Gen_i::getVersion()
5036 #if SMESH_DEVELOPMENT
5037 return CORBA::string_dup(SMESH_VERSION_STR"dev");
5039 return CORBA::string_dup(SMESH_VERSION_STR);
5043 //=================================================================================
5044 // function : Move()
5045 // purpose : Moves objects to the specified position.
5046 // Is used in the drag-n-drop functionality.
5047 //=================================================================================
5048 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
5049 SALOMEDS::SObject_ptr where,
5052 if ( CORBA::is_nil( where ) ) return;
5054 SALOMEDS::Study_var study = where->GetStudy();
5055 SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder();
5056 SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder();
5057 SALOMEDS::SComponent_var father = where->GetFatherComponent();
5058 std::string dataType = father->ComponentDataType();
5059 if ( dataType != "SMESH" ) return; // not a SMESH component
5061 SALOMEDS::SObject_var objAfter;
5062 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
5063 // insert at given row -> find insertion position
5064 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
5066 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
5067 if ( i == row && useCaseIt->More() ) {
5068 objAfter = useCaseIt->Value();
5072 for ( int i = 0; i < what.length(); i++ ) {
5073 SALOMEDS::SObject_var sobj = what[i];
5074 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
5075 // insert the object to the use case tree
5076 if ( !CORBA::is_nil( objAfter ) )
5077 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
5079 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
5082 //================================================================================
5084 * \brief Returns true if algorithm can be used to mesh a given geometry
5085 * \param [in] theAlgoType - the algorithm type
5086 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
5087 * \param [in] theGeomObject - the geometry to mesh
5088 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
5089 * else, returns \c True if at least one shape is meshable
5090 * \return CORBA::Boolean - can or can't
5092 //================================================================================
5094 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
5095 const char* theLibName,
5096 GEOM::GEOM_Object_ptr theGeomObject,
5097 CORBA::Boolean toCheckAll)
5101 std::string aPlatformLibName;
5102 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
5103 GenericHypothesisCreator_i* aCreator =
5104 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
5107 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
5108 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll );
5115 SMESH_CATCH( SMESH::doNothing );
5118 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
5123 //=================================================================================
5124 // function : GetInsideSphere
5125 // purpose : Collect indices of elements, which are located inside the sphere
5126 //=================================================================================
5127 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
5128 SMESH::ElementType theElemType,
5132 CORBA::Double theR) {
5133 SMESH::long_array_var aResult = new SMESH::long_array();
5134 if(meshPart->_is_nil())
5135 return aResult._retn();
5137 // 1. Create geometrical object
5138 gp_Pnt aP( theX, theY, theZ );
5139 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
5141 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5143 if( lst.size() > 0 ) {
5144 aResult->length( lst.size() );
5145 for ( long i = 0; i < lst.size(); i++ ) {
5146 aResult[i] = lst[i];
5149 return aResult._retn();
5152 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
5153 SMESH::ElementType theElemType,
5154 CORBA::Double theX1,
5155 CORBA::Double theY1,
5156 CORBA::Double theZ1,
5157 CORBA::Double theX2,
5158 CORBA::Double theY2,
5159 CORBA::Double theZ2) {
5160 SMESH::long_array_var aResult = new SMESH::long_array();
5161 if( meshPart->_is_nil() )
5162 return aResult._retn();
5164 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
5166 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5168 if( lst.size() > 0 ) {
5169 aResult->length( lst.size() );
5170 for ( long i = 0; i < lst.size(); i++ ) {
5171 aResult[i] = lst[i];
5174 return aResult._retn();
5177 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
5178 SMESH::ElementType theElemType,
5182 CORBA::Double theDX,
5183 CORBA::Double theDY,
5184 CORBA::Double theDZ,
5186 CORBA::Double theR ){
5187 SMESH::long_array_var aResult = new SMESH::long_array();
5188 if( meshPart->_is_nil() )
5189 return aResult._retn();
5191 gp_Pnt aP( theX, theY, theZ );
5192 gp_Vec aV( theDX, theDY, theDZ );
5193 gp_Ax2 anAxes (aP, aV);
5195 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
5197 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5199 if( lst.size() > 0 ) {
5200 aResult->length( lst.size() );
5201 for ( long i = 0; i < lst.size(); i++ ) {
5202 aResult[i] = lst[i];
5205 return aResult._retn();
5208 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5209 SMESH::ElementType theElemType,
5210 GEOM::GEOM_Object_ptr theGeom,
5211 CORBA::Double theTolerance ) {
5212 SMESH::long_array_var aResult = new SMESH::long_array();
5213 if( meshPart->_is_nil() || theGeom->_is_nil() )
5214 return aResult._retn();
5216 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
5218 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
5220 if( lst.size() > 0 ) {
5221 aResult->length( lst.size() );
5222 for ( long i = 0; i < lst.size(); i++ ) {
5223 aResult[i] = lst[i];
5226 return aResult._retn();
5231 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5232 SMESH::ElementType theElemType,
5233 TopoDS_Shape& aShape,
5234 double* theTolerance) {
5236 std::vector<long> res;
5237 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
5239 if ( mesh->_is_nil() )
5242 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
5246 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
5251 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
5252 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
5253 anElementsOnShape->SetAllNodes( true );
5254 anElementsOnShape->SetMesh( meshDS );
5255 anElementsOnShape->SetShape( aShape, aType );
5258 anElementsOnShape->SetTolerance(*theTolerance);
5260 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
5261 if ( !msource->_is_nil() ) { // Mesh case
5262 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
5264 while ( elemIt->more() ) {
5265 const SMDS_MeshElement* anElem = elemIt->next();
5266 long anId = anElem->GetID();
5267 if ( anElementsOnShape->IsSatisfy( anId ) )
5268 res.push_back( anId );
5272 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
5273 if ( !gsource->_is_nil() ) {
5274 if(theElemType == SMESH::NODE) {
5275 SMESH::long_array_var nodes = gsource->GetNodeIDs();
5276 for ( int i = 0; i < nodes->length(); ++i ) {
5277 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] ) ) {
5278 long anId = node->GetID();
5279 if ( anElementsOnShape->IsSatisfy( anId ) )
5280 res.push_back( anId );
5283 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
5284 SMESH::long_array_var elems = gsource->GetListOfID();
5285 for ( int i = 0; i < elems->length(); ++i ) {
5286 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] ) ) {
5287 long anId = elem->GetID();
5288 if ( anElementsOnShape->IsSatisfy( anId ) )
5289 res.push_back( anId );
5294 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
5295 if ( !smsource->_is_nil() ) {
5296 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
5297 for ( int i = 0; i < elems->length(); ++i ) {
5298 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
5300 long anId = elem->GetID();
5301 if ( anElementsOnShape->IsSatisfy( anId ) )
5302 res.push_back( anId );
5310 //=============================================================================
5312 * SMESHEngine_factory
5314 * C factory, accessible with dlsym, after dlopen
5316 //=============================================================================
5320 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
5321 PortableServer::POA_ptr poa,
5322 PortableServer::ObjectId* contId,
5323 const char* instanceName,
5324 const char* interfaceName )
5326 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
5327 if(MYDEBUG) SCRUTE(interfaceName);
5328 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
5329 return aSMESHGen->getId() ;