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"
106 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
108 #include CORBA_SERVER_HEADER(SMESH_Group)
109 #include CORBA_SERVER_HEADER(SMESH_Filter)
110 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
113 #include <GEOM_Client.hxx>
115 #include <Basics_Utils.hxx>
116 #include <Basics_DirUtils.hxx>
118 #include <OpUtil.hxx>
119 #include <SALOMEDS_Tool.hxx>
120 #include <SALOME_Container_i.hxx>
121 #include <SALOME_LifeCycleCORBA.hxx>
122 #include <SALOME_NamingService.hxx>
123 #include <Utils_CorbaException.hxx>
124 #include <Utils_ExceptHandlers.hxx>
125 #include <Utils_SINGLETON.hxx>
126 #include <utilities.h>
128 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
129 #include CORBA_CLIENT_HEADER(SALOME_Session)
131 // helpers about SALOME::GenericObj
132 #include <SALOMEDS_wrap.hxx>
133 #include <SALOMEDS_Attributes_wrap.hxx>
134 #include <GEOM_wrap.hxx>
143 using SMESH::TPythonDump;
146 #define NUM_TMP_FILES 2
149 static int MYDEBUG = 0;
151 static int MYDEBUG = 0;
154 // Static variables definition
155 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
156 CORBA::ORB_var SMESH_Gen_i::myOrb;
157 PortableServer::POA_var SMESH_Gen_i::myPoa;
158 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
159 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
160 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
163 const int nbElemPerDiagonal = 10;
165 //=============================================================================
167 * GetServant [ static ]
169 * Get servant of the CORBA object
171 //=============================================================================
173 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
175 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
178 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
181 catch (PortableServer::POA::ObjectNotActive &ex)
183 INFOS("GetServant: ObjectNotActive");
186 catch (PortableServer::POA::WrongAdapter &ex)
188 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
191 catch (PortableServer::POA::WrongPolicy &ex)
193 INFOS("GetServant: WrongPolicy");
198 INFOS( "GetServant - Unknown exception was caught!!!" );
203 //=============================================================================
205 * SObjectToObject [ static ]
207 * Get CORBA object corresponding to the SALOMEDS::SObject
209 //=============================================================================
211 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
213 SALOMEDS::GenericAttribute_wrap anAttr;
214 CORBA::Object_var anObj;
215 if ( !theSObject->_is_nil() ) {
217 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
218 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
219 CORBA::String_var aValue = anIOR->Value();
220 if( strcmp( aValue, "" ) != 0 )
221 anObj = GetORB()->string_to_object( aValue );
225 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
231 //=============================================================================
235 * Get SALOME_NamingService object
237 //=============================================================================
239 SALOME_NamingService* SMESH_Gen_i::GetNS()
241 if ( myNS == NULL ) {
242 myNS = SINGLETON_<SALOME_NamingService>::Instance();
243 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
244 myNS->init_orb( GetORB() );
249 //=============================================================================
253 * Get SALOME_LifeCycleCORBA object
255 //=============================================================================
256 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC() {
257 if ( myLCC == NULL ) {
258 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
264 //=============================================================================
266 * GetGeomEngine [ static ]
268 * Get GEOM::GEOM_Gen reference
270 //=============================================================================
271 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine() {
272 //CCRT GEOM::GEOM_Gen_var aGeomEngine =
273 //CCRT GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
274 //CCRT return aGeomEngine._retn();
275 if(CORBA::is_nil(myGeomGen))
277 Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
278 myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
283 //=============================================================================
285 * SMESH_Gen_i::SMESH_Gen_i
287 * Default constructor: not for use
289 //=============================================================================
291 SMESH_Gen_i::SMESH_Gen_i()
295 //=============================================================================
297 * SMESH_Gen_i::SMESH_Gen_i
299 * Standard constructor, used with Container
301 //=============================================================================
303 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
304 PortableServer::POA_ptr poa,
305 PortableServer::ObjectId* contId,
306 const char* instanceName,
307 const char* interfaceName )
308 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
311 myOrb = CORBA::ORB::_duplicate(orb);
312 myPoa = PortableServer::POA::_duplicate(poa);
315 _id = myPoa->activate_object( _thisObj );
317 myStudyContext = new StudyContext;
319 myIsEmbeddedMode = false;
320 myIsEnablePublish = true;
321 myShapeReader = NULL; // shape reader
323 myIsHistoricalPythonDump = true;
324 myToForgetMeshDataOnHypModif = false;
326 // set it in standalone mode only
327 //OSD::SetSignal( true );
329 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
330 // find out mode (embedded or standalone) here else
331 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
332 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
333 if ( SALOME_NamingService* ns = GetNS() )
335 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
336 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
337 if ( !session->_is_nil() )
339 CORBA::String_var str_host = session->getHostname();
340 CORBA::Long s_pid = session->getPID();
341 string my_host = Kernel_Utils::GetHostname();
343 long my_pid = (long)_getpid();
345 long my_pid = (long) getpid();
347 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
352 //=============================================================================
354 * SMESH_Gen_i::~SMESH_Gen_i
358 //=============================================================================
360 SMESH_Gen_i::~SMESH_Gen_i()
362 // delete hypothesis creators
363 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
364 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
366 // same creator can be mapped under different names
367 GenericHypothesisCreator_i* creator = (*itHyp).second;
371 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
372 if ( creator == (*itHyp2).second )
373 (*itHyp2).second = 0;
375 myHypCreatorMap.clear();
377 // Clear study contexts data
378 delete myStudyContext;
380 // delete shape reader
382 delete myShapeReader;
384 //=============================================================================
386 * SMESH_Gen_i::getHypothesisCreator
388 * Get hypothesis creator
390 //=============================================================================
391 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
392 const char* theLibName,
393 std::string& thePlatformLibName)
394 throw (SALOME::SALOME_Exception)
396 std::string aPlatformLibName;
397 /* It's Need to translate lib name for WIN32 or X platform */
398 if ( theLibName && theLibName[0] != '\0' )
400 int libNameLen = strlen(theLibName);
401 //check for old format "libXXXXXXX.so"
402 if (libNameLen > 7 &&
403 !strncmp( theLibName, "lib", 3 ) &&
404 !strcmp( theLibName+libNameLen-3, ".so" ))
408 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
409 #elif defined(__APPLE__)
410 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
412 aPlatformLibName = theLibName;
417 //try to use new format
419 aPlatformLibName = theLibName;
420 aPlatformLibName += ".dll";
421 #elif defined(__APPLE__)
422 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
424 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
428 thePlatformLibName = aPlatformLibName;
430 Unexpect aCatch(SALOME_SalomeException);
431 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
433 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
434 GenericHypothesisCreator_i* aCreator;
437 // check, if creator for this hypothesis type already exists
438 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
440 // load plugin library
441 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
444 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
446 const char* path = aPlatformLibName.c_str()
449 const char* path = aPlatformLibName.c_str()
451 LibHandle libHandle = LoadLib( path );
452 #if defined(WIN32) && defined(UNICODE)
457 // report any error, if occurred
459 const char* anError = dlerror();
460 throw(SALOME_Exception(anError));
462 throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
466 // get method, returning hypothesis creator
467 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
468 GetHypothesisCreator procHandle =
469 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
472 throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
473 UnLoadLib(libHandle);
476 // get hypothesis creator
477 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
478 aCreator = procHandle(theHypName);
481 throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
483 // map hypothesis creator to a hypothesis name
484 myHypCreatorMap[string(theHypName)] = aCreator;
489 return myHypCreatorMap[string(theHypName)];
492 catch (SALOME_Exception& S_ex)
494 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
499 //=============================================================================
501 * SMESH_Gen_i::createHypothesis
503 * Create hypothesis of given type
505 //=============================================================================
506 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
507 const char* theLibName)
509 SMESH_Hypothesis_i* myHypothesis_i = 0;
510 SMESH::SMESH_Hypothesis_var hypothesis_i;
511 std::string aPlatformLibName;
512 GenericHypothesisCreator_i* aCreator =
513 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
515 // create a new hypothesis object, store its ref. in studyContext
516 myHypothesis_i = aCreator->Create(myPoa, &myGen);
519 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
520 CORBA::String_var hypName = myHypothesis_i->GetName();
521 myHypCreatorMap[ hypName.in() ] = aCreator;
523 // activate the CORBA servant of hypothesis
524 hypothesis_i = myHypothesis_i->_this();
525 int nextId = RegisterObject( hypothesis_i );
526 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
527 else { nextId = 0; } // avoid "unused variable" warning in release mode
529 return hypothesis_i._retn();
532 //=============================================================================
534 * SMESH_Gen_i::createMesh
536 * Create empty mesh on shape
538 //=============================================================================
539 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
540 throw ( SALOME::SALOME_Exception )
542 Unexpect aCatch(SALOME_SalomeException);
543 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
545 // Get or create the GEOM_Client instance
547 // create a new mesh object servant, store it in a map in study context
548 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
549 // create a new mesh object
550 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
551 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
553 // activate the CORBA servant of Mesh
554 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
555 int nextId = RegisterObject( mesh );
556 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
557 else { nextId = 0; } // avoid "unused variable" warning in release mode
560 catch (SALOME_Exception& S_ex) {
561 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
563 return SMESH::SMESH_Mesh::_nil();
566 //=============================================================================
568 * SMESH_Gen_i::GetShapeReader
572 //=============================================================================
573 GEOM_Client* SMESH_Gen_i::GetShapeReader()
575 // create shape reader if necessary
576 if ( !myShapeReader )
577 myShapeReader = new GEOM_Client(GetContainerRef());
578 ASSERT( myShapeReader );
579 return myShapeReader;
582 //=============================================================================
584 * SMESH_Gen_i::SetGeomEngine
586 * Set GEOM::GEOM_Gen reference
588 //=============================================================================
589 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
590 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
592 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
593 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
594 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
598 //=============================================================================
600 * SMESH_Gen_i::SetEmbeddedMode
604 //=============================================================================
606 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
608 myIsEmbeddedMode = theMode;
610 if ( !myIsEmbeddedMode ) {
611 //PAL10867: disable signals catching with "noexcepthandler" option
612 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
613 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
618 char* envDisableFPE = getenv("DISABLE_FPE");
619 if (envDisableFPE && atoi(envDisableFPE))
624 OSD::SetSignal( raiseFPE );
626 // else OSD::SetSignal() is called in GUI
630 //=============================================================================
632 * SMESH_Gen_i::IsEmbeddedMode
636 //=============================================================================
638 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
640 return myIsEmbeddedMode;
643 //=============================================================================
645 * SMESH_Gen_i::SetEnablePublish
647 * Set enable publishing in the study
649 //=============================================================================
650 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
652 myIsEnablePublish = theIsEnablePublish;
655 //=============================================================================
657 * SMESH_Gen_i::IsEnablePublish
659 * Check enable publishing
661 //=============================================================================
663 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
665 return myIsEnablePublish;
668 //=============================================================================
670 * SMESH_Gen_i::UpdateStudy
672 * Update study (needed at switching GEOM->SMESH)
674 //=============================================================================
676 void SMESH_Gen_i::UpdateStudy()
678 if ( !myStudyContext )
679 myStudyContext = new StudyContext;
681 SALOMEDS::Study_var aStudy = getStudyServant();
682 if ( !CORBA::is_nil( aStudy ) ) {
683 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
684 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
685 if( !GEOM_var->_is_nil() )
686 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
687 // NPAL16168, issue 0020210
688 // Let meshes update their data depending on GEOM groups that could change
689 CORBA::String_var compDataType = ComponentDataType();
690 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
691 if ( !me->_is_nil() ) {
692 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
693 for ( ; anIter->More(); anIter->Next() ) {
694 SALOMEDS::SObject_wrap so = anIter->Value();
695 CORBA::Object_var ior = SObjectToObject( so );
696 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
697 mesh->CheckGeomModif();
703 //=============================================================================
705 * SMESH_Gen_i::GetStudyContext
709 //=============================================================================
710 StudyContext* SMESH_Gen_i::GetStudyContext()
712 return myStudyContext;
715 //=============================================================================
717 * SMESH_Gen_i::CreateHypothesis
719 * Create hypothesis/algorothm of given type and publish it in the study
721 //=============================================================================
723 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
724 const char* theLibName )
725 throw ( SALOME::SALOME_Exception )
727 Unexpect aCatch(SALOME_SalomeException);
728 // Create hypothesis/algorithm
729 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
731 // Publish hypothesis/algorithm in the study
732 if ( CanPublishInStudy( hyp ) ) {
733 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
734 if ( !aSO->_is_nil() ) {
735 // Update Python script
736 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
737 << theHypName << "', '" << theLibName << "')";
744 //================================================================================
746 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
747 * existing on the given geometry or to size of the geometry.
748 * \param theHypType - hypothesis type name
749 * \param theLibName - plugin library name
750 * \param theMesh - The mesh of interest
751 * \param theGeom - The shape to get parameter values from
752 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
753 * in a study and used to compute the mesh, or a temporary one created just to pass
756 //================================================================================
758 SMESH::SMESH_Hypothesis_ptr
759 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
760 const char* theLibName,
761 SMESH::SMESH_Mesh_ptr theMesh,
762 GEOM::GEOM_Object_ptr theGeom,
763 CORBA::Boolean byMesh)
764 throw ( SALOME::SALOME_Exception )
766 Unexpect aCatch(SALOME_SalomeException);
767 if ( byMesh && CORBA::is_nil( theMesh ) )
768 return SMESH::SMESH_Hypothesis::_nil();
769 if ( byMesh && CORBA::is_nil( theGeom ) )
770 return SMESH::SMESH_Hypothesis::_nil();
772 // -----------------------------------------------
773 // find hypothesis used to mesh theGeom
774 // -----------------------------------------------
776 // get mesh and shape
777 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
778 TopoDS_Shape shape = GeomObjectToShape( theGeom );
779 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
780 return SMESH::SMESH_Hypothesis::_nil();
781 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
783 // create a temporary hypothesis to know its dimension
784 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
785 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
787 return SMESH::SMESH_Hypothesis::_nil();
788 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
791 // look for a hypothesis of theHypType used to mesh the shape
792 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
795 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
796 int nbLocalHyps = aHypList->length();
797 for ( int i = 0; i < nbLocalHyps; i++ ) {
798 CORBA::String_var hypName = aHypList[i]->GetName();
799 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
800 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
802 // check super shapes
803 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
804 while ( nbLocalHyps == 0 && itShape.More() ) {
805 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
806 if ( ! CORBA::is_nil( geomObj )) {
807 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
808 nbLocalHyps = aHypList->length();
809 for ( int i = 0; i < nbLocalHyps; i++ )
810 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
811 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
817 // let the temporary hypothesis find out somehow parameter values by mesh
818 if ( hyp->SetParametersByMesh( mesh, shape ))
819 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
824 diagonal = mesh->GetShapeDiagonalSize();
826 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
827 ::SMESH_Hypothesis::TDefaults dflts;
828 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
829 dflts._nbSegments = myGen.GetDefaultNbSegments();
830 dflts._shape = &shape;
831 // let the temporary hypothesis initialize it's values
832 if ( hyp->SetParametersByDefaults( dflts, mesh ))
833 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
836 return SMESH::SMESH_Hypothesis::_nil();
839 //=============================================================================
841 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
842 * \param [in] theHyp - the hypothesis of interest
843 * \param [out] theMesh - the sole mesh using \a theHyp
844 * \param [out] theShape - the sole geometry \a theHyp is assigned to
845 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
847 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
848 * considered as SAME sub-mesh => result is \c true.
849 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
850 * a shape to which an hyp being edited is assigned.
852 //=============================================================================
854 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
855 SMESH::SMESH_Mesh_out theMesh,
856 GEOM::GEOM_Object_out theShape)
858 if ( CORBA::is_nil( theHyp ))
861 // get Mesh component SO
862 CORBA::String_var compDataType = ComponentDataType();
863 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
864 if ( CORBA::is_nil( comp ))
867 // look for child SO of meshes
868 SMESH::SMESH_Mesh_var foundMesh;
869 TopoDS_Shape foundShape;
871 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
872 for ( ; meshIter->More() && isSole; meshIter->Next() )
874 SALOMEDS::SObject_wrap curSO = meshIter->Value();
875 CORBA::Object_var obj = SObjectToObject( curSO );
876 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
880 // look for a sole shape where theHyp is assigned
881 bool isHypFound = false;
882 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
883 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
884 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
886 const THypList& hyps = s2hypsIt.Value();
887 THypList::const_iterator h = hyps.begin();
888 for ( ; h != hyps.end(); ++h )
889 if ( (*h)->GetID() == theHyp->GetId() )
891 if ( h != hyps.end()) // theHyp found
894 if ( ! foundShape.IsNull() &&
895 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
897 foundShape.Nullify();
901 foundShape = s2hypsIt.Key();
903 } // loop on assigned hyps
905 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
907 if ( !foundMesh->_is_nil() ) // not a sole mesh
909 if ( !foundMesh->HasShapeToMesh() ||
910 !mesh_i ->HasShapeToMesh() )
912 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
916 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
917 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
918 isSole = s1->IsSame( s2 );
921 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
927 ! foundMesh->_is_nil() &&
928 ! foundShape.IsNull() )
930 theMesh = foundMesh._retn();
931 theShape = ShapeToGeomObject( foundShape );
932 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
937 //=============================================================================
939 * Sets number of segments per diagonal of boundary box of geometry by which
940 * default segment length of appropriate 1D hypotheses is defined
942 //=============================================================================
944 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
945 throw ( SALOME::SALOME_Exception )
947 if ( theNbSegments > 0 )
948 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
950 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
952 //=============================================================================
954 * \brief Sets default number of segments per edge
956 //=============================================================================
957 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
958 throw ( SALOME::SALOME_Exception )
960 if ( theNbSegments > 0 )
961 myGen.SetDefaultNbSegments( int(theNbSegments) );
963 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
966 //=============================================================================
970 //=============================================================================
972 void SMESH_Gen_i::SetOption(const char* name, const char* value)
974 if ( name && value && strlen( value ) > 0 )
977 if ( strcmp(name, "historical_python_dump") == 0 )
979 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
980 msgToGUI = "preferences/SMESH/historical_python_dump/";
981 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
983 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
985 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
986 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
987 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
989 else if ( strcmp(name, "default_grp_color") == 0 )
993 // color must be presented as a string of following form:
994 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
996 for ( size_t i = 0; i < str.length()/2; i++ )
997 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
998 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1000 else if ( value ) { // rgb color ("255,170,0", for example)
1001 string tempValue( value );
1002 char* colorValue = strtok( &tempValue[0], "," );
1003 while ( colorValue != NULL ) {
1004 int c_value = atoi( colorValue );
1005 if ( c_value >= 0 && c_value <= 255 )
1006 color.push_back( c_value );
1007 colorValue = strtok( NULL, "," );
1010 if ( color.size() == 3 ) { // color must have three valid component
1011 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1012 myDefaultGroupColor = value;
1013 msgToGUI = "preferences/SMESH/default_grp_color/";
1018 // update preferences in case if SetOption() is invoked from python console
1019 if ( !msgToGUI.empty() )
1021 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1022 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1023 if ( !CORBA::is_nil( session ) )
1024 session->emitMessageOneWay(msgToGUI.c_str());
1029 //=============================================================================
1031 Return an option value
1033 //=============================================================================
1035 char* SMESH_Gen_i::GetOption(const char* name)
1039 if ( strcmp(name, "historical_python_dump") == 0 )
1041 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1043 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1045 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1047 if ( strcmp(name, "default_grp_color") == 0 )
1049 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1052 return CORBA::string_dup( "" );
1055 //=============================================================================
1057 * SMESH_Gen_i::CreateMesh
1059 * Create empty mesh on a shape and publish it in the study
1061 //=============================================================================
1063 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1064 throw ( SALOME::SALOME_Exception )
1066 Unexpect aCatch(SALOME_SalomeException);
1067 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1069 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1071 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1072 ASSERT( meshServant );
1073 meshServant->SetShape( theShapeObject );
1075 // publish mesh in the study
1076 if ( CanPublishInStudy( mesh ) ) {
1077 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1078 aStudyBuilder->NewCommand(); // There is a transaction
1079 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1080 aStudyBuilder->CommitCommand();
1081 if ( !aSO->_is_nil() ) {
1082 // Update Python script
1083 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1087 return mesh._retn();
1090 //=============================================================================
1092 * SMESH_Gen_i::CreateEmptyMesh
1096 //=============================================================================
1098 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1099 throw ( SALOME::SALOME_Exception )
1101 Unexpect aCatch(SALOME_SalomeException);
1102 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1104 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1106 // publish mesh in the study
1107 if ( CanPublishInStudy( mesh ) ) {
1108 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1109 aStudyBuilder->NewCommand(); // There is a transaction
1110 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1111 aStudyBuilder->CommitCommand();
1112 if ( !aSO->_is_nil() ) {
1113 // Update Python script
1114 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1118 return mesh._retn();
1123 //================================================================================
1125 * \brief Throws an exception in case if the file can't be read
1127 //================================================================================
1129 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1131 SMESH_File f ( theFileName );
1134 if ( !f.error().empty() )
1135 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1137 THROW_SALOME_CORBA_EXCEPTION
1138 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1139 SALOME::BAD_PARAM );
1144 //=============================================================================
1146 * SMESH_Gen_i::CreateMeshFromUNV
1148 * Create mesh and import data from UNV file
1150 //=============================================================================
1152 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1153 throw ( SALOME::SALOME_Exception )
1155 Unexpect aCatch(SALOME_SalomeException);
1157 checkFileReadable( theFileName );
1159 SMESH::SMESH_Mesh_var aMesh = createMesh();
1161 // publish mesh in the study
1162 if ( CanPublishInStudy( aMesh ) ) {
1163 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1164 aStudyBuilder->NewCommand(); // There is a transaction
1165 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1166 aStudyBuilder->CommitCommand();
1167 if ( !aSO->_is_nil() ) {
1168 // Update Python script
1169 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1173 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1175 aServant->ImportUNVFile( theFileName );
1177 // Dump creation of groups
1178 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1180 aServant->GetImpl().GetMeshDS()->Modified();
1181 return aMesh._retn();
1184 //=============================================================================
1186 * SMESH_Gen_i::CreateMeshFromMED
1188 * Create mesh and import data from MED file
1190 //=============================================================================
1192 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1193 SMESH::DriverMED_ReadStatus& theStatus,
1194 const char* theCommandNameForPython,
1195 const char* theFileNameForPython)
1198 char bname[ _MAX_FNAME ];
1199 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1200 string aFileName = bname;
1202 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1204 // Retrieve mesh names from the file
1205 DriverMED_R_SMESHDS_Mesh myReader;
1206 myReader.SetFile( theFileName );
1207 myReader.SetMeshId( -1 );
1208 Driver_Mesh::Status aStatus;
1209 list<string> aNames = myReader.GetMeshNames(aStatus);
1210 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1211 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1213 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1216 TPythonDump aPythonDump;
1217 aPythonDump << "([";
1219 if (theStatus == SMESH::DRS_OK) {
1220 SALOMEDS::StudyBuilder_var aStudyBuilder;
1221 aStudyBuilder = getStudyServant()->NewBuilder();
1222 aStudyBuilder->NewCommand(); // There is a transaction
1224 aResult->length( aNames.size() );
1227 // Iterate through all meshes and create mesh objects
1228 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1231 if (i > 0) aPythonDump << ", ";
1234 SMESH::SMESH_Mesh_var mesh = createMesh();
1236 // publish mesh in the study
1237 SALOMEDS::SObject_wrap aSO;
1238 if ( CanPublishInStudy( mesh ) )
1239 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1240 // - as names of meshes are stored in MED file, we use them for data publishing
1241 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1242 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1245 if ( !aSO->_is_nil() ) {
1248 aPythonDump << "mesh_" << i;
1251 // Read mesh data (groups are published automatically by ImportMEDFile())
1252 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1253 ASSERT( meshServant );
1254 SMESH::DriverMED_ReadStatus status1 =
1255 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1256 if (status1 > theStatus)
1257 theStatus = status1;
1259 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1260 meshServant->GetImpl().GetMeshDS()->Modified();
1262 if ( !aStudyBuilder->_is_nil() )
1263 aStudyBuilder->CommitCommand();
1266 // Update Python script
1267 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1269 // Dump creation of groups
1270 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1271 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1273 return aResult._retn();
1276 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1277 SMESH::DriverMED_ReadStatus& theStatus)
1278 throw ( SALOME::SALOME_Exception )
1280 Unexpect aCatch(SALOME_SalomeException);
1281 checkFileReadable( theFileName );
1283 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1287 //=============================================================================
1289 * SMESH_Gen_i::CreateMeshFromSAUV
1291 * Create mesh and import data from SAUV file
1293 //=============================================================================
1295 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1296 SMESH::DriverMED_ReadStatus& theStatus)
1297 throw ( SALOME::SALOME_Exception )
1299 Unexpect aCatch(SALOME_SalomeException);
1300 checkFileReadable( theFileName );
1302 std::string sauvfilename(theFileName);
1303 std::string medfilename(theFileName);
1304 medfilename += ".med";
1307 cmd = "%PYTHONBIN% ";
1312 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1314 system(cmd.c_str());
1315 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1317 cmd = "%PYTHONBIN% ";
1322 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1324 system(cmd.c_str());
1328 //=============================================================================
1330 * SMESH_Gen_i::CreateMeshFromSTL
1332 * Create mesh and import data from STL file
1334 //=============================================================================
1336 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1337 throw ( SALOME::SALOME_Exception )
1339 Unexpect aCatch(SALOME_SalomeException);
1340 checkFileReadable( theFileName );
1342 SMESH::SMESH_Mesh_var aMesh = createMesh();
1345 char bname[ _MAX_FNAME ];
1346 _splitpath( theFileName, NULL, NULL, bname, NULL );
1347 string aFileName = bname;
1349 string aFileName = basename( const_cast<char *>(theFileName) );
1351 // publish mesh in the study
1352 if ( CanPublishInStudy( aMesh ) ) {
1353 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1354 aStudyBuilder->NewCommand(); // There is a transaction
1355 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1356 aStudyBuilder->CommitCommand();
1357 if ( !aSO->_is_nil() ) {
1358 // Update Python script
1359 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1363 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1365 aServant->ImportSTLFile( theFileName );
1366 aServant->GetImpl().GetMeshDS()->Modified();
1367 return aMesh._retn();
1370 //================================================================================
1372 * \brief Create meshes and import data from the CGSN file
1374 //================================================================================
1376 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1377 SMESH::DriverMED_ReadStatus& theStatus)
1378 throw ( SALOME::SALOME_Exception )
1380 Unexpect aCatch(SALOME_SalomeException);
1381 checkFileReadable( theFileName );
1383 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1386 // Retrieve nb meshes from the file
1387 DriverCGNS_Read myReader;
1388 myReader.SetFile( theFileName );
1389 Driver_Mesh::Status aStatus;
1390 int nbMeshes = myReader.GetNbMeshes(aStatus);
1391 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1393 aResult->length( nbMeshes );
1395 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1398 TPythonDump aPythonDump;
1399 aPythonDump << "([";
1401 if (theStatus == SMESH::DRS_OK)
1403 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1404 aStudyBuilder->NewCommand(); // There is a transaction
1408 // Iterate through all meshes and create mesh objects
1409 for ( ; i < nbMeshes; ++i )
1412 if (i > 0) aPythonDump << ", ";
1415 SMESH::SMESH_Mesh_var mesh = createMesh();
1416 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1418 // Read mesh data (groups are published automatically by ImportMEDFile())
1419 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1420 ASSERT( meshServant );
1422 SMESH::DriverMED_ReadStatus status1 =
1423 meshServant->ImportCGNSFile( theFileName, i, meshName );
1424 if (status1 > theStatus)
1425 theStatus = status1;
1427 meshServant->GetImpl().GetMeshDS()->Modified();
1428 // publish mesh in the study
1429 SALOMEDS::SObject_wrap aSO;
1430 if ( CanPublishInStudy( mesh ) )
1431 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1434 if ( !aSO->_is_nil() ) {
1438 aPythonDump << "mesh_" << i;
1441 aStudyBuilder->CommitCommand();
1444 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1446 // Dump creation of groups
1447 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1448 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1450 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1453 return aResult._retn();
1456 //================================================================================
1458 * \brief Create a mesh and import data from a GMF file
1460 //================================================================================
1462 SMESH::SMESH_Mesh_ptr
1463 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1464 CORBA::Boolean theMakeRequiredGroups,
1465 SMESH::ComputeError_out theError)
1466 throw ( SALOME::SALOME_Exception )
1468 Unexpect aCatch(SALOME_SalomeException);
1469 checkFileReadable( theFileName );
1471 SMESH::SMESH_Mesh_var aMesh = createMesh();
1473 char bname[ _MAX_FNAME ];
1474 _splitpath( theFileName, NULL, NULL, bname, NULL );
1475 string aFileName = bname;
1477 string aFileName = basename( const_cast<char *>(theFileName) );
1479 // publish mesh in the study
1480 if ( CanPublishInStudy( aMesh ) ) {
1481 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1482 aStudyBuilder->NewCommand(); // There is a transaction
1483 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1484 aStudyBuilder->CommitCommand();
1485 if ( !aSO->_is_nil() ) {
1486 // Update Python script
1487 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1488 << theFileName << "', "
1489 << theMakeRequiredGroups << " )";
1492 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1494 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1495 aServant->GetImpl().GetMeshDS()->Modified();
1496 return aMesh._retn();
1500 //=============================================================================
1502 * SMESH_Gen_i::IsReadyToCompute
1504 * Returns true if mesh contains enough data to be computed
1506 //=============================================================================
1508 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1509 GEOM::GEOM_Object_ptr theShapeObject )
1510 throw ( SALOME::SALOME_Exception )
1512 Unexpect aCatch(SALOME_SalomeException);
1513 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1515 if ( CORBA::is_nil( theShapeObject ) )
1516 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1517 SALOME::BAD_PARAM );
1519 if ( CORBA::is_nil( theMesh ) )
1520 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1521 SALOME::BAD_PARAM );
1525 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1526 ASSERT( meshServant );
1527 if ( meshServant ) {
1528 // get local TopoDS_Shape
1529 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1530 // call implementation
1531 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1532 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1535 catch ( SALOME_Exception& S_ex ) {
1536 INFOS( "catch exception "<< S_ex.what() );
1541 //================================================================================
1543 * \brief Find SObject for an algo
1545 //================================================================================
1547 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1550 SALOMEDS::Study_var aStudy = getStudyServant();
1551 if ( !aStudy->_is_nil() ) {
1552 // find algo in the study
1553 CORBA::String_var compDataType = ComponentDataType();
1554 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1555 if ( !father->_is_nil() ) {
1556 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1557 for ( ; itBig->More(); itBig->Next() ) {
1558 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1559 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1560 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1561 for ( ; algoIt->More(); algoIt->Next() ) {
1562 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1563 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1564 if ( !CORBA::is_nil( algoIOR )) {
1565 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1566 if ( impl && impl->GetImpl() == algo )
1567 return algoSO._retn();
1569 } // loop on algo SO's
1572 } // SMESH component iterator
1576 return SALOMEDS::SObject::_nil();
1579 //================================================================================
1581 * \brief Return errors of mesh computation
1583 //================================================================================
1585 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1586 GEOM::GEOM_Object_ptr theSubObject )
1587 throw ( SALOME::SALOME_Exception )
1589 Unexpect aCatch(SALOME_SalomeException);
1590 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1592 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1593 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1595 if ( CORBA::is_nil( theMesh ) )
1596 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1598 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1600 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1603 if(theMesh->HasShapeToMesh())
1604 shape = GeomObjectToShape( theSubObject );
1606 shape = SMESH_Mesh::PseudoShape();
1608 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1610 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1613 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1614 const bool includeSelf = true, complexShapeFirst = true;
1615 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1617 while ( smIt->more() )
1620 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1622 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1623 if ( error && !error->IsOK() )
1625 if ( !( error->myAlgo ) &&
1626 !( error->myAlgo = sm->GetAlgo() ))
1628 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1629 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1630 errStruct.comment = error->myComment.c_str();
1631 errStruct.subShapeID = sm->GetId();
1632 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1633 if ( !algoSO->_is_nil() ) {
1634 CORBA::String_var algoName = algoSO->GetName();
1635 errStruct.algoName = algoName;
1638 errStruct.algoName = error->myAlgo->GetName();
1640 errStruct.hasBadMesh = error->HasBadElems();
1643 error_array->length( nbErr );
1646 catch ( SALOME_Exception& S_ex ) {
1647 INFOS( "catch exception "<< S_ex.what() );
1650 return error_array._retn();
1653 //================================================================================
1655 * \brief Return mesh elements preventing computation of a subshape
1657 //================================================================================
1659 SMESH::MeshPreviewStruct*
1660 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1661 CORBA::Short theSubShapeID )
1662 throw ( SALOME::SALOME_Exception )
1664 Unexpect aCatch(SALOME_SalomeException);
1665 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1667 if ( CORBA::is_nil( theMesh ) )
1668 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1670 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1673 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1675 // mesh implementation
1676 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1677 // submesh by subshape id
1678 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1681 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1682 if ( error && error->HasBadElems() )
1684 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1685 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1687 // get nodes of elements and count elements
1688 TNode2LocalIDMap mapNode2LocalID;
1689 list< TNodeLocalID > connectivity;
1690 int i, nbElements = 0, nbConnNodes = 0;
1692 const list<const SMDS_MeshElement*>& badElems =
1693 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1694 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1695 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1696 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1698 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1699 while ( nIt->more() )
1700 connectivity.push_back
1701 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1703 // fill node coords and assign local ids to the nodes
1704 int nbNodes = mapNode2LocalID.size();
1705 result->nodesXYZ.length( nbNodes );
1706 TNodeLocalID node2ID = mapNode2LocalID.begin();
1707 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1708 node2ID->second = i;
1709 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1710 result->nodesXYZ[i].x = node->X();
1711 result->nodesXYZ[i].y = node->Y();
1712 result->nodesXYZ[i].z = node->Z();
1714 // fill connectivity
1715 result->elementConnectivities.length( nbConnNodes );
1716 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1717 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1718 result->elementConnectivities[i] = (*connIt)->second;
1720 // fill element types
1721 result->elementTypes.length( nbElements );
1722 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1724 const SMDS_MeshElement* elem = *elemIt;
1725 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1726 result->elementTypes[i].isPoly = elem->IsPoly();
1727 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1733 catch ( SALOME_Exception& S_ex ) {
1734 INFOS( "catch exception "<< S_ex.what() );
1737 return result._retn();
1740 //================================================================================
1742 * \brief Create a group of elements preventing computation of a sub-shape
1744 //================================================================================
1746 SMESH::ListOfGroups*
1747 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1748 CORBA::Short theSubShapeID,
1749 const char* theGroupName )
1750 throw ( SALOME::SALOME_Exception )
1752 Unexpect aCatch(SALOME_SalomeException);
1754 SMESH::ListOfGroups_var groups;
1756 if ( CORBA::is_nil( theMesh ) )
1757 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1760 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1762 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1763 TPythonDump() << groups << " = " << this
1764 << ".MakeGroupsOfBadInputElements( "
1765 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1768 catch ( SALOME_Exception& S_ex ) {
1769 INFOS( "catch exception "<< S_ex.what() );
1771 return groups._retn();
1774 //================================================================================
1776 * \brief Returns errors of hypotheses definition
1777 * \param theMesh - the mesh
1778 * \param theSubObject - the main or sub- shape
1779 * \retval SMESH::algo_error_array* - sequence of errors
1781 //================================================================================
1783 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1784 GEOM::GEOM_Object_ptr theSubObject )
1785 throw ( SALOME::SALOME_Exception )
1787 Unexpect aCatch(SALOME_SalomeException);
1788 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1790 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1791 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1793 if ( CORBA::is_nil( theMesh ) )
1794 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1796 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1798 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1799 ASSERT( meshServant );
1800 if ( meshServant ) {
1801 TopoDS_Shape myLocShape;
1802 if(theMesh->HasShapeToMesh())
1803 myLocShape = GeomObjectToShape( theSubObject );
1805 myLocShape = SMESH_Mesh::PseudoShape();
1807 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1808 list< ::SMESH_Gen::TAlgoStateError > error_list;
1809 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1810 // call ::SMESH_Gen::GetAlgoState()
1811 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1812 error_array->length( error_list.size() );
1814 for ( error = error_list.begin(); error != error_list.end(); ++error )
1816 // fill AlgoStateError structure
1817 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1818 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1819 errStruct.algoDim = error->_algoDim;
1820 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1821 errStruct.algoName = "";
1822 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1823 if ( !algoSO->_is_nil() ) {
1824 CORBA::String_var algoName = algoSO->GetName();
1825 errStruct.algoName = algoName.in();
1830 catch ( SALOME_Exception& S_ex ) {
1831 INFOS( "catch exception "<< S_ex.what() );
1833 return error_array._retn();
1836 //=============================================================================
1838 * SMESH_Gen_i::GetSubShapesId
1840 * Get sub-shapes unique ID's list
1842 //=============================================================================
1845 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1846 const SMESH::object_array& theListOfSubShapeObject )
1847 throw ( SALOME::SALOME_Exception )
1849 Unexpect aCatch(SALOME_SalomeException);
1850 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1852 SMESH::long_array_var shapesId = new SMESH::long_array;
1855 if ( CORBA::is_nil( theMainShapeObject ) )
1856 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1860 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1861 TopTools_IndexedMapOfShape myIndexToShape;
1862 TopExp::MapShapes(myMainShape,myIndexToShape);
1864 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1866 GEOM::GEOM_Object_var aShapeObject
1867 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1868 if ( CORBA::is_nil( aShapeObject ) )
1869 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1870 SALOME::BAD_PARAM );
1872 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1873 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1875 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1876 setId.insert(myIndexToShape.FindIndex(F));
1877 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1879 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1881 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1882 setId.insert(myIndexToShape.FindIndex(E));
1883 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1885 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1887 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1888 setId.insert(myIndexToShape.FindIndex(V));
1889 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1892 shapesId->length(setId.size());
1893 set<int>::iterator iind;
1895 for (iind = setId.begin(); iind != setId.end(); iind++)
1897 if(MYDEBUG) SCRUTE((*iind));
1898 shapesId[i] = (*iind);
1899 if(MYDEBUG) SCRUTE(shapesId[i]);
1903 catch (SALOME_Exception& S_ex)
1905 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1908 return shapesId._retn();
1911 //=============================================================================
1913 * SMESH_Gen_i::Compute
1915 * Compute mesh on a shape
1917 //=============================================================================
1919 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1920 GEOM::GEOM_Object_ptr theShapeObject )
1921 throw ( SALOME::SALOME_Exception )
1924 Unexpect aCatch(SALOME_SalomeException);
1925 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1927 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1928 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1929 SALOME::BAD_PARAM );
1931 if ( CORBA::is_nil( theMesh ) )
1932 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1933 SALOME::BAD_PARAM );
1935 // Update Python script
1936 TPythonDump() << "isDone = " << this << ".Compute( "
1937 << theMesh << ", " << theShapeObject << ")";
1941 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1942 ASSERT( meshServant );
1943 if ( meshServant ) {
1944 meshServant->Load();
1945 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
1946 meshServant->CheckGeomModif();
1947 // get local TopoDS_Shape
1948 TopoDS_Shape myLocShape;
1949 if(theMesh->HasShapeToMesh())
1950 myLocShape = GeomObjectToShape( theShapeObject );
1952 myLocShape = SMESH_Mesh::PseudoShape();
1953 // call implementation compute
1954 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1955 myGen.PrepareCompute( myLocMesh, myLocShape );
1956 int how = ::SMESH_Gen::COMPACT_MESH;
1957 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
1958 how |= ::SMESH_Gen::SHAPE_ONLY;
1959 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
1960 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1961 myLocMesh.GetMeshDS()->Modified();
1962 UpdateIcons( theMesh );
1966 catch ( std::bad_alloc ) {
1967 INFOS( "Compute(): lack of memory" );
1969 catch ( SALOME_Exception& S_ex ) {
1970 INFOS( "Compute(): catch exception "<< S_ex.what() );
1973 INFOS( "Compute(): unknown exception " );
1978 //=============================================================================
1980 * SMESH_Gen_i::CancelCompute
1982 * Cancel Compute mesh on a shape
1984 //=============================================================================
1986 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
1987 GEOM::GEOM_Object_ptr theShapeObject )
1989 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1990 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1991 TopoDS_Shape myLocShape;
1992 if(theMesh->HasShapeToMesh())
1993 myLocShape = GeomObjectToShape( theShapeObject );
1995 myLocShape = SMESH_Mesh::PseudoShape();
1996 myGen.CancelCompute( myLocMesh, myLocShape);
1999 //=============================================================================
2001 * SMESH_Gen_i::Precompute
2003 * Compute mesh as preview till indicated dimension on shape
2005 //=============================================================================
2007 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2008 GEOM::GEOM_Object_ptr theShapeObject,
2009 SMESH::Dimension theDimension,
2010 SMESH::long_array& theShapesId)
2011 throw ( SALOME::SALOME_Exception )
2013 Unexpect aCatch(SALOME_SalomeException);
2014 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2016 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2017 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2018 SALOME::BAD_PARAM );
2020 if ( CORBA::is_nil( theMesh ) )
2021 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2022 SALOME::BAD_PARAM );
2024 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2027 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2028 meshServant->Load();
2029 ASSERT( meshServant );
2030 if ( meshServant ) {
2031 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2032 meshServant->CheckGeomModif();
2033 // get local TopoDS_Shape
2034 TopoDS_Shape myLocShape;
2035 if(theMesh->HasShapeToMesh())
2036 myLocShape = GeomObjectToShape( theShapeObject );
2038 return result._retn();;
2040 // call implementation compute
2041 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2043 ::MeshDimension aDim = (MeshDimension)theDimension;
2044 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2046 int nbShapeId = shapeIds.size();
2047 theShapesId.length( nbShapeId );
2048 // iterates on shapes and collect mesh entities into mesh preview
2049 TSetOfInt::const_iterator idIt = shapeIds.begin();
2050 TSetOfInt::const_iterator idEnd = shapeIds.end();
2051 std::map< int, int > mapOfShIdNb;
2052 std::set< SMESH_TLink > setOfEdge;
2053 std::list< SMDSAbs_ElementType > listOfElemType;
2054 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2055 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2056 TNode2LocalIDMap mapNode2LocalID;
2057 list< TNodeLocalID > connectivity;
2058 int i, nbConnNodes = 0;
2059 std::set< const SMESH_subMesh* > setOfVSubMesh;
2060 // iterates on shapes
2061 for ( ; idIt != idEnd; idIt++ )
2063 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2065 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2066 if ( !sm || !sm->IsMeshComputed() )
2069 const TopoDS_Shape& aSh = sm->GetSubShape();
2070 const int shDim = myGen.GetShapeDim( aSh );
2071 if ( shDim < 1 || shDim > theDimension )
2074 mapOfShIdNb[ *idIt ] = 0;
2075 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2077 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2078 if ( !smDS ) continue;
2080 if ( theDimension == SMESH::DIM_2D )
2082 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2083 while ( faceIt->more() )
2085 const SMDS_MeshElement* face = faceIt->next();
2086 int aNbNode = face->NbNodes();
2088 aNbNode /= 2; // do not take into account additional middle nodes
2090 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2091 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2093 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2094 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2096 listOfElemType.push_back( SMDSAbs_Edge );
2097 connectivity.push_back
2098 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2099 connectivity.push_back
2100 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2106 else if ( theDimension == SMESH::DIM_1D )
2108 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2109 while ( nodeIt->more() )
2111 listOfElemType.push_back( SMDSAbs_Node );
2112 connectivity.push_back
2113 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2115 // add corner nodes by first vertex from edge
2116 SMESH_subMeshIteratorPtr edgeSmIt =
2117 sm->getDependsOnIterator(/*includeSelf*/false,
2118 /*complexShapeFirst*/false);
2119 while ( edgeSmIt->more() )
2121 SMESH_subMesh* vertexSM = edgeSmIt->next();
2122 // check that vertex is not already treated
2123 if ( !setOfVSubMesh.insert( vertexSM ).second )
2125 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2128 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2129 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2130 while ( nodeIt->more() )
2132 listOfElemType.push_back( SMDSAbs_Node );
2133 connectivity.push_back
2134 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2140 // fill node coords and assign local ids to the nodes
2141 int nbNodes = mapNode2LocalID.size();
2142 result->nodesXYZ.length( nbNodes );
2143 TNodeLocalID node2ID = mapNode2LocalID.begin();
2144 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2145 node2ID->second = i;
2146 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2147 result->nodesXYZ[i].x = node->X();
2148 result->nodesXYZ[i].y = node->Y();
2149 result->nodesXYZ[i].z = node->Z();
2151 // fill connectivity
2152 result->elementConnectivities.length( nbConnNodes );
2153 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2154 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2155 result->elementConnectivities[i] = (*connIt)->second;
2158 // fill element types
2159 result->elementTypes.length( listOfElemType.size() );
2160 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2161 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2162 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2164 SMDSAbs_ElementType elemType = *typeIt;
2165 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2166 result->elementTypes[i].isPoly = false;
2167 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2170 // correct number of shapes
2171 theShapesId.length( mapOfShIdNb.size() );
2175 catch ( std::bad_alloc ) {
2176 INFOS( "Precompute(): lack of memory" );
2178 catch ( SALOME_Exception& S_ex ) {
2179 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2182 INFOS( "Precompute(): unknown exception " );
2184 return result._retn();
2188 //=============================================================================
2190 * SMESH_Gen_i::Evaluate
2192 * Evaluate mesh on a shape
2194 //=============================================================================
2196 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2197 GEOM::GEOM_Object_ptr theShapeObject)
2198 // SMESH::long_array& theNbElems)
2199 throw ( SALOME::SALOME_Exception )
2201 Unexpect aCatch(SALOME_SalomeException);
2202 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2204 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2205 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2206 SALOME::BAD_PARAM );
2208 if ( CORBA::is_nil( theMesh ) )
2209 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2210 SALOME::BAD_PARAM );
2212 SMESH::long_array_var nbels = new SMESH::long_array;
2213 nbels->length(SMESH::Entity_Last);
2214 int i = SMESH::Entity_Node;
2215 for (; i < SMESH::Entity_Last; i++)
2218 // Update Python script
2219 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2220 << theMesh << ", " << theShapeObject << ")";
2224 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2225 ASSERT( meshServant );
2226 if ( meshServant ) {
2227 meshServant->Load();
2228 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2229 meshServant->CheckGeomModif();
2230 // get local TopoDS_Shape
2231 TopoDS_Shape myLocShape;
2232 if(theMesh->HasShapeToMesh())
2233 myLocShape = GeomObjectToShape( theShapeObject );
2235 myLocShape = SMESH_Mesh::PseudoShape();
2236 // call implementation compute
2237 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2238 MapShapeNbElems aResMap;
2239 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2240 MapShapeNbElemsItr anIt = aResMap.begin();
2241 for(; anIt!=aResMap.end(); anIt++) {
2242 const vector<int>& aVec = (*anIt).second;
2243 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2244 int nbElem = aVec[i];
2245 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2247 SMESH_subMesh* sm = anIt->first;
2248 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2249 const SMESH_Algo* algo = sm->GetAlgo();
2250 if ( (algo && !error.get()) || error->IsOK() )
2251 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2255 nbels[i] += aVec[i];
2259 return nbels._retn();
2262 catch ( std::bad_alloc ) {
2263 INFOS( "Evaluate(): lack of memory" );
2265 catch ( SALOME_Exception& S_ex ) {
2266 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2269 INFOS( "Evaluate(): unknown exception " );
2272 return nbels._retn();
2275 //================================================================================
2277 * \brief Return geometrical object the given element is built on
2278 * \param theMesh - the mesh the element is in
2279 * \param theElementID - the element ID
2280 * \param theGeomName - the name of the result geom object if it is not yet published
2281 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2283 //================================================================================
2285 GEOM::GEOM_Object_ptr
2286 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2287 CORBA::Long theElementID,
2288 const char* theGeomName)
2289 throw ( SALOME::SALOME_Exception )
2291 Unexpect aCatch(SALOME_SalomeException);
2293 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2294 if ( !geom->_is_nil() ) {
2295 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2296 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2298 // try to find the corresponding SObject
2299 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2300 if ( SObj->_is_nil() ) // submesh can be not found even if published
2302 // try to find published submesh
2303 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2304 if ( !geom->IsMainShape() && list->length() == 1 ) {
2305 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2306 SALOMEDS::ChildIterator_wrap it;
2307 if ( !mainSO->_is_nil() ) {
2308 it = getStudyServant()->NewChildIterator( mainSO );
2310 if ( !it->_is_nil() ) {
2311 for ( it->InitEx(true); it->More(); it->Next() ) {
2312 SALOMEDS::SObject_wrap so = it->Value();
2313 CORBA::Object_var obj = SObjectToObject( so );
2314 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2315 if ( !subGeom->_is_nil() ) {
2316 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2317 if ( subList->length() == 1 && list[0] == subList[0] ) {
2327 if ( SObj->_is_nil() ) // publish a new subshape
2328 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2330 // return only published geometry
2331 if ( !SObj->_is_nil() ) {
2332 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2333 CORBA::Object_var obj = SObjectToObject( SObj );
2334 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2338 return GEOM::GEOM_Object::_nil();
2341 //================================================================================
2343 * \brief Return geometrical object the given element is built on.
2344 * \param theMesh - the mesh the element is in
2345 * \param theElementID - the element ID
2346 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2348 //================================================================================
2350 GEOM::GEOM_Object_ptr
2351 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2352 CORBA::Long theElementID)
2353 throw ( SALOME::SALOME_Exception )
2355 Unexpect aCatch(SALOME_SalomeException);
2356 if ( CORBA::is_nil( theMesh ) )
2357 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2359 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2360 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2362 // get a core mesh DS
2363 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2364 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2366 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2367 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2368 // find the element in mesh
2369 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2370 // find a shape id by the element
2371 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2372 // get a geom object by the shape id
2373 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2374 if ( geom->_is_nil() ) {
2375 // try to find a published sub-shape
2376 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2377 SALOMEDS::ChildIterator_wrap it;
2378 if ( !mainSO->_is_nil() ) {
2379 it = getStudyServant()->NewChildIterator( mainSO );
2381 if ( !it->_is_nil() ) {
2382 for ( it->InitEx(true); it->More(); it->Next() ) {
2383 SALOMEDS::SObject_wrap so = it->Value();
2384 CORBA::Object_var obj = SObjectToObject( so );
2385 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2386 if ( !subGeom->_is_nil() ) {
2387 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2388 if ( subList->length() == 1 && shapeID == subList[0] ) {
2396 if ( geom->_is_nil() ) {
2398 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2399 if ( !op->_is_nil() )
2400 geom = op->GetSubShape( mainShape, shapeID );
2405 if ( !geom->_is_nil() ) {
2406 GeomObjectToShape( geom ); // let geom client remember the found shape
2407 return geom._retn();
2412 return GEOM::GEOM_Object::_nil();
2415 //================================================================================
2417 * SMESH_Gen_i::Concatenate
2419 * Concatenate the given meshes into one mesh
2421 //================================================================================
2423 SMESH::SMESH_Mesh_ptr
2424 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2425 CORBA::Boolean theUniteIdenticalGroups,
2426 CORBA::Boolean theMergeNodesAndElements,
2427 CORBA::Double theMergeTolerance)
2428 throw ( SALOME::SALOME_Exception )
2430 return ConcatenateCommon(theMeshesArray,
2431 theUniteIdenticalGroups,
2432 theMergeNodesAndElements,
2437 //================================================================================
2439 * SMESH_Gen_i::ConcatenateWithGroups
2441 * Concatenate the given meshes into one mesh
2442 * Create the groups of all elements from initial meshes
2444 //================================================================================
2446 SMESH::SMESH_Mesh_ptr
2447 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2448 CORBA::Boolean theUniteIdenticalGroups,
2449 CORBA::Boolean theMergeNodesAndElements,
2450 CORBA::Double theMergeTolerance)
2451 throw ( SALOME::SALOME_Exception )
2453 return ConcatenateCommon(theMeshesArray,
2454 theUniteIdenticalGroups,
2455 theMergeNodesAndElements,
2460 //================================================================================
2462 * SMESH_Gen_i::ConcatenateCommon
2464 * Concatenate the given meshes into one mesh
2466 //================================================================================
2468 SMESH::SMESH_Mesh_ptr
2469 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2470 CORBA::Boolean theUniteIdenticalGroups,
2471 CORBA::Boolean theMergeNodesAndElements,
2472 CORBA::Double theMergeTolerance,
2473 CORBA::Boolean theCommonGroups)
2474 throw ( SALOME::SALOME_Exception )
2476 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2477 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2480 SMESH::SMESH_Mesh_var newMesh = CreateEmptyMesh();
2481 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2482 if ( !newImpl ) return newMesh._retn();
2484 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2485 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2487 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2488 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2489 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2490 TGroupsMap groupsMap;
2491 TListOfNewGroups listOfNewGroups;
2493 ::SMESH_MeshEditor newEditor( &locMesh );
2494 ::SMESH_MeshEditor::ElemFeatures elemType;
2496 // loop on sub-meshes
2497 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2499 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2500 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2501 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2502 if ( !initImpl ) continue;
2505 // assure that IDs increments by one during iteration
2506 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2507 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2508 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2509 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2511 initMeshDS->Modified();
2512 initMeshDS->CompactMesh();
2515 // remember nb of elements before filling in
2516 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2520 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2521 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2522 while ( elemIt->more() )
2524 SMESH_NodeXYZ node = elemIt->next();
2525 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2530 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2531 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2532 while ( elemIt->more() )
2534 const SMDS_MeshElement* elem = elemIt->next();
2535 elemType.myNodes.resize( elem->NbNodes() );
2537 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2538 for ( int k = 0; itNodes->more(); k++)
2540 const SMDS_MeshNode* node = itNodes->next();
2541 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2544 // creates a corresponding element on existent nodes in new mesh
2545 newElems[ elem->GetID() ] =
2546 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2548 newEditor.ClearLastCreated(); // forget the history
2551 // create groups of just added elements
2552 SMESH::SMESH_Group_var newGroup;
2553 SMESH::ElementType groupType;
2554 if ( theCommonGroups )
2557 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2558 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2559 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2560 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2563 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2565 for( groupType = SMESH::NODE;
2566 groupType < SMESH::NB_ELEMENT_TYPES;
2567 groupType = (SMESH::ElementType)( groupType + 1 ))
2569 if ( curState[ groupType ] <= prevState[ groupType ])
2570 continue; // no elements of groupType added from the i-th mesh
2572 // make a group name
2573 std::string groupName = "Gr";
2574 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2576 CORBA::String_var name = meshSO->GetName();
2580 groupName += typeNames[ groupType ];
2582 // make and fill a group
2583 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2584 std::vector< const SMDS_MeshElement* > & elemVec =
2585 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2586 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2588 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2590 for ( size_t j = 0; j < elemVec.size(); ++j )
2592 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2593 grpDS->Add( elemVec[j] );
2597 listOfNewGroups.clear();
2598 listOfNewGroups.push_back( newGroup );
2599 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2604 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2608 SMESH::SMESH_GroupBase_ptr group;
2609 CORBA::String_var groupName;
2610 SMESH::long_array_var newIDs = new SMESH::long_array();
2612 // loop on groups of a source mesh
2613 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2614 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2616 group = listOfGroups[iG];
2617 groupType = group->GetType();
2618 groupName = group->GetName();
2619 std::string name = groupName.in();
2621 // convert a list of IDs
2622 newIDs->length( group->Size() );
2623 std::vector< const SMDS_MeshElement* > & elemVec =
2624 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2625 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2627 while ( itGrElems->more() )
2629 const SMDS_MeshElement* elem = itGrElems->next();
2630 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2632 newIDs[ nbElems++ ] = newElem->GetID();
2634 newIDs->length( nbElems );
2636 // check that a current group name and type don't have identical ones in final mesh
2637 listOfNewGroups.clear();
2638 TNameAndType nameAndType( name, groupType );
2639 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2640 if ( anIter == groupsMap.end() )
2642 // add a new group in the mesh
2643 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2644 newGroup->Add( newIDs );
2646 listOfNewGroups.push_back( newGroup );
2647 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2649 else if ( theUniteIdenticalGroups )
2651 // unite identical groups
2652 TListOfNewGroups& aNewGroups = anIter->second;
2653 aNewGroups.front()->Add( newIDs );
2657 // rename identical groups
2658 newGroup = newImpl->CreateGroup( groupType, groupName );
2659 newGroup->Add( newIDs );
2661 TListOfNewGroups& newGroups = anIter->second;
2662 std::string newGroupName;
2663 if ( newGroups.size() == 1 )
2665 newGroupName = name + "_1";
2666 newGroups.front()->SetName( newGroupName.c_str() );
2668 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2669 newGroup->SetName( newGroupName.c_str() );
2670 newGroups.push_back( newGroup );
2673 } // if an IDSource is a mesh
2676 if ( theMergeNodesAndElements ) // merge nodes
2678 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2679 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2680 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2681 /*SeparateCornersAndMedium=*/ false );
2682 newEditor.MergeNodes( groupsOfNodes );
2684 newEditor.MergeEqualElements();
2687 // Update Python script
2688 pythonDump << newMesh << " = " << this
2689 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "("
2690 << theMeshesArray << ", "
2691 << theUniteIdenticalGroups << ", "
2692 << theMergeNodesAndElements << ", "
2693 << TVar( theMergeTolerance ) << ")";
2695 pPythonDump.reset(); // enable python dump from GetGroups()
2697 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2698 if ( !newMesh->_is_nil() )
2700 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2703 // IPAL21468 Change icon of compound because it need not be computed.
2704 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2705 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2707 newMeshDS->Modified();
2709 return newMesh._retn();
2712 //================================================================================
2714 * \brief Create a mesh by copying a part of another mesh
2715 * \param meshPart - a part of mesh to copy
2716 * \param toCopyGroups - to create in the new mesh groups
2717 * the copied elements belongs to
2718 * \param toKeepIDs - to preserve IDs of the copied elements or not
2719 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2721 //================================================================================
2723 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2724 const char* meshName,
2725 CORBA::Boolean toCopyGroups,
2726 CORBA::Boolean toKeepIDs)
2728 Unexpect aCatch(SALOME_SalomeException);
2730 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2732 // 1. Get source mesh
2734 if ( CORBA::is_nil( meshPart ))
2735 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2737 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2738 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2740 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2742 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2744 // 2. Make a new mesh
2746 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2747 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2749 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2750 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2751 if ( !meshSO->_is_nil() )
2753 SetName( meshSO, meshName, "Mesh" );
2754 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2756 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2757 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2758 ::SMESH_MeshEditor::ElemFeatures elemType;
2760 // 3. Get elements to copy
2762 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2763 TIDSortedElemSet srcElems;
2764 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2765 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2768 srcElemIt = srcMeshDS->elementsIterator();
2769 srcNodeIt = srcMeshDS->nodesIterator();
2773 SMESH::long_array_var ids = meshPart->GetIDs();
2774 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2776 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2777 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2778 srcElems.insert( elem );
2782 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2783 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2784 srcElems.insert( elem );
2786 if ( srcElems.empty() )
2787 return newMesh._retn();
2789 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2790 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2795 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2796 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2797 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2799 const SMDS_MeshNode *nSrc, *nTgt;
2800 vector< const SMDS_MeshNode* > nodes;
2801 while ( srcElemIt->more() )
2803 const SMDS_MeshElement * elem = srcElemIt->next();
2805 nodes.resize( elem->NbNodes());
2806 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2808 for ( iN = 0; nIt->more(); ++iN )
2810 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2811 nTgt = newMeshDS->FindNode( nSrc->GetID());
2813 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2818 for ( iN = 0; nIt->more(); ++iN )
2820 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2821 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2823 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2824 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2828 if ( elem->GetType() != SMDSAbs_Node )
2830 elemType.Init( elem, /*basicOnly=*/false );
2831 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2833 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2834 if ( toCopyGroups && !toKeepIDs )
2835 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2837 } // while ( srcElemIt->more() )
2839 // 4(b). Copy free nodes
2841 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2843 while ( srcNodeIt->more() )
2845 nSrc = srcNodeIt->next();
2846 if ( nSrc->NbInverseElements() == 0 )
2849 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2851 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2858 int nbNewGroups = 0;
2861 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2862 while ( gIt->more() )
2864 SMESH_Group* group = gIt->next();
2865 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2867 // Check group type. We copy nodal groups containing nodes of copied element
2868 SMDSAbs_ElementType groupType = groupDS->GetType();
2869 if ( groupType != SMDSAbs_Node &&
2870 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2871 continue; // group type differs from types of meshPart
2873 // Find copied elements in the group
2874 vector< const SMDS_MeshElement* > groupElems;
2875 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2878 const SMDS_MeshElement* foundElem;
2879 if ( groupType == SMDSAbs_Node )
2881 while ( eIt->more() )
2882 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2883 groupElems.push_back( foundElem );
2887 while ( eIt->more() )
2888 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2889 groupElems.push_back( foundElem );
2894 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2895 if ( e2eMap.empty() ) continue;
2896 int minID = e2eMap.begin()->first->GetID();
2897 int maxID = e2eMap.rbegin()->first->GetID();
2898 TE2EMap::iterator e2e;
2899 while ( eIt->more() && groupElems.size() < e2eMap.size())
2901 const SMDS_MeshElement* e = eIt->next();
2902 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2903 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2904 groupElems.push_back( e2e->second );
2908 if ( !groupElems.empty() )
2910 SMESH::SMESH_Group_var newGroupObj =
2911 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2912 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2914 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2915 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2916 for ( unsigned i = 0; i < groupElems.size(); ++i )
2917 smdsGroup.Add( groupElems[i] );
2925 newMeshDS->Modified();
2927 *pyDump << newMesh << " = " << this
2928 << ".CopyMesh( " << meshPart << ", "
2929 << "'" << meshName << "', "
2930 << toCopyGroups << ", "
2931 << toKeepIDs << ")";
2933 delete pyDump; pyDump = 0; // allow dump in GetGroups()
2935 if ( nbNewGroups > 0 ) // dump created groups
2936 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2938 return newMesh._retn();
2941 //================================================================================
2943 * \brief Get version of MED format being used.
2945 //================================================================================
2947 char* SMESH_Gen_i::GetMEDFileVersion()
2949 MED::TInt majeur, mineur, release;
2950 majeur = mineur = release = 0;
2951 MED::GetVersionRelease(majeur, mineur, release);
2952 std::ostringstream version;
2953 version << majeur << "." << mineur << "." << release;
2954 return CORBA::string_dup( version.str().c_str() );
2957 //================================================================================
2959 * SMESH_Gen_i::GetMEDVersion
2961 * Get MED version of the file by its name
2963 //================================================================================
2964 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
2966 std::string version = MED::GetMEDVersion( theFileName );
2967 return CORBA::string_dup( version.c_str() );
2970 //================================================================================
2972 * SMESH_Gen_i::CheckCompatibility
2974 * Check compatibility of file with MED format being used, read only.
2976 //================================================================================
2977 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
2979 return MED::CheckCompatibility( theFileName );
2982 //================================================================================
2984 * SMESH_Gen_i::CheckWriteCompatibility
2986 * Check compatibility of file with MED format being used, for append on write.
2988 //================================================================================
2989 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
2991 return MED::CheckCompatibility( theFileName, true );
2994 //================================================================================
2996 * SMESH_Gen_i::GetMeshNames
2998 * Get names of meshes defined in file with the specified name
3000 //================================================================================
3001 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
3003 //MESSAGE("GetMeshNames " << theFileName);
3004 SMESH::string_array_var aResult = new SMESH::string_array();
3005 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
3007 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
3008 //MESSAGE("---" << aNbMeshes);
3010 aResult->length( aNbMeshes );
3011 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
3012 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
3013 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
3016 return aResult._retn();
3019 //=============================================================================
3023 * Save SMESH module's data
3025 //=============================================================================
3026 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
3030 if (!myStudyContext)
3033 // Store study contents as a set of python commands
3036 SALOMEDS::Study_var aStudy = getStudyServant();
3038 // Declare a byte stream
3039 SALOMEDS::TMPFile_var aStreamFile;
3041 // Obtain a temporary dir
3042 TCollection_AsciiString tmpDir =
3043 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
3045 // Create a sequence of files processed
3046 SALOMEDS_Tool::ListOfFiles aFileSeq;
3047 aFileSeq.reserve( NUM_TMP_FILES );
3049 TCollection_AsciiString aStudyName( "" );
3051 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
3053 // Set names of temporary files
3054 TCollection_AsciiString filename =
3055 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
3056 TCollection_AsciiString meshfile =
3057 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
3058 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
3059 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
3060 filename = tmpDir + filename;
3061 meshfile = tmpDir + meshfile;
3064 HDFdataset* aDataset;
3065 HDFgroup* aTopGroup;
3067 HDFgroup* aSubGroup;
3068 HDFgroup* aSubSubGroup;
3069 hdf_size aSize[ 1 ];
3072 //Remove the files if they exist: BugID: 11225
3073 #ifndef WIN32 /* unix functionality */
3074 TCollection_AsciiString cmd("rm -f \"");
3076 TCollection_AsciiString cmd("del /F \"");
3083 system(cmd.ToCString());
3085 // MED writer to be used by storage process
3086 DriverMED_W_SMESHDS_Mesh myWriter;
3087 myWriter.SetFile( meshfile.ToCString() );
3090 // SetStoreName() to groups before storing hypotheses to let them refer to
3091 // groups using "store name", which is "Group <group_persistent_id>"
3093 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
3094 for ( ; itBig->More(); itBig->Next() ) {
3095 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3096 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3097 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3098 if ( !CORBA::is_nil( anObject ) ) {
3099 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3100 if ( !myMesh->_is_nil() ) {
3101 myMesh->Load(); // load from study file if not yet done
3102 TPythonDump pd; // not to dump GetGroups()
3103 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
3104 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
3106 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
3109 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
3110 int anId = myStudyContext->findId( string( objStr.in() ) );
3112 sprintf( grpName, "Group %d", anId );
3113 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
3114 aGrpBaseDS->SetStoreName( grpName );
3124 // ---> create HDF file
3125 aFile = new HDFfile( (char*) filename.ToCString() );
3126 aFile->CreateOnDisk();
3128 // --> iterator for top-level objects
3129 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
3130 for ( ; itBig->More(); itBig->Next() ) {
3131 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3133 // --> hypotheses root branch (only one for the study)
3134 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
3135 // create hypotheses root HDF group
3136 aTopGroup = new HDFgroup( "Hypotheses", aFile );
3137 aTopGroup->CreateOnDisk();
3139 // iterator for all hypotheses
3140 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
3141 for ( ; it->More(); it->Next() ) {
3142 SALOMEDS::SObject_wrap mySObject = it->Value();
3143 CORBA::Object_var anObject = SObjectToObject( mySObject );
3144 if ( !CORBA::is_nil( anObject ) ) {
3145 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3146 if ( !myHyp->_is_nil() ) {
3147 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3149 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
3150 std::string hypname = hn.in();
3151 std::string libname = ln.in();
3153 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3154 // WIN32 and ".so" for X-system) must be deleted
3155 int libname_len = libname.length();
3157 if( libname_len > 4 )
3158 libname.resize( libname_len - 4 );
3160 // PAL17753 (Regression: missing hypothesis in restored study)
3161 // "lib" also should be removed from the beginning
3162 //if( libname_len > 3 )
3163 //libname.resize( libname_len - 3 );
3164 if( libname_len > 6 )
3165 libname = libname.substr( 3, libname_len - 3 - 3 );
3167 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3168 CORBA::String_var hypdata = myImpl->SaveTo();
3169 int id = myStudyContext->findId( string( objStr.in() ));
3171 // for each hypothesis create HDF group basing on its id
3172 char hypGrpName[30];
3173 sprintf( hypGrpName, "Hypothesis %d", id );
3174 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3175 aGroup->CreateOnDisk();
3176 // --> type name of hypothesis
3177 aSize[ 0 ] = hypname.length() + 1;
3178 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3179 aDataset->CreateOnDisk();
3180 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3181 aDataset->CloseOnDisk();
3182 // --> server plugin library name of hypothesis
3183 aSize[ 0 ] = libname.length() + 1;
3184 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3185 aDataset->CreateOnDisk();
3186 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3187 aDataset->CloseOnDisk();
3188 // --> persistent data of hypothesis
3189 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
3190 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3191 aDataset->CreateOnDisk();
3192 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
3193 aDataset->CloseOnDisk();
3194 // close hypothesis HDF group
3195 aGroup->CloseOnDisk();
3200 // close hypotheses root HDF group
3201 aTopGroup->CloseOnDisk();
3203 // --> algorithms root branch (only one for the study)
3204 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
3205 // create algorithms root HDF group
3206 aTopGroup = new HDFgroup( "Algorithms", aFile );
3207 aTopGroup->CreateOnDisk();
3209 // iterator for all algorithms
3210 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
3211 for ( ; it->More(); it->Next() ) {
3212 SALOMEDS::SObject_wrap mySObject = it->Value();
3213 CORBA::Object_var anObject = SObjectToObject( mySObject );
3214 if ( !CORBA::is_nil( anObject ) ) {
3215 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3216 if ( !myHyp->_is_nil() ) {
3217 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3219 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
3220 std::string hypname = hn.in();
3221 std::string libname = ln.in();
3223 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3224 // WIN32 and ".so" for X-system) must be deleted
3225 int libname_len = libname.length();
3227 if( libname_len > 4 )
3228 libname.resize( libname_len - 4 );
3230 // PAL17753 (Regression: missing hypothesis in restored study)
3231 // "lib" also should be removed from the beginning
3232 //if( libname_len > 3 )
3233 //libname.resize( libname_len - 3 );
3234 if( libname_len > 6 )
3235 libname = libname.substr( 3, libname_len - 3 - 3 );
3237 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3238 CORBA::String_var hypdata = myImpl->SaveTo();
3239 int id = myStudyContext->findId( string( objStr.in() ) );
3241 // for each algorithm create HDF group basing on its id
3242 char hypGrpName[30];
3243 sprintf( hypGrpName, "Algorithm %d", id );
3244 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3245 aGroup->CreateOnDisk();
3246 // --> type name of algorithm
3247 aSize[0] = hypname.length() + 1;
3248 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3249 aDataset->CreateOnDisk();
3250 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3251 aDataset->CloseOnDisk();
3252 // --> server plugin library name of hypothesis
3253 aSize[0] = libname.length() + 1;
3254 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3255 aDataset->CreateOnDisk();
3256 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3257 aDataset->CloseOnDisk();
3258 // --> persistent data of algorithm
3259 aSize[0] = strlen( hypdata.in() ) + 1;
3260 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3261 aDataset->CreateOnDisk();
3262 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
3263 aDataset->CloseOnDisk();
3264 // close algorithm HDF group
3265 aGroup->CloseOnDisk();
3270 // close algorithms root HDF group
3271 aTopGroup->CloseOnDisk();
3273 // --> mesh objects roots branches
3274 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3275 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3276 if ( !CORBA::is_nil( anObject ) ) {
3277 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3278 if ( !myMesh->_is_nil() ) {
3279 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
3281 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3282 int id = myStudyContext->findId( string( objStr.in() ) );
3283 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
3284 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
3285 bool hasShape = myLocMesh.HasShapeToMesh();
3287 // for each mesh open the HDF group basing on its id
3288 char meshGrpName[ 30 ];
3289 sprintf( meshGrpName, "Mesh %d", id );
3290 aTopGroup = new HDFgroup( meshGrpName, aFile );
3291 aTopGroup->CreateOnDisk();
3293 // --> put dataset to hdf file which is a flag that mesh has data
3294 string strHasData = "0";
3295 // check if the mesh is not empty
3296 if ( mySMESHDSMesh->NbNodes() > 0 ) {
3297 // write mesh data to med file
3298 myWriter.SetMesh( mySMESHDSMesh );
3299 myWriter.SetMeshId( id );
3302 aSize[ 0 ] = strHasData.length() + 1;
3303 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
3304 aDataset->CreateOnDisk();
3305 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
3306 aDataset->CloseOnDisk();
3309 // for each mesh open the HDF group basing on its auto color parameter
3310 char meshAutoColorName[ 30 ];
3311 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
3313 anAutoColor[0] = myImpl->GetAutoColor();
3315 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
3316 aDataset->CreateOnDisk();
3317 aDataset->WriteOnDisk( anAutoColor );
3318 aDataset->CloseOnDisk();
3320 // issue 0020693. Store _isModified flag
3321 int isModified = myLocMesh.GetIsModified();
3323 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
3324 aDataset->CreateOnDisk();
3325 aDataset->WriteOnDisk( &isModified );
3326 aDataset->CloseOnDisk();
3328 // issue 20918. Store Persistent Id of SMESHDS_Mesh
3329 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
3331 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
3332 aDataset->CreateOnDisk();
3333 aDataset->WriteOnDisk( &meshPersistentId );
3334 aDataset->CloseOnDisk();
3336 // write reference on a shape if exists
3337 SALOMEDS::SObject_wrap myRef;
3338 bool shapeRefFound = false;
3339 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
3341 SALOMEDS::SObject_wrap myShape;
3342 bool ok = myRef->ReferencedObject( myShape.inout() );
3344 CORBA::Object_var shapeObj = myShape->GetObject();
3345 shapeRefFound = (! CORBA::is_nil( shapeObj ));
3346 CORBA::String_var myRefOnObject = myShape->GetID();
3347 if ( shapeRefFound && myRefOnObject.in()[0] ) {
3348 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
3349 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
3350 aDataset->CreateOnDisk();
3351 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
3352 aDataset->CloseOnDisk();
3358 std::string info = myImpl->FileInfoToString();
3359 if ( !info.empty() )
3361 aSize[ 0 ] = info.size();
3362 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
3363 aDataset->CreateOnDisk();
3364 aDataset->WriteOnDisk( (char*) info.data() );
3365 aDataset->CloseOnDisk();
3368 // write applied hypotheses if exist
3369 SALOMEDS::SObject_wrap myHypBranch;
3370 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
3371 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
3372 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
3374 if ( found && (shapeRefFound || !hasShape) ) {
3375 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
3376 aGroup->CreateOnDisk();
3378 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
3380 for ( ; it->More(); it->Next() ) {
3381 SALOMEDS::SObject_wrap mySObject = it->Value();
3382 SALOMEDS::SObject_wrap myRefOnHyp;
3383 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
3385 // san - it is impossible to recover applied hypotheses
3386 // using their entries within Load() method,
3387 // for there are no AttributeIORs in the study when Load() is working.
3388 // Hence, it is better to store persistent IDs of hypotheses as references to them
3390 //string myRefOnObject = myRefOnHyp->GetID();
3391 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3392 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3393 int id = myStudyContext->findId( string( objStr.in() ) );
3394 //if ( myRefOnObject.length() > 0 ) {
3395 //aSize[ 0 ] = myRefOnObject.length() + 1;
3396 char hypName[ 30 ], hypId[ 30 ];
3397 sprintf( hypName, "Hyp %d", ++hypNb );
3398 sprintf( hypId, "%d", id );
3399 aSize[ 0 ] = strlen( hypId ) + 1;
3400 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
3401 aDataset->CreateOnDisk();
3402 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3403 aDataset->WriteOnDisk( hypId );
3404 aDataset->CloseOnDisk();
3408 aGroup->CloseOnDisk();
3411 // write applied algorithms if exist
3412 SALOMEDS::SObject_wrap myAlgoBranch;
3413 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3414 myAlgoBranch.inout() );
3415 if ( found && !shapeRefFound && hasShape) { // remove applied algos
3416 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
3418 if ( found && (shapeRefFound || !hasShape)) {
3419 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3420 aGroup->CreateOnDisk();
3422 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
3424 for ( ; it->More(); it->Next() ) {
3425 SALOMEDS::SObject_wrap mySObject = it->Value();
3426 SALOMEDS::SObject_wrap myRefOnAlgo;
3427 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
3429 // san - it is impossible to recover applied algorithms
3430 // using their entries within Load() method,
3431 // for there are no AttributeIORs in the study when Load() is working.
3432 // Hence, it is better to store persistent IDs of algorithms as references to them
3434 //string myRefOnObject = myRefOnAlgo->GetID();
3435 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3436 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3437 int id = myStudyContext->findId( string( objStr.in() ) );
3438 //if ( myRefOnObject.length() > 0 ) {
3439 //aSize[ 0 ] = myRefOnObject.length() + 1;
3440 char algoName[ 30 ], algoId[ 30 ];
3441 sprintf( algoName, "Algo %d", ++algoNb );
3442 sprintf( algoId, "%d", id );
3443 aSize[ 0 ] = strlen( algoId ) + 1;
3444 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
3445 aDataset->CreateOnDisk();
3446 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3447 aDataset->WriteOnDisk( algoId );
3448 aDataset->CloseOnDisk();
3452 aGroup->CloseOnDisk();
3455 // --> submesh objects sub-branches
3457 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
3458 SALOMEDS::SObject_wrap mySubmeshBranch;
3459 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
3461 if ( found ) // check if there is shape reference in submeshes
3463 bool hasShapeRef = false;
3464 SALOMEDS::ChildIterator_wrap itSM =
3465 aStudy->NewChildIterator( mySubmeshBranch );
3466 for ( ; itSM->More(); itSM->Next() ) {
3467 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
3468 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3469 mySubRef->ReferencedObject( myShape.inout() );
3470 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
3473 { // remove one submesh
3474 if ( shapeRefFound )
3475 { // unassign hypothesis
3476 SMESH::SMESH_subMesh_var mySubMesh =
3477 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
3478 if ( !mySubMesh->_is_nil() ) {
3479 int shapeID = mySubMesh->GetId();
3480 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
3481 const list<const SMESHDS_Hypothesis*>& hypList =
3482 mySMESHDSMesh->GetHypothesis( S );
3483 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
3484 while ( hyp != hypList.end() ) {
3485 int hypID = (*hyp++)->GetID(); // goto next hyp here because
3486 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
3490 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
3492 } // loop on submeshes of a type
3493 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
3494 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
3497 } // end check if there is shape reference in submeshes
3499 char name_meshgroup[ 30 ];
3500 if ( i == GetSubMeshOnVertexTag() )
3501 strcpy( name_meshgroup, "SubMeshes On Vertex" );
3502 else if ( i == GetSubMeshOnEdgeTag() )
3503 strcpy( name_meshgroup, "SubMeshes On Edge" );
3504 else if ( i == GetSubMeshOnWireTag() )
3505 strcpy( name_meshgroup, "SubMeshes On Wire" );
3506 else if ( i == GetSubMeshOnFaceTag() )
3507 strcpy( name_meshgroup, "SubMeshes On Face" );
3508 else if ( i == GetSubMeshOnShellTag() )
3509 strcpy( name_meshgroup, "SubMeshes On Shell" );
3510 else if ( i == GetSubMeshOnSolidTag() )
3511 strcpy( name_meshgroup, "SubMeshes On Solid" );
3512 else if ( i == GetSubMeshOnCompoundTag() )
3513 strcpy( name_meshgroup, "SubMeshes On Compound" );
3515 // for each type of submeshes create container HDF group
3516 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
3517 aGroup->CreateOnDisk();
3519 // iterator for all submeshes of given type
3520 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
3521 for ( ; itSM->More(); itSM->Next() ) {
3522 SALOMEDS::SObject_wrap mySObject = itSM->Value();
3523 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
3524 if ( !CORBA::is_nil( anSubObject ))
3526 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
3527 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
3528 int subid = myStudyContext->findId( string( objStr.in() ) );
3530 // for each mesh open the HDF group basing on its id
3531 char submeshGrpName[ 30 ];
3532 sprintf( submeshGrpName, "SubMesh %d", subid );
3533 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
3534 aSubGroup->CreateOnDisk();
3536 // write reference on a shape, already checked if it exists
3537 SALOMEDS::SObject_wrap mySubRef, myShape;
3538 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3539 mySubRef->ReferencedObject( myShape.inout() );
3540 string myRefOnObject = myShape->GetID();
3541 if ( myRefOnObject.length() > 0 ) {
3542 aSize[ 0 ] = myRefOnObject.length() + 1;
3543 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
3544 aDataset->CreateOnDisk();
3545 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3546 aDataset->CloseOnDisk();
3549 // write applied hypotheses if exist
3550 SALOMEDS::SObject_wrap mySubHypBranch;
3551 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
3552 mySubHypBranch.inout() );
3554 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
3555 aSubSubGroup->CreateOnDisk();
3557 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
3559 for ( ; it->More(); it->Next() ) {
3560 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3561 SALOMEDS::SObject_wrap myRefOnHyp;
3562 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
3564 //string myRefOnObject = myRefOnHyp->GetID();
3565 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3566 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3567 int id = myStudyContext->findId( string( objStr.in() ) );
3568 //if ( myRefOnObject.length() > 0 ) {
3569 //aSize[ 0 ] = myRefOnObject.length() + 1;
3570 char hypName[ 30 ], hypId[ 30 ];
3571 sprintf( hypName, "Hyp %d", ++hypNb );
3572 sprintf( hypId, "%d", id );
3573 aSize[ 0 ] = strlen( hypId ) + 1;
3574 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
3575 aDataset->CreateOnDisk();
3576 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3577 aDataset->WriteOnDisk( hypId );
3578 aDataset->CloseOnDisk();
3582 aSubSubGroup->CloseOnDisk();
3585 // write applied algorithms if exist
3586 SALOMEDS::SObject_wrap mySubAlgoBranch;
3587 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3588 mySubAlgoBranch.inout() );
3590 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3591 aSubSubGroup->CreateOnDisk();
3593 SALOMEDS::ChildIterator_wrap it =
3594 aStudy->NewChildIterator( mySubAlgoBranch );
3596 for ( ; it->More(); it->Next() ) {
3597 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3598 SALOMEDS::SObject_wrap myRefOnAlgo;
3599 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
3601 //string myRefOnObject = myRefOnAlgo->GetID();
3602 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3603 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3604 int id = myStudyContext->findId( string( objStr.in() ) );
3605 //if ( myRefOnObject.length() > 0 ) {
3606 //aSize[ 0 ] = myRefOnObject.length() + 1;
3607 char algoName[ 30 ], algoId[ 30 ];
3608 sprintf( algoName, "Algo %d", ++algoNb );
3609 sprintf( algoId, "%d", id );
3610 aSize[ 0 ] = strlen( algoId ) + 1;
3611 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
3612 aDataset->CreateOnDisk();
3613 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3614 aDataset->WriteOnDisk( algoId );
3615 aDataset->CloseOnDisk();
3619 aSubSubGroup->CloseOnDisk();
3621 // close submesh HDF group
3622 aSubGroup->CloseOnDisk();
3625 // close container of submeshes by type HDF group
3626 aGroup->CloseOnDisk();
3629 // All sub-meshes will be stored in MED file
3630 // .. will NOT (PAL 12992)
3631 //if ( shapeRefFound )
3632 //myWriter.AddAllSubMeshes();
3634 // store submesh order if any
3635 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
3636 if ( theOrderIds.size() ) {
3637 char order_list[ 30 ];
3638 strcpy( order_list, "Mesh Order" );
3639 // count number of submesh ids
3641 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
3642 for ( ; idIt != theOrderIds.end(); idIt++ )
3643 nbIDs += (*idIt).size();
3644 // number of values = number of IDs +
3645 // number of lists (for separators) - 1
3646 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
3647 idIt = theOrderIds.begin();
3648 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
3649 const TListOfInt& idList = *idIt;
3650 if (idIt != theOrderIds.begin()) // not first list
3651 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
3652 // dump submesh ids from current list
3653 TListOfInt::const_iterator id_smId = idList.begin();
3654 for( ; id_smId != idList.end(); id_smId++ )
3655 smIDs[ i++ ] = *id_smId;
3658 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
3660 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
3661 aDataset->CreateOnDisk();
3662 aDataset->WriteOnDisk( smIDs );
3663 aDataset->CloseOnDisk();
3668 // groups root sub-branch
3669 SALOMEDS::SObject_wrap myGroupsBranch;
3670 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
3671 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
3673 char name_group[ 30 ];
3674 if ( i == GetNodeGroupsTag() )
3675 strcpy( name_group, "Groups of Nodes" );
3676 else if ( i == GetEdgeGroupsTag() )
3677 strcpy( name_group, "Groups of Edges" );
3678 else if ( i == GetFaceGroupsTag() )
3679 strcpy( name_group, "Groups of Faces" );
3680 else if ( i == GetVolumeGroupsTag() )
3681 strcpy( name_group, "Groups of Volumes" );
3682 else if ( i == Get0DElementsGroupsTag() )
3683 strcpy( name_group, "Groups of 0D Elements" );
3684 else if ( i == GetBallElementsGroupsTag() )
3685 strcpy( name_group, "Groups of Balls" );
3687 aGroup = new HDFgroup( name_group, aTopGroup );
3688 aGroup->CreateOnDisk();
3690 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
3691 for ( ; it->More(); it->Next() ) {
3692 SALOMEDS::SObject_wrap mySObject = it->Value();
3693 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
3694 if ( !CORBA::is_nil( aSubObject ) ) {
3695 SMESH_GroupBase_i* myGroupImpl =
3696 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
3699 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
3703 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
3704 int anId = myStudyContext->findId( string( objStr.in() ) );
3706 // For each group, create a dataset named "Group <group_persistent_id>"
3707 // and store the group's user name into it
3708 const char* grpName = aGrpBaseDS->GetStoreName();
3709 CORBA::String_var aUserName = myGroupImpl->GetName();
3710 aSize[ 0 ] = strlen( aUserName ) + 1;
3712 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
3713 aDataset->CreateOnDisk();
3714 aDataset->WriteOnDisk( aUserName );
3715 aDataset->CloseOnDisk();
3718 // For each group, create a dataset named "Group <group_persistent_id> Color"
3719 // and store the group's color into it
3720 char grpColorName[ 30 ];
3721 sprintf( grpColorName, "ColorGroup %d", anId );
3722 SALOMEDS::Color aColor = myGroupImpl->GetColor();
3724 anRGB[ 0 ] = aColor.R;
3725 anRGB[ 1 ] = aColor.G;
3726 anRGB[ 2 ] = aColor.B;
3728 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
3729 aDataset->CreateOnDisk();
3730 aDataset->WriteOnDisk( anRGB );
3731 aDataset->CloseOnDisk();
3733 // Pass SMESHDS_Group to MED writer
3734 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
3736 myWriter.AddGroup( aGrpDS );
3738 // write reference on a shape if exists
3739 SMESHDS_GroupOnGeom* aGeomGrp =
3740 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
3742 SALOMEDS::SObject_wrap mySubRef, myShape;
3743 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
3744 mySubRef->ReferencedObject( myShape.inout() ) &&
3745 !CORBA::is_nil( myShape->GetObject() ))
3747 CORBA::String_var myRefOnObject = myShape->GetID();
3748 if ( myRefOnObject.in()[0] ) {
3749 char aRefName[ 30 ];
3750 sprintf( aRefName, "Ref on shape %d", anId);
3751 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
3752 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
3753 aDataset->CreateOnDisk();
3754 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
3755 aDataset->CloseOnDisk();
3758 else // shape ref is invalid:
3760 // save a group on geometry as ordinary group
3761 myWriter.AddGroup( aGeomGrp );
3764 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
3765 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
3767 std::string str = aFilterGrp_i->FilterToString();
3768 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
3769 aSize[ 0 ] = str.length() + 1;
3770 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
3771 aDataset->CreateOnDisk();
3772 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
3773 aDataset->CloseOnDisk();
3777 aGroup->CloseOnDisk();
3781 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
3783 // Flush current mesh information into MED file
3786 // save info on nb of elements
3787 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
3789 // maybe a shape was deleted in the study
3790 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
3791 TopoDS_Shape nullShape;
3792 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
3795 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
3800 aGroup = new HDFgroup( "Submeshes", aTopGroup );
3801 aGroup->CreateOnDisk();
3803 // each element belongs to one or none submesh,
3804 // so for each node/element, we store a submesh ID
3806 // Store submesh IDs
3807 for ( int isNode = 0; isNode < 2; ++isNode )
3809 SMDS_ElemIteratorPtr eIt =
3810 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
3811 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
3814 std::vector<int> smIDs; smIDs.reserve( nbElems );
3815 while ( eIt->more() )
3816 if ( const SMDS_MeshElement* e = eIt->next())
3817 smIDs.push_back( e->getshapeId() );
3819 aSize[ 0 ] = nbElems;
3820 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3821 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3822 aDataset->CreateOnDisk();
3823 aDataset->WriteOnDisk( & smIDs[0] );
3824 aDataset->CloseOnDisk();
3827 aGroup->CloseOnDisk();
3829 // Store node positions on sub-shapes (SMDS_Position):
3830 // ----------------------------------------------------
3832 aGroup = new HDFgroup( "Node Positions", aTopGroup );
3833 aGroup->CreateOnDisk();
3835 // in aGroup, create 5 datasets to contain:
3836 // "Nodes on Edges" - ID of node on edge
3837 // "Edge positions" - U parameter on node on edge
3838 // "Nodes on Faces" - ID of node on face
3839 // "Face U positions" - U parameter of node on face
3840 // "Face V positions" - V parameter of node on face
3842 // Find out nb of nodes on edges and faces
3843 // Collect corresponding sub-meshes
3844 int nbEdgeNodes = 0, nbFaceNodes = 0;
3845 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
3846 // loop on SMESHDS_SubMesh'es
3847 while ( smIt->more() )
3849 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
3850 if ( aSubMesh->IsComplexSubmesh() )
3851 continue; // submesh containing other submeshs
3852 int nbNodes = aSubMesh->NbNodes();
3853 if ( nbNodes == 0 ) continue;
3855 int aShapeID = aSubMesh->GetID();
3856 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
3858 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
3859 // write only SMDS_FacePosition and SMDS_EdgePosition
3860 switch ( aShapeType ) {
3862 nbFaceNodes += nbNodes;
3863 aFaceSM.push_back( aSubMesh );
3866 nbEdgeNodes += nbNodes;
3867 aEdgeSM.push_back( aSubMesh );
3873 // Treat positions on edges or faces
3874 for ( int onFace = 0; onFace < 2; onFace++ )
3876 // Create arrays to store in datasets
3877 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
3878 if (!nbNodes) continue;
3879 int* aNodeIDs = new int [ nbNodes ];
3880 double* aUPos = new double [ nbNodes ];
3881 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
3884 // loop on sub-meshes
3885 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
3886 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
3887 for ( ; itSM != pListSM->end(); itSM++ )
3889 SMESHDS_SubMesh* aSubMesh = (*itSM);
3891 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
3892 // loop on nodes in aSubMesh
3893 while ( itNode->more() )
3896 const SMDS_MeshNode* node = itNode->next();
3897 aNodeIDs [ iNode ] = node->GetID();
3900 const SMDS_PositionPtr pos = node->GetPosition();
3901 if ( onFace ) { // on FACE
3902 SMDS_FacePositionPtr fPos = pos;
3904 aUPos[ iNode ] = fPos->GetUParameter();
3905 aVPos[ iNode ] = fPos->GetVParameter();
3912 SMDS_EdgePositionPtr ePos = pos;
3914 aUPos[ iNode ] = ePos->GetUParameter();
3920 } // loop on nodes in aSubMesh
3921 } // loop on sub-meshes
3926 aSize[ 0 ] = nbNodes;
3928 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
3929 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3930 aDataset->CreateOnDisk();
3931 aDataset->WriteOnDisk( aNodeIDs );
3932 aDataset->CloseOnDisk();
3935 aDSName = ( onFace ? "Face U positions" : "Edge positions");
3936 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
3937 aDataset->CreateOnDisk();
3938 aDataset->WriteOnDisk( aUPos );
3939 aDataset->CloseOnDisk();
3942 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
3943 aDataset->CreateOnDisk();
3944 aDataset->WriteOnDisk( aVPos );
3945 aDataset->CloseOnDisk();
3950 if ( aVPos ) delete [] aVPos;
3952 } // treat positions on edges or faces
3954 // close "Node Positions" group
3955 aGroup->CloseOnDisk();
3957 } // if ( there are submeshes in SMESHDS_Mesh )
3960 // close mesh HDF group
3961 aTopGroup->CloseOnDisk();
3969 aFile->CloseOnDisk();
3972 // Convert temporary files to stream
3973 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
3975 // Remove temporary files and directory
3977 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
3979 return aStreamFile._retn();
3982 //=============================================================================
3984 * SMESH_Gen_i::SaveASCII
3986 * Save SMESH module's data in ASCII format
3988 //=============================================================================
3990 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
3992 bool isMultiFile ) {
3993 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
3994 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
3995 return aStreamFile._retn();
3997 //after usual saving needs to encipher binary to text string
3998 //Any binary symbol will be represent as "|xx" () hexadecimal format number
3999 int size = aStreamFile.in().length();
4000 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
4001 for ( int i = 0; i < size; i++ )
4002 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
4004 buffer[size * 3] = '\0';
4006 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
4008 return anAsciiStreamFile._retn();
4011 //=============================================================================
4013 * SMESH_Gen_i::loadGeomData
4015 * Load GEOM module data
4017 //=============================================================================
4019 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
4021 if ( theCompRoot->_is_nil() )
4024 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
4025 aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
4028 //=============================================================================
4032 * Load SMESH module's data
4034 //=============================================================================
4036 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
4037 const SALOMEDS::TMPFile& theStream,
4041 //if (!myStudyContext)
4043 SALOMEDS::Study_var aStudy = getStudyServant();
4044 /* if( !theComponent->_is_nil() )
4046 if( !aStudy->FindComponent( "GEOM" )->_is_nil() )
4047 loadGeomData( aStudy->FindComponent( "GEOM" ) );
4050 // Get temporary files location
4051 TCollection_AsciiString tmpDir =
4052 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
4054 // Convert the stream into sequence of files to process
4055 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
4058 TCollection_AsciiString aStudyName( "" );
4059 if ( isMultiFile ) {
4060 CORBA::WString_var url = aStudy->URL();
4061 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
4063 // Set names of temporary files
4064 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
4065 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
4069 HDFdataset* aDataset;
4070 HDFgroup* aTopGroup;
4072 HDFgroup* aSubGroup;
4073 HDFgroup* aSubSubGroup;
4076 // ---> open HDF file
4077 aFile = new HDFfile( (char*) filename.ToCString() );
4079 aFile->OpenOnDisk( HDF_RDONLY );
4081 catch ( HDFexception ) {
4082 INFOS( "Load(): " << filename << " not found!" );
4086 TPythonDump pd; // prevent dump during loading
4088 // DriverMED_R_SMESHDS_Mesh myReader;
4089 // myReader.SetFile( meshfile.ToCString() );
4091 // For PAL13473 ("Repetitive mesh") implementation.
4092 // New dependencies between SMESH objects are established:
4093 // now hypotheses can refer to meshes, shapes and other hypotheses.
4094 // To keep data consistent, the following order of data restoration
4096 // 1. Create hypotheses
4097 // 2. Create all meshes
4098 // 3. Load hypotheses' data
4101 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
4102 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
4103 list< SMESH::Filter_var > filters;
4105 // get total number of top-level groups
4106 int aNbGroups = aFile->nInternalObjects();
4107 if ( aNbGroups > 0 ) {
4108 // --> in first turn we should read&create hypotheses
4109 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
4110 // open hypotheses root HDF group
4111 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4112 aTopGroup->OpenOnDisk();
4114 // get number of hypotheses
4115 int aNbObjects = aTopGroup->nInternalObjects();
4116 for ( int j = 0; j < aNbObjects; j++ ) {
4117 // try to identify hypothesis
4118 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4119 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4121 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
4122 // open hypothesis group
4123 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4124 aGroup->OpenOnDisk();
4126 // --> get hypothesis id
4127 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
4132 // get number of datasets
4133 int aNbSubObjects = aGroup->nInternalObjects();
4134 for ( int k = 0; k < aNbSubObjects; k++ ) {
4136 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4137 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4138 // --> get hypothesis name
4139 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4140 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4141 aDataset->OpenOnDisk();
4142 size = aDataset->GetSize();
4143 char* hypname_str = new char[ size ];
4144 aDataset->ReadFromDisk( hypname_str );
4145 hypname = string( hypname_str );
4146 delete [] hypname_str;
4147 aDataset->CloseOnDisk();
4149 // --> get hypothesis plugin library name
4150 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4151 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4152 aDataset->OpenOnDisk();
4153 size = aDataset->GetSize();
4154 char* libname_str = new char[ size ];
4155 aDataset->ReadFromDisk( libname_str );
4156 if(MYDEBUG) SCRUTE( libname_str );
4157 libname = string( libname_str );
4158 delete [] libname_str;
4159 aDataset->CloseOnDisk();
4161 // --> get hypothesis data
4162 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4163 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4164 aDataset->OpenOnDisk();
4165 size = aDataset->GetSize();
4166 char* hypdata_str = new char[ size ];
4167 aDataset->ReadFromDisk( hypdata_str );
4168 hypdata = string( hypdata_str );
4169 delete [] hypdata_str;
4170 aDataset->CloseOnDisk();
4173 // close hypothesis HDF group
4174 aGroup->CloseOnDisk();
4176 // --> restore hypothesis from data
4177 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4178 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
4179 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4180 SMESH::SMESH_Hypothesis_var myHyp;
4182 try { // protect persistence mechanism against exceptions
4183 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4186 INFOS( "Exception during hypothesis creation" );
4189 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4191 // myImpl->LoadFrom( hypdata.c_str() );
4192 hypDataList.push_back( make_pair( myImpl, hypdata ));
4193 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4194 int newId = myStudyContext->findId( iorString.in() );
4195 myStudyContext->mapOldToNew( id, newId );
4198 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4202 // close hypotheses root HDF group
4203 aTopGroup->CloseOnDisk();
4207 // --> then we should read&create algorithms
4208 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
4209 // open algorithms root HDF group
4210 aTopGroup = new HDFgroup( "Algorithms", aFile );
4211 aTopGroup->OpenOnDisk();
4213 // get number of algorithms
4214 int aNbObjects = aTopGroup->nInternalObjects();
4215 for ( int j = 0; j < aNbObjects; j++ ) {
4216 // try to identify algorithm
4217 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4218 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4220 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
4221 // open algorithm group
4222 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4223 aGroup->OpenOnDisk();
4225 // --> get algorithm id
4226 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
4231 // get number of datasets
4232 int aNbSubObjects = aGroup->nInternalObjects();
4233 for ( int k = 0; k < aNbSubObjects; k++ ) {
4235 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4236 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4237 // --> get algorithm name
4238 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4239 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4240 aDataset->OpenOnDisk();
4241 size = aDataset->GetSize();
4242 char* hypname_str = new char[ size ];
4243 aDataset->ReadFromDisk( hypname_str );
4244 hypname = string( hypname_str );
4245 delete [] hypname_str;
4246 aDataset->CloseOnDisk();
4248 // --> get algorithm plugin library name
4249 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4250 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4251 aDataset->OpenOnDisk();
4252 size = aDataset->GetSize();
4253 char* libname_str = new char[ size ];
4254 aDataset->ReadFromDisk( libname_str );
4255 if(MYDEBUG) SCRUTE( libname_str );
4256 libname = string( libname_str );
4257 delete [] libname_str;
4258 aDataset->CloseOnDisk();
4260 // --> get algorithm data
4261 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4262 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4263 aDataset->OpenOnDisk();
4264 size = aDataset->GetSize();
4265 char* hypdata_str = new char[ size ];
4266 aDataset->ReadFromDisk( hypdata_str );
4267 if(MYDEBUG) SCRUTE( hypdata_str );
4268 hypdata = string( hypdata_str );
4269 delete [] hypdata_str;
4270 aDataset->CloseOnDisk();
4273 // close algorithm HDF group
4274 aGroup->CloseOnDisk();
4276 // --> restore algorithm from data
4277 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4278 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
4279 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4280 SMESH::SMESH_Hypothesis_var myHyp;
4282 try { // protect persistence mechanism against exceptions
4283 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4286 INFOS( "Exception during hypothesis creation" );
4289 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4291 //myImpl->LoadFrom( hypdata.c_str() );
4292 hypDataList.push_back( make_pair( myImpl, hypdata ));
4293 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4294 int newId = myStudyContext->findId( iorString.in() );
4295 myStudyContext->mapOldToNew( id, newId );
4298 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4302 // close algorithms root HDF group
4303 aTopGroup->CloseOnDisk();
4307 // --> the rest groups should be meshes
4308 for ( int i = 0; i < aNbGroups; i++ ) {
4309 // identify next group
4310 char meshName[ HDF_NAME_MAX_LEN+1 ];
4311 aFile->InternalObjectIndentify( i, meshName );
4313 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
4315 int id = atoi( string( meshName ).substr( 4 ).c_str() );
4319 // open mesh HDF group
4320 aTopGroup = new HDFgroup( meshName, aFile );
4321 aTopGroup->OpenOnDisk();
4323 // get number of child HDF objects
4324 int aNbObjects = aTopGroup->nInternalObjects();
4325 if ( aNbObjects > 0 ) {
4327 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
4328 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
4329 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
4330 if ( !myNewMeshImpl )
4332 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
4334 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
4335 int newId = myStudyContext->findId( iorString.in() );
4336 myStudyContext->mapOldToNew( id, newId );
4339 // try to read and set auto color flag
4340 char aMeshAutoColorName[ 30 ];
4341 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
4342 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
4344 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
4345 aDataset->OpenOnDisk();
4346 size = aDataset->GetSize();
4347 int* anAutoColor = new int[ size ];
4348 aDataset->ReadFromDisk( anAutoColor );
4349 aDataset->CloseOnDisk();
4350 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
4351 delete [] anAutoColor;
4354 // try to read and set reference to shape
4355 GEOM::GEOM_Object_var aShapeObject;
4356 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
4357 // load mesh "Ref on shape" - it's an entry to SObject
4358 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
4359 aDataset->OpenOnDisk();
4360 size = aDataset->GetSize();
4361 char* refFromFile = new char[ size ];
4362 aDataset->ReadFromDisk( refFromFile );
4363 aDataset->CloseOnDisk();
4364 if ( strlen( refFromFile ) > 0 ) {
4365 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
4367 // Make sure GEOM data are loaded first
4368 //loadGeomData( shapeSO->GetFatherComponent() );
4370 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4371 if ( !CORBA::is_nil( shapeObject ) ) {
4372 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4373 if ( !aShapeObject->_is_nil() )
4374 myNewMeshImpl->SetShape( aShapeObject );
4377 delete [] refFromFile;
4380 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
4381 if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
4383 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
4384 aDataset->OpenOnDisk();
4385 size = aDataset->GetSize();
4386 int* meshPersistentId = new int[ size ];
4387 aDataset->ReadFromDisk( meshPersistentId );
4388 aDataset->CloseOnDisk();
4389 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
4390 delete [] meshPersistentId;
4393 // Restore file info
4394 if ( aTopGroup->ExistInternalObject( "file info" ))
4396 aDataset = new HDFdataset( "file info", aTopGroup );
4397 aDataset->OpenOnDisk();
4398 size = aDataset->GetSize();
4399 std::string info( size, ' ');
4400 aDataset->ReadFromDisk( (char*) info.data() );
4401 aDataset->CloseOnDisk();
4402 myNewMeshImpl->FileInfoFromString( info );
4408 // As all object that can be referred by hypothesis are created,
4409 // we can restore hypothesis data
4411 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
4412 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4414 SMESH_Hypothesis_i* hyp = hyp_data->first;
4415 string & data = hyp_data->second;
4416 hyp->LoadFrom( data.c_str() );
4419 // Restore the rest mesh data
4421 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
4422 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4424 aTopGroup = meshi_group->second;
4425 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4426 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4427 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4429 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
4430 bool hasData = false;
4433 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
4434 int newId = myStudyContext->findId( iorString.in() );
4435 int id = myStudyContext->getOldId( newId );
4437 // try to find mesh data dataset
4438 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
4439 // load mesh "has data" flag
4440 aDataset = new HDFdataset( "Has data", aTopGroup );
4441 aDataset->OpenOnDisk();
4442 size = aDataset->GetSize();
4443 char* strHasData = new char[ size ];
4444 aDataset->ReadFromDisk( strHasData );
4445 aDataset->CloseOnDisk();
4446 if ( strcmp( strHasData, "1") == 0 ) {
4447 // read mesh data from MED file
4448 // myReader.SetMesh( mySMESHDSMesh );
4449 // myReader.SetMeshId( id );
4450 // myReader.Perform();
4453 delete [] strHasData;
4456 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
4457 // nodes and elements are not yet put into sub-meshes)
4458 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4459 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4460 aGroup->OpenOnDisk();
4461 // get number of applied algorithms
4462 int aNbSubObjects = aGroup->nInternalObjects();
4463 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
4464 for ( int j = 0; j < aNbSubObjects; j++ ) {
4465 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4466 aGroup->InternalObjectIndentify( j, name_dataset );
4467 // check if it is an algorithm
4468 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
4469 aDataset = new HDFdataset( name_dataset, aGroup );
4470 aDataset->OpenOnDisk();
4471 size = aDataset->GetSize();
4472 char* refFromFile = new char[ size ];
4473 aDataset->ReadFromDisk( refFromFile );
4474 aDataset->CloseOnDisk();
4475 // san - it is impossible to recover applied algorithms using their entries within Load() method
4476 //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
4477 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4478 int id = atoi( refFromFile );
4479 delete [] refFromFile;
4480 string anIOR = myStudyContext->getIORbyOldId( id );
4481 if ( !anIOR.empty() ) {
4482 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4483 if ( !CORBA::is_nil( hypObject ) ) {
4484 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4485 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4486 || !myNewMeshImpl->HasShapeToMesh()) )
4487 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4492 aGroup->CloseOnDisk();
4495 // try to get applied hypotheses
4496 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4497 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4498 aGroup->OpenOnDisk();
4499 // get number of applied hypotheses
4500 int aNbSubObjects = aGroup->nInternalObjects();
4501 for ( int j = 0; j < aNbSubObjects; j++ ) {
4502 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4503 aGroup->InternalObjectIndentify( j, name_dataset );
4504 // check if it is a hypothesis
4505 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4506 aDataset = new HDFdataset( name_dataset, aGroup );
4507 aDataset->OpenOnDisk();
4508 size = aDataset->GetSize();
4509 char* refFromFile = new char[ size ];
4510 aDataset->ReadFromDisk( refFromFile );
4511 aDataset->CloseOnDisk();
4512 // san - it is impossible to recover applied hypotheses using their entries within Load() method
4513 //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
4514 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4515 int id = atoi( refFromFile );
4516 delete [] refFromFile;
4517 string anIOR = myStudyContext->getIORbyOldId( id );
4518 if ( !anIOR.empty() ) {
4519 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4520 if ( !CORBA::is_nil( hypObject ) ) {
4521 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4522 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4523 || !myNewMeshImpl->HasShapeToMesh()) )
4524 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4529 aGroup->CloseOnDisk();
4532 // --> try to find SUB-MESHES containers for each type of submesh
4533 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
4534 const char* name_meshgroup = 0;
4535 if ( j == GetSubMeshOnVertexTag() )
4536 name_meshgroup = "SubMeshes On Vertex";
4537 else if ( j == GetSubMeshOnEdgeTag() )
4538 name_meshgroup = "SubMeshes On Edge";
4539 else if ( j == GetSubMeshOnWireTag() )
4540 name_meshgroup = "SubMeshes On Wire";
4541 else if ( j == GetSubMeshOnFaceTag() )
4542 name_meshgroup = "SubMeshes On Face";
4543 else if ( j == GetSubMeshOnShellTag() )
4544 name_meshgroup = "SubMeshes On Shell";
4545 else if ( j == GetSubMeshOnSolidTag() )
4546 name_meshgroup = "SubMeshes On Solid";
4547 else if ( j == GetSubMeshOnCompoundTag() )
4548 name_meshgroup = "SubMeshes On Compound";
4550 // try to get submeshes container HDF group
4551 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
4552 // open submeshes containers HDF group
4553 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4554 aGroup->OpenOnDisk();
4556 // get number of submeshes
4557 int aNbSubMeshes = aGroup->nInternalObjects();
4558 for ( int k = 0; k < aNbSubMeshes; k++ ) {
4560 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
4561 aGroup->InternalObjectIndentify( k, name_submeshgroup );
4562 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
4563 // --> get submesh id
4564 int subid = atoi( name_submeshgroup + 7 );
4567 // open submesh HDF group
4568 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
4569 aSubGroup->OpenOnDisk();
4571 // try to read and set reference to subshape
4572 GEOM::GEOM_Object_var aSubShapeObject;
4573 SMESH::SMESH_subMesh_var aSubMesh;
4575 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
4576 // load submesh "Ref on shape" - it's an entry to SObject
4577 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
4578 aDataset->OpenOnDisk();
4579 size = aDataset->GetSize();
4580 char* refFromFile = new char[ size ];
4581 aDataset->ReadFromDisk( refFromFile );
4582 aDataset->CloseOnDisk();
4583 if ( strlen( refFromFile ) > 0 ) {
4584 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
4585 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
4586 if ( !CORBA::is_nil( subShapeObject ) ) {
4587 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
4588 if ( !aSubShapeObject->_is_nil() )
4589 aSubMesh = SMESH::SMESH_subMesh::_duplicate
4590 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
4591 if ( aSubMesh->_is_nil() )
4593 string iorSubString = GetORB()->object_to_string( aSubMesh );
4594 int newSubId = myStudyContext->findId( iorSubString );
4595 myStudyContext->mapOldToNew( subid, newSubId );
4598 delete [] refFromFile;
4601 if ( aSubMesh->_is_nil() )
4604 // try to get applied algorithms
4605 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4606 // open "applied algorithms" HDF group
4607 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4608 aSubSubGroup->OpenOnDisk();
4609 // get number of applied algorithms
4610 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4611 for ( int l = 0; l < aNbSubObjects; l++ ) {
4612 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4613 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4614 // check if it is an algorithm
4615 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
4616 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4617 aDataset->OpenOnDisk();
4618 size = aDataset->GetSize();
4619 char* refFromFile = new char[ size ];
4620 aDataset->ReadFromDisk( refFromFile );
4621 aDataset->CloseOnDisk();
4623 int id = atoi( refFromFile );
4624 string anIOR = myStudyContext->getIORbyOldId( id );
4625 if ( !anIOR.empty() ) {
4626 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4627 if ( !CORBA::is_nil( hypObject ) ) {
4628 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4629 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4630 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4633 delete [] refFromFile;
4636 // close "applied algorithms" HDF group
4637 aSubSubGroup->CloseOnDisk();
4640 // try to get applied hypotheses
4641 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4642 // open "applied hypotheses" HDF group
4643 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4644 aSubSubGroup->OpenOnDisk();
4645 // get number of applied hypotheses
4646 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4647 for ( int l = 0; l < aNbSubObjects; l++ ) {
4648 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4649 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4650 // check if it is a hypothesis
4651 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4652 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4653 aDataset->OpenOnDisk();
4654 size = aDataset->GetSize();
4655 char* refFromFile = new char[ size ];
4656 aDataset->ReadFromDisk( refFromFile );
4657 aDataset->CloseOnDisk();
4659 int id = atoi( refFromFile );
4660 string anIOR = myStudyContext->getIORbyOldId( id );
4661 if ( !anIOR.empty() ) {
4662 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4663 if ( !CORBA::is_nil( hypObject ) ) {
4664 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4665 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4666 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4669 delete [] refFromFile;
4672 // close "APPLIED HYPOTHESES" hdf group
4673 aSubSubGroup->CloseOnDisk();
4676 // close SUB-MESH hdf group
4677 aSubGroup->CloseOnDisk();
4680 // close SUB-MESHES containers hdf group
4681 aGroup->CloseOnDisk();
4685 // try to get GROUPS
4686 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
4687 char name_group[ 30 ];
4688 if ( ii == GetNodeGroupsTag() )
4689 strcpy( name_group, "Groups of Nodes" );
4690 else if ( ii == GetEdgeGroupsTag() )
4691 strcpy( name_group, "Groups of Edges" );
4692 else if ( ii == GetFaceGroupsTag() )
4693 strcpy( name_group, "Groups of Faces" );
4694 else if ( ii == GetVolumeGroupsTag() )
4695 strcpy( name_group, "Groups of Volumes" );
4696 else if ( ii == Get0DElementsGroupsTag() )
4697 strcpy( name_group, "Groups of 0D Elements" );
4698 else if ( ii == GetBallElementsGroupsTag() )
4699 strcpy( name_group, "Groups of Balls" );
4701 if ( aTopGroup->ExistInternalObject( name_group ) ) {
4702 aGroup = new HDFgroup( name_group, aTopGroup );
4703 aGroup->OpenOnDisk();
4704 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
4705 // within aGroup->ExistInternalObject( name )
4706 std::vector< std::string > subNames;
4707 TColStd_MapOfAsciiString mapOfNames;
4708 aGroup->GetAllObjects( subNames );
4709 for ( size_t iN = 0; iN < subNames.size(); ++iN )
4710 mapOfNames.Add( subNames[ iN ].c_str() );
4712 for ( size_t j = 0; j < subNames.size(); j++ ) {
4713 const std::string& name_dataset = subNames[ j ];
4714 // check if it is a group
4715 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
4717 int subid = atoi( name_dataset.substr( 5 ).c_str() );
4720 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
4721 aDataset->OpenOnDisk();
4723 // Retrieve actual group name
4724 size = aDataset->GetSize();
4725 char* nameFromFile = new char[ size ];
4726 aDataset->ReadFromDisk( nameFromFile );
4727 aDataset->CloseOnDisk();
4729 // Try to find a shape reference
4730 TopoDS_Shape aShape;
4731 char aRefName[ 30 ];
4732 sprintf( aRefName, "Ref on shape %d", subid);
4733 if ( mapOfNames.Contains( aRefName ))
4735 // load mesh "Ref on shape" - it's an entry to SObject
4736 aDataset = new HDFdataset( aRefName, aGroup );
4737 aDataset->OpenOnDisk();
4738 size = aDataset->GetSize();
4739 char* refFromFile = new char[ size ];
4740 aDataset->ReadFromDisk( refFromFile );
4741 aDataset->CloseOnDisk();
4742 if ( strlen( refFromFile ) > 0 ) {
4743 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
4744 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4745 if ( !CORBA::is_nil( shapeObject ) ) {
4746 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4747 if ( !aShapeObject->_is_nil() )
4748 aShape = GeomObjectToShape( aShapeObject );
4751 delete [] refFromFile;
4753 // Try to read a filter of SMESH_GroupOnFilter
4754 SMESH::Filter_var filter;
4755 SMESH_PredicatePtr predicate;
4756 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
4757 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
4759 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
4760 aDataset->OpenOnDisk();
4761 size = aDataset->GetSize();
4762 char* persistStr = new char[ size ];
4763 aDataset->ReadFromDisk( persistStr );
4764 aDataset->CloseOnDisk();
4765 if ( strlen( persistStr ) > 0 ) {
4766 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
4767 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
4768 filters.push_back( filter );
4770 delete [] persistStr;
4773 // Create group servant
4774 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
4775 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
4776 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape, predicate ) );
4777 delete [] nameFromFile;
4778 // Obtain a SMESHDS_Group object
4779 if ( aNewGroup->_is_nil() )
4782 string iorSubString = GetORB()->object_to_string( aNewGroup );
4783 int newSubId = myStudyContext->findId( iorSubString );
4784 myStudyContext->mapOldToNew( subid, newSubId );
4786 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
4790 if ( SMESH_GroupOnFilter_i* aFilterGroup =
4791 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
4793 aFilterGroup->SetFilter( filter );
4794 filter->UnRegister();
4796 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
4797 if ( !aGroupBaseDS )
4800 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
4803 // Read color of the group
4804 char aGroupColorName[ 30 ];
4805 sprintf( aGroupColorName, "ColorGroup %d", subid);
4806 if ( mapOfNames.Contains( aGroupColorName ))
4808 aDataset = new HDFdataset( aGroupColorName, aGroup );
4809 aDataset->OpenOnDisk();
4810 size = aDataset->GetSize();
4811 double* anRGB = new double[ size ];
4812 aDataset->ReadFromDisk( anRGB );
4813 aDataset->CloseOnDisk();
4814 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
4815 aGroupBaseDS->SetColor( aColor );
4820 aGroup->CloseOnDisk();
4824 // instead of reading mesh data, we read only brief information of all
4825 // objects: mesh, groups, sub-meshes (issue 0021208 )
4828 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, id,
4829 meshfile.ToCString(), filename.ToCString(),
4833 // read Sub-Mesh ORDER if any
4834 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
4835 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
4836 aDataset->OpenOnDisk();
4837 size = aDataset->GetSize();
4838 int* smIDs = new int[ size ];
4839 aDataset->ReadFromDisk( smIDs );
4840 aDataset->CloseOnDisk();
4841 TListOfListOfInt anOrderIds;
4842 anOrderIds.push_back( TListOfInt() );
4843 for ( int i = 0; i < size; i++ )
4844 if ( smIDs[ i ] < 0 ) // is separator
4845 anOrderIds.push_back( TListOfInt() );
4847 anOrderIds.back().push_back(smIDs[ i ]);
4849 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
4854 // update hyps needing full mesh data restored (issue 20918)
4855 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4857 SMESH_Hypothesis_i* hyp = hyp_data->first;
4858 hyp->UpdateAsMeshesRestored();
4861 // notify algos on completed restoration to set sub-mesh event listeners
4862 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4864 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4865 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4867 TopoDS_Shape myLocShape;
4868 if(myLocMesh.HasShapeToMesh())
4869 myLocShape = myLocMesh.GetShapeToMesh();
4871 myLocShape = SMESH_Mesh::PseudoShape();
4873 myLocMesh.GetSubMesh(myLocShape)->
4874 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
4877 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
4878 list< SMESH::Filter_var >::iterator f = filters.begin();
4879 for ( ; f != filters.end(); ++f )
4880 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
4881 fi->FindBaseObjects();
4886 aTopGroup->CloseOnDisk();
4889 aFile->CloseOnDisk();
4892 // Remove temporary files created from the stream
4895 SMESH_File meshFile( meshfile.ToCString() );
4896 if ( !meshFile ) // no meshfile exists
4898 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
4902 Engines::Container_var container = GetContainerRef();
4903 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
4905 container_i->registerTemporaryFile( filename.ToCString() );
4906 container_i->registerTemporaryFile( meshfile.ToCString() );
4907 container_i->registerTemporaryFile( tmpDir.ToCString() );
4911 pd << ""; // prevent optimizing pd out
4913 // creation of tree nodes for all data objects in the study
4914 // to support tree representation customization and drag-n-drop:
4915 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
4916 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
4917 useCaseBuilder->SetRootCurrent();
4918 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
4919 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
4920 for (it->InitEx(true); it->More(); it->Next()) {
4921 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
4928 //=============================================================================
4930 * SMESH_Gen_i::LoadASCII
4932 * Load SMESH module's data in ASCII format
4934 //=============================================================================
4936 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
4937 const SALOMEDS::TMPFile& theStream,
4939 bool isMultiFile ) {
4940 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
4941 return Load( theComponent, theStream, theURL, isMultiFile );
4943 //before call main ::Load method it's need for decipher text format to
4944 //binary ( "|xx" => x' )
4945 int size = theStream.length();
4946 if ( int((size / 3 )*3) != size ) //error size of buffer
4949 int real_size = int(size / 3);
4951 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
4954 unsigned int c = -1;
4955 for ( int i = 0; i < real_size; i++ )
4957 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
4958 sscanf( tmp, "%x", &c );
4959 sprintf( (char*)&(buffer[i]), "%c", (char)c );
4962 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
4964 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
4967 //=============================================================================
4969 * SMESH_Gen_i::Close
4971 * Clears study-connected data when it is closed
4973 //=============================================================================
4975 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
4977 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
4979 // Clear study contexts data
4980 myStudyContext->Clear();
4982 // remove the tmp files meshes are loaded from
4983 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
4985 // Clean trace of API methods calls
4991 //=============================================================================
4993 * SMESH_Gen_i::ComponentDataType
4995 * Get component data type
4997 //=============================================================================
4999 char* SMESH_Gen_i::ComponentDataType()
5001 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
5002 return CORBA::string_dup( "SMESH" );
5006 //=============================================================================
5008 * SMESH_Gen_i::IORToLocalPersistentID
5010 * Transform data from transient form to persistent
5012 //=============================================================================
5014 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
5015 const char* IORString,
5016 CORBA::Boolean /*isMultiFile*/,
5017 CORBA::Boolean /*isASCII*/ )
5019 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
5021 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
5022 int anId = myStudyContext->findId( IORString );
5024 if(MYDEBUG) MESSAGE( "VSR " << anId )
5026 sprintf( strId, "%d", anId );
5027 return CORBA::string_dup( strId );
5030 return CORBA::string_dup( "" );
5033 //=============================================================================
5035 * SMESH_Gen_i::LocalPersistentIDToIOR
5037 * Transform data from persistent form to transient
5039 //=============================================================================
5041 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
5042 const char* aLocalPersistentID,
5043 CORBA::Boolean /*isMultiFile*/,
5044 CORBA::Boolean /*isASCII*/ )
5046 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
5048 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
5049 int anId = atoi( aLocalPersistentID );
5050 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
5052 return CORBA::string_dup( "" );
5055 //=======================================================================
5056 //function : RegisterObject
5058 //=======================================================================
5060 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
5062 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5063 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
5064 return myStudyContext->addObject( string( iorString.in() ) );
5069 //================================================================================
5071 * \brief Return id of registered object
5072 * \param theObject - the Object
5073 * \retval int - Object id
5075 //================================================================================
5077 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
5079 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5080 string iorString = GetORB()->object_to_string( theObject );
5081 return myStudyContext->findId( iorString );
5086 //=============================================================================
5088 * SMESH_Gen_i::SetName
5090 * Set a new object name
5092 //=============================================================================
5093 void SMESH_Gen_i::SetName(const char* theIOR,
5094 const char* theName)
5096 if ( theIOR && strcmp( theIOR, "" ) ) {
5097 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
5098 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
5099 if ( !aSO->_is_nil() ) {
5100 SetName( aSO, theName );
5105 // Version information
5106 char* SMESH_Gen_i::getVersion()
5108 #if SMESH_DEVELOPMENT
5109 return CORBA::string_dup(SMESH_VERSION_STR"dev");
5111 return CORBA::string_dup(SMESH_VERSION_STR);
5115 //=================================================================================
5116 // function : Move()
5117 // purpose : Moves objects to the specified position.
5118 // Is used in the drag-n-drop functionality.
5119 //=================================================================================
5120 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
5121 SALOMEDS::SObject_ptr where,
5124 if ( CORBA::is_nil( where ) ) return;
5126 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
5127 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
5128 SALOMEDS::SComponent_var father = where->GetFatherComponent();
5129 std::string dataType = father->ComponentDataType();
5130 if ( dataType != "SMESH" ) return; // not a SMESH component
5132 SALOMEDS::SObject_var objAfter;
5133 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
5134 // insert at given row -> find insertion position
5135 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
5137 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
5138 if ( i == row && useCaseIt->More() ) {
5139 objAfter = useCaseIt->Value();
5143 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
5144 SALOMEDS::SObject_var sobj = what[i];
5145 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
5146 // insert the object to the use case tree
5147 if ( !CORBA::is_nil( objAfter ) )
5148 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
5150 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
5153 //================================================================================
5155 * \brief Returns true if algorithm can be used to mesh a given geometry
5156 * \param [in] theAlgoType - the algorithm type
5157 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
5158 * \param [in] theGeomObject - the geometry to mesh
5159 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
5160 * else, returns \c True if at least one shape is meshable
5161 * \return CORBA::Boolean - can or can't
5163 //================================================================================
5165 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
5166 const char* theLibName,
5167 GEOM::GEOM_Object_ptr theGeomObject,
5168 CORBA::Boolean toCheckAll)
5172 std::string aPlatformLibName;
5173 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
5174 GenericHypothesisCreator_i* aCreator =
5175 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
5178 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
5179 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll );
5186 SMESH_CATCH( SMESH::doNothing );
5189 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
5194 //=================================================================================
5195 // function : GetInsideSphere
5196 // purpose : Collect indices of elements, which are located inside the sphere
5197 //=================================================================================
5198 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
5199 SMESH::ElementType theElemType,
5205 SMESH::long_array_var aResult = new SMESH::long_array();
5206 if ( meshPart->_is_nil() )
5207 return aResult._retn();
5209 // 1. Create geometrical object
5210 gp_Pnt aP( theX, theY, theZ );
5211 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
5213 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5215 if ( lst.size() > 0 ) {
5216 aResult->length( lst.size() );
5217 for ( size_t i = 0; i < lst.size(); i++ ) {
5218 aResult[i] = lst[i];
5221 return aResult._retn();
5224 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
5225 SMESH::ElementType theElemType,
5226 CORBA::Double theX1,
5227 CORBA::Double theY1,
5228 CORBA::Double theZ1,
5229 CORBA::Double theX2,
5230 CORBA::Double theY2,
5231 CORBA::Double theZ2) {
5232 SMESH::long_array_var aResult = new SMESH::long_array();
5233 if( meshPart->_is_nil() )
5234 return aResult._retn();
5236 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
5238 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5240 if( lst.size() > 0 ) {
5241 aResult->length( lst.size() );
5242 for ( size_t i = 0; i < lst.size(); i++ ) {
5243 aResult[i] = lst[i];
5246 return aResult._retn();
5249 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
5250 SMESH::ElementType theElemType,
5254 CORBA::Double theDX,
5255 CORBA::Double theDY,
5256 CORBA::Double theDZ,
5258 CORBA::Double theR ){
5259 SMESH::long_array_var aResult = new SMESH::long_array();
5260 if( meshPart->_is_nil() )
5261 return aResult._retn();
5263 gp_Pnt aP( theX, theY, theZ );
5264 gp_Vec aV( theDX, theDY, theDZ );
5265 gp_Ax2 anAxes (aP, aV);
5267 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
5269 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5271 if( lst.size() > 0 ) {
5272 aResult->length( lst.size() );
5273 for ( size_t i = 0; i < lst.size(); i++ ) {
5274 aResult[i] = lst[i];
5277 return aResult._retn();
5280 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5281 SMESH::ElementType theElemType,
5282 GEOM::GEOM_Object_ptr theGeom,
5283 CORBA::Double theTolerance ) {
5284 SMESH::long_array_var aResult = new SMESH::long_array();
5285 if( meshPart->_is_nil() || theGeom->_is_nil() )
5286 return aResult._retn();
5288 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
5290 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
5292 if( lst.size() > 0 ) {
5293 aResult->length( lst.size() );
5294 for ( size_t i = 0; i < lst.size(); i++ ) {
5295 aResult[i] = lst[i];
5298 return aResult._retn();
5303 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5304 SMESH::ElementType theElemType,
5305 TopoDS_Shape& aShape,
5306 double* theTolerance) {
5308 std::vector<long> res;
5309 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
5311 if ( mesh->_is_nil() )
5314 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
5318 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
5323 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
5324 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
5325 anElementsOnShape->SetAllNodes( true );
5326 anElementsOnShape->SetMesh( meshDS );
5327 anElementsOnShape->SetShape( aShape, aType );
5330 anElementsOnShape->SetTolerance(*theTolerance);
5332 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
5333 if ( !msource->_is_nil() ) { // Mesh case
5334 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
5336 while ( elemIt->more() ) {
5337 const SMDS_MeshElement* anElem = elemIt->next();
5338 long anId = anElem->GetID();
5339 if ( anElementsOnShape->IsSatisfy( anId ) )
5340 res.push_back( anId );
5344 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
5345 if ( !gsource->_is_nil() ) {
5346 if(theElemType == SMESH::NODE) {
5347 SMESH::long_array_var nodes = gsource->GetNodeIDs();
5348 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
5349 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
5350 long anId = node->GetID();
5351 if ( anElementsOnShape->IsSatisfy( anId ) )
5352 res.push_back( anId );
5355 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
5356 SMESH::long_array_var elems = gsource->GetListOfID();
5357 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
5358 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
5359 long anId = elem->GetID();
5360 if ( anElementsOnShape->IsSatisfy( anId ) )
5361 res.push_back( anId );
5366 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
5367 if ( !smsource->_is_nil() ) {
5368 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
5369 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
5370 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
5372 long anId = elem->GetID();
5373 if ( anElementsOnShape->IsSatisfy( anId ) )
5374 res.push_back( anId );
5382 //=============================================================================
5384 * SMESHEngine_factory
5386 * C factory, accessible with dlsym, after dlopen
5388 //=============================================================================
5392 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
5393 PortableServer::POA_ptr poa,
5394 PortableServer::ObjectId* contId,
5395 const char* instanceName,
5396 const char* interfaceName )
5398 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
5399 if(MYDEBUG) SCRUTE(interfaceName);
5400 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
5401 return aSMESHGen->getId() ;