1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_Gen_i.cxx
23 // Author : Paul RASCLE, EDF
26 #include <BRepPrimAPI_MakeBox.hxx>
27 #include <BRepPrimAPI_MakeCylinder.hxx>
28 #include <BRepPrimAPI_MakeSphere.hxx>
29 #include <BRep_Tool.hxx>
31 #include <TColStd_MapOfAsciiString.hxx>
32 #include <TCollection_AsciiString.hxx>
34 #include <TopExp_Explorer.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopTools_ListIteratorOfListOfShape.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <TopTools_MapOfShape.hxx>
40 #include <TopoDS_CompSolid.hxx>
41 #include <TopoDS_Compound.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS_Face.hxx>
44 #include <TopoDS_Iterator.hxx>
45 #include <TopoDS_Shape.hxx>
46 #include <TopoDS_Shell.hxx>
47 #include <TopoDS_Solid.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopoDS_Wire.hxx>
58 #include <libgen.h> // for basename function
62 #define LibHandle HMODULE
63 #define LoadLib( name ) LoadLibrary( name )
64 #define GetProc GetProcAddress
65 #define UnLoadLib( handle ) FreeLibrary( handle );
67 #define LibHandle void*
69 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
70 #else // DYNLOAD_LOCAL
71 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
72 #endif // DYNLOAD_LOCAL
74 #define UnLoadLib( handle ) dlclose( handle );
77 #include "SMESH_Gen_i.hxx"
78 #include "SMESH_version.h"
80 #include "DriverMED_W_SMESHDS_Mesh.h"
81 #include "DriverMED_R_SMESHDS_Mesh.h"
83 #include "DriverCGNS_Read.hxx"
85 #include "MED_Factory.hxx"
86 #include "SMDS_EdgePosition.hxx"
87 #include "SMDS_FacePosition.hxx"
88 #include "SMDS_SetIterator.hxx"
89 #include "SMDS_SpacePosition.hxx"
90 #include "SMDS_VertexPosition.hxx"
91 #include "SMESHDS_Document.hxx"
92 #include "SMESHDS_Group.hxx"
93 #include "SMESHDS_GroupOnGeom.hxx"
94 #include "SMESH_Algo_i.hxx"
95 #include "SMESH_File.hxx"
96 #include "SMESH_Group.hxx"
97 #include "SMESH_Group_i.hxx"
98 #include "SMESH_Hypothesis.hxx"
99 #include "SMESH_Hypothesis_i.hxx"
100 #include "SMESH_Mesh.hxx"
101 #include "SMESH_MeshEditor.hxx"
102 #include "SMESH_Mesh_i.hxx"
103 #include "SMESH_PreMeshInfo.hxx"
104 #include "SMESH_PythonDump.hxx"
105 #include "SMESH_ControlsDef.hxx"
107 // to pass CORBA exception through SMESH_TRY
108 #define SMY_OWN_CATCH catch( SALOME::SALOME_Exception& se ) { throw se; }
109 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
111 #include CORBA_SERVER_HEADER(SMESH_Group)
112 #include CORBA_SERVER_HEADER(SMESH_Filter)
113 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
116 #include <GEOMImpl_Types.hxx>
117 #include <GEOM_Client.hxx>
119 #include <Basics_Utils.hxx>
120 #include <Basics_DirUtils.hxx>
122 #include <OpUtil.hxx>
123 #include <SALOMEDS_Tool.hxx>
124 #include <SALOME_Container_i.hxx>
125 #include <SALOME_LifeCycleCORBA.hxx>
126 #include <SALOME_NamingService.hxx>
127 #include <Utils_CorbaException.hxx>
128 #include <Utils_ExceptHandlers.hxx>
129 #include <Utils_SINGLETON.hxx>
130 #include <utilities.h>
132 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
133 #include CORBA_CLIENT_HEADER(SALOME_Session)
135 // helpers about SALOME::GenericObj
136 #include <SALOMEDS_wrap.hxx>
137 #include <SALOMEDS_Attributes_wrap.hxx>
138 #include <GEOM_wrap.hxx>
147 using SMESH::TPythonDump;
150 #define NUM_TMP_FILES 2
153 static int MYDEBUG = 0;
155 static int MYDEBUG = 0;
158 // Static variables definition
159 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
160 CORBA::ORB_var SMESH_Gen_i::myOrb;
161 PortableServer::POA_var SMESH_Gen_i::myPoa;
162 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
163 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
164 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
167 const int nbElemPerDiagonal = 10;
169 //=============================================================================
171 * GetServant [ static ]
173 * Get servant of the CORBA object
175 //=============================================================================
177 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
179 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
182 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
185 catch (PortableServer::POA::ObjectNotActive &ex)
187 INFOS("GetServant: ObjectNotActive");
190 catch (PortableServer::POA::WrongAdapter &ex)
192 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
195 catch (PortableServer::POA::WrongPolicy &ex)
197 INFOS("GetServant: WrongPolicy");
202 INFOS( "GetServant - Unknown exception was caught!!!" );
207 //=============================================================================
209 * SObjectToObject [ static ]
211 * Get CORBA object corresponding to the SALOMEDS::SObject
213 //=============================================================================
215 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
217 SALOMEDS::GenericAttribute_wrap anAttr;
218 CORBA::Object_var anObj;
219 if ( !theSObject->_is_nil() ) {
221 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
222 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
223 CORBA::String_var aValue = anIOR->Value();
224 if( strcmp( aValue, "" ) != 0 )
225 anObj = GetORB()->string_to_object( aValue );
229 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
235 //=============================================================================
239 * Get SALOME_NamingService object
241 //=============================================================================
243 SALOME_NamingService* SMESH_Gen_i::GetNS()
245 if ( myNS == NULL ) {
246 myNS = SINGLETON_<SALOME_NamingService>::Instance();
247 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
248 myNS->init_orb( GetORB() );
253 //=============================================================================
257 * Get SALOME_LifeCycleCORBA object
259 //=============================================================================
260 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC() {
261 if ( myLCC == NULL ) {
262 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
268 //=============================================================================
270 * GetGeomEngine [ static ]
272 * Get GEOM::GEOM_Gen reference
274 //=============================================================================
275 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine() {
276 //CCRT GEOM::GEOM_Gen_var aGeomEngine =
277 //CCRT GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
278 //CCRT return aGeomEngine._retn();
279 if(CORBA::is_nil(myGeomGen))
281 Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
282 myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
287 //=============================================================================
289 * SMESH_Gen_i::SMESH_Gen_i
291 * Default constructor: not for use
293 //=============================================================================
295 SMESH_Gen_i::SMESH_Gen_i()
299 //=============================================================================
301 * SMESH_Gen_i::SMESH_Gen_i
303 * Standard constructor, used with Container
305 //=============================================================================
307 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
308 PortableServer::POA_ptr poa,
309 PortableServer::ObjectId* contId,
310 const char* instanceName,
311 const char* interfaceName )
312 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
315 myOrb = CORBA::ORB::_duplicate(orb);
316 myPoa = PortableServer::POA::_duplicate(poa);
319 _id = myPoa->activate_object( _thisObj );
321 myIsEmbeddedMode = false;
322 myShapeReader = NULL; // shape reader
324 myIsHistoricalPythonDump = true;
325 myToForgetMeshDataOnHypModif = false;
327 // set it in standalone mode only
328 //OSD::SetSignal( true );
330 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
331 // find out mode (embedded or standalone) here else
332 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
333 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
334 if ( SALOME_NamingService* ns = GetNS() )
336 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
337 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
338 if ( !session->_is_nil() )
340 CORBA::String_var str_host = session->getHostname();
341 CORBA::Long s_pid = session->getPID();
342 string my_host = Kernel_Utils::GetHostname();
344 long my_pid = (long)_getpid();
346 long my_pid = (long) getpid();
348 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
353 //=============================================================================
355 * SMESH_Gen_i::~SMESH_Gen_i
359 //=============================================================================
361 SMESH_Gen_i::~SMESH_Gen_i()
363 // delete hypothesis creators
364 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
365 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
367 // same creator can be mapped under different names
368 GenericHypothesisCreator_i* creator = (*itHyp).second;
372 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
373 if ( creator == (*itHyp2).second )
374 (*itHyp2).second = 0;
376 myHypCreatorMap.clear();
378 // Clear study contexts data
379 map<int, StudyContext*>::iterator it;
380 for ( it = myStudyContextMap.begin(); it != myStudyContextMap.end(); ++it ) {
383 myStudyContextMap.clear();
384 // delete shape reader
386 delete myShapeReader;
388 //=============================================================================
390 * SMESH_Gen_i::getHypothesisCreator
392 * Get hypothesis creator
394 //=============================================================================
395 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
396 const char* theLibName,
397 std::string& thePlatformLibName)
398 throw (SALOME::SALOME_Exception)
400 std::string aPlatformLibName;
401 /* It's Need to translate lib name for WIN32 or X platform */
402 if ( theLibName && theLibName[0] != '\0' )
404 int libNameLen = strlen(theLibName);
405 //check for old format "libXXXXXXX.so"
406 if (libNameLen > 7 &&
407 !strncmp( theLibName, "lib", 3 ) &&
408 !strcmp( theLibName+libNameLen-3, ".so" ))
412 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
413 #elif defined(__APPLE__)
414 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
416 aPlatformLibName = theLibName;
421 //try to use new format
423 aPlatformLibName = theLibName;
424 aPlatformLibName += ".dll";
425 #elif defined(__APPLE__)
426 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
428 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
432 thePlatformLibName = aPlatformLibName;
434 Unexpect aCatch(SALOME_SalomeException);
435 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
437 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
438 GenericHypothesisCreator_i* aCreator;
441 // check, if creator for this hypothesis type already exists
442 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
444 // load plugin library
445 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
446 LibHandle libHandle = LoadLib( aPlatformLibName.c_str() );
449 // report any error, if occurred
451 const char* anError = dlerror();
452 throw(SALOME_Exception(anError));
454 throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
458 // get method, returning hypothesis creator
459 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
460 GetHypothesisCreator procHandle =
461 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
464 throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
465 UnLoadLib(libHandle);
468 // get hypothesis creator
469 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
470 aCreator = procHandle(theHypName);
473 throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
475 // map hypothesis creator to a hypothesis name
476 myHypCreatorMap[string(theHypName)] = aCreator;
481 return myHypCreatorMap[string(theHypName)];
484 catch (SALOME_Exception& S_ex)
486 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
491 //=============================================================================
493 * SMESH_Gen_i::createHypothesis
495 * Create hypothesis of given type
497 //=============================================================================
498 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
499 const char* theLibName)
501 SMESH_Hypothesis_i* myHypothesis_i = 0;
502 SMESH::SMESH_Hypothesis_var hypothesis_i;
503 std::string aPlatformLibName;
504 GenericHypothesisCreator_i* aCreator =
505 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
507 // create a new hypothesis object, store its ref. in studyContext
508 myHypothesis_i = aCreator->Create(myPoa, GetCurrentStudyID(), &myGen);
511 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
512 CORBA::String_var hypName = myHypothesis_i->GetName();
513 myHypCreatorMap[ hypName.in() ] = aCreator;
515 // activate the CORBA servant of hypothesis
516 hypothesis_i = myHypothesis_i->_this();
517 int nextId = RegisterObject( hypothesis_i );
518 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
519 else { nextId = 0; } // avoid "unused variable" warning in release mode
521 return hypothesis_i._retn();
524 //=============================================================================
526 * SMESH_Gen_i::createMesh
528 * Create empty mesh on shape
530 //=============================================================================
531 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
532 throw ( SALOME::SALOME_Exception )
534 Unexpect aCatch(SALOME_SalomeException);
535 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
537 // Get or create the GEOM_Client instance
539 // create a new mesh object servant, store it in a map in study context
540 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this, GetCurrentStudyID() );
541 // create a new mesh object
542 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
543 meshServant->SetImpl( myGen.CreateMesh( GetCurrentStudyID(), myIsEmbeddedMode ));
545 // activate the CORBA servant of Mesh
546 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
547 int nextId = RegisterObject( mesh );
548 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
549 else { nextId = 0; } // avoid "unused variable" warning in release mode
552 catch (SALOME_Exception& S_ex) {
553 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
555 return SMESH::SMESH_Mesh::_nil();
558 //=============================================================================
560 * SMESH_Gen_i::GetShapeReader
564 //=============================================================================
565 GEOM_Client* SMESH_Gen_i::GetShapeReader()
567 // create shape reader if necessary
568 if ( !myShapeReader )
569 myShapeReader = new GEOM_Client(GetContainerRef());
570 ASSERT( myShapeReader );
571 return myShapeReader;
574 //=============================================================================
576 * SMESH_Gen_i::SetGeomEngine
578 * Set GEOM::GEOM_Gen reference
580 //=============================================================================
581 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
582 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
584 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
585 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
586 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
590 //=============================================================================
592 * SMESH_Gen_i::SetEmbeddedMode
596 //=============================================================================
598 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
600 myIsEmbeddedMode = theMode;
602 if ( !myIsEmbeddedMode ) {
603 //PAL10867: disable signals catching with "noexcepthandler" option
604 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
605 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
610 char* envDisableFPE = getenv("DISABLE_FPE");
611 if (envDisableFPE && atoi(envDisableFPE))
616 OSD::SetSignal( raiseFPE );
618 // else OSD::SetSignal() is called in GUI
622 //=============================================================================
624 * SMESH_Gen_i::IsEmbeddedMode
628 //=============================================================================
630 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
632 return myIsEmbeddedMode;
635 //=============================================================================
637 * SMESH_Gen_i::SetCurrentStudy
641 //=============================================================================
643 void SMESH_Gen_i::SetCurrentStudy( SALOMEDS::Study_ptr theStudy )
645 setCurrentStudy( theStudy );
648 void SMESH_Gen_i::setCurrentStudy( SALOMEDS::Study_ptr theStudy,
649 bool theStudyIsBeingClosed)
651 int curStudyId = GetCurrentStudyID();
652 MESSAGE("curStudyId " << curStudyId);
653 myCurrentStudy = SALOMEDS::Study::_duplicate( theStudy );
654 // create study context, if it doesn't exist and set current study
655 int studyId = GetCurrentStudyID();
656 MESSAGE("studyId " << studyId);
657 if ( myStudyContextMap.find( studyId ) == myStudyContextMap.end() )
658 myStudyContextMap[ studyId ] = new StudyContext;
660 // myCurrentStudy may be nil
661 if ( !theStudyIsBeingClosed && !CORBA::is_nil( myCurrentStudy ) ) {
662 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
663 SALOMEDS::SComponent_wrap GEOM_var = myCurrentStudy->FindComponent( "GEOM" );
664 if( !GEOM_var->_is_nil() )
665 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
666 // NPAL16168, issue 0020210
667 // Let meshes update their data depending on GEOM groups that could change
668 if ( curStudyId != studyId )
670 MESSAGE("curStudyId " << curStudyId << " studyId " << studyId);
671 CORBA::String_var compDataType = ComponentDataType();
672 SALOMEDS::SComponent_wrap me = myCurrentStudy->FindComponent( compDataType.in() );
673 if ( !me->_is_nil() ) {
674 SALOMEDS::ChildIterator_wrap anIter = myCurrentStudy->NewChildIterator( me );
675 for ( ; anIter->More(); anIter->Next() ) {
676 SALOMEDS::SObject_wrap so = anIter->Value();
677 CORBA::Object_var ior = SObjectToObject( so );
678 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
679 mesh->CheckGeomModif();
686 //=============================================================================
688 * SMESH_Gen_i::GetCurrentStudy
692 //=============================================================================
694 SALOMEDS::Study_ptr SMESH_Gen_i::GetCurrentStudy()
696 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetCurrentStudy: study Id = " << GetCurrentStudyID() );
697 if ( GetCurrentStudyID() < 0 )
698 return SALOMEDS::Study::_nil();
699 return SALOMEDS::Study::_duplicate( myCurrentStudy );
702 //=============================================================================
704 * SMESH_Gen_i::GetCurrentStudyContext
706 * Get current study context
708 //=============================================================================
709 StudyContext* SMESH_Gen_i::GetCurrentStudyContext()
711 if ( !CORBA::is_nil( myCurrentStudy ) &&
712 myStudyContextMap.find( GetCurrentStudyID() ) != myStudyContextMap.end() )
713 return myStudyContextMap[ myCurrentStudy->StudyId() ];
718 //=============================================================================
720 * SMESH_Gen_i::CreateHypothesis
722 * Create hypothesis/algorothm of given type and publish it in the study
724 //=============================================================================
726 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
727 const char* theLibName )
728 throw ( SALOME::SALOME_Exception )
730 Unexpect aCatch(SALOME_SalomeException);
731 // Create hypothesis/algorithm
732 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
734 // Publish hypothesis/algorithm in the study
735 if ( CanPublishInStudy( hyp ) ) {
736 SALOMEDS::SObject_wrap aSO = PublishHypothesis( myCurrentStudy, hyp );
737 if ( !aSO->_is_nil() ) {
738 // Update Python script
739 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
740 << theHypName << "', '" << theLibName << "')";
747 //================================================================================
749 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
750 * existing on the given geometry or to size of the geometry.
751 * \param theHypType - hypothesis type name
752 * \param theLibName - plugin library name
753 * \param theMesh - The mesh of interest
754 * \param theGeom - The shape to get parameter values from
755 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
756 * in a study and used to compute the mesh, or a temporary one created just to pass
759 //================================================================================
761 SMESH::SMESH_Hypothesis_ptr
762 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
763 const char* theLibName,
764 SMESH::SMESH_Mesh_ptr theMesh,
765 GEOM::GEOM_Object_ptr theGeom,
766 CORBA::Boolean byMesh)
767 throw ( SALOME::SALOME_Exception )
769 Unexpect aCatch(SALOME_SalomeException);
770 if ( byMesh && CORBA::is_nil( theMesh ) )
771 return SMESH::SMESH_Hypothesis::_nil();
772 if ( byMesh && CORBA::is_nil( theGeom ) )
773 return SMESH::SMESH_Hypothesis::_nil();
775 // -----------------------------------------------
776 // find hypothesis used to mesh theGeom
777 // -----------------------------------------------
779 // get mesh and shape
780 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
781 TopoDS_Shape shape = GeomObjectToShape( theGeom );
782 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
783 return SMESH::SMESH_Hypothesis::_nil();
784 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
786 // create a temporary hypothesis to know its dimension
787 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
788 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
790 return SMESH::SMESH_Hypothesis::_nil();
791 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
794 // look for a hypothesis of theHypType used to mesh the shape
795 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
798 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
799 int nbLocalHyps = aHypList->length();
800 for ( int i = 0; i < nbLocalHyps; i++ ) {
801 CORBA::String_var hypName = aHypList[i]->GetName();
802 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
803 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
805 // check super shapes
806 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
807 while ( nbLocalHyps == 0 && itShape.More() ) {
808 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
809 if ( ! CORBA::is_nil( geomObj )) {
810 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
811 nbLocalHyps = aHypList->length();
812 for ( int i = 0; i < nbLocalHyps; i++ )
813 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
814 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
820 // let the temporary hypothesis find out somehow parameter values by mesh
821 if ( hyp->SetParametersByMesh( mesh, shape ))
822 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
827 diagonal = mesh->GetShapeDiagonalSize();
829 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
830 ::SMESH_Hypothesis::TDefaults dflts;
831 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
832 dflts._nbSegments = myGen.GetDefaultNbSegments();
833 dflts._shape = &shape;
834 // let the temporary hypothesis initialize it's values
835 if ( hyp->SetParametersByDefaults( dflts, mesh ))
836 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
839 return SMESH::SMESH_Hypothesis::_nil();
842 //=============================================================================
844 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
845 * \param [in] theHyp - the hypothesis of interest
846 * \param [out] theMesh - the sole mesh using \a theHyp
847 * \param [out] theShape - the sole geometry \a theHyp is assigned to
848 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
850 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
851 * considered as SAME sub-mesh => result is \c true.
852 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
853 * a shape to which an hyp being edited is assigned.
855 //=============================================================================
857 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
858 SMESH::SMESH_Mesh_out theMesh,
859 GEOM::GEOM_Object_out theShape)
861 if ( GetCurrentStudyID() < 0 || CORBA::is_nil( theHyp ))
864 // get Mesh component SO
865 CORBA::String_var compDataType = ComponentDataType();
866 SALOMEDS::SComponent_wrap comp = myCurrentStudy->FindComponent( compDataType.in() );
867 if ( CORBA::is_nil( comp ))
870 // look for child SO of meshes
871 SMESH::SMESH_Mesh_var foundMesh;
872 TopoDS_Shape foundShape;
874 SALOMEDS::ChildIterator_wrap meshIter = myCurrentStudy->NewChildIterator( comp );
875 for ( ; meshIter->More() && isSole; meshIter->Next() )
877 SALOMEDS::SObject_wrap curSO = meshIter->Value();
878 CORBA::Object_var obj = SObjectToObject( curSO );
879 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
883 // look for a sole shape where theHyp is assigned
884 bool isHypFound = false;
885 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
886 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
887 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
889 const THypList& hyps = s2hypsIt.Value();
890 THypList::const_iterator h = hyps.begin();
891 for ( ; h != hyps.end(); ++h )
892 if ( (*h)->GetID() == theHyp->GetId() )
894 if ( h != hyps.end()) // theHyp found
897 if ( ! foundShape.IsNull() &&
898 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
900 foundShape.Nullify();
904 foundShape = s2hypsIt.Key();
906 } // loop on assigned hyps
908 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
910 if ( !foundMesh->_is_nil() ) // not a sole mesh
912 if ( !foundMesh->HasShapeToMesh() ||
913 !mesh_i ->HasShapeToMesh() )
915 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
919 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
920 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
921 isSole = s1->IsSame( s2 );
924 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
930 ! foundMesh->_is_nil() &&
931 ! foundShape.IsNull() )
933 theMesh = foundMesh._retn();
934 theShape = ShapeToGeomObject( foundShape );
935 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
940 //=============================================================================
942 * Sets number of segments per diagonal of boundary box of geometry by which
943 * default segment length of appropriate 1D hypotheses is defined
945 //=============================================================================
947 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
948 throw ( SALOME::SALOME_Exception )
950 if ( theNbSegments > 0 )
951 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
953 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
955 //=============================================================================
957 * \brief Sets default number of segments per edge
959 //=============================================================================
960 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
961 throw ( SALOME::SALOME_Exception )
963 if ( theNbSegments > 0 )
964 myGen.SetDefaultNbSegments( int(theNbSegments) );
966 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
969 //=============================================================================
973 //=============================================================================
975 void SMESH_Gen_i::SetOption(const char* name, const char* value)
977 if ( name && value && strlen( value ) > 0 )
980 if ( strcmp(name, "historical_python_dump") == 0 )
982 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
983 msgToGUI = "preferences/SMESH/historical_python_dump/";
984 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
986 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
988 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
989 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
990 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
992 else if ( strcmp(name, "default_grp_color") == 0 )
996 // color must be presented as a string of following form:
997 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
999 for ( size_t i = 0; i < str.length()/2; i++ )
1000 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1001 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1003 else if ( value ) { // rgb color ("255,170,0", for example)
1004 string tempValue( value );
1005 char* colorValue = strtok( &tempValue[0], "," );
1006 while ( colorValue != NULL ) {
1007 int c_value = atoi( colorValue );
1008 if ( c_value >= 0 && c_value <= 255 )
1009 color.push_back( c_value );
1010 colorValue = strtok( NULL, "," );
1013 if ( color.size() == 3 ) { // color must have three valid component
1014 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1015 myDefaultGroupColor = value;
1016 msgToGUI = "preferences/SMESH/default_grp_color/";
1021 // update preferences in case if SetOption() is invoked from python console
1022 if ( !msgToGUI.empty() )
1024 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1025 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1026 if ( !CORBA::is_nil( session ) )
1027 session->emitMessageOneWay(msgToGUI.c_str());
1032 //=============================================================================
1034 Return an option value
1036 //=============================================================================
1038 char* SMESH_Gen_i::GetOption(const char* name)
1042 if ( strcmp(name, "historical_python_dump") == 0 )
1044 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1046 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1048 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1050 if ( strcmp(name, "default_grp_color") == 0 )
1052 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1055 return CORBA::string_dup( "" );
1058 //=============================================================================
1060 * SMESH_Gen_i::CreateMesh
1062 * Create empty mesh on a shape and publish it in the study
1064 //=============================================================================
1066 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1067 throw ( SALOME::SALOME_Exception )
1069 Unexpect aCatch(SALOME_SalomeException);
1070 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1072 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1074 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1075 ASSERT( meshServant );
1076 meshServant->SetShape( theShapeObject );
1078 // publish mesh in the study
1079 if ( CanPublishInStudy( mesh ) ) {
1080 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1081 aStudyBuilder->NewCommand(); // There is a transaction
1082 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1083 aStudyBuilder->CommitCommand();
1084 if ( !aSO->_is_nil() ) {
1085 // Update Python script
1086 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1090 return mesh._retn();
1093 //=============================================================================
1095 * SMESH_Gen_i::CreateEmptyMesh
1099 //=============================================================================
1101 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1102 throw ( SALOME::SALOME_Exception )
1104 Unexpect aCatch(SALOME_SalomeException);
1105 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1107 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1109 // publish mesh in the study
1110 if ( CanPublishInStudy( mesh ) ) {
1111 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1112 aStudyBuilder->NewCommand(); // There is a transaction
1113 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1114 aStudyBuilder->CommitCommand();
1115 if ( !aSO->_is_nil() ) {
1116 // Update Python script
1117 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1121 return mesh._retn();
1126 //================================================================================
1128 * \brief Throws an exception in case if the file can't be read
1130 //================================================================================
1132 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1134 SMESH_File f ( theFileName );
1137 if ( !f.error().empty() )
1138 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1140 THROW_SALOME_CORBA_EXCEPTION
1141 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1142 SALOME::BAD_PARAM );
1147 //=============================================================================
1149 * SMESH_Gen_i::CreateMeshFromUNV
1151 * Create mesh and import data from UNV file
1153 //=============================================================================
1155 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1156 throw ( SALOME::SALOME_Exception )
1158 Unexpect aCatch(SALOME_SalomeException);
1160 checkFileReadable( theFileName );
1162 SMESH::SMESH_Mesh_var aMesh = createMesh();
1164 // publish mesh in the study
1165 if ( CanPublishInStudy( aMesh ) ) {
1166 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1167 aStudyBuilder->NewCommand(); // There is a transaction
1168 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, aMesh.in(), aFileName.c_str() );
1169 aStudyBuilder->CommitCommand();
1170 if ( !aSO->_is_nil() ) {
1171 // Update Python script
1172 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1176 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1178 aServant->ImportUNVFile( theFileName );
1180 // Dump creation of groups
1181 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1183 aServant->GetImpl().GetMeshDS()->Modified();
1184 return aMesh._retn();
1187 //=============================================================================
1189 * SMESH_Gen_i::CreateMeshFromMED
1191 * Create mesh and import data from MED file
1193 //=============================================================================
1195 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1196 SMESH::DriverMED_ReadStatus& theStatus,
1197 const char* theCommandNameForPython,
1198 const char* theFileNameForPython)
1201 char bname[ _MAX_FNAME ];
1202 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1203 string aFileName = bname;
1205 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1207 // Retrieve mesh names from the file
1208 DriverMED_R_SMESHDS_Mesh myReader;
1209 myReader.SetFile( theFileName );
1210 myReader.SetMeshId( -1 );
1211 Driver_Mesh::Status aStatus;
1212 list<string> aNames = myReader.GetMeshNames(aStatus);
1213 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1214 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1216 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1219 TPythonDump aPythonDump;
1220 aPythonDump << "([";
1222 if (theStatus == SMESH::DRS_OK) {
1223 SALOMEDS::StudyBuilder_var aStudyBuilder;
1224 if ( GetCurrentStudyID() > -1 )
1226 aStudyBuilder = myCurrentStudy->NewBuilder();
1227 aStudyBuilder->NewCommand(); // There is a transaction
1229 aResult->length( aNames.size() );
1232 // Iterate through all meshes and create mesh objects
1233 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1236 if (i > 0) aPythonDump << ", ";
1239 SMESH::SMESH_Mesh_var mesh = createMesh();
1241 // publish mesh in the study
1242 SALOMEDS::SObject_wrap aSO;
1243 if ( CanPublishInStudy( mesh ) )
1244 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1245 // - as names of meshes are stored in MED file, we use them for data publishing
1246 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1247 aSO = PublishMesh( myCurrentStudy, mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1250 if ( !aSO->_is_nil() ) {
1253 aPythonDump << "mesh_" << i;
1256 // Read mesh data (groups are published automatically by ImportMEDFile())
1257 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1258 ASSERT( meshServant );
1259 SMESH::DriverMED_ReadStatus status1 =
1260 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1261 if (status1 > theStatus)
1262 theStatus = status1;
1264 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1265 meshServant->GetImpl().GetMeshDS()->Modified();
1267 if ( !aStudyBuilder->_is_nil() )
1268 aStudyBuilder->CommitCommand();
1271 // Update Python script
1272 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1274 // Dump creation of groups
1275 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1276 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1278 return aResult._retn();
1281 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1282 SMESH::DriverMED_ReadStatus& theStatus)
1283 throw ( SALOME::SALOME_Exception )
1285 Unexpect aCatch(SALOME_SalomeException);
1286 checkFileReadable( theFileName );
1288 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1292 //=============================================================================
1294 * SMESH_Gen_i::CreateMeshFromSAUV
1296 * Create mesh and import data from SAUV file
1298 //=============================================================================
1300 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1301 SMESH::DriverMED_ReadStatus& theStatus)
1302 throw ( SALOME::SALOME_Exception )
1304 Unexpect aCatch(SALOME_SalomeException);
1305 checkFileReadable( theFileName );
1307 std::string sauvfilename(theFileName);
1308 std::string medfilename(theFileName);
1309 medfilename += ".med";
1312 cmd = "%PYTHONBIN% ";
1317 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1319 system(cmd.c_str());
1320 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1322 cmd = "%PYTHONBIN% ";
1327 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1329 system(cmd.c_str());
1333 //=============================================================================
1335 * SMESH_Gen_i::CreateMeshFromSTL
1337 * Create mesh and import data from STL file
1339 //=============================================================================
1341 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1342 throw ( SALOME::SALOME_Exception )
1344 Unexpect aCatch(SALOME_SalomeException);
1345 checkFileReadable( theFileName );
1347 SMESH::SMESH_Mesh_var aMesh = createMesh();
1350 char bname[ _MAX_FNAME ];
1351 _splitpath( theFileName, NULL, NULL, bname, NULL );
1352 string aFileName = bname;
1354 string aFileName = basename( const_cast<char *>(theFileName) );
1356 // publish mesh in the study
1357 if ( CanPublishInStudy( aMesh ) ) {
1358 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1359 aStudyBuilder->NewCommand(); // There is a transaction
1360 SALOMEDS::SObject_wrap aSO = PublishInStudy
1361 ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1362 aStudyBuilder->CommitCommand();
1363 if ( !aSO->_is_nil() ) {
1364 // Update Python script
1365 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1369 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1371 aServant->ImportSTLFile( theFileName );
1372 aServant->GetImpl().GetMeshDS()->Modified();
1373 return aMesh._retn();
1376 //================================================================================
1378 * \brief Create meshes and import data from the CGSN file
1380 //================================================================================
1382 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1383 SMESH::DriverMED_ReadStatus& theStatus)
1384 throw ( SALOME::SALOME_Exception )
1386 Unexpect aCatch(SALOME_SalomeException);
1387 checkFileReadable( theFileName );
1389 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1392 // Retrieve nb meshes from the file
1393 DriverCGNS_Read myReader;
1394 myReader.SetFile( theFileName );
1395 Driver_Mesh::Status aStatus;
1396 int nbMeshes = myReader.GetNbMeshes(aStatus);
1397 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1399 aResult->length( nbMeshes );
1401 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1404 TPythonDump aPythonDump;
1405 aPythonDump << "([";
1407 if (theStatus == SMESH::DRS_OK)
1409 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1410 aStudyBuilder->NewCommand(); // There is a transaction
1414 // Iterate through all meshes and create mesh objects
1415 for ( ; i < nbMeshes; ++i )
1418 if (i > 0) aPythonDump << ", ";
1421 SMESH::SMESH_Mesh_var mesh = createMesh();
1422 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1424 // Read mesh data (groups are published automatically by ImportMEDFile())
1425 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1426 ASSERT( meshServant );
1428 SMESH::DriverMED_ReadStatus status1 =
1429 meshServant->ImportCGNSFile( theFileName, i, meshName );
1430 if (status1 > theStatus)
1431 theStatus = status1;
1433 meshServant->GetImpl().GetMeshDS()->Modified();
1434 // publish mesh in the study
1435 SALOMEDS::SObject_wrap aSO;
1436 if ( CanPublishInStudy( mesh ) )
1437 aSO = PublishMesh( myCurrentStudy, mesh.in(), meshName.c_str() );
1440 if ( !aSO->_is_nil() ) {
1444 aPythonDump << "mesh_" << i;
1447 aStudyBuilder->CommitCommand();
1450 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1452 // Dump creation of groups
1453 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1454 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1456 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1459 return aResult._retn();
1462 //================================================================================
1464 * \brief Create a mesh and import data from a GMF file
1466 //================================================================================
1468 SMESH::SMESH_Mesh_ptr
1469 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1470 CORBA::Boolean theMakeRequiredGroups,
1471 SMESH::ComputeError_out theError)
1472 throw ( SALOME::SALOME_Exception )
1474 Unexpect aCatch(SALOME_SalomeException);
1475 checkFileReadable( theFileName );
1477 SMESH::SMESH_Mesh_var aMesh = createMesh();
1479 char bname[ _MAX_FNAME ];
1480 _splitpath( theFileName, NULL, NULL, bname, NULL );
1481 string aFileName = bname;
1483 string aFileName = basename( const_cast<char *>(theFileName) );
1485 // publish mesh in the study
1486 if ( CanPublishInStudy( aMesh ) ) {
1487 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1488 aStudyBuilder->NewCommand(); // There is a transaction
1489 SALOMEDS::SObject_wrap aSO = PublishInStudy
1490 ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1491 aStudyBuilder->CommitCommand();
1492 if ( !aSO->_is_nil() ) {
1493 // Update Python script
1494 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1495 << theFileName << "', "
1496 << theMakeRequiredGroups << " )";
1499 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1501 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1502 aServant->GetImpl().GetMeshDS()->Modified();
1503 return aMesh._retn();
1507 //=============================================================================
1509 * SMESH_Gen_i::IsReadyToCompute
1511 * Returns true if mesh contains enough data to be computed
1513 //=============================================================================
1515 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1516 GEOM::GEOM_Object_ptr theShapeObject )
1517 throw ( SALOME::SALOME_Exception )
1519 Unexpect aCatch(SALOME_SalomeException);
1520 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1522 if ( CORBA::is_nil( theShapeObject ) )
1523 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1524 SALOME::BAD_PARAM );
1526 if ( CORBA::is_nil( theMesh ) )
1527 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1528 SALOME::BAD_PARAM );
1532 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1533 ASSERT( meshServant );
1534 if ( meshServant ) {
1535 // get local TopoDS_Shape
1536 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1537 // call implementation
1538 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1539 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1542 catch ( SALOME_Exception& S_ex ) {
1543 INFOS( "catch exception "<< S_ex.what() );
1548 //================================================================================
1550 * \brief Find SObject for an algo
1552 //================================================================================
1554 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1557 if ( !myCurrentStudy->_is_nil() ) {
1558 // find algo in the study
1559 CORBA::String_var compDataType = ComponentDataType();
1560 SALOMEDS::SComponent_wrap father = myCurrentStudy->FindComponent( compDataType.in() );
1561 if ( !father->_is_nil() ) {
1562 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( father );
1563 for ( ; itBig->More(); itBig->Next() ) {
1564 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1565 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1566 SALOMEDS::ChildIterator_wrap algoIt = myCurrentStudy->NewChildIterator( gotBranch );
1567 for ( ; algoIt->More(); algoIt->Next() ) {
1568 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1569 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1570 if ( !CORBA::is_nil( algoIOR )) {
1571 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1572 if ( impl && impl->GetImpl() == algo )
1573 return algoSO._retn();
1575 } // loop on algo SO's
1578 } // SMESH component iterator
1582 return SALOMEDS::SObject::_nil();
1585 //================================================================================
1587 * \brief Return errors of mesh computation
1589 //================================================================================
1591 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1592 GEOM::GEOM_Object_ptr theSubObject )
1593 throw ( SALOME::SALOME_Exception )
1595 Unexpect aCatch(SALOME_SalomeException);
1596 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1598 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1599 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1601 if ( CORBA::is_nil( theMesh ) )
1602 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1604 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1606 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1609 if(theMesh->HasShapeToMesh())
1610 shape = GeomObjectToShape( theSubObject );
1612 shape = SMESH_Mesh::PseudoShape();
1614 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1616 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1619 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1620 const bool includeSelf = true, complexShapeFirst = true;
1621 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1623 while ( smIt->more() )
1626 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1628 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1629 if ( error && !error->IsOK() )
1631 if ( !( error->myAlgo ) &&
1632 !( error->myAlgo = sm->GetAlgo() ))
1634 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1635 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1636 errStruct.comment = error->myComment.c_str();
1637 errStruct.subShapeID = sm->GetId();
1638 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1639 if ( !algoSO->_is_nil() ) {
1640 CORBA::String_var algoName = algoSO->GetName();
1641 errStruct.algoName = algoName;
1644 errStruct.algoName = error->myAlgo->GetName();
1646 errStruct.hasBadMesh = error->HasBadElems();
1649 error_array->length( nbErr );
1652 catch ( SALOME_Exception& S_ex ) {
1653 INFOS( "catch exception "<< S_ex.what() );
1656 return error_array._retn();
1659 //================================================================================
1661 * \brief Return mesh elements preventing computation of a subshape
1663 //================================================================================
1665 SMESH::MeshPreviewStruct*
1666 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1667 CORBA::Short theSubShapeID )
1668 throw ( SALOME::SALOME_Exception )
1670 Unexpect aCatch(SALOME_SalomeException);
1671 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1673 if ( CORBA::is_nil( theMesh ) )
1674 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1676 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1679 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1681 // mesh implementation
1682 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1683 // submesh by subshape id
1684 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1687 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1688 if ( error && error->HasBadElems() )
1690 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1691 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1693 // get nodes of elements and count elements
1694 TNode2LocalIDMap mapNode2LocalID;
1695 list< TNodeLocalID > connectivity;
1696 int i, nbElements = 0, nbConnNodes = 0;
1698 const list<const SMDS_MeshElement*>& badElems =
1699 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1700 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1701 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1702 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1704 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1705 while ( nIt->more() )
1706 connectivity.push_back
1707 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1709 // fill node coords and assign local ids to the nodes
1710 int nbNodes = mapNode2LocalID.size();
1711 result->nodesXYZ.length( nbNodes );
1712 TNodeLocalID node2ID = mapNode2LocalID.begin();
1713 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1714 node2ID->second = i;
1715 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1716 result->nodesXYZ[i].x = node->X();
1717 result->nodesXYZ[i].y = node->Y();
1718 result->nodesXYZ[i].z = node->Z();
1720 // fill connectivity
1721 result->elementConnectivities.length( nbConnNodes );
1722 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1723 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1724 result->elementConnectivities[i] = (*connIt)->second;
1726 // fill element types
1727 result->elementTypes.length( nbElements );
1728 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1730 const SMDS_MeshElement* elem = *elemIt;
1731 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1732 result->elementTypes[i].isPoly = elem->IsPoly();
1733 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1739 catch ( SALOME_Exception& S_ex ) {
1740 INFOS( "catch exception "<< S_ex.what() );
1743 return result._retn();
1746 //================================================================================
1748 * \brief Create a group of elements preventing computation of a sub-shape
1750 //================================================================================
1752 SMESH::ListOfGroups*
1753 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1754 CORBA::Short theSubShapeID,
1755 const char* theGroupName )
1756 throw ( SALOME::SALOME_Exception )
1758 Unexpect aCatch(SALOME_SalomeException);
1760 SMESH::ListOfGroups_var groups;
1762 if ( CORBA::is_nil( theMesh ) )
1763 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1766 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1768 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1769 TPythonDump() << groups << " = " << this
1770 << ".MakeGroupsOfBadInputElements( "
1771 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1774 catch ( SALOME_Exception& S_ex ) {
1775 INFOS( "catch exception "<< S_ex.what() );
1777 return groups._retn();
1780 //================================================================================
1782 * \brief Returns errors of hypotheses definition
1783 * \param theMesh - the mesh
1784 * \param theSubObject - the main or sub- shape
1785 * \retval SMESH::algo_error_array* - sequence of errors
1787 //================================================================================
1789 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1790 GEOM::GEOM_Object_ptr theSubObject )
1791 throw ( SALOME::SALOME_Exception )
1793 Unexpect aCatch(SALOME_SalomeException);
1794 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1796 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1797 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1799 if ( CORBA::is_nil( theMesh ) )
1800 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1802 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1804 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1805 ASSERT( meshServant );
1806 if ( meshServant ) {
1807 TopoDS_Shape myLocShape;
1808 if(theMesh->HasShapeToMesh())
1809 myLocShape = GeomObjectToShape( theSubObject );
1811 myLocShape = SMESH_Mesh::PseudoShape();
1813 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1814 list< ::SMESH_Gen::TAlgoStateError > error_list;
1815 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1816 // call ::SMESH_Gen::GetAlgoState()
1817 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1818 error_array->length( error_list.size() );
1820 for ( error = error_list.begin(); error != error_list.end(); ++error )
1822 // fill AlgoStateError structure
1823 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1824 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1825 errStruct.algoDim = error->_algoDim;
1826 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1827 errStruct.algoName = "";
1828 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1829 if ( !algoSO->_is_nil() ) {
1830 CORBA::String_var algoName = algoSO->GetName();
1831 errStruct.algoName = algoName.in();
1836 catch ( SALOME_Exception& S_ex ) {
1837 INFOS( "catch exception "<< S_ex.what() );
1839 return error_array._retn();
1842 //=============================================================================
1844 * SMESH_Gen_i::GetSubShapesId
1846 * Get sub-shapes unique ID's list
1848 //=============================================================================
1851 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1852 const SMESH::object_array& theListOfSubShapeObject )
1853 throw ( SALOME::SALOME_Exception )
1855 Unexpect aCatch(SALOME_SalomeException);
1856 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1858 SMESH::long_array_var shapesId = new SMESH::long_array;
1861 if ( CORBA::is_nil( theMainShapeObject ) )
1862 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1866 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1867 TopTools_IndexedMapOfShape myIndexToShape;
1868 TopExp::MapShapes(myMainShape,myIndexToShape);
1870 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1872 GEOM::GEOM_Object_var aShapeObject
1873 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1874 if ( CORBA::is_nil( aShapeObject ) )
1875 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1876 SALOME::BAD_PARAM );
1878 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1879 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1881 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1882 setId.insert(myIndexToShape.FindIndex(F));
1883 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1885 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1887 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1888 setId.insert(myIndexToShape.FindIndex(E));
1889 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1891 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1893 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1894 setId.insert(myIndexToShape.FindIndex(V));
1895 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1898 shapesId->length(setId.size());
1899 set<int>::iterator iind;
1901 for (iind = setId.begin(); iind != setId.end(); iind++)
1903 if(MYDEBUG) SCRUTE((*iind));
1904 shapesId[i] = (*iind);
1905 if(MYDEBUG) SCRUTE(shapesId[i]);
1909 catch (SALOME_Exception& S_ex)
1911 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1914 return shapesId._retn();
1917 //=============================================================================
1919 * SMESH_Gen_i::Compute
1921 * Compute mesh on a shape
1923 //=============================================================================
1925 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1926 GEOM::GEOM_Object_ptr theShapeObject )
1927 throw ( SALOME::SALOME_Exception )
1930 Unexpect aCatch(SALOME_SalomeException);
1931 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1933 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1934 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1935 SALOME::BAD_PARAM );
1937 if ( CORBA::is_nil( theMesh ) )
1938 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1939 SALOME::BAD_PARAM );
1941 // Update Python script
1942 TPythonDump() << "isDone = " << this << ".Compute( "
1943 << theMesh << ", " << theShapeObject << ")";
1947 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1948 ASSERT( meshServant );
1949 if ( meshServant ) {
1950 meshServant->Load();
1951 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1952 meshServant->CheckGeomModif();
1953 // get local TopoDS_Shape
1954 TopoDS_Shape myLocShape;
1955 if(theMesh->HasShapeToMesh())
1956 myLocShape = GeomObjectToShape( theShapeObject );
1958 myLocShape = SMESH_Mesh::PseudoShape();
1959 // call implementation compute
1960 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1961 myGen.PrepareCompute( myLocMesh, myLocShape );
1962 int how = ::SMESH_Gen::COMPACT_MESH;
1963 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
1964 how |= ::SMESH_Gen::SHAPE_ONLY;
1965 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
1966 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1967 myLocMesh.GetMeshDS()->Modified();
1969 HighLightInvalid( theMesh, /*isInvalid=*/false );
1973 catch ( std::bad_alloc ) {
1974 INFOS( "Compute(): lack of memory" );
1976 catch ( SALOME_Exception& S_ex ) {
1977 INFOS( "Compute(): catch exception "<< S_ex.what() );
1980 INFOS( "Compute(): unknown exception " );
1985 //=============================================================================
1987 * SMESH_Gen_i::CancelCompute
1989 * Cancel Compute mesh on a shape
1991 //=============================================================================
1993 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
1994 GEOM::GEOM_Object_ptr theShapeObject )
1996 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1997 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1998 TopoDS_Shape myLocShape;
1999 if(theMesh->HasShapeToMesh())
2000 myLocShape = GeomObjectToShape( theShapeObject );
2002 myLocShape = SMESH_Mesh::PseudoShape();
2003 myGen.CancelCompute( myLocMesh, myLocShape);
2006 //=============================================================================
2008 * SMESH_Gen_i::Precompute
2010 * Compute mesh as preview till indicated dimension on shape
2012 //=============================================================================
2014 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2015 GEOM::GEOM_Object_ptr theShapeObject,
2016 SMESH::Dimension theDimension,
2017 SMESH::long_array& theShapesId)
2018 throw ( SALOME::SALOME_Exception )
2020 Unexpect aCatch(SALOME_SalomeException);
2021 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2023 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2024 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2025 SALOME::BAD_PARAM );
2027 if ( CORBA::is_nil( theMesh ) )
2028 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2029 SALOME::BAD_PARAM );
2031 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2034 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2035 meshServant->Load();
2036 ASSERT( meshServant );
2037 if ( meshServant ) {
2038 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
2039 meshServant->CheckGeomModif();
2040 // get local TopoDS_Shape
2041 TopoDS_Shape myLocShape;
2042 if(theMesh->HasShapeToMesh())
2043 myLocShape = GeomObjectToShape( theShapeObject );
2045 return result._retn();;
2047 // call implementation compute
2048 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2050 ::MeshDimension aDim = (MeshDimension)theDimension;
2051 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2053 int nbShapeId = shapeIds.size();
2054 theShapesId.length( nbShapeId );
2055 // iterates on shapes and collect mesh entities into mesh preview
2056 TSetOfInt::const_iterator idIt = shapeIds.begin();
2057 TSetOfInt::const_iterator idEnd = shapeIds.end();
2058 std::map< int, int > mapOfShIdNb;
2059 std::set< SMESH_TLink > setOfEdge;
2060 std::list< SMDSAbs_ElementType > listOfElemType;
2061 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2062 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2063 TNode2LocalIDMap mapNode2LocalID;
2064 list< TNodeLocalID > connectivity;
2065 int i, nbConnNodes = 0;
2066 std::set< const SMESH_subMesh* > setOfVSubMesh;
2067 // iterates on shapes
2068 for ( ; idIt != idEnd; idIt++ )
2070 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2072 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2073 if ( !sm || !sm->IsMeshComputed() )
2076 const TopoDS_Shape& aSh = sm->GetSubShape();
2077 const int shDim = myGen.GetShapeDim( aSh );
2078 if ( shDim < 1 || shDim > theDimension )
2081 mapOfShIdNb[ *idIt ] = 0;
2082 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2084 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2085 if ( !smDS ) continue;
2087 if ( theDimension == SMESH::DIM_2D )
2089 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2090 while ( faceIt->more() )
2092 const SMDS_MeshElement* face = faceIt->next();
2093 int aNbNode = face->NbNodes();
2095 aNbNode /= 2; // do not take into account additional middle nodes
2097 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2098 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2100 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2101 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2103 listOfElemType.push_back( SMDSAbs_Edge );
2104 connectivity.push_back
2105 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2106 connectivity.push_back
2107 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2113 else if ( theDimension == SMESH::DIM_1D )
2115 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2116 while ( nodeIt->more() )
2118 listOfElemType.push_back( SMDSAbs_Node );
2119 connectivity.push_back
2120 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2122 // add corner nodes by first vertex from edge
2123 SMESH_subMeshIteratorPtr edgeSmIt =
2124 sm->getDependsOnIterator(/*includeSelf*/false,
2125 /*complexShapeFirst*/false);
2126 while ( edgeSmIt->more() )
2128 SMESH_subMesh* vertexSM = edgeSmIt->next();
2129 // check that vertex is not already treated
2130 if ( !setOfVSubMesh.insert( vertexSM ).second )
2132 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2135 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2136 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2137 while ( nodeIt->more() )
2139 listOfElemType.push_back( SMDSAbs_Node );
2140 connectivity.push_back
2141 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2147 // fill node coords and assign local ids to the nodes
2148 int nbNodes = mapNode2LocalID.size();
2149 result->nodesXYZ.length( nbNodes );
2150 TNodeLocalID node2ID = mapNode2LocalID.begin();
2151 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2152 node2ID->second = i;
2153 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2154 result->nodesXYZ[i].x = node->X();
2155 result->nodesXYZ[i].y = node->Y();
2156 result->nodesXYZ[i].z = node->Z();
2158 // fill connectivity
2159 result->elementConnectivities.length( nbConnNodes );
2160 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2161 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2162 result->elementConnectivities[i] = (*connIt)->second;
2165 // fill element types
2166 result->elementTypes.length( listOfElemType.size() );
2167 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2168 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2169 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2171 SMDSAbs_ElementType elemType = *typeIt;
2172 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2173 result->elementTypes[i].isPoly = false;
2174 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2177 // correct number of shapes
2178 theShapesId.length( mapOfShIdNb.size() );
2182 catch ( std::bad_alloc ) {
2183 INFOS( "Precompute(): lack of memory" );
2185 catch ( SALOME_Exception& S_ex ) {
2186 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2189 INFOS( "Precompute(): unknown exception " );
2191 return result._retn();
2195 //=============================================================================
2197 * SMESH_Gen_i::Evaluate
2199 * Evaluate mesh on a shape
2201 //=============================================================================
2203 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2204 GEOM::GEOM_Object_ptr theShapeObject)
2205 // SMESH::long_array& theNbElems)
2206 throw ( SALOME::SALOME_Exception )
2208 Unexpect aCatch(SALOME_SalomeException);
2209 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2211 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2212 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2213 SALOME::BAD_PARAM );
2215 if ( CORBA::is_nil( theMesh ) )
2216 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2217 SALOME::BAD_PARAM );
2219 SMESH::long_array_var nbels = new SMESH::long_array;
2220 nbels->length(SMESH::Entity_Last);
2221 int i = SMESH::Entity_Node;
2222 for (; i < SMESH::Entity_Last; i++)
2225 // Update Python script
2226 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2227 << theMesh << ", " << theShapeObject << ")";
2231 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2232 ASSERT( meshServant );
2233 if ( meshServant ) {
2234 meshServant->Load();
2235 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
2236 meshServant->CheckGeomModif();
2237 // get local TopoDS_Shape
2238 TopoDS_Shape myLocShape;
2239 if(theMesh->HasShapeToMesh())
2240 myLocShape = GeomObjectToShape( theShapeObject );
2242 myLocShape = SMESH_Mesh::PseudoShape();
2243 // call implementation compute
2244 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2245 MapShapeNbElems aResMap;
2246 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2247 MapShapeNbElemsItr anIt = aResMap.begin();
2248 for(; anIt!=aResMap.end(); anIt++) {
2249 const vector<int>& aVec = (*anIt).second;
2250 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2251 int nbElem = aVec[i];
2252 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2254 SMESH_subMesh* sm = anIt->first;
2255 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2256 const SMESH_Algo* algo = sm->GetAlgo();
2257 if ( (algo && !error.get()) || error->IsOK() )
2258 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2262 nbels[i] += aVec[i];
2266 return nbels._retn();
2269 catch ( std::bad_alloc ) {
2270 INFOS( "Evaluate(): lack of memory" );
2272 catch ( SALOME_Exception& S_ex ) {
2273 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2276 INFOS( "Evaluate(): unknown exception " );
2279 return nbels._retn();
2282 //================================================================================
2284 * \brief Return geometrical object the given element is built on
2285 * \param theMesh - the mesh the element is in
2286 * \param theElementID - the element ID
2287 * \param theGeomName - the name of the result geom object if it is not yet published
2288 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2290 //================================================================================
2292 GEOM::GEOM_Object_ptr
2293 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2294 CORBA::Long theElementID,
2295 const char* theGeomName)
2296 throw ( SALOME::SALOME_Exception )
2298 Unexpect aCatch(SALOME_SalomeException);
2300 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2301 if ( !geom->_is_nil() ) {
2302 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2303 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2305 // try to find the corresponding SObject
2306 SALOMEDS::SObject_wrap SObj = ObjectToSObject( myCurrentStudy, geom.in() );
2307 if ( SObj->_is_nil() ) // submesh can be not found even if published
2309 // try to find published submesh
2310 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2311 if ( !geom->IsMainShape() && list->length() == 1 ) {
2312 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2313 SALOMEDS::ChildIterator_wrap it;
2314 if ( !mainSO->_is_nil() ) {
2315 it = myCurrentStudy->NewChildIterator( mainSO );
2317 if ( !it->_is_nil() ) {
2318 for ( it->InitEx(true); it->More(); it->Next() ) {
2319 SALOMEDS::SObject_wrap so = it->Value();
2320 CORBA::Object_var obj = SObjectToObject( so );
2321 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2322 if ( !subGeom->_is_nil() ) {
2323 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2324 if ( subList->length() == 1 && list[0] == subList[0] ) {
2334 if ( SObj->_is_nil() ) // publish a new subshape
2335 SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
2337 // return only published geometry
2338 if ( !SObj->_is_nil() ) {
2339 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2340 CORBA::Object_var obj = SObjectToObject( SObj );
2341 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2345 return GEOM::GEOM_Object::_nil();
2348 //================================================================================
2350 * \brief Return geometrical object the given element is built on.
2351 * \param theMesh - the mesh the element is in
2352 * \param theElementID - the element ID
2353 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2355 //================================================================================
2357 GEOM::GEOM_Object_ptr
2358 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2359 CORBA::Long theElementID)
2360 throw ( SALOME::SALOME_Exception )
2362 Unexpect aCatch(SALOME_SalomeException);
2363 if ( CORBA::is_nil( theMesh ) )
2364 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2366 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2367 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2369 // get a core mesh DS
2370 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2371 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2373 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2374 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2375 // find the element in mesh
2376 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2377 // find a shape id by the element
2378 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2379 // get a geom object by the shape id
2380 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2381 if ( geom->_is_nil() ) {
2382 // try to find a published sub-shape
2383 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2384 SALOMEDS::ChildIterator_wrap it;
2385 if ( !mainSO->_is_nil() ) {
2386 it = myCurrentStudy->NewChildIterator( mainSO );
2388 if ( !it->_is_nil() ) {
2389 for ( it->InitEx(true); it->More(); it->Next() ) {
2390 SALOMEDS::SObject_wrap so = it->Value();
2391 CORBA::Object_var obj = SObjectToObject( so );
2392 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2393 if ( !subGeom->_is_nil() ) {
2394 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2395 if ( subList->length() == 1 && shapeID == subList[0] ) {
2403 if ( geom->_is_nil() ) {
2405 GEOM::GEOM_IShapesOperations_wrap op =
2406 geomGen->GetIShapesOperations( GetCurrentStudyID() );
2407 if ( !op->_is_nil() )
2408 geom = op->GetSubShape( mainShape, shapeID );
2413 if ( !geom->_is_nil() ) {
2414 GeomObjectToShape( geom ); // let geom client remember the found shape
2415 return geom._retn();
2420 return GEOM::GEOM_Object::_nil();
2423 //================================================================================
2425 * SMESH_Gen_i::Concatenate
2427 * Concatenate the given meshes into one mesh
2429 //================================================================================
2431 SMESH::SMESH_Mesh_ptr
2432 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2433 CORBA::Boolean theUniteIdenticalGroups,
2434 CORBA::Boolean theMergeNodesAndElements,
2435 CORBA::Double theMergeTolerance)
2436 throw ( SALOME::SALOME_Exception )
2438 return ConcatenateCommon(theMeshesArray,
2439 theUniteIdenticalGroups,
2440 theMergeNodesAndElements,
2445 //================================================================================
2447 * SMESH_Gen_i::ConcatenateWithGroups
2449 * Concatenate the given meshes into one mesh
2450 * Create the groups of all elements from initial meshes
2452 //================================================================================
2454 SMESH::SMESH_Mesh_ptr
2455 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2456 CORBA::Boolean theUniteIdenticalGroups,
2457 CORBA::Boolean theMergeNodesAndElements,
2458 CORBA::Double theMergeTolerance)
2459 throw ( SALOME::SALOME_Exception )
2461 return ConcatenateCommon(theMeshesArray,
2462 theUniteIdenticalGroups,
2463 theMergeNodesAndElements,
2468 //================================================================================
2470 * SMESH_Gen_i::ConcatenateCommon
2472 * Concatenate the given meshes into one mesh
2474 //================================================================================
2476 SMESH::SMESH_Mesh_ptr
2477 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2478 CORBA::Boolean theUniteIdenticalGroups,
2479 CORBA::Boolean theMergeNodesAndElements,
2480 CORBA::Double theMergeTolerance,
2481 CORBA::Boolean theCommonGroups)
2482 throw ( SALOME::SALOME_Exception )
2484 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2485 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2488 SMESH::SMESH_Mesh_var newMesh = CreateEmptyMesh();
2489 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2490 if ( !newImpl ) return newMesh._retn();
2492 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2493 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2495 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2496 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2497 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2498 TGroupsMap groupsMap;
2499 TListOfNewGroups listOfNewGroups;
2501 ::SMESH_MeshEditor newEditor( &locMesh );
2502 ::SMESH_MeshEditor::ElemFeatures elemType;
2504 // loop on sub-meshes
2505 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2507 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2508 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2509 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2510 if ( !initImpl ) continue;
2513 // assure that IDs increments by one during iteration
2514 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2515 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2516 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2517 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2519 initMeshDS->Modified();
2520 initMeshDS->CompactMesh();
2523 // remember nb of elements before filling in
2524 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2528 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2529 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2530 while ( elemIt->more() )
2532 SMESH_NodeXYZ node = elemIt->next();
2533 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2538 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2539 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2540 while ( elemIt->more() )
2542 const SMDS_MeshElement* elem = elemIt->next();
2543 elemType.myNodes.resize( elem->NbNodes() );
2545 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2546 for ( int k = 0; itNodes->more(); k++)
2548 const SMDS_MeshNode* node = itNodes->next();
2549 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2552 // creates a corresponding element on existent nodes in new mesh
2553 newElems[ elem->GetID() ] =
2554 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2556 newEditor.ClearLastCreated(); // forget the history
2559 // create groups of just added elements
2560 SMESH::SMESH_Group_var newGroup;
2561 SMESH::ElementType groupType;
2562 if ( theCommonGroups )
2565 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2566 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2567 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2568 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2571 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2573 for( groupType = SMESH::NODE;
2574 groupType < SMESH::NB_ELEMENT_TYPES;
2575 groupType = (SMESH::ElementType)( groupType + 1 ))
2577 if ( curState[ groupType ] <= prevState[ groupType ])
2578 continue; // no elements of groupType added from the i-th mesh
2580 // make a group name
2581 std::string groupName = "Gr";
2582 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( myCurrentStudy, theMeshesArray[i] );
2584 CORBA::String_var name = meshSO->GetName();
2588 groupName += typeNames[ groupType ];
2590 // make and fill a group
2591 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2592 std::vector< const SMDS_MeshElement* > & elemVec =
2593 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2594 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2596 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2598 for ( size_t j = 0; j < elemVec.size(); ++j )
2600 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2601 grpDS->Add( elemVec[j] );
2605 listOfNewGroups.clear();
2606 listOfNewGroups.push_back( newGroup );
2607 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2612 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2616 SMESH::SMESH_GroupBase_ptr group;
2617 CORBA::String_var groupName;
2618 SMESH::long_array_var newIDs = new SMESH::long_array();
2620 // loop on groups of a source mesh
2621 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2622 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2624 group = listOfGroups[iG];
2625 groupType = group->GetType();
2626 groupName = group->GetName();
2627 std::string name = groupName.in();
2629 // convert a list of IDs
2630 newIDs->length( group->Size() );
2631 std::vector< const SMDS_MeshElement* > & elemVec =
2632 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2633 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2635 while ( itGrElems->more() )
2637 const SMDS_MeshElement* elem = itGrElems->next();
2638 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2640 newIDs[ nbElems++ ] = newElem->GetID();
2642 newIDs->length( nbElems );
2644 // check that a current group name and type don't have identical ones in final mesh
2645 listOfNewGroups.clear();
2646 TNameAndType nameAndType( name, groupType );
2647 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2648 if ( anIter == groupsMap.end() )
2650 // add a new group in the mesh
2651 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2652 newGroup->Add( newIDs );
2654 listOfNewGroups.push_back( newGroup );
2655 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2657 else if ( theUniteIdenticalGroups )
2659 // unite identical groups
2660 TListOfNewGroups& aNewGroups = anIter->second;
2661 aNewGroups.front()->Add( newIDs );
2665 // rename identical groups
2666 newGroup = newImpl->CreateGroup( groupType, groupName );
2667 newGroup->Add( newIDs );
2669 TListOfNewGroups& newGroups = anIter->second;
2670 std::string newGroupName;
2671 if ( newGroups.size() == 1 )
2673 newGroupName = name + "_1";
2674 newGroups.front()->SetName( newGroupName.c_str() );
2676 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2677 newGroup->SetName( newGroupName.c_str() );
2678 newGroups.push_back( newGroup );
2681 } // if an IDSource is a mesh
2684 if ( theMergeNodesAndElements ) // merge nodes
2686 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2687 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2688 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2689 /*SeparateCornersAndMedium=*/ false );
2690 newEditor.MergeNodes( groupsOfNodes );
2692 newEditor.MergeEqualElements();
2695 // Update Python script
2696 pythonDump << newMesh << " = " << this
2697 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "("
2698 << theMeshesArray << ", "
2699 << theUniteIdenticalGroups << ", "
2700 << theMergeNodesAndElements << ", "
2701 << TVar( theMergeTolerance ) << ")";
2703 pPythonDump.reset(); // enable python dump from GetGroups()
2705 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2706 if ( !newMesh->_is_nil() )
2708 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2711 // IPAL21468 Change icon of compound because it need not be computed.
2712 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( myCurrentStudy, newMesh );
2713 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2715 newMeshDS->Modified();
2717 return newMesh._retn();
2720 //================================================================================
2722 * \brief Create a mesh by copying a part of another mesh
2723 * \param meshPart - a part of mesh to copy
2724 * \param toCopyGroups - to create in the new mesh groups
2725 * the copied elements belongs to
2726 * \param toKeepIDs - to preserve IDs of the copied elements or not
2727 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2729 //================================================================================
2731 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2732 const char* meshName,
2733 CORBA::Boolean toCopyGroups,
2734 CORBA::Boolean toKeepIDs)
2735 throw ( SALOME::SALOME_Exception )
2737 Unexpect aCatch(SALOME_SalomeException);
2739 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2740 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2742 // 1. Get source mesh
2744 if ( CORBA::is_nil( meshPart ))
2745 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2747 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2748 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2750 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2752 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2754 // 2. Make a new mesh
2756 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2757 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2759 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2760 SALOMEDS::SObject_wrap meshSO = ObjectToSObject(myCurrentStudy, newMesh );
2761 if ( !meshSO->_is_nil() )
2763 SetName( meshSO, meshName, "Mesh" );
2764 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2766 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2767 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2768 ::SMESH_MeshEditor::ElemFeatures elemType;
2770 // 3. Get elements to copy
2772 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2773 TIDSortedElemSet srcElems;
2774 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2775 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2778 srcElemIt = srcMeshDS->elementsIterator();
2779 srcNodeIt = srcMeshDS->nodesIterator();
2783 SMESH::long_array_var ids = meshPart->GetIDs();
2784 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2786 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2787 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2788 srcElems.insert( elem );
2792 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2793 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2794 srcElems.insert( elem );
2796 if ( srcElems.empty() )
2797 return newMesh._retn();
2799 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2800 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2805 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2806 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2807 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2809 const SMDS_MeshNode *nSrc, *nTgt;
2810 vector< const SMDS_MeshNode* > nodes;
2811 while ( srcElemIt->more() )
2813 const SMDS_MeshElement * elem = srcElemIt->next();
2815 nodes.resize( elem->NbNodes());
2816 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2818 for ( iN = 0; nIt->more(); ++iN )
2820 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2821 nTgt = newMeshDS->FindNode( nSrc->GetID());
2823 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2828 for ( iN = 0; nIt->more(); ++iN )
2830 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2831 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2833 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2834 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2838 if ( elem->GetType() != SMDSAbs_Node )
2840 elemType.Init( elem, /*basicOnly=*/false );
2841 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2843 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2844 if ( toCopyGroups && !toKeepIDs )
2845 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2847 } // while ( srcElemIt->more() )
2849 // 4(b). Copy free nodes
2851 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2853 while ( srcNodeIt->more() )
2855 nSrc = srcNodeIt->next();
2856 if ( nSrc->NbInverseElements() == 0 )
2859 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2861 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2868 int nbNewGroups = 0;
2871 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2872 while ( gIt->more() )
2874 SMESH_Group* group = gIt->next();
2875 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2877 // Check group type. We copy nodal groups containing nodes of copied element
2878 SMDSAbs_ElementType groupType = groupDS->GetType();
2879 if ( groupType != SMDSAbs_Node &&
2880 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2881 continue; // group type differs from types of meshPart
2883 // Find copied elements in the group
2884 vector< const SMDS_MeshElement* > groupElems;
2885 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2888 const SMDS_MeshElement* foundElem;
2889 if ( groupType == SMDSAbs_Node )
2891 while ( eIt->more() )
2892 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2893 groupElems.push_back( foundElem );
2897 while ( eIt->more() )
2898 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2899 groupElems.push_back( foundElem );
2904 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2905 if ( e2eMap.empty() ) continue;
2906 int minID = e2eMap.begin()->first->GetID();
2907 int maxID = e2eMap.rbegin()->first->GetID();
2908 TE2EMap::iterator e2e;
2909 while ( eIt->more() && groupElems.size() < e2eMap.size())
2911 const SMDS_MeshElement* e = eIt->next();
2912 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2913 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2914 groupElems.push_back( e2e->second );
2918 if ( !groupElems.empty() )
2920 SMESH::SMESH_Group_var newGroupObj =
2921 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2922 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2924 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2925 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2926 for ( unsigned i = 0; i < groupElems.size(); ++i )
2927 smdsGroup.Add( groupElems[i] );
2935 newMeshDS->Modified();
2937 *pyDump << newMesh << " = " << this
2938 << ".CopyMesh( " << meshPart << ", "
2939 << "'" << meshName << "', "
2940 << toCopyGroups << ", "
2941 << toKeepIDs << ")";
2943 pyDumpDeleter.reset(); // allow dump in GetGroups()
2945 if ( nbNewGroups > 0 ) // dump created groups
2946 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2948 return newMesh._retn();
2952 namespace // utils for CopyMeshWithGeom()
2954 typedef std::map< std::string, std::string > TStr2StrMap;
2955 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
2957 //================================================================================
2959 * \brief Return a new sub-shape corresponding to an old one
2961 //================================================================================
2965 SMESH_Mesh_i* mySrcMesh_i;
2966 SMESH_Mesh_i* myNewMesh_i;
2967 SMESH_Gen_i* myGen_i;
2971 TStr2StrMap myOld2NewEntryMap; // map of study entries
2974 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
2976 // not directly relating to shape search
2977 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
2979 //================================================================================
2981 * \brief Constructor
2983 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
2984 SMESH_Mesh_i* newMesh_i,
2985 SMESH_Gen_i* smeshGen_i )
2986 : mySrcMesh_i( srcMesh_i ),
2987 myNewMesh_i( newMesh_i ),
2988 myGen_i ( smeshGen_i ),
2989 myToPublish( !smeshGen_i->GetCurrentStudy()->_is_nil() ),
2990 myGIPMapDone( false )
2992 // retrieve from the study shape mapping made thanks to
2993 // "Set presentation parameters and sub-shapes from arguments" option
2995 SALOMEDS::Study_var study = smeshGen_i->GetCurrentStudy();
2996 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
2997 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
2998 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( study, mainShapeOld );
2999 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( study, mainShapeNew );
3000 if ( newSO->_is_nil() )
3002 myToPublish = false;
3005 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3007 CORBA::String_var oldEntry = oldSO->GetID();
3008 CORBA::String_var newEntry = newSO->GetID();
3009 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3010 std::string( newEntry.in() )));
3012 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3013 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations( myGen_i->GetCurrentStudyID() );
3014 GEOM::ListOfGO_var subShapes = op->GetExistingSubObjects( mainShapeNew,
3015 /*groupsOnly=*/false );
3016 for ( CORBA::ULong i = 0; i < subShapes->length(); ++i )
3018 newSO = myGen_i->ObjectToSObject( study, subShapes[ i ]);
3019 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3020 for ( ; anIter->More(); anIter->Next() )
3022 SALOMEDS::SObject_wrap so = anIter->Value();
3023 if ( so->ReferencedObject( oldSO.inout() ))
3025 oldEntry = oldSO->GetID();
3026 newEntry = newSO->GetID();
3027 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3028 std::string( newEntry.in() )));
3034 //================================================================================
3036 * \brief Find a new sub-shape corresponding to an old one
3038 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3041 return GEOM::GEOM_Object::_duplicate( oldShape );
3043 GEOM::GEOM_Object_var newShape;
3045 if ( CORBA::is_nil( oldShape ))
3046 return newShape._retn();
3048 if ( !isChildOfOld( oldShape ))
3049 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3051 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3052 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3054 // try to find by entry
3057 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3058 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3059 if ( o2nID != myOld2NewEntryMap.end() )
3061 newShape = getShapeByEntry( o2nID->second );
3065 if ( newShape->_is_nil() )
3067 // try to construct a new sub-shape using myGIPMap
3069 std::vector< int > newIndices;
3070 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3071 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3073 findNewIDs( oldIndices[i], newIndices );
3075 if ( !newIndices.empty() )
3079 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3081 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3083 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations( myGen_i->GetCurrentStudyID() );
3084 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3086 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3087 newIndicesList->length( newIndices.size() );
3088 for ( size_t i = 0; i < newIndices.size(); ++i )
3089 newIndicesList[ i ] = newIndices[ i ];
3090 grOp->UnionIDs( newShape, newIndicesList );
3094 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations(myGen_i->GetCurrentStudyID() );
3095 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3104 if ( !newShape->_is_nil() && myToPublish )
3106 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3107 if ( !newEntry.in() || !newEntry.in()[0] )
3109 SALOMEDS::Study_var study = myGen_i->GetCurrentStudy();
3110 CORBA::String_var name = oldShape->GetName();
3111 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( study, newShape, name, mainShapeNew );
3112 newEntry = newShape->GetStudyEntry();
3113 oldEntry = oldShape->GetStudyEntry();
3114 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3115 std::string( newEntry.in() )));
3119 return newShape._retn();
3122 //================================================================================
3124 * \brief Return a study entry of a new shape by study entry of the old one
3126 std::string FindNew( const std::string & oldEntry )
3131 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3132 if ( o2nID != myOld2NewEntryMap.end() )
3133 return o2nID->second;
3135 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3136 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3139 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3140 if ( newShape->_is_nil() )
3141 return std::string();
3143 CORBA::String_var newEntry = newShape->GetStudyEntry();
3144 return newEntry.in();
3147 //================================================================================
3149 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3150 * Return zero if not found or there are more than one new ID
3152 int FindNew( int oldID )
3161 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3163 if ( myGIPMap[ oldID ].length() == 1 )
3165 newID = myGIPMap[ oldID ][ 0 ];
3167 else if ( myGIPMap[ oldID ].length() > 1 &&
3168 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3170 // select a meshed VERTEX
3171 SMESH_subMesh* newSM;
3172 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3173 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3174 ( !newSM->IsEmpty() ))
3175 newID = myGIPMap[ oldID ][ i ];
3181 //================================================================================
3183 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3184 * Return zero if the old shape is not kept as is in the new shape.
3186 int FindNewNotChanged( SMESH_subMesh* oldSM )
3189 return oldSM->GetId();
3191 int newID = FindNew( oldSM->GetId() );
3195 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3199 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3200 // one new sub-shape of the same type.
3202 if ( oldSM->DependsOn().size() !=
3203 newSM->DependsOn().size() )
3206 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3207 while ( srcSMIt->more() )
3209 oldSM = srcSMIt->next();
3210 int newSubID = FindNew( oldSM->GetId() );
3211 if ( getShapeType( myNewMesh_i, newSubID ) !=
3212 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3218 //================================================================================
3220 * \brief Return shape by study entry
3222 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3224 GEOM::GEOM_Object_var shape;
3225 SALOMEDS::Study_var study = myGen_i->GetCurrentStudy();
3226 if ( !study->_is_nil() )
3228 SALOMEDS::SObject_wrap so = study->FindObjectID( entry.c_str() );
3229 if ( !so->_is_nil() )
3231 CORBA::Object_var obj = so->GetObject();
3232 shape = GEOM::GEOM_Object::_narrow( obj );
3235 return shape._retn();
3238 //================================================================================
3240 * \brief Fill myGIPMap by calling GetInPlaceMap()
3244 if ( !myGIPMapDone )
3246 myGIPMapDone = true;
3248 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3249 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3250 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3251 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations(myGen_i->GetCurrentStudyID() );
3254 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3258 myGIPMap = new GEOM::ListOfListOfLong();
3263 //================================================================================
3265 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3266 * number of found IDs
3268 int findNewIDs( int oldID, std::vector< int >& newIDs )
3270 size_t prevNbIDs = newIDs.size();
3272 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3274 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3275 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3277 return newIDs.size() - prevNbIDs;
3280 //================================================================================
3282 * \brief Check if an object relates to the old shape
3284 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3286 if ( CORBA::is_nil( oldShape ))
3288 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3289 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3290 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3291 mainShapeOld1->_is_equivalent( oldShape ));
3294 //================================================================================
3296 * \brief Return shape type by shape ID
3298 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3300 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3301 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3302 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3305 //================================================================================
3307 * \brief Store a source sub-shape for which a counterpart not found and
3308 * a smesh object invalid due to that
3310 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3311 SALOMEDS::SObject_wrap smeshSO )
3313 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3314 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3316 CORBA::String_var smeshEntry = smeshSO->GetID();
3317 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3321 //================================================================================
3323 * \brief Store a source sub-shape for which a counterpart not found and
3324 * a smesh object invalid due to that
3326 void AddInvalid( std::string geomEntry,
3327 SALOMEDS::SObject_wrap smeshSO )
3329 if ( !geomEntry.empty() )
3331 CORBA::String_var smeshEntry = smeshSO->GetID();
3332 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3336 //================================================================================
3338 * \brief Store a source sub-shape for which a counterpart not found and
3339 * a smesh object invalid due to that
3341 void AddInvalid( int oldGeomID,
3342 SALOMEDS::SObject_wrap smeshSO )
3344 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3345 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3348 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3349 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3351 SMESH_Comment geomName( typeName[ shapeType ]);
3352 geomName << " #" << oldGeomID;
3354 CORBA::String_var smeshEntry = smeshSO->GetID();
3355 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3358 //================================================================================
3360 * \brief Return entries of a source sub-shape for which a counterpart not found and
3361 * of smesh objects invalid due to that
3363 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3364 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3366 SALOMEDS::Study_var study = myGen_i->GetCurrentStudy();
3367 if ( study->_is_nil() )
3370 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3371 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3373 nbSO += 1 + entry2entrySet->second.size();
3375 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3376 theInvalidEntries->length ( nbSO );
3377 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3379 entry2entrySet = myInvalidMap.begin();
3380 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3382 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3384 std::set< std::string > & entrySet = entry2entrySet->second;
3385 std::set< std::string >::iterator entry = entrySet.begin();
3386 for ( ; entry != entrySet.end(); ++entry )
3388 theInvalidEntries[ iEntry++ ] = entry->c_str();
3390 SALOMEDS::SObject_wrap so = study->FindObjectID( entry->c_str() );
3391 if ( !so->_is_nil() )
3392 theInvalidMeshSObjects[ iSO++ ] = so;
3397 }; // struct ShapeMapper
3399 //================================================================================
3401 * \brief Append an item to a CORBA sequence
3403 template < class CORBA_seq, class ITEM >
3404 void append( CORBA_seq& seq, ITEM item )
3406 if ( !CORBA::is_nil( item ))
3408 seq->length( 1 + seq->length() );
3409 seq[ seq->length() - 1 ] = item;
3412 } // namespace // utils for CopyMeshWithGeom()
3414 //================================================================================
3416 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3417 * \param [in] sourceMesh - a mesh to copy
3418 * \param [in] newGeometry - a new geometry
3419 * \param [in] toCopyGroups - to create groups in the new mesh
3420 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3421 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3422 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3423 * \param [out] newMesh - return a new mesh
3424 * \param [out] newGroups - return new groups
3425 * \param [out] newSubmeshes - return new sub-meshes
3426 * \param [out] newHypotheses - return new algorithms and hypotheses
3427 * \param [out] invalidEntries - return study entries of objects whose
3428 * counterparts are not found in the newGeometry, followed by entries
3429 * of mesh sub-objects that are invalid because they depend on a not found
3430 * preceeding sub-shape
3431 * \return CORBA::Boolean - is a success
3433 //================================================================================
3435 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3436 GEOM::GEOM_Object_ptr theNewGeometry,
3437 const char* theMeshName,
3438 CORBA::Boolean theToCopyGroups,
3439 CORBA::Boolean theToReuseHypotheses,
3440 CORBA::Boolean theToCopyElements,
3441 SMESH::SMESH_Mesh_out theNewMesh,
3442 SMESH::ListOfGroups_out theNewGroups,
3443 SMESH::submesh_array_out theNewSubmeshes,
3444 SMESH::ListOfHypothesis_out theNewHypotheses,
3445 SMESH::string_array_out theInvalidEntries)
3446 throw ( SALOME::SALOME_Exception )
3448 if ( CORBA::is_nil( theSourceMesh ) ||
3449 CORBA::is_nil( theNewGeometry ))
3450 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3452 if ( !theSourceMesh->HasShapeToMesh() )
3453 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3458 TPythonDump pyDump; // prevent dump from CreateMesh()
3460 theNewMesh = CreateMesh( theNewGeometry );
3461 theNewGroups = new SMESH::ListOfGroups();
3462 theNewSubmeshes = new SMESH::submesh_array();
3463 theNewHypotheses = new SMESH::ListOfHypothesis();
3464 theInvalidEntries = new SMESH::string_array();
3466 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3468 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3469 GEOM::GEOM_Object_var geom, newGeom;
3470 SALOMEDS::SObject_wrap so;
3471 SALOMEDS::Study_var study = GetCurrentStudy();
3473 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3474 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3477 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3479 // treat hypotheses of mesh and sub-meshes
3480 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3481 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3483 bool isSubMesh = ( iSM < smList->length() );
3486 // create a new sub-mesh
3487 SMESH::SMESH_subMesh_var newSM;
3488 geom = smList[iSM]->GetSubShape();
3489 so = ObjectToSObject( study, smList[iSM] );
3490 CORBA::String_var name;
3491 if ( !so->_is_nil() )
3492 name = so->GetName();
3493 newGeom = shapeMapper.FindNew( geom );
3494 if ( newGeom->_is_nil() )
3496 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3497 shapeMapper.AddInvalid( geom, ObjectToSObject( study, newSM ));
3502 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3504 append( theNewSubmeshes, newSM );
3506 if ( newGeom->_is_nil() )
3507 continue; // don't assign hypotheses
3511 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3513 so = ObjectToSObject( study, theNewMesh );
3514 SetName( so, theMeshName, "Mesh" );
3517 // assign hypotheses
3518 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3519 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3521 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3522 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3524 // get geometry hyp depends on
3525 std::vector< std::string > entryArray;
3526 std::vector< int > subIDArray;
3527 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3529 if ( !theToReuseHypotheses || dependsOnGeom )
3531 // create a new hypothesis
3532 CORBA::String_var type = hyp->GetName();
3533 CORBA::String_var lib = hyp->GetLibName();
3534 CORBA::String_var data = hyp_i->SaveTo();
3537 hyp = CreateHypothesis( type, lib );
3538 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3539 hyp_i->LoadFrom( data.in() );
3540 append( theNewHypotheses, hyp );
3544 // update geometry hyp depends on
3545 if ( dependsOnGeom )
3547 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3549 if ( !entryArray[ iGeo ].empty() )
3551 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3552 if ( newEntry.empty() )
3555 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( study, hyp ));
3556 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3558 entryArray[ iGeo ] = newEntry;
3561 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3563 if ( subIDArray[ iGeo ] > 0 )
3565 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3569 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( study, hyp ));
3570 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3572 subIDArray[ iGeo ] = newID;
3575 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3579 CORBA::String_var errorText;
3580 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3581 if ( errorText.in()[0] )
3584 } // loop on hypotheses
3585 } // loop on sub-meshes and mesh
3588 // copy mesh elements, keeping IDs
3589 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3590 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3592 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3593 ::SMESH_MeshEditor::ElemFeatures elemData;
3595 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3596 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3597 /*vertexLast=*/false);
3598 while ( srcSMIt->more() )
3600 SMESH_subMesh* srcSM = srcSMIt->next();
3601 if ( srcSM->IsEmpty() )
3602 continue; // not yet computed
3603 int newID = shapeMapper.FindNewNotChanged( srcSM );
3607 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3608 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3609 while ( nIt->more() )
3611 SMESH_NodeXYZ node( nIt->next() );
3612 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3614 const SMDS_PositionPtr pos = node->GetPosition();
3615 const double* uv = pos->GetParameters();
3616 switch ( pos->GetTypeOfPosition() )
3618 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3619 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3620 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3621 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3625 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3626 while( eIt->more() )
3628 const SMDS_MeshElement* e = eIt->next();
3629 elemData.Init( e, /*basicOnly=*/false );
3630 elemData.SetID( e->GetID() );
3631 elemData.myNodes.resize( e->NbNodes() );
3632 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3634 for ( iN = 0; nnIt->more(); ++iN )
3636 const SMDS_MeshNode* srcNode = nnIt->next();
3637 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3638 if ( !elemData.myNodes[ iN ])
3641 if ( iN == elemData.myNodes.size() )
3642 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3643 newMeshDS->SetMeshElementOnShape( newElem, newID );
3645 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3646 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3649 newMeshDS->Modified();
3655 TStr2StrMap old2newGroupMap;
3657 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3659 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3660 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3661 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3663 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3664 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3665 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3667 CORBA::String_var name = groups[ i ]->GetName();
3668 SMESH::ElementType elemType = groups[ i ]->GetType();
3670 SMESH::SMESH_GroupBase_var newGroup;
3672 if ( !stdlGroup->_is_nil() )
3674 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3676 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3677 CORBA::ULong iE = 0;
3678 for ( ; iE < elemIDs->length(); ++iE ) // check if elements have been copied
3679 if ( newMeshDS->GetElementType( elemIDs[ iE ], elemType != SMESH::NODE ))
3681 if ( iE < elemIDs->length() )
3683 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3684 stdlGroup->Add( elemIDs );
3685 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3689 else if ( !geomGroup->_is_nil() )
3691 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3692 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3693 if ( newGeom->_is_nil() )
3695 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3696 shapeMapper.AddInvalid( geom, ObjectToSObject( study, newGroup ));
3701 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3704 else if ( !fltrGroup->_is_nil() )
3706 // replace geometry in a filter
3707 SMESH::Filter_var filter = fltrGroup->GetFilter();
3708 SMESH::Filter::Criteria_var criteria;
3709 filter->GetCriteria( criteria.out() );
3711 bool isMissingGroup = false;
3712 std::vector< std::string > badEntries;
3714 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3716 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3717 switch ( criteria[ iCr ].Type )
3719 case SMESH::FT_BelongToMeshGroup:
3721 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3722 btgg->SetGroupID( thresholdID );
3723 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3724 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( study, refGroup );
3725 if ( refGroupSO->_is_nil() )
3727 CORBA::String_var refID = refGroupSO->GetID();
3728 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3729 if ( o2nID == old2newGroupMap.end() )
3731 isMissingGroup = true; // corresponding new group not yet created
3734 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3736 if ( o2nID->second.empty() ) // new referred group is invalid
3737 badEntries.push_back( refID.in() );
3740 case SMESH::FT_BelongToGeom:
3741 case SMESH::FT_BelongToPlane:
3742 case SMESH::FT_BelongToCylinder:
3743 case SMESH::FT_BelongToGenSurface:
3744 case SMESH::FT_LyingOnGeom:
3746 std::string newID = shapeMapper.FindNew( thresholdID );
3747 criteria[ iCr ].ThresholdID = newID.c_str();
3748 if ( newID.empty() )
3749 badEntries.push_back( thresholdID );
3752 case SMESH::FT_ConnectedElements:
3754 if ( thresholdID && thresholdID[0] )
3756 std::string newID = shapeMapper.FindNew( thresholdID );
3757 criteria[ iCr ].ThresholdID = newID.c_str();
3758 if ( newID.empty() )
3759 badEntries.push_back( thresholdID );
3765 } // loop on criteria
3767 if ( isMissingGroup && i < nbGroups )
3769 // to treat the group again
3770 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3774 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3775 newFilter->SetCriteria( criteria );
3777 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3778 newFilter->UnRegister();
3780 SALOMEDS::SObject_wrap newSO = ObjectToSObject( study, newGroup );
3781 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3782 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3784 if ( isMissingGroup ) // all groups treated but a referred groups still not found
3786 invalidSObjects.push_back( ObjectToSObject( study, newGroup ));
3789 if ( !badEntries.empty() )
3792 } // treat a group on filter
3794 append( theNewGroups, newGroup );
3796 // fill old2newGroupMap
3797 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( study, groups[i] );
3798 SALOMEDS::SObject_wrap newSO = ObjectToSObject( study, newGroup );
3799 if ( !srcSO->_is_nil() )
3801 CORBA::String_var srcID, newID("");
3802 srcID = srcSO->GetID();
3803 if ( !newSO->_is_nil() )
3804 newID = newSO->GetID();
3805 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
3806 std::string( newID.in() )));
3809 if ( newGroup->_is_nil() )
3814 newMeshDS->CompactMesh();
3817 SALOMEDS::SObject_wrap soNew = ObjectToSObject( study, theNewMesh );
3818 SALOMEDS::SObject_wrap soOld = ObjectToSObject( study, theSourceMesh );
3819 CORBA::String_var oldName = soOld->GetName();
3820 SetName( soNew, oldName.in(), "Mesh" );
3822 // mark invalid objects
3823 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
3825 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
3826 highLightInvalid( invalidSObjects[i].in(), true );
3829 << theNewMesh << ", "
3830 << theNewGroups << ", "
3831 << *theNewSubmeshes.ptr() << ", "
3832 << *theNewHypotheses.ptr() << ", "
3833 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
3834 << theSourceMesh << ", "
3835 << theNewGeometry << ", "
3836 << "'" << theMeshName << "', "
3837 << theToCopyGroups << ", "
3838 << theToReuseHypotheses << ", "
3839 << theToCopyElements << " )";
3841 SMESH_CATCH( SMESH::throwCorbaException );
3846 //================================================================================
3848 * SMESH_Gen_i::GetMEDVersion
3850 * Get MED version of the file by its name
3852 //================================================================================
3853 CORBA::Boolean SMESH_Gen_i::GetMEDVersion(const char* theFileName,
3854 SMESH::MED_VERSION& theVersion)
3856 theVersion = SMESH::MED_V2_1;
3857 MED::EVersion aVersion = MED::GetVersionId( theFileName );
3858 switch( aVersion ) {
3859 case MED::eV2_1 : theVersion = SMESH::MED_V2_1; return true;
3860 case MED::eV2_2 : theVersion = SMESH::MED_V2_2; return true;
3861 case MED::eLATEST : theVersion = SMESH::MED_LATEST; return true;
3862 case MED::eMINOR_0 : theVersion = SMESH::MED_MINOR_0; return true;
3863 case MED::eMINOR_1 : theVersion = SMESH::MED_MINOR_1; return true;
3864 case MED::eMINOR_2 : theVersion = SMESH::MED_MINOR_2; return true;
3865 case MED::eMINOR_3 : theVersion = SMESH::MED_MINOR_3; return true;
3866 case MED::eMINOR_4 : theVersion = SMESH::MED_MINOR_4; return true;
3867 case MED::eMINOR_5 : theVersion = SMESH::MED_MINOR_5; return true;
3868 case MED::eMINOR_6 : theVersion = SMESH::MED_MINOR_6; return true;
3869 case MED::eMINOR_7 : theVersion = SMESH::MED_MINOR_7; return true;
3870 case MED::eMINOR_8 : theVersion = SMESH::MED_MINOR_8; return true;
3871 case MED::eMINOR_9 : theVersion = SMESH::MED_MINOR_9; return true;
3872 case MED::eVUnknown : return false;
3877 //================================================================================
3879 * SMESH_Gen_i::GetMeshNames
3881 * Get names of meshes defined in file with the specified name
3883 //================================================================================
3884 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
3886 SMESH::string_array_var aResult = new SMESH::string_array();
3887 MED::PWrapper aMed = MED::CrWrapper( theFileName );
3889 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
3891 aResult->length( aNbMeshes );
3892 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
3893 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
3894 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
3897 return aResult._retn();
3900 //=============================================================================
3904 * Save SMESH module's data
3906 //=============================================================================
3907 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
3911 // ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
3912 // san -- in case <myCurrentStudy> differs from theComponent's study,
3913 // use that of the component
3914 if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
3915 SetCurrentStudy( theComponent->GetStudy() );
3917 // Store study contents as a set of python commands
3918 SavePython(myCurrentStudy);
3920 StudyContext* myStudyContext = GetCurrentStudyContext();
3922 // Declare a byte stream
3923 SALOMEDS::TMPFile_var aStreamFile;
3925 // Obtain a temporary dir
3926 TCollection_AsciiString tmpDir =
3927 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
3929 // Create a sequence of files processed
3930 SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
3931 aFileSeq->length( NUM_TMP_FILES );
3933 TCollection_AsciiString aStudyName( "" );
3935 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
3937 // Set names of temporary files
3938 TCollection_AsciiString filename =
3939 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
3940 TCollection_AsciiString meshfile =
3941 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
3942 aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
3943 aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
3944 filename = tmpDir + filename;
3945 meshfile = tmpDir + meshfile;
3948 HDFdataset* aDataset;
3949 HDFgroup* aTopGroup;
3951 HDFgroup* aSubGroup;
3952 HDFgroup* aSubSubGroup;
3953 hdf_size aSize[ 1 ];
3956 //Remove the files if they exist: BugID: 11225
3957 #ifndef WIN32 /* unix functionality */
3958 TCollection_AsciiString cmd("rm -f \"");
3960 TCollection_AsciiString cmd("del /F \"");
3967 system(cmd.ToCString());
3969 // MED writer to be used by storage process
3970 DriverMED_W_SMESHDS_Mesh myWriter;
3971 myWriter.SetFile( meshfile.ToCString() );
3974 // SetStoreName() to groups before storing hypotheses to let them refer to
3975 // groups using "store name", which is "Group <group_persistent_id>"
3977 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
3978 for ( ; itBig->More(); itBig->Next() ) {
3979 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3980 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3981 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3982 if ( !CORBA::is_nil( anObject ) ) {
3983 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3984 if ( !myMesh->_is_nil() ) {
3985 myMesh->Load(); // load from study file if not yet done
3986 TPythonDump pd; // not to dump GetGroups()
3987 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
3988 pd << ""; // to avoid optimizing pd out
3989 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
3991 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
3994 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
3995 int anId = myStudyContext->findId( string( objStr.in() ) );
3997 sprintf( grpName, "Group %d", anId );
3998 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
3999 aGrpBaseDS->SetStoreName( grpName );
4009 // ---> create HDF file
4010 aFile = new HDFfile( (char*) filename.ToCString() );
4011 aFile->CreateOnDisk();
4013 // --> iterator for top-level objects
4014 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
4015 for ( ; itBig->More(); itBig->Next() ) {
4016 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4018 // --> hypotheses root branch (only one for the study)
4019 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4020 // create hypotheses root HDF group
4021 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4022 aTopGroup->CreateOnDisk();
4024 // iterator for all hypotheses
4025 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
4026 for ( ; it->More(); it->Next() ) {
4027 SALOMEDS::SObject_wrap mySObject = it->Value();
4028 CORBA::Object_var anObject = SObjectToObject( mySObject );
4029 if ( !CORBA::is_nil( anObject ) ) {
4030 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4031 if ( !myHyp->_is_nil() ) {
4032 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4034 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4035 std::string hypname = hn.in();
4036 std::string libname = ln.in();
4038 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4039 // WIN32 and ".so" for X-system) must be deleted
4040 int libname_len = libname.length();
4042 if( libname_len > 4 )
4043 libname.resize( libname_len - 4 );
4045 // PAL17753 (Regression: missing hypothesis in restored study)
4046 // "lib" also should be removed from the beginning
4047 //if( libname_len > 3 )
4048 //libname.resize( libname_len - 3 );
4049 if( libname_len > 6 )
4050 libname = libname.substr( 3, libname_len - 3 - 3 );
4052 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4053 CORBA::String_var hypdata = myImpl->SaveTo();
4054 int id = myStudyContext->findId( string( objStr.in() ));
4056 // for each hypothesis create HDF group basing on its id
4057 char hypGrpName[30];
4058 sprintf( hypGrpName, "Hypothesis %d", id );
4059 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4060 aGroup->CreateOnDisk();
4061 // --> type name of hypothesis
4062 aSize[ 0 ] = hypname.length() + 1;
4063 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4064 aDataset->CreateOnDisk();
4065 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4066 aDataset->CloseOnDisk();
4067 // --> server plugin library name of hypothesis
4068 aSize[ 0 ] = libname.length() + 1;
4069 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4070 aDataset->CreateOnDisk();
4071 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4072 aDataset->CloseOnDisk();
4073 // --> persistent data of hypothesis
4074 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4075 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4076 aDataset->CreateOnDisk();
4077 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4078 aDataset->CloseOnDisk();
4079 // close hypothesis HDF group
4080 aGroup->CloseOnDisk();
4085 // close hypotheses root HDF group
4086 aTopGroup->CloseOnDisk();
4088 // --> algorithms root branch (only one for the study)
4089 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4090 // create algorithms root HDF group
4091 aTopGroup = new HDFgroup( "Algorithms", aFile );
4092 aTopGroup->CreateOnDisk();
4094 // iterator for all algorithms
4095 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
4096 for ( ; it->More(); it->Next() ) {
4097 SALOMEDS::SObject_wrap mySObject = it->Value();
4098 CORBA::Object_var anObject = SObjectToObject( mySObject );
4099 if ( !CORBA::is_nil( anObject ) ) {
4100 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4101 if ( !myHyp->_is_nil() ) {
4102 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4104 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4105 std::string hypname = hn.in();
4106 std::string libname = ln.in();
4108 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4109 // WIN32 and ".so" for X-system) must be deleted
4110 int libname_len = libname.length();
4112 if( libname_len > 4 )
4113 libname.resize( libname_len - 4 );
4115 // PAL17753 (Regression: missing hypothesis in restored study)
4116 // "lib" also should be removed from the beginning
4117 //if( libname_len > 3 )
4118 //libname.resize( libname_len - 3 );
4119 if( libname_len > 6 )
4120 libname = libname.substr( 3, libname_len - 3 - 3 );
4122 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4123 CORBA::String_var hypdata = myImpl->SaveTo();
4124 int id = myStudyContext->findId( string( objStr.in() ) );
4126 // for each algorithm create HDF group basing on its id
4127 char hypGrpName[30];
4128 sprintf( hypGrpName, "Algorithm %d", id );
4129 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4130 aGroup->CreateOnDisk();
4131 // --> type name of algorithm
4132 aSize[0] = hypname.length() + 1;
4133 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4134 aDataset->CreateOnDisk();
4135 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4136 aDataset->CloseOnDisk();
4137 // --> server plugin library name of hypothesis
4138 aSize[0] = libname.length() + 1;
4139 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4140 aDataset->CreateOnDisk();
4141 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4142 aDataset->CloseOnDisk();
4143 // --> persistent data of algorithm
4144 aSize[0] = strlen( hypdata.in() ) + 1;
4145 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4146 aDataset->CreateOnDisk();
4147 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4148 aDataset->CloseOnDisk();
4149 // close algorithm HDF group
4150 aGroup->CloseOnDisk();
4155 // close algorithms root HDF group
4156 aTopGroup->CloseOnDisk();
4158 // --> mesh objects roots branches
4159 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4160 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4161 if ( !CORBA::is_nil( anObject ) ) {
4162 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4163 if ( !myMesh->_is_nil() ) {
4164 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4166 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4167 int id = myStudyContext->findId( string( objStr.in() ) );
4168 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4169 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4170 bool hasShape = myLocMesh.HasShapeToMesh();
4172 // for each mesh open the HDF group basing on its id
4173 char meshGrpName[ 30 ];
4174 sprintf( meshGrpName, "Mesh %d", id );
4175 aTopGroup = new HDFgroup( meshGrpName, aFile );
4176 aTopGroup->CreateOnDisk();
4178 // --> put dataset to hdf file which is a flag that mesh has data
4179 string strHasData = "0";
4180 // check if the mesh is not empty
4181 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4182 // write mesh data to med file
4183 myWriter.SetMesh( mySMESHDSMesh );
4184 myWriter.SetMeshId( id );
4187 aSize[ 0 ] = strHasData.length() + 1;
4188 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4189 aDataset->CreateOnDisk();
4190 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4191 aDataset->CloseOnDisk();
4194 // for each mesh open the HDF group basing on its auto color parameter
4195 char meshAutoColorName[ 30 ];
4196 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4198 anAutoColor[0] = myImpl->GetAutoColor();
4200 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4201 aDataset->CreateOnDisk();
4202 aDataset->WriteOnDisk( anAutoColor );
4203 aDataset->CloseOnDisk();
4205 // issue 0020693. Store _isModified flag
4206 int isModified = myLocMesh.GetIsModified();
4208 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4209 aDataset->CreateOnDisk();
4210 aDataset->WriteOnDisk( &isModified );
4211 aDataset->CloseOnDisk();
4213 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4214 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4216 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4217 aDataset->CreateOnDisk();
4218 aDataset->WriteOnDisk( &meshPersistentId );
4219 aDataset->CloseOnDisk();
4221 // write reference on a shape if exists
4222 SALOMEDS::SObject_wrap myRef;
4223 bool shapeRefFound = false;
4224 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4226 SALOMEDS::SObject_wrap myShape;
4227 bool ok = myRef->ReferencedObject( myShape.inout() );
4229 CORBA::Object_var shapeObj = myShape->GetObject();
4230 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4231 CORBA::String_var myRefOnObject = myShape->GetID();
4232 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4233 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4234 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4235 aDataset->CreateOnDisk();
4236 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4237 aDataset->CloseOnDisk();
4242 // write applied hypotheses if exist
4243 SALOMEDS::SObject_wrap myHypBranch;
4244 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4245 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4246 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4248 if ( found && (shapeRefFound || !hasShape) ) {
4249 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4250 aGroup->CreateOnDisk();
4252 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myHypBranch );
4254 for ( ; it->More(); it->Next() ) {
4255 SALOMEDS::SObject_wrap mySObject = it->Value();
4256 SALOMEDS::SObject_wrap myRefOnHyp;
4257 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4259 // san - it is impossible to recover applied hypotheses
4260 // using their entries within Load() method,
4261 // for there are no AttributeIORs in the study when Load() is working.
4262 // Hence, it is better to store persistent IDs of hypotheses as references to them
4264 //string myRefOnObject = myRefOnHyp->GetID();
4265 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4266 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4267 int id = myStudyContext->findId( string( objStr.in() ) );
4268 //if ( myRefOnObject.length() > 0 ) {
4269 //aSize[ 0 ] = myRefOnObject.length() + 1;
4270 char hypName[ 30 ], hypId[ 30 ];
4271 sprintf( hypName, "Hyp %d", ++hypNb );
4272 sprintf( hypId, "%d", id );
4273 aSize[ 0 ] = strlen( hypId ) + 1;
4274 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4275 aDataset->CreateOnDisk();
4276 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4277 aDataset->WriteOnDisk( hypId );
4278 aDataset->CloseOnDisk();
4282 aGroup->CloseOnDisk();
4285 // write applied algorithms if exist
4286 SALOMEDS::SObject_wrap myAlgoBranch;
4287 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4288 myAlgoBranch.inout() );
4289 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4290 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4292 if ( found && (shapeRefFound || !hasShape)) {
4293 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4294 aGroup->CreateOnDisk();
4296 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myAlgoBranch );
4298 for ( ; it->More(); it->Next() ) {
4299 SALOMEDS::SObject_wrap mySObject = it->Value();
4300 SALOMEDS::SObject_wrap myRefOnAlgo;
4301 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4303 // san - it is impossible to recover applied algorithms
4304 // using their entries within Load() method,
4305 // for there are no AttributeIORs in the study when Load() is working.
4306 // Hence, it is better to store persistent IDs of algorithms as references to them
4308 //string myRefOnObject = myRefOnAlgo->GetID();
4309 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4310 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4311 int id = myStudyContext->findId( string( objStr.in() ) );
4312 //if ( myRefOnObject.length() > 0 ) {
4313 //aSize[ 0 ] = myRefOnObject.length() + 1;
4314 char algoName[ 30 ], algoId[ 30 ];
4315 sprintf( algoName, "Algo %d", ++algoNb );
4316 sprintf( algoId, "%d", id );
4317 aSize[ 0 ] = strlen( algoId ) + 1;
4318 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4319 aDataset->CreateOnDisk();
4320 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4321 aDataset->WriteOnDisk( algoId );
4322 aDataset->CloseOnDisk();
4326 aGroup->CloseOnDisk();
4329 // --> submesh objects sub-branches
4331 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4332 SALOMEDS::SObject_wrap mySubmeshBranch;
4333 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4335 if ( found ) // check if there is shape reference in submeshes
4337 bool hasShapeRef = false;
4338 SALOMEDS::ChildIterator_wrap itSM =
4339 myCurrentStudy->NewChildIterator( mySubmeshBranch );
4340 for ( ; itSM->More(); itSM->Next() ) {
4341 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4342 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4343 mySubRef->ReferencedObject( myShape.inout() );
4344 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4347 { // remove one submesh
4348 if ( shapeRefFound )
4349 { // unassign hypothesis
4350 SMESH::SMESH_subMesh_var mySubMesh =
4351 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4352 if ( !mySubMesh->_is_nil() ) {
4353 int shapeID = mySubMesh->GetId();
4354 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4355 const list<const SMESHDS_Hypothesis*>& hypList =
4356 mySMESHDSMesh->GetHypothesis( S );
4357 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4358 while ( hyp != hypList.end() ) {
4359 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4360 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4364 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4366 } // loop on submeshes of a type
4367 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4368 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4371 } // end check if there is shape reference in submeshes
4373 char name_meshgroup[ 30 ];
4374 if ( i == GetSubMeshOnVertexTag() )
4375 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4376 else if ( i == GetSubMeshOnEdgeTag() )
4377 strcpy( name_meshgroup, "SubMeshes On Edge" );
4378 else if ( i == GetSubMeshOnWireTag() )
4379 strcpy( name_meshgroup, "SubMeshes On Wire" );
4380 else if ( i == GetSubMeshOnFaceTag() )
4381 strcpy( name_meshgroup, "SubMeshes On Face" );
4382 else if ( i == GetSubMeshOnShellTag() )
4383 strcpy( name_meshgroup, "SubMeshes On Shell" );
4384 else if ( i == GetSubMeshOnSolidTag() )
4385 strcpy( name_meshgroup, "SubMeshes On Solid" );
4386 else if ( i == GetSubMeshOnCompoundTag() )
4387 strcpy( name_meshgroup, "SubMeshes On Compound" );
4389 // for each type of submeshes create container HDF group
4390 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4391 aGroup->CreateOnDisk();
4393 // iterator for all submeshes of given type
4394 SALOMEDS::ChildIterator_wrap itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
4395 for ( ; itSM->More(); itSM->Next() ) {
4396 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4397 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4398 if ( !CORBA::is_nil( anSubObject ))
4400 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4401 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4402 int subid = myStudyContext->findId( string( objStr.in() ) );
4404 // for each mesh open the HDF group basing on its id
4405 char submeshGrpName[ 30 ];
4406 sprintf( submeshGrpName, "SubMesh %d", subid );
4407 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4408 aSubGroup->CreateOnDisk();
4410 // write reference on a shape, already checked if it exists
4411 SALOMEDS::SObject_wrap mySubRef, myShape;
4412 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4413 mySubRef->ReferencedObject( myShape.inout() );
4414 string myRefOnObject = myShape->GetID();
4415 if ( myRefOnObject.length() > 0 ) {
4416 aSize[ 0 ] = myRefOnObject.length() + 1;
4417 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4418 aDataset->CreateOnDisk();
4419 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4420 aDataset->CloseOnDisk();
4423 // write applied hypotheses if exist
4424 SALOMEDS::SObject_wrap mySubHypBranch;
4425 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4426 mySubHypBranch.inout() );
4428 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4429 aSubSubGroup->CreateOnDisk();
4431 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( mySubHypBranch );
4433 for ( ; it->More(); it->Next() ) {
4434 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4435 SALOMEDS::SObject_wrap myRefOnHyp;
4436 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4438 //string myRefOnObject = myRefOnHyp->GetID();
4439 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4440 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4441 int id = myStudyContext->findId( string( objStr.in() ) );
4442 //if ( myRefOnObject.length() > 0 ) {
4443 //aSize[ 0 ] = myRefOnObject.length() + 1;
4444 char hypName[ 30 ], hypId[ 30 ];
4445 sprintf( hypName, "Hyp %d", ++hypNb );
4446 sprintf( hypId, "%d", id );
4447 aSize[ 0 ] = strlen( hypId ) + 1;
4448 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4449 aDataset->CreateOnDisk();
4450 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4451 aDataset->WriteOnDisk( hypId );
4452 aDataset->CloseOnDisk();
4456 aSubSubGroup->CloseOnDisk();
4459 // write applied algorithms if exist
4460 SALOMEDS::SObject_wrap mySubAlgoBranch;
4461 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4462 mySubAlgoBranch.inout() );
4464 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4465 aSubSubGroup->CreateOnDisk();
4467 SALOMEDS::ChildIterator_wrap it =
4468 myCurrentStudy->NewChildIterator( mySubAlgoBranch );
4470 for ( ; it->More(); it->Next() ) {
4471 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4472 SALOMEDS::SObject_wrap myRefOnAlgo;
4473 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4475 //string myRefOnObject = myRefOnAlgo->GetID();
4476 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4477 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4478 int id = myStudyContext->findId( string( objStr.in() ) );
4479 //if ( myRefOnObject.length() > 0 ) {
4480 //aSize[ 0 ] = myRefOnObject.length() + 1;
4481 char algoName[ 30 ], algoId[ 30 ];
4482 sprintf( algoName, "Algo %d", ++algoNb );
4483 sprintf( algoId, "%d", id );
4484 aSize[ 0 ] = strlen( algoId ) + 1;
4485 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4486 aDataset->CreateOnDisk();
4487 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4488 aDataset->WriteOnDisk( algoId );
4489 aDataset->CloseOnDisk();
4493 aSubSubGroup->CloseOnDisk();
4495 // close submesh HDF group
4496 aSubGroup->CloseOnDisk();
4499 // close container of submeshes by type HDF group
4500 aGroup->CloseOnDisk();
4503 // All sub-meshes will be stored in MED file
4504 // .. will NOT (PAL 12992)
4505 //if ( shapeRefFound )
4506 //myWriter.AddAllSubMeshes();
4508 // store submesh order if any
4509 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4510 if ( theOrderIds.size() ) {
4511 char order_list[ 30 ];
4512 strcpy( order_list, "Mesh Order" );
4513 // count number of submesh ids
4515 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4516 for ( ; idIt != theOrderIds.end(); idIt++ )
4517 nbIDs += (*idIt).size();
4518 // number of values = number of IDs +
4519 // number of lists (for separators) - 1
4520 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4521 idIt = theOrderIds.begin();
4522 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4523 const TListOfInt& idList = *idIt;
4524 if (idIt != theOrderIds.begin()) // not first list
4525 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4526 // dump submesh ids from current list
4527 TListOfInt::const_iterator id_smId = idList.begin();
4528 for( ; id_smId != idList.end(); id_smId++ )
4529 smIDs[ i++ ] = *id_smId;
4532 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4534 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4535 aDataset->CreateOnDisk();
4536 aDataset->WriteOnDisk( smIDs );
4537 aDataset->CloseOnDisk();
4542 // groups root sub-branch
4543 SALOMEDS::SObject_wrap myGroupsBranch;
4544 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4545 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4547 char name_group[ 30 ];
4548 if ( i == GetNodeGroupsTag() )
4549 strcpy( name_group, "Groups of Nodes" );
4550 else if ( i == GetEdgeGroupsTag() )
4551 strcpy( name_group, "Groups of Edges" );
4552 else if ( i == GetFaceGroupsTag() )
4553 strcpy( name_group, "Groups of Faces" );
4554 else if ( i == GetVolumeGroupsTag() )
4555 strcpy( name_group, "Groups of Volumes" );
4556 else if ( i == Get0DElementsGroupsTag() )
4557 strcpy( name_group, "Groups of 0D Elements" );
4558 else if ( i == GetBallElementsGroupsTag() )
4559 strcpy( name_group, "Groups of Balls" );
4561 aGroup = new HDFgroup( name_group, aTopGroup );
4562 aGroup->CreateOnDisk();
4564 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myGroupsBranch );
4565 for ( ; it->More(); it->Next() ) {
4566 SALOMEDS::SObject_wrap mySObject = it->Value();
4567 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4568 if ( !CORBA::is_nil( aSubObject ) ) {
4569 SMESH_GroupBase_i* myGroupImpl =
4570 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4573 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4577 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4578 int anId = myStudyContext->findId( string( objStr.in() ) );
4580 // For each group, create a dataset named "Group <group_persistent_id>"
4581 // and store the group's user name into it
4582 const char* grpName = aGrpBaseDS->GetStoreName();
4583 CORBA::String_var aUserName = myGroupImpl->GetName();
4584 aSize[ 0 ] = strlen( aUserName ) + 1;
4586 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4587 aDataset->CreateOnDisk();
4588 aDataset->WriteOnDisk( aUserName );
4589 aDataset->CloseOnDisk();
4592 // For each group, create a dataset named "Group <group_persistent_id> Color"
4593 // and store the group's color into it
4594 char grpColorName[ 30 ];
4595 sprintf( grpColorName, "ColorGroup %d", anId );
4596 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4598 anRGB[ 0 ] = aColor.R;
4599 anRGB[ 1 ] = aColor.G;
4600 anRGB[ 2 ] = aColor.B;
4602 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4603 aDataset->CreateOnDisk();
4604 aDataset->WriteOnDisk( anRGB );
4605 aDataset->CloseOnDisk();
4607 // Pass SMESHDS_Group to MED writer
4608 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4610 myWriter.AddGroup( aGrpDS );
4612 // write reference on a shape if exists
4613 SMESHDS_GroupOnGeom* aGeomGrp =
4614 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4616 SALOMEDS::SObject_wrap mySubRef, myShape;
4617 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4618 mySubRef->ReferencedObject( myShape.inout() ) &&
4619 !CORBA::is_nil( myShape->GetObject() ))
4621 CORBA::String_var myRefOnObject = myShape->GetID();
4622 if ( myRefOnObject.in()[0] ) {
4623 char aRefName[ 30 ];
4624 sprintf( aRefName, "Ref on shape %d", anId);
4625 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4626 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4627 aDataset->CreateOnDisk();
4628 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4629 aDataset->CloseOnDisk();
4632 else // shape ref is invalid:
4634 // save a group on geometry as ordinary group
4635 myWriter.AddGroup( aGeomGrp );
4638 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4639 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4641 std::string str = aFilterGrp_i->FilterToString();
4642 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4643 aSize[ 0 ] = str.length() + 1;
4644 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4645 aDataset->CreateOnDisk();
4646 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4647 aDataset->CloseOnDisk();
4651 aGroup->CloseOnDisk();
4655 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4657 // Flush current mesh information into MED file
4660 // save info on nb of elements
4661 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4663 // maybe a shape was deleted in the study
4664 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4665 TopoDS_Shape nullShape;
4666 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4669 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4674 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4675 aGroup->CreateOnDisk();
4677 // each element belongs to one or none submesh,
4678 // so for each node/element, we store a submesh ID
4680 // Store submesh IDs
4681 for ( int isNode = 0; isNode < 2; ++isNode )
4683 SMDS_ElemIteratorPtr eIt =
4684 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4685 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4688 std::vector<int> smIDs; smIDs.reserve( nbElems );
4689 while ( eIt->more() )
4690 if ( const SMDS_MeshElement* e = eIt->next())
4691 smIDs.push_back( e->getshapeId() );
4693 aSize[ 0 ] = nbElems;
4694 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4695 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4696 aDataset->CreateOnDisk();
4697 aDataset->WriteOnDisk( & smIDs[0] );
4698 aDataset->CloseOnDisk();
4701 aGroup->CloseOnDisk();
4703 // Store node positions on sub-shapes (SMDS_Position):
4704 // ----------------------------------------------------
4706 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4707 aGroup->CreateOnDisk();
4709 // in aGroup, create 5 datasets to contain:
4710 // "Nodes on Edges" - ID of node on edge
4711 // "Edge positions" - U parameter on node on edge
4712 // "Nodes on Faces" - ID of node on face
4713 // "Face U positions" - U parameter of node on face
4714 // "Face V positions" - V parameter of node on face
4716 // Find out nb of nodes on edges and faces
4717 // Collect corresponding sub-meshes
4718 int nbEdgeNodes = 0, nbFaceNodes = 0;
4719 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4720 // loop on SMESHDS_SubMesh'es
4721 while ( smIt->more() )
4723 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4724 if ( aSubMesh->IsComplexSubmesh() )
4725 continue; // submesh containing other submeshs
4726 int nbNodes = aSubMesh->NbNodes();
4727 if ( nbNodes == 0 ) continue;
4729 int aShapeID = aSubMesh->GetID();
4730 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
4732 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
4733 // write only SMDS_FacePosition and SMDS_EdgePosition
4734 switch ( aShapeType ) {
4736 nbFaceNodes += nbNodes;
4737 aFaceSM.push_back( aSubMesh );
4740 nbEdgeNodes += nbNodes;
4741 aEdgeSM.push_back( aSubMesh );
4747 // Treat positions on edges or faces
4748 for ( int onFace = 0; onFace < 2; onFace++ )
4750 // Create arrays to store in datasets
4751 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
4752 if (!nbNodes) continue;
4753 int* aNodeIDs = new int [ nbNodes ];
4754 double* aUPos = new double [ nbNodes ];
4755 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
4758 // loop on sub-meshes
4759 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
4760 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
4761 for ( ; itSM != pListSM->end(); itSM++ )
4763 SMESHDS_SubMesh* aSubMesh = (*itSM);
4765 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
4766 // loop on nodes in aSubMesh
4767 while ( itNode->more() )
4770 const SMDS_MeshNode* node = itNode->next();
4771 aNodeIDs [ iNode ] = node->GetID();
4774 const SMDS_PositionPtr pos = node->GetPosition();
4775 if ( onFace ) { // on FACE
4776 SMDS_FacePositionPtr fPos = pos;
4778 aUPos[ iNode ] = fPos->GetUParameter();
4779 aVPos[ iNode ] = fPos->GetVParameter();
4786 SMDS_EdgePositionPtr ePos = pos;
4788 aUPos[ iNode ] = ePos->GetUParameter();
4794 } // loop on nodes in aSubMesh
4795 } // loop on sub-meshes
4800 aSize[ 0 ] = nbNodes;
4802 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
4803 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4804 aDataset->CreateOnDisk();
4805 aDataset->WriteOnDisk( aNodeIDs );
4806 aDataset->CloseOnDisk();
4809 aDSName = ( onFace ? "Face U positions" : "Edge positions");
4810 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
4811 aDataset->CreateOnDisk();
4812 aDataset->WriteOnDisk( aUPos );
4813 aDataset->CloseOnDisk();
4816 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
4817 aDataset->CreateOnDisk();
4818 aDataset->WriteOnDisk( aVPos );
4819 aDataset->CloseOnDisk();
4824 if ( aVPos ) delete [] aVPos;
4826 } // treat positions on edges or faces
4828 // close "Node Positions" group
4829 aGroup->CloseOnDisk();
4831 } // if ( there are submeshes in SMESHDS_Mesh )
4834 // close mesh HDF group
4835 aTopGroup->CloseOnDisk();
4843 aFile->CloseOnDisk();
4846 // Convert temporary files to stream
4847 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
4849 // Remove temporary files and directory
4851 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
4853 return aStreamFile._retn();
4856 //=============================================================================
4858 * SMESH_Gen_i::SaveASCII
4860 * Save SMESH module's data in ASCII format
4862 //=============================================================================
4864 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
4866 bool isMultiFile ) {
4867 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
4868 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
4869 return aStreamFile._retn();
4871 //after usual saving needs to encipher binary to text string
4872 //Any binary symbol will be represent as "|xx" () hexadecimal format number
4873 int size = aStreamFile.in().length();
4874 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
4875 for ( int i = 0; i < size; i++ )
4876 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
4878 buffer[size * 3] = '\0';
4880 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
4882 return anAsciiStreamFile._retn();
4885 //=============================================================================
4887 * SMESH_Gen_i::loadGeomData
4889 * Load GEOM module data
4891 //=============================================================================
4893 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
4895 if ( theCompRoot->_is_nil() )
4898 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
4899 if ( aStudy->_is_nil() )
4902 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
4903 aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
4906 //=============================================================================
4910 * Load SMESH module's data
4912 //=============================================================================
4914 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
4915 const SALOMEDS::TMPFile& theStream,
4919 if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
4920 SetCurrentStudy( theComponent->GetStudy() );
4922 /* if( !theComponent->_is_nil() )
4924 //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
4925 if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
4926 loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
4929 StudyContext* myStudyContext = GetCurrentStudyContext();
4931 // Get temporary files location
4932 TCollection_AsciiString tmpDir =
4933 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
4935 // Convert the stream into sequence of files to process
4936 SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
4939 TCollection_AsciiString aStudyName( "" );
4940 if ( isMultiFile ) {
4941 CORBA::String_var url = myCurrentStudy->URL();
4942 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( url.in() ).c_str();
4944 // Set names of temporary files
4945 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
4946 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
4950 HDFdataset* aDataset;
4951 HDFgroup* aTopGroup;
4953 HDFgroup* aSubGroup;
4954 HDFgroup* aSubSubGroup;
4957 // ---> open HDF file
4958 aFile = new HDFfile( (char*) filename.ToCString() );
4960 aFile->OpenOnDisk( HDF_RDONLY );
4962 catch ( HDFexception ) {
4963 INFOS( "Load(): " << filename << " not found!" );
4967 TPythonDump pd; // prevent dump during loading
4969 // DriverMED_R_SMESHDS_Mesh myReader;
4970 // myReader.SetFile( meshfile.ToCString() );
4972 // For PAL13473 ("Repetitive mesh") implementation.
4973 // New dependencies between SMESH objects are established:
4974 // now hypotheses can refer to meshes, shapes and other hypotheses.
4975 // To keep data consistent, the following order of data restoration
4977 // 1. Create hypotheses
4978 // 2. Create all meshes
4979 // 3. Load hypotheses' data
4982 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
4983 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
4984 list< SMESH::Filter_var > filters;
4986 // get total number of top-level groups
4987 int aNbGroups = aFile->nInternalObjects();
4988 if ( aNbGroups > 0 ) {
4989 // --> in first turn we should read&create hypotheses
4990 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
4991 // open hypotheses root HDF group
4992 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4993 aTopGroup->OpenOnDisk();
4995 // get number of hypotheses
4996 int aNbObjects = aTopGroup->nInternalObjects();
4997 for ( int j = 0; j < aNbObjects; j++ ) {
4998 // try to identify hypothesis
4999 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5000 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5002 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5003 // open hypothesis group
5004 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5005 aGroup->OpenOnDisk();
5007 // --> get hypothesis id
5008 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5013 // get number of datasets
5014 int aNbSubObjects = aGroup->nInternalObjects();
5015 for ( int k = 0; k < aNbSubObjects; k++ ) {
5017 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5018 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5019 // --> get hypothesis name
5020 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5021 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5022 aDataset->OpenOnDisk();
5023 size = aDataset->GetSize();
5024 char* hypname_str = new char[ size ];
5025 aDataset->ReadFromDisk( hypname_str );
5026 hypname = string( hypname_str );
5027 delete [] hypname_str;
5028 aDataset->CloseOnDisk();
5030 // --> get hypothesis plugin library name
5031 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5032 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5033 aDataset->OpenOnDisk();
5034 size = aDataset->GetSize();
5035 char* libname_str = new char[ size ];
5036 aDataset->ReadFromDisk( libname_str );
5037 if(MYDEBUG) SCRUTE( libname_str );
5038 libname = string( libname_str );
5039 delete [] libname_str;
5040 aDataset->CloseOnDisk();
5042 // --> get hypothesis data
5043 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5044 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5045 aDataset->OpenOnDisk();
5046 size = aDataset->GetSize();
5047 char* hypdata_str = new char[ size ];
5048 aDataset->ReadFromDisk( hypdata_str );
5049 hypdata = string( hypdata_str );
5050 delete [] hypdata_str;
5051 aDataset->CloseOnDisk();
5054 // close hypothesis HDF group
5055 aGroup->CloseOnDisk();
5057 // --> restore hypothesis from data
5058 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5059 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5060 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5061 SMESH::SMESH_Hypothesis_var myHyp;
5063 try { // protect persistence mechanism against exceptions
5064 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5067 INFOS( "Exception during hypothesis creation" );
5070 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5072 // myImpl->LoadFrom( hypdata.c_str() );
5073 hypDataList.push_back( make_pair( myImpl, hypdata ));
5074 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5075 int newId = myStudyContext->findId( iorString.in() );
5076 myStudyContext->mapOldToNew( id, newId );
5079 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5083 // close hypotheses root HDF group
5084 aTopGroup->CloseOnDisk();
5088 // --> then we should read&create algorithms
5089 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5090 // open algorithms root HDF group
5091 aTopGroup = new HDFgroup( "Algorithms", aFile );
5092 aTopGroup->OpenOnDisk();
5094 // get number of algorithms
5095 int aNbObjects = aTopGroup->nInternalObjects();
5096 for ( int j = 0; j < aNbObjects; j++ ) {
5097 // try to identify algorithm
5098 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5099 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5101 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5102 // open algorithm group
5103 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5104 aGroup->OpenOnDisk();
5106 // --> get algorithm id
5107 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5112 // get number of datasets
5113 int aNbSubObjects = aGroup->nInternalObjects();
5114 for ( int k = 0; k < aNbSubObjects; k++ ) {
5116 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5117 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5118 // --> get algorithm name
5119 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5120 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5121 aDataset->OpenOnDisk();
5122 size = aDataset->GetSize();
5123 char* hypname_str = new char[ size ];
5124 aDataset->ReadFromDisk( hypname_str );
5125 hypname = string( hypname_str );
5126 delete [] hypname_str;
5127 aDataset->CloseOnDisk();
5129 // --> get algorithm plugin library name
5130 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5131 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5132 aDataset->OpenOnDisk();
5133 size = aDataset->GetSize();
5134 char* libname_str = new char[ size ];
5135 aDataset->ReadFromDisk( libname_str );
5136 if(MYDEBUG) SCRUTE( libname_str );
5137 libname = string( libname_str );
5138 delete [] libname_str;
5139 aDataset->CloseOnDisk();
5141 // --> get algorithm data
5142 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5143 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5144 aDataset->OpenOnDisk();
5145 size = aDataset->GetSize();
5146 char* hypdata_str = new char[ size ];
5147 aDataset->ReadFromDisk( hypdata_str );
5148 if(MYDEBUG) SCRUTE( hypdata_str );
5149 hypdata = string( hypdata_str );
5150 delete [] hypdata_str;
5151 aDataset->CloseOnDisk();
5154 // close algorithm HDF group
5155 aGroup->CloseOnDisk();
5157 // --> restore algorithm from data
5158 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5159 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5160 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5161 SMESH::SMESH_Hypothesis_var myHyp;
5163 try { // protect persistence mechanism against exceptions
5164 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5167 INFOS( "Exception during hypothesis creation" );
5170 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5172 //myImpl->LoadFrom( hypdata.c_str() );
5173 hypDataList.push_back( make_pair( myImpl, hypdata ));
5174 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5175 int newId = myStudyContext->findId( iorString.in() );
5176 myStudyContext->mapOldToNew( id, newId );
5179 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5183 // close algorithms root HDF group
5184 aTopGroup->CloseOnDisk();
5188 // --> the rest groups should be meshes
5189 for ( int i = 0; i < aNbGroups; i++ ) {
5190 // identify next group
5191 char meshName[ HDF_NAME_MAX_LEN+1 ];
5192 aFile->InternalObjectIndentify( i, meshName );
5194 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5196 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5200 // open mesh HDF group
5201 aTopGroup = new HDFgroup( meshName, aFile );
5202 aTopGroup->OpenOnDisk();
5204 // get number of child HDF objects
5205 int aNbObjects = aTopGroup->nInternalObjects();
5206 if ( aNbObjects > 0 ) {
5208 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5209 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5210 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5211 if ( !myNewMeshImpl )
5213 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5215 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5216 int newId = myStudyContext->findId( iorString.in() );
5217 myStudyContext->mapOldToNew( id, newId );
5220 // try to read and set auto color flag
5221 char aMeshAutoColorName[ 30 ];
5222 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5223 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5225 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5226 aDataset->OpenOnDisk();
5227 size = aDataset->GetSize();
5228 int* anAutoColor = new int[ size ];
5229 aDataset->ReadFromDisk( anAutoColor );
5230 aDataset->CloseOnDisk();
5231 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5232 delete [] anAutoColor;
5235 // try to read and set reference to shape
5236 GEOM::GEOM_Object_var aShapeObject;
5237 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5238 // load mesh "Ref on shape" - it's an entry to SObject
5239 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5240 aDataset->OpenOnDisk();
5241 size = aDataset->GetSize();
5242 char* refFromFile = new char[ size ];
5243 aDataset->ReadFromDisk( refFromFile );
5244 aDataset->CloseOnDisk();
5245 if ( strlen( refFromFile ) > 0 ) {
5246 SALOMEDS::SObject_wrap shapeSO = myCurrentStudy->FindObjectID( refFromFile );
5248 // Make sure GEOM data are loaded first
5249 //loadGeomData( shapeSO->GetFatherComponent() );
5251 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5252 if ( !CORBA::is_nil( shapeObject ) ) {
5253 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5254 if ( !aShapeObject->_is_nil() )
5255 myNewMeshImpl->SetShape( aShapeObject );
5258 delete [] refFromFile;
5261 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5262 if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5264 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5265 aDataset->OpenOnDisk();
5266 size = aDataset->GetSize();
5267 int* meshPersistentId = new int[ size ];
5268 aDataset->ReadFromDisk( meshPersistentId );
5269 aDataset->CloseOnDisk();
5270 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5271 delete [] meshPersistentId;
5277 // As all object that can be referred by hypothesis are created,
5278 // we can restore hypothesis data
5280 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5281 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5283 SMESH_Hypothesis_i* hyp = hyp_data->first;
5284 string & data = hyp_data->second;
5285 hyp->LoadFrom( data.c_str() );
5288 // Restore the rest mesh data
5290 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5291 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5293 aTopGroup = meshi_group->second;
5294 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5295 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5296 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
5298 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5299 bool hasData = false;
5302 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5303 int newId = myStudyContext->findId( iorString.in() );
5304 int id = myStudyContext->getOldId( newId );
5306 // try to find mesh data dataset
5307 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5308 // load mesh "has data" flag
5309 aDataset = new HDFdataset( "Has data", aTopGroup );
5310 aDataset->OpenOnDisk();
5311 size = aDataset->GetSize();
5312 char* strHasData = new char[ size ];
5313 aDataset->ReadFromDisk( strHasData );
5314 aDataset->CloseOnDisk();
5315 if ( strcmp( strHasData, "1") == 0 ) {
5316 // read mesh data from MED file
5317 // myReader.SetMesh( mySMESHDSMesh );
5318 // myReader.SetMeshId( id );
5319 // myReader.Perform();
5322 delete [] strHasData;
5325 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5326 // nodes and elements are not yet put into sub-meshes)
5327 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5328 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5329 aGroup->OpenOnDisk();
5330 // get number of applied algorithms
5331 int aNbSubObjects = aGroup->nInternalObjects();
5332 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5333 for ( int j = 0; j < aNbSubObjects; j++ ) {
5334 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5335 aGroup->InternalObjectIndentify( j, name_dataset );
5336 // check if it is an algorithm
5337 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5338 aDataset = new HDFdataset( name_dataset, aGroup );
5339 aDataset->OpenOnDisk();
5340 size = aDataset->GetSize();
5341 char* refFromFile = new char[ size ];
5342 aDataset->ReadFromDisk( refFromFile );
5343 aDataset->CloseOnDisk();
5344 // san - it is impossible to recover applied algorithms using their entries within Load() method
5345 //SALOMEDS::SObject_wrap hypSO = myCurrentStudy->FindObjectID( refFromFile );
5346 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5347 int id = atoi( refFromFile );
5348 delete [] refFromFile;
5349 string anIOR = myStudyContext->getIORbyOldId( id );
5350 if ( !anIOR.empty() ) {
5351 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5352 if ( !CORBA::is_nil( hypObject ) ) {
5353 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5354 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5355 || !myNewMeshImpl->HasShapeToMesh()) )
5356 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5361 aGroup->CloseOnDisk();
5364 // try to get applied hypotheses
5365 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5366 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5367 aGroup->OpenOnDisk();
5368 // get number of applied hypotheses
5369 int aNbSubObjects = aGroup->nInternalObjects();
5370 for ( int j = 0; j < aNbSubObjects; j++ ) {
5371 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5372 aGroup->InternalObjectIndentify( j, name_dataset );
5373 // check if it is a hypothesis
5374 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5375 aDataset = new HDFdataset( name_dataset, aGroup );
5376 aDataset->OpenOnDisk();
5377 size = aDataset->GetSize();
5378 char* refFromFile = new char[ size ];
5379 aDataset->ReadFromDisk( refFromFile );
5380 aDataset->CloseOnDisk();
5381 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5382 //SALOMEDS::SObject_wrap hypSO = myCurrentStudy->FindObjectID( refFromFile );
5383 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5384 int id = atoi( refFromFile );
5385 delete [] refFromFile;
5386 string anIOR = myStudyContext->getIORbyOldId( id );
5387 if ( !anIOR.empty() ) {
5388 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5389 if ( !CORBA::is_nil( hypObject ) ) {
5390 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5391 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5392 || !myNewMeshImpl->HasShapeToMesh()) )
5393 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5398 aGroup->CloseOnDisk();
5401 // --> try to find SUB-MESHES containers for each type of submesh
5402 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5403 const char* name_meshgroup = 0;
5404 if ( j == GetSubMeshOnVertexTag() )
5405 name_meshgroup = "SubMeshes On Vertex";
5406 else if ( j == GetSubMeshOnEdgeTag() )
5407 name_meshgroup = "SubMeshes On Edge";
5408 else if ( j == GetSubMeshOnWireTag() )
5409 name_meshgroup = "SubMeshes On Wire";
5410 else if ( j == GetSubMeshOnFaceTag() )
5411 name_meshgroup = "SubMeshes On Face";
5412 else if ( j == GetSubMeshOnShellTag() )
5413 name_meshgroup = "SubMeshes On Shell";
5414 else if ( j == GetSubMeshOnSolidTag() )
5415 name_meshgroup = "SubMeshes On Solid";
5416 else if ( j == GetSubMeshOnCompoundTag() )
5417 name_meshgroup = "SubMeshes On Compound";
5419 // try to get submeshes container HDF group
5420 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5421 // open submeshes containers HDF group
5422 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5423 aGroup->OpenOnDisk();
5425 // get number of submeshes
5426 int aNbSubMeshes = aGroup->nInternalObjects();
5427 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5429 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5430 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5431 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5432 // --> get submesh id
5433 int subid = atoi( name_submeshgroup + 7 );
5436 // open submesh HDF group
5437 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5438 aSubGroup->OpenOnDisk();
5440 // try to read and set reference to subshape
5441 GEOM::GEOM_Object_var aSubShapeObject;
5442 SMESH::SMESH_subMesh_var aSubMesh;
5444 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5445 // load submesh "Ref on shape" - it's an entry to SObject
5446 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5447 aDataset->OpenOnDisk();
5448 size = aDataset->GetSize();
5449 char* refFromFile = new char[ size ];
5450 aDataset->ReadFromDisk( refFromFile );
5451 aDataset->CloseOnDisk();
5452 if ( strlen( refFromFile ) > 0 ) {
5453 SALOMEDS::SObject_wrap subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
5454 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5455 if ( !CORBA::is_nil( subShapeObject ) ) {
5456 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5457 if ( !aSubShapeObject->_is_nil() )
5458 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5459 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5460 if ( aSubMesh->_is_nil() )
5462 string iorSubString = GetORB()->object_to_string( aSubMesh );
5463 int newSubId = myStudyContext->findId( iorSubString );
5464 myStudyContext->mapOldToNew( subid, newSubId );
5467 delete [] refFromFile;
5470 if ( aSubMesh->_is_nil() )
5473 // try to get applied algorithms
5474 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5475 // open "applied algorithms" HDF group
5476 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5477 aSubSubGroup->OpenOnDisk();
5478 // get number of applied algorithms
5479 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5480 for ( int l = 0; l < aNbSubObjects; l++ ) {
5481 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5482 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5483 // check if it is an algorithm
5484 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5485 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5486 aDataset->OpenOnDisk();
5487 size = aDataset->GetSize();
5488 char* refFromFile = new char[ size ];
5489 aDataset->ReadFromDisk( refFromFile );
5490 aDataset->CloseOnDisk();
5492 int id = atoi( refFromFile );
5493 string anIOR = myStudyContext->getIORbyOldId( id );
5494 if ( !anIOR.empty() ) {
5495 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5496 if ( !CORBA::is_nil( hypObject ) ) {
5497 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5498 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5499 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5502 delete [] refFromFile;
5505 // close "applied algorithms" HDF group
5506 aSubSubGroup->CloseOnDisk();
5509 // try to get applied hypotheses
5510 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5511 // open "applied hypotheses" HDF group
5512 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5513 aSubSubGroup->OpenOnDisk();
5514 // get number of applied hypotheses
5515 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5516 for ( int l = 0; l < aNbSubObjects; l++ ) {
5517 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5518 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5519 // check if it is a hypothesis
5520 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5521 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5522 aDataset->OpenOnDisk();
5523 size = aDataset->GetSize();
5524 char* refFromFile = new char[ size ];
5525 aDataset->ReadFromDisk( refFromFile );
5526 aDataset->CloseOnDisk();
5528 int id = atoi( refFromFile );
5529 string anIOR = myStudyContext->getIORbyOldId( id );
5530 if ( !anIOR.empty() ) {
5531 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5532 if ( !CORBA::is_nil( hypObject ) ) {
5533 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5534 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5535 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5538 delete [] refFromFile;
5541 // close "APPLIED HYPOTHESES" hdf group
5542 aSubSubGroup->CloseOnDisk();
5545 // close SUB-MESH hdf group
5546 aSubGroup->CloseOnDisk();
5549 // close SUB-MESHES containers hdf group
5550 aGroup->CloseOnDisk();
5554 // try to get GROUPS
5555 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5556 char name_group[ 30 ];
5557 if ( ii == GetNodeGroupsTag() )
5558 strcpy( name_group, "Groups of Nodes" );
5559 else if ( ii == GetEdgeGroupsTag() )
5560 strcpy( name_group, "Groups of Edges" );
5561 else if ( ii == GetFaceGroupsTag() )
5562 strcpy( name_group, "Groups of Faces" );
5563 else if ( ii == GetVolumeGroupsTag() )
5564 strcpy( name_group, "Groups of Volumes" );
5565 else if ( ii == Get0DElementsGroupsTag() )
5566 strcpy( name_group, "Groups of 0D Elements" );
5567 else if ( ii == GetBallElementsGroupsTag() )
5568 strcpy( name_group, "Groups of Balls" );
5570 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5571 aGroup = new HDFgroup( name_group, aTopGroup );
5572 aGroup->OpenOnDisk();
5573 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5574 // within aGroup->ExistInternalObject( name )
5575 std::vector< std::string > subNames;
5576 TColStd_MapOfAsciiString mapOfNames;
5577 aGroup->GetAllObjects( subNames );
5578 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5579 mapOfNames.Add( subNames[ iN ].c_str() );
5581 for ( size_t j = 0; j < subNames.size(); j++ ) {
5582 const std::string& name_dataset = subNames[ j ];
5583 // check if it is a group
5584 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5586 int subid = atoi( name_dataset.substr( 5 ).c_str() );
5589 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5590 aDataset->OpenOnDisk();
5592 // Retrieve actual group name
5593 size = aDataset->GetSize();
5594 char* nameFromFile = new char[ size ];
5595 aDataset->ReadFromDisk( nameFromFile );
5596 aDataset->CloseOnDisk();
5598 // Try to find a shape reference
5599 TopoDS_Shape aShape;
5600 char aRefName[ 30 ];
5601 sprintf( aRefName, "Ref on shape %d", subid);
5602 if ( mapOfNames.Contains( aRefName ))
5604 // load mesh "Ref on shape" - it's an entry to SObject
5605 aDataset = new HDFdataset( aRefName, aGroup );
5606 aDataset->OpenOnDisk();
5607 size = aDataset->GetSize();
5608 char* refFromFile = new char[ size ];
5609 aDataset->ReadFromDisk( refFromFile );
5610 aDataset->CloseOnDisk();
5611 if ( strlen( refFromFile ) > 0 ) {
5612 SALOMEDS::SObject_wrap shapeSO = myCurrentStudy->FindObjectID( refFromFile );
5613 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5614 if ( !CORBA::is_nil( shapeObject ) ) {
5615 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5616 if ( !aShapeObject->_is_nil() )
5617 aShape = GeomObjectToShape( aShapeObject );
5620 delete [] refFromFile;
5622 // Try to read a filter of SMESH_GroupOnFilter
5623 SMESH::Filter_var filter;
5624 SMESH_PredicatePtr predicate;
5625 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5626 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5628 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5629 aDataset->OpenOnDisk();
5630 size = aDataset->GetSize();
5631 char* persistStr = new char[ size ];
5632 aDataset->ReadFromDisk( persistStr );
5633 aDataset->CloseOnDisk();
5634 if ( strlen( persistStr ) > 0 ) {
5635 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5636 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5637 filters.push_back( filter );
5639 delete [] persistStr;
5642 // Create group servant
5643 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5644 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5645 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape, predicate ) );
5646 delete [] nameFromFile;
5647 // Obtain a SMESHDS_Group object
5648 if ( aNewGroup->_is_nil() )
5651 string iorSubString = GetORB()->object_to_string( aNewGroup );
5652 int newSubId = myStudyContext->findId( iorSubString );
5653 myStudyContext->mapOldToNew( subid, newSubId );
5655 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5659 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5660 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5662 aFilterGroup->SetFilter( filter );
5663 filter->UnRegister();
5665 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5666 if ( !aGroupBaseDS )
5669 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5672 // Read color of the group
5673 char aGroupColorName[ 30 ];
5674 sprintf( aGroupColorName, "ColorGroup %d", subid);
5675 if ( mapOfNames.Contains( aGroupColorName ))
5677 aDataset = new HDFdataset( aGroupColorName, aGroup );
5678 aDataset->OpenOnDisk();
5679 size = aDataset->GetSize();
5680 double* anRGB = new double[ size ];
5681 aDataset->ReadFromDisk( anRGB );
5682 aDataset->CloseOnDisk();
5683 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5684 aGroupBaseDS->SetColor( aColor );
5689 aGroup->CloseOnDisk();
5693 // instead of reading mesh data, we read only brief information of all
5694 // objects: mesh, groups, sub-meshes (issue 0021208 )
5697 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, id,
5698 meshfile.ToCString(), filename.ToCString(),
5702 // read Sub-Mesh ORDER if any
5703 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
5704 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5705 aDataset->OpenOnDisk();
5706 size = aDataset->GetSize();
5707 int* smIDs = new int[ size ];
5708 aDataset->ReadFromDisk( smIDs );
5709 aDataset->CloseOnDisk();
5710 TListOfListOfInt anOrderIds;
5711 anOrderIds.push_back( TListOfInt() );
5712 for ( int i = 0; i < size; i++ )
5713 if ( smIDs[ i ] < 0 ) // is separator
5714 anOrderIds.push_back( TListOfInt() );
5716 anOrderIds.back().push_back(smIDs[ i ]);
5718 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5723 // update hyps needing full mesh data restored (issue 20918)
5724 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5726 SMESH_Hypothesis_i* hyp = hyp_data->first;
5727 hyp->UpdateAsMeshesRestored();
5730 // notify algos on completed restoration to set sub-mesh event listeners
5731 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5733 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5734 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5736 TopoDS_Shape myLocShape;
5737 if(myLocMesh.HasShapeToMesh())
5738 myLocShape = myLocMesh.GetShapeToMesh();
5740 myLocShape = SMESH_Mesh::PseudoShape();
5742 myLocMesh.GetSubMesh(myLocShape)->
5743 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
5746 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
5747 list< SMESH::Filter_var >::iterator f = filters.begin();
5748 for ( ; f != filters.end(); ++f )
5749 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
5750 fi->FindBaseObjects();
5755 aTopGroup->CloseOnDisk();
5758 aFile->CloseOnDisk();
5761 // Remove temporary files created from the stream
5764 SMESH_File meshFile( meshfile.ToCString() );
5765 if ( !meshFile ) // no meshfile exists
5767 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
5771 Engines::Container_var container = GetContainerRef();
5772 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
5774 container_i->registerTemporaryFile( filename.ToCString() );
5775 container_i->registerTemporaryFile( meshfile.ToCString() );
5776 container_i->registerTemporaryFile( tmpDir.ToCString() );
5780 pd << ""; // prevent optimizing pd out
5782 // creation of tree nodes for all data objects in the study
5783 // to support tree representation customization and drag-n-drop:
5784 SALOMEDS::Study_var study = theComponent->GetStudy();
5785 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = study->GetUseCaseBuilder();
5786 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
5787 useCaseBuilder->SetRootCurrent();
5788 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
5789 SALOMEDS::ChildIterator_wrap it = study->NewChildIterator( theComponent );
5790 for (it->InitEx(true); it->More(); it->Next()) {
5791 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
5798 //=============================================================================
5800 * SMESH_Gen_i::LoadASCII
5802 * Load SMESH module's data in ASCII format
5804 //=============================================================================
5806 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
5807 const SALOMEDS::TMPFile& theStream,
5809 bool isMultiFile ) {
5810 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
5811 return Load( theComponent, theStream, theURL, isMultiFile );
5813 //before call main ::Load method it's need for decipher text format to
5814 //binary ( "|xx" => x' )
5815 int size = theStream.length();
5816 if ( int((size / 3 )*3) != size ) //error size of buffer
5819 int real_size = int(size / 3);
5821 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
5824 unsigned int c = -1;
5825 for ( int i = 0; i < real_size; i++ )
5827 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
5828 sscanf( tmp, "%x", &c );
5829 sprintf( (char*)&(buffer[i]), "%c", (char)c );
5832 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
5834 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
5837 //=============================================================================
5839 * SMESH_Gen_i::Close
5841 * Clears study-connected data when it is closed
5843 //=============================================================================
5845 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
5847 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
5849 // set correct current study
5850 SALOMEDS::Study_var study = theComponent->GetStudy();
5851 if ( study->StudyId() != GetCurrentStudyID())
5852 setCurrentStudy( study, /*IsBeingClosed=*/true );
5854 // Clear study contexts data
5855 int studyId = GetCurrentStudyID();
5856 if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
5857 delete myStudyContextMap[ studyId ];
5858 myStudyContextMap.erase( studyId );
5861 // remove the tmp files meshes are loaded from
5862 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
5864 myCurrentStudy = SALOMEDS::Study::_nil();
5868 //=============================================================================
5870 * SMESH_Gen_i::ComponentDataType
5872 * Get component data type
5874 //=============================================================================
5876 char* SMESH_Gen_i::ComponentDataType()
5878 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
5879 return CORBA::string_dup( "SMESH" );
5883 //=============================================================================
5885 * SMESH_Gen_i::IORToLocalPersistentID
5887 * Transform data from transient form to persistent
5889 //=============================================================================
5891 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
5892 const char* IORString,
5893 CORBA::Boolean /*isMultiFile*/,
5894 CORBA::Boolean /*isASCII*/ )
5896 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
5897 StudyContext* myStudyContext = GetCurrentStudyContext();
5899 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
5900 int anId = myStudyContext->findId( IORString );
5902 if(MYDEBUG) MESSAGE( "VSR " << anId )
5904 sprintf( strId, "%d", anId );
5905 return CORBA::string_dup( strId );
5908 return CORBA::string_dup( "" );
5911 //=============================================================================
5913 * SMESH_Gen_i::LocalPersistentIDToIOR
5915 * Transform data from persistent form to transient
5917 //=============================================================================
5919 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
5920 const char* aLocalPersistentID,
5921 CORBA::Boolean /*isMultiFile*/,
5922 CORBA::Boolean /*isASCII*/ )
5924 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
5925 StudyContext* myStudyContext = GetCurrentStudyContext();
5927 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
5928 int anId = atoi( aLocalPersistentID );
5929 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
5931 return CORBA::string_dup( "" );
5934 //=======================================================================
5935 //function : RegisterObject
5937 //=======================================================================
5939 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
5941 StudyContext* myStudyContext = GetCurrentStudyContext();
5942 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5943 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
5944 return myStudyContext->addObject( string( iorString.in() ) );
5949 //================================================================================
5951 * \brief Return id of registered object
5952 * \param theObject - the Object
5953 * \retval int - Object id
5955 //================================================================================
5957 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
5959 StudyContext* myStudyContext = GetCurrentStudyContext();
5960 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5961 string iorString = GetORB()->object_to_string( theObject );
5962 return myStudyContext->findId( iorString );
5967 //=============================================================================
5969 * SMESH_Gen_i::SetName
5971 * Set a new object name
5973 //=============================================================================
5974 void SMESH_Gen_i::SetName(const char* theIOR,
5975 const char* theName)
5977 if ( theIOR && strcmp( theIOR, "" ) ) {
5978 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
5979 SALOMEDS::SObject_wrap aSO = ObjectToSObject( myCurrentStudy, anObject );
5980 if ( !aSO->_is_nil() ) {
5981 SetName( aSO, theName );
5986 int SMESH_Gen_i::GetCurrentStudyID()
5988 return myCurrentStudy->_is_nil() || myCurrentStudy->_non_existent() ? -1 : myCurrentStudy->StudyId();
5991 // Version information
5992 char* SMESH_Gen_i::getVersion()
5994 #if SMESH_DEVELOPMENT
5995 return CORBA::string_dup(SMESH_VERSION_STR"dev");
5997 return CORBA::string_dup(SMESH_VERSION_STR);
6001 //=================================================================================
6002 // function : Move()
6003 // purpose : Moves objects to the specified position.
6004 // Is used in the drag-n-drop functionality.
6005 //=================================================================================
6006 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6007 SALOMEDS::SObject_ptr where,
6010 if ( CORBA::is_nil( where ) ) return;
6012 SALOMEDS::Study_var study = where->GetStudy();
6013 SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder();
6014 SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder();
6015 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6016 std::string dataType = father->ComponentDataType();
6017 if ( dataType != "SMESH" ) return; // not a SMESH component
6019 SALOMEDS::SObject_var objAfter;
6020 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6021 // insert at given row -> find insertion position
6022 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6024 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6025 if ( i == row && useCaseIt->More() ) {
6026 objAfter = useCaseIt->Value();
6030 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6031 SALOMEDS::SObject_var sobj = what[i];
6032 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6033 // insert the object to the use case tree
6034 if ( !CORBA::is_nil( objAfter ) )
6035 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6037 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6040 //================================================================================
6042 * \brief Returns true if algorithm can be used to mesh a given geometry
6043 * \param [in] theAlgoType - the algorithm type
6044 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6045 * \param [in] theGeomObject - the geometry to mesh
6046 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6047 * else, returns \c True if at least one shape is meshable
6048 * \return CORBA::Boolean - can or can't
6050 //================================================================================
6052 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6053 const char* theLibName,
6054 GEOM::GEOM_Object_ptr theGeomObject,
6055 CORBA::Boolean toCheckAll)
6059 std::string aPlatformLibName;
6060 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
6061 GenericHypothesisCreator_i* aCreator =
6062 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6065 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6066 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll );
6073 SMESH_CATCH( SMESH::doNothing );
6076 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6081 //=================================================================================
6082 // function : GetInsideSphere
6083 // purpose : Collect indices of elements, which are located inside the sphere
6084 //=================================================================================
6085 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6086 SMESH::ElementType theElemType,
6092 SMESH::long_array_var aResult = new SMESH::long_array();
6093 if ( meshPart->_is_nil() )
6094 return aResult._retn();
6096 // 1. Create geometrical object
6097 gp_Pnt aP( theX, theY, theZ );
6098 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6100 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6102 if ( lst.size() > 0 ) {
6103 aResult->length( lst.size() );
6104 for ( size_t i = 0; i < lst.size(); i++ ) {
6105 aResult[i] = lst[i];
6108 return aResult._retn();
6111 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6112 SMESH::ElementType theElemType,
6113 CORBA::Double theX1,
6114 CORBA::Double theY1,
6115 CORBA::Double theZ1,
6116 CORBA::Double theX2,
6117 CORBA::Double theY2,
6118 CORBA::Double theZ2) {
6119 SMESH::long_array_var aResult = new SMESH::long_array();
6120 if( meshPart->_is_nil() )
6121 return aResult._retn();
6123 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6125 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6127 if( lst.size() > 0 ) {
6128 aResult->length( lst.size() );
6129 for ( size_t i = 0; i < lst.size(); i++ ) {
6130 aResult[i] = lst[i];
6133 return aResult._retn();
6136 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6137 SMESH::ElementType theElemType,
6141 CORBA::Double theDX,
6142 CORBA::Double theDY,
6143 CORBA::Double theDZ,
6145 CORBA::Double theR ){
6146 SMESH::long_array_var aResult = new SMESH::long_array();
6147 if( meshPart->_is_nil() )
6148 return aResult._retn();
6150 gp_Pnt aP( theX, theY, theZ );
6151 gp_Vec aV( theDX, theDY, theDZ );
6152 gp_Ax2 anAxes (aP, aV);
6154 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6156 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6158 if( lst.size() > 0 ) {
6159 aResult->length( lst.size() );
6160 for ( size_t i = 0; i < lst.size(); i++ ) {
6161 aResult[i] = lst[i];
6164 return aResult._retn();
6167 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6168 SMESH::ElementType theElemType,
6169 GEOM::GEOM_Object_ptr theGeom,
6170 CORBA::Double theTolerance ) {
6171 SMESH::long_array_var aResult = new SMESH::long_array();
6172 if( meshPart->_is_nil() || theGeom->_is_nil() )
6173 return aResult._retn();
6175 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6177 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6179 if( lst.size() > 0 ) {
6180 aResult->length( lst.size() );
6181 for ( size_t i = 0; i < lst.size(); i++ ) {
6182 aResult[i] = lst[i];
6185 return aResult._retn();
6190 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6191 SMESH::ElementType theElemType,
6192 TopoDS_Shape& aShape,
6193 double* theTolerance) {
6195 std::vector<long> res;
6196 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6198 if ( mesh->_is_nil() )
6201 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6205 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6210 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6211 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6212 anElementsOnShape->SetAllNodes( true );
6213 anElementsOnShape->SetMesh( meshDS );
6214 anElementsOnShape->SetShape( aShape, aType );
6217 anElementsOnShape->SetTolerance(*theTolerance);
6219 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6220 if ( !msource->_is_nil() ) { // Mesh case
6221 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6223 while ( elemIt->more() ) {
6224 const SMDS_MeshElement* anElem = elemIt->next();
6225 long anId = anElem->GetID();
6226 if ( anElementsOnShape->IsSatisfy( anId ) )
6227 res.push_back( anId );
6231 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6232 if ( !gsource->_is_nil() ) {
6233 if(theElemType == SMESH::NODE) {
6234 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6235 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6236 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6237 long anId = node->GetID();
6238 if ( anElementsOnShape->IsSatisfy( anId ) )
6239 res.push_back( anId );
6242 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6243 SMESH::long_array_var elems = gsource->GetListOfID();
6244 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6245 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6246 long anId = elem->GetID();
6247 if ( anElementsOnShape->IsSatisfy( anId ) )
6248 res.push_back( anId );
6253 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6254 if ( !smsource->_is_nil() ) {
6255 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6256 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6257 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6259 long anId = elem->GetID();
6260 if ( anElementsOnShape->IsSatisfy( anId ) )
6261 res.push_back( anId );
6269 //=============================================================================
6271 * SMESHEngine_factory
6273 * C factory, accessible with dlsym, after dlopen
6275 //=============================================================================
6279 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6280 PortableServer::POA_ptr poa,
6281 PortableServer::ObjectId* contId,
6282 const char* instanceName,
6283 const char* interfaceName )
6285 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6286 if(MYDEBUG) SCRUTE(interfaceName);
6287 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6288 return aSMESHGen->getId() ;