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 ...");
442 LibHandle libHandle = LoadLib( aPlatformLibName.c_str() );
445 // report any error, if occurred
447 const char* anError = dlerror();
448 throw(SALOME_Exception(anError));
450 throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
454 // get method, returning hypothesis creator
455 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
456 GetHypothesisCreator procHandle =
457 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
460 throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
461 UnLoadLib(libHandle);
464 // get hypothesis creator
465 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
466 aCreator = procHandle(theHypName);
469 throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
471 // map hypothesis creator to a hypothesis name
472 myHypCreatorMap[string(theHypName)] = aCreator;
477 return myHypCreatorMap[string(theHypName)];
480 catch (SALOME_Exception& S_ex)
482 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
487 //=============================================================================
489 * SMESH_Gen_i::createHypothesis
491 * Create hypothesis of given type
493 //=============================================================================
494 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
495 const char* theLibName)
497 SMESH_Hypothesis_i* myHypothesis_i = 0;
498 SMESH::SMESH_Hypothesis_var hypothesis_i;
499 std::string aPlatformLibName;
500 GenericHypothesisCreator_i* aCreator =
501 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
503 // create a new hypothesis object, store its ref. in studyContext
504 myHypothesis_i = aCreator->Create(myPoa, &myGen);
507 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
508 CORBA::String_var hypName = myHypothesis_i->GetName();
509 myHypCreatorMap[ hypName.in() ] = aCreator;
511 // activate the CORBA servant of hypothesis
512 hypothesis_i = myHypothesis_i->_this();
513 int nextId = RegisterObject( hypothesis_i );
514 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
515 else { nextId = 0; } // avoid "unused variable" warning in release mode
517 return hypothesis_i._retn();
520 //=============================================================================
522 * SMESH_Gen_i::createMesh
524 * Create empty mesh on shape
526 //=============================================================================
527 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
528 throw ( SALOME::SALOME_Exception )
530 Unexpect aCatch(SALOME_SalomeException);
531 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
533 // Get or create the GEOM_Client instance
535 // create a new mesh object servant, store it in a map in study context
536 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
537 // create a new mesh object
538 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
539 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
541 // activate the CORBA servant of Mesh
542 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
543 int nextId = RegisterObject( mesh );
544 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
545 else { nextId = 0; } // avoid "unused variable" warning in release mode
548 catch (SALOME_Exception& S_ex) {
549 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
551 return SMESH::SMESH_Mesh::_nil();
554 //=============================================================================
556 * SMESH_Gen_i::GetShapeReader
560 //=============================================================================
561 GEOM_Client* SMESH_Gen_i::GetShapeReader()
563 // create shape reader if necessary
564 if ( !myShapeReader )
565 myShapeReader = new GEOM_Client(GetContainerRef());
566 ASSERT( myShapeReader );
567 return myShapeReader;
570 //=============================================================================
572 * SMESH_Gen_i::SetGeomEngine
574 * Set GEOM::GEOM_Gen reference
576 //=============================================================================
577 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
578 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
580 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
581 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
582 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
586 //=============================================================================
588 * SMESH_Gen_i::SetEmbeddedMode
592 //=============================================================================
594 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
596 myIsEmbeddedMode = theMode;
598 if ( !myIsEmbeddedMode ) {
599 //PAL10867: disable signals catching with "noexcepthandler" option
600 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
601 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
606 char* envDisableFPE = getenv("DISABLE_FPE");
607 if (envDisableFPE && atoi(envDisableFPE))
612 OSD::SetSignal( raiseFPE );
614 // else OSD::SetSignal() is called in GUI
618 //=============================================================================
620 * SMESH_Gen_i::IsEmbeddedMode
624 //=============================================================================
626 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
628 return myIsEmbeddedMode;
631 //=============================================================================
633 * SMESH_Gen_i::SetEnablePublish
635 * Set enable publishing in the study
637 //=============================================================================
638 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
640 myIsEnablePublish = theIsEnablePublish;
643 //=============================================================================
645 * SMESH_Gen_i::IsEnablePublish
647 * Check enable publishing
649 //=============================================================================
651 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
653 return myIsEnablePublish;
656 //=============================================================================
658 * SMESH_Gen_i::UpdateStudy
660 * Update study (needed at switching GEOM->SMESH)
662 //=============================================================================
664 void SMESH_Gen_i::UpdateStudy()
666 if ( !myStudyContext )
667 myStudyContext = new StudyContext;
669 SALOMEDS::Study_var aStudy = getStudyServant();
670 if ( !CORBA::is_nil( aStudy ) ) {
671 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
672 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
673 if( !GEOM_var->_is_nil() )
674 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
675 // NPAL16168, issue 0020210
676 // Let meshes update their data depending on GEOM groups that could change
677 CORBA::String_var compDataType = ComponentDataType();
678 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
679 if ( !me->_is_nil() ) {
680 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
681 for ( ; anIter->More(); anIter->Next() ) {
682 SALOMEDS::SObject_wrap so = anIter->Value();
683 CORBA::Object_var ior = SObjectToObject( so );
684 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
685 mesh->CheckGeomModif();
691 //=============================================================================
693 * SMESH_Gen_i::GetStudyContext
697 //=============================================================================
698 StudyContext* SMESH_Gen_i::GetStudyContext()
700 return myStudyContext;
703 //=============================================================================
705 * SMESH_Gen_i::CreateHypothesis
707 * Create hypothesis/algorothm of given type and publish it in the study
709 //=============================================================================
711 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
712 const char* theLibName )
713 throw ( SALOME::SALOME_Exception )
715 Unexpect aCatch(SALOME_SalomeException);
716 // Create hypothesis/algorithm
717 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
719 // Publish hypothesis/algorithm in the study
720 if ( CanPublishInStudy( hyp ) ) {
721 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
722 if ( !aSO->_is_nil() ) {
723 // Update Python script
724 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
725 << theHypName << "', '" << theLibName << "')";
732 //================================================================================
734 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
735 * existing on the given geometry or to size of the geometry.
736 * \param theHypType - hypothesis type name
737 * \param theLibName - plugin library name
738 * \param theMesh - The mesh of interest
739 * \param theGeom - The shape to get parameter values from
740 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
741 * in a study and used to compute the mesh, or a temporary one created just to pass
744 //================================================================================
746 SMESH::SMESH_Hypothesis_ptr
747 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
748 const char* theLibName,
749 SMESH::SMESH_Mesh_ptr theMesh,
750 GEOM::GEOM_Object_ptr theGeom,
751 CORBA::Boolean byMesh)
752 throw ( SALOME::SALOME_Exception )
754 Unexpect aCatch(SALOME_SalomeException);
755 if ( byMesh && CORBA::is_nil( theMesh ) )
756 return SMESH::SMESH_Hypothesis::_nil();
757 if ( byMesh && CORBA::is_nil( theGeom ) )
758 return SMESH::SMESH_Hypothesis::_nil();
760 // -----------------------------------------------
761 // find hypothesis used to mesh theGeom
762 // -----------------------------------------------
764 // get mesh and shape
765 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
766 TopoDS_Shape shape = GeomObjectToShape( theGeom );
767 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
768 return SMESH::SMESH_Hypothesis::_nil();
769 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
771 // create a temporary hypothesis to know its dimension
772 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
773 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
775 return SMESH::SMESH_Hypothesis::_nil();
776 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
779 // look for a hypothesis of theHypType used to mesh the shape
780 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
783 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
784 int nbLocalHyps = aHypList->length();
785 for ( int i = 0; i < nbLocalHyps; i++ ) {
786 CORBA::String_var hypName = aHypList[i]->GetName();
787 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
788 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
790 // check super shapes
791 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
792 while ( nbLocalHyps == 0 && itShape.More() ) {
793 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
794 if ( ! CORBA::is_nil( geomObj )) {
795 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
796 nbLocalHyps = aHypList->length();
797 for ( int i = 0; i < nbLocalHyps; i++ )
798 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
799 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
805 // let the temporary hypothesis find out somehow parameter values by mesh
806 if ( hyp->SetParametersByMesh( mesh, shape ))
807 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
812 diagonal = mesh->GetShapeDiagonalSize();
814 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
815 ::SMESH_Hypothesis::TDefaults dflts;
816 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
817 dflts._nbSegments = myGen.GetDefaultNbSegments();
818 dflts._shape = &shape;
819 // let the temporary hypothesis initialize it's values
820 if ( hyp->SetParametersByDefaults( dflts, mesh ))
821 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
824 return SMESH::SMESH_Hypothesis::_nil();
827 //=============================================================================
829 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
830 * \param [in] theHyp - the hypothesis of interest
831 * \param [out] theMesh - the sole mesh using \a theHyp
832 * \param [out] theShape - the sole geometry \a theHyp is assigned to
833 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
835 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
836 * considered as SAME sub-mesh => result is \c true.
837 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
838 * a shape to which an hyp being edited is assigned.
840 //=============================================================================
842 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
843 SMESH::SMESH_Mesh_out theMesh,
844 GEOM::GEOM_Object_out theShape)
846 if ( CORBA::is_nil( theHyp ))
849 // get Mesh component SO
850 CORBA::String_var compDataType = ComponentDataType();
851 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
852 if ( CORBA::is_nil( comp ))
855 // look for child SO of meshes
856 SMESH::SMESH_Mesh_var foundMesh;
857 TopoDS_Shape foundShape;
859 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
860 for ( ; meshIter->More() && isSole; meshIter->Next() )
862 SALOMEDS::SObject_wrap curSO = meshIter->Value();
863 CORBA::Object_var obj = SObjectToObject( curSO );
864 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
868 // look for a sole shape where theHyp is assigned
869 bool isHypFound = false;
870 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
871 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
872 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
874 const THypList& hyps = s2hypsIt.Value();
875 THypList::const_iterator h = hyps.begin();
876 for ( ; h != hyps.end(); ++h )
877 if ( (*h)->GetID() == theHyp->GetId() )
879 if ( h != hyps.end()) // theHyp found
882 if ( ! foundShape.IsNull() &&
883 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
885 foundShape.Nullify();
889 foundShape = s2hypsIt.Key();
891 } // loop on assigned hyps
893 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
895 if ( !foundMesh->_is_nil() ) // not a sole mesh
897 if ( !foundMesh->HasShapeToMesh() ||
898 !mesh_i ->HasShapeToMesh() )
900 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
904 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
905 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
906 isSole = s1->IsSame( s2 );
909 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
915 ! foundMesh->_is_nil() &&
916 ! foundShape.IsNull() )
918 theMesh = foundMesh._retn();
919 theShape = ShapeToGeomObject( foundShape );
920 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
925 //=============================================================================
927 * Sets number of segments per diagonal of boundary box of geometry by which
928 * default segment length of appropriate 1D hypotheses is defined
930 //=============================================================================
932 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
933 throw ( SALOME::SALOME_Exception )
935 if ( theNbSegments > 0 )
936 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
938 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
940 //=============================================================================
942 * \brief Sets default number of segments per edge
944 //=============================================================================
945 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
946 throw ( SALOME::SALOME_Exception )
948 if ( theNbSegments > 0 )
949 myGen.SetDefaultNbSegments( int(theNbSegments) );
951 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
954 //=============================================================================
958 //=============================================================================
960 void SMESH_Gen_i::SetOption(const char* name, const char* value)
962 if ( name && value && strlen( value ) > 0 )
965 if ( strcmp(name, "historical_python_dump") == 0 )
967 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
968 msgToGUI = "preferences/SMESH/historical_python_dump/";
969 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
971 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
973 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
974 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
975 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
977 else if ( strcmp(name, "default_grp_color") == 0 )
981 // color must be presented as a string of following form:
982 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
984 for ( size_t i = 0; i < str.length()/2; i++ )
985 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
986 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
988 else if ( value ) { // rgb color ("255,170,0", for example)
989 string tempValue( value );
990 char* colorValue = strtok( &tempValue[0], "," );
991 while ( colorValue != NULL ) {
992 int c_value = atoi( colorValue );
993 if ( c_value >= 0 && c_value <= 255 )
994 color.push_back( c_value );
995 colorValue = strtok( NULL, "," );
998 if ( color.size() == 3 ) { // color must have three valid component
999 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1000 myDefaultGroupColor = value;
1001 msgToGUI = "preferences/SMESH/default_grp_color/";
1006 // update preferences in case if SetOption() is invoked from python console
1007 if ( !msgToGUI.empty() )
1009 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1010 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1011 if ( !CORBA::is_nil( session ) )
1012 session->emitMessageOneWay(msgToGUI.c_str());
1017 //=============================================================================
1019 Return an option value
1021 //=============================================================================
1023 char* SMESH_Gen_i::GetOption(const char* name)
1027 if ( strcmp(name, "historical_python_dump") == 0 )
1029 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1031 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1033 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1035 if ( strcmp(name, "default_grp_color") == 0 )
1037 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1040 return CORBA::string_dup( "" );
1043 //=============================================================================
1045 * SMESH_Gen_i::CreateMesh
1047 * Create empty mesh on a shape and publish it in the study
1049 //=============================================================================
1051 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1052 throw ( SALOME::SALOME_Exception )
1054 Unexpect aCatch(SALOME_SalomeException);
1055 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1057 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1059 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1060 ASSERT( meshServant );
1061 meshServant->SetShape( theShapeObject );
1063 // publish mesh in the study
1064 if ( CanPublishInStudy( mesh ) ) {
1065 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1066 aStudyBuilder->NewCommand(); // There is a transaction
1067 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1068 aStudyBuilder->CommitCommand();
1069 if ( !aSO->_is_nil() ) {
1070 // Update Python script
1071 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1075 return mesh._retn();
1078 //=============================================================================
1080 * SMESH_Gen_i::CreateEmptyMesh
1084 //=============================================================================
1086 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1087 throw ( SALOME::SALOME_Exception )
1089 Unexpect aCatch(SALOME_SalomeException);
1090 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1092 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1094 // publish mesh in the study
1095 if ( CanPublishInStudy( mesh ) ) {
1096 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1097 aStudyBuilder->NewCommand(); // There is a transaction
1098 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1099 aStudyBuilder->CommitCommand();
1100 if ( !aSO->_is_nil() ) {
1101 // Update Python script
1102 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1106 return mesh._retn();
1111 //================================================================================
1113 * \brief Throws an exception in case if the file can't be read
1115 //================================================================================
1117 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1119 SMESH_File f ( theFileName );
1122 if ( !f.error().empty() )
1123 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1125 THROW_SALOME_CORBA_EXCEPTION
1126 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1127 SALOME::BAD_PARAM );
1132 //=============================================================================
1134 * SMESH_Gen_i::CreateMeshFromUNV
1136 * Create mesh and import data from UNV file
1138 //=============================================================================
1140 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1141 throw ( SALOME::SALOME_Exception )
1143 Unexpect aCatch(SALOME_SalomeException);
1145 checkFileReadable( theFileName );
1147 SMESH::SMESH_Mesh_var aMesh = createMesh();
1149 // publish mesh in the study
1150 if ( CanPublishInStudy( aMesh ) ) {
1151 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1152 aStudyBuilder->NewCommand(); // There is a transaction
1153 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1154 aStudyBuilder->CommitCommand();
1155 if ( !aSO->_is_nil() ) {
1156 // Update Python script
1157 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1161 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1163 aServant->ImportUNVFile( theFileName );
1165 // Dump creation of groups
1166 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1168 aServant->GetImpl().GetMeshDS()->Modified();
1169 return aMesh._retn();
1172 //=============================================================================
1174 * SMESH_Gen_i::CreateMeshFromMED
1176 * Create mesh and import data from MED file
1178 //=============================================================================
1180 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1181 SMESH::DriverMED_ReadStatus& theStatus,
1182 const char* theCommandNameForPython,
1183 const char* theFileNameForPython)
1186 char bname[ _MAX_FNAME ];
1187 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1188 string aFileName = bname;
1190 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1192 // Retrieve mesh names from the file
1193 DriverMED_R_SMESHDS_Mesh myReader;
1194 myReader.SetFile( theFileName );
1195 myReader.SetMeshId( -1 );
1196 Driver_Mesh::Status aStatus;
1197 list<string> aNames = myReader.GetMeshNames(aStatus);
1198 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1199 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1201 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1204 TPythonDump aPythonDump;
1205 aPythonDump << "([";
1207 if (theStatus == SMESH::DRS_OK) {
1208 SALOMEDS::StudyBuilder_var aStudyBuilder;
1209 aStudyBuilder = getStudyServant()->NewBuilder();
1210 aStudyBuilder->NewCommand(); // There is a transaction
1212 aResult->length( aNames.size() );
1215 // Iterate through all meshes and create mesh objects
1216 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1219 if (i > 0) aPythonDump << ", ";
1222 SMESH::SMESH_Mesh_var mesh = createMesh();
1224 // publish mesh in the study
1225 SALOMEDS::SObject_wrap aSO;
1226 if ( CanPublishInStudy( mesh ) )
1227 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1228 // - as names of meshes are stored in MED file, we use them for data publishing
1229 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1230 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1233 if ( !aSO->_is_nil() ) {
1236 aPythonDump << "mesh_" << i;
1239 // Read mesh data (groups are published automatically by ImportMEDFile())
1240 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1241 ASSERT( meshServant );
1242 SMESH::DriverMED_ReadStatus status1 =
1243 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1244 if (status1 > theStatus)
1245 theStatus = status1;
1247 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1248 meshServant->GetImpl().GetMeshDS()->Modified();
1250 if ( !aStudyBuilder->_is_nil() )
1251 aStudyBuilder->CommitCommand();
1254 // Update Python script
1255 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1257 // Dump creation of groups
1258 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1259 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1261 return aResult._retn();
1264 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1265 SMESH::DriverMED_ReadStatus& theStatus)
1266 throw ( SALOME::SALOME_Exception )
1268 Unexpect aCatch(SALOME_SalomeException);
1269 checkFileReadable( theFileName );
1271 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1275 //=============================================================================
1277 * SMESH_Gen_i::CreateMeshFromSAUV
1279 * Create mesh and import data from SAUV file
1281 //=============================================================================
1283 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1284 SMESH::DriverMED_ReadStatus& theStatus)
1285 throw ( SALOME::SALOME_Exception )
1287 Unexpect aCatch(SALOME_SalomeException);
1288 checkFileReadable( theFileName );
1290 std::string sauvfilename(theFileName);
1291 std::string medfilename(theFileName);
1292 medfilename += ".med";
1295 cmd = "%PYTHONBIN% ";
1300 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1302 system(cmd.c_str());
1303 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1305 cmd = "%PYTHONBIN% ";
1310 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1312 system(cmd.c_str());
1316 //=============================================================================
1318 * SMESH_Gen_i::CreateMeshFromSTL
1320 * Create mesh and import data from STL file
1322 //=============================================================================
1324 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1325 throw ( SALOME::SALOME_Exception )
1327 Unexpect aCatch(SALOME_SalomeException);
1328 checkFileReadable( theFileName );
1330 SMESH::SMESH_Mesh_var aMesh = createMesh();
1333 char bname[ _MAX_FNAME ];
1334 _splitpath( theFileName, NULL, NULL, bname, NULL );
1335 string aFileName = bname;
1337 string aFileName = basename( const_cast<char *>(theFileName) );
1339 // publish mesh in the study
1340 if ( CanPublishInStudy( aMesh ) ) {
1341 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1342 aStudyBuilder->NewCommand(); // There is a transaction
1343 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1344 aStudyBuilder->CommitCommand();
1345 if ( !aSO->_is_nil() ) {
1346 // Update Python script
1347 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1351 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1353 aServant->ImportSTLFile( theFileName );
1354 aServant->GetImpl().GetMeshDS()->Modified();
1355 return aMesh._retn();
1358 //================================================================================
1360 * \brief Create meshes and import data from the CGSN file
1362 //================================================================================
1364 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1365 SMESH::DriverMED_ReadStatus& theStatus)
1366 throw ( SALOME::SALOME_Exception )
1368 Unexpect aCatch(SALOME_SalomeException);
1369 checkFileReadable( theFileName );
1371 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1374 // Retrieve nb meshes from the file
1375 DriverCGNS_Read myReader;
1376 myReader.SetFile( theFileName );
1377 Driver_Mesh::Status aStatus;
1378 int nbMeshes = myReader.GetNbMeshes(aStatus);
1379 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1381 aResult->length( nbMeshes );
1383 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1386 TPythonDump aPythonDump;
1387 aPythonDump << "([";
1389 if (theStatus == SMESH::DRS_OK)
1391 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1392 aStudyBuilder->NewCommand(); // There is a transaction
1396 // Iterate through all meshes and create mesh objects
1397 for ( ; i < nbMeshes; ++i )
1400 if (i > 0) aPythonDump << ", ";
1403 SMESH::SMESH_Mesh_var mesh = createMesh();
1404 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1406 // Read mesh data (groups are published automatically by ImportMEDFile())
1407 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1408 ASSERT( meshServant );
1410 SMESH::DriverMED_ReadStatus status1 =
1411 meshServant->ImportCGNSFile( theFileName, i, meshName );
1412 if (status1 > theStatus)
1413 theStatus = status1;
1415 meshServant->GetImpl().GetMeshDS()->Modified();
1416 // publish mesh in the study
1417 SALOMEDS::SObject_wrap aSO;
1418 if ( CanPublishInStudy( mesh ) )
1419 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1422 if ( !aSO->_is_nil() ) {
1426 aPythonDump << "mesh_" << i;
1429 aStudyBuilder->CommitCommand();
1432 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1434 // Dump creation of groups
1435 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1436 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1438 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1441 return aResult._retn();
1444 //================================================================================
1446 * \brief Create a mesh and import data from a GMF file
1448 //================================================================================
1450 SMESH::SMESH_Mesh_ptr
1451 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1452 CORBA::Boolean theMakeRequiredGroups,
1453 SMESH::ComputeError_out theError)
1454 throw ( SALOME::SALOME_Exception )
1456 Unexpect aCatch(SALOME_SalomeException);
1457 checkFileReadable( theFileName );
1459 SMESH::SMESH_Mesh_var aMesh = createMesh();
1461 char bname[ _MAX_FNAME ];
1462 _splitpath( theFileName, NULL, NULL, bname, NULL );
1463 string aFileName = bname;
1465 string aFileName = basename( const_cast<char *>(theFileName) );
1467 // publish mesh in the study
1468 if ( CanPublishInStudy( aMesh ) ) {
1469 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1470 aStudyBuilder->NewCommand(); // There is a transaction
1471 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1472 aStudyBuilder->CommitCommand();
1473 if ( !aSO->_is_nil() ) {
1474 // Update Python script
1475 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1476 << theFileName << "', "
1477 << theMakeRequiredGroups << " )";
1480 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1482 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1483 aServant->GetImpl().GetMeshDS()->Modified();
1484 return aMesh._retn();
1488 //=============================================================================
1490 * SMESH_Gen_i::IsReadyToCompute
1492 * Returns true if mesh contains enough data to be computed
1494 //=============================================================================
1496 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1497 GEOM::GEOM_Object_ptr theShapeObject )
1498 throw ( SALOME::SALOME_Exception )
1500 Unexpect aCatch(SALOME_SalomeException);
1501 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1503 if ( CORBA::is_nil( theShapeObject ) )
1504 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1505 SALOME::BAD_PARAM );
1507 if ( CORBA::is_nil( theMesh ) )
1508 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1509 SALOME::BAD_PARAM );
1513 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1514 ASSERT( meshServant );
1515 if ( meshServant ) {
1516 // get local TopoDS_Shape
1517 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1518 // call implementation
1519 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1520 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1523 catch ( SALOME_Exception& S_ex ) {
1524 INFOS( "catch exception "<< S_ex.what() );
1529 //================================================================================
1531 * \brief Find SObject for an algo
1533 //================================================================================
1535 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1538 SALOMEDS::Study_var aStudy = getStudyServant();
1539 if ( !aStudy->_is_nil() ) {
1540 // find algo in the study
1541 CORBA::String_var compDataType = ComponentDataType();
1542 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1543 if ( !father->_is_nil() ) {
1544 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1545 for ( ; itBig->More(); itBig->Next() ) {
1546 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1547 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1548 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1549 for ( ; algoIt->More(); algoIt->Next() ) {
1550 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1551 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1552 if ( !CORBA::is_nil( algoIOR )) {
1553 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1554 if ( impl && impl->GetImpl() == algo )
1555 return algoSO._retn();
1557 } // loop on algo SO's
1560 } // SMESH component iterator
1564 return SALOMEDS::SObject::_nil();
1567 //================================================================================
1569 * \brief Return errors of mesh computation
1571 //================================================================================
1573 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1574 GEOM::GEOM_Object_ptr theSubObject )
1575 throw ( SALOME::SALOME_Exception )
1577 Unexpect aCatch(SALOME_SalomeException);
1578 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1580 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1581 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1583 if ( CORBA::is_nil( theMesh ) )
1584 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1586 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1588 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1591 if(theMesh->HasShapeToMesh())
1592 shape = GeomObjectToShape( theSubObject );
1594 shape = SMESH_Mesh::PseudoShape();
1596 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1598 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1601 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1602 const bool includeSelf = true, complexShapeFirst = true;
1603 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1605 while ( smIt->more() )
1608 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1610 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1611 if ( error && !error->IsOK() )
1613 if ( !( error->myAlgo ) &&
1614 !( error->myAlgo = sm->GetAlgo() ))
1616 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1617 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1618 errStruct.comment = error->myComment.c_str();
1619 errStruct.subShapeID = sm->GetId();
1620 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1621 if ( !algoSO->_is_nil() ) {
1622 CORBA::String_var algoName = algoSO->GetName();
1623 errStruct.algoName = algoName;
1626 errStruct.algoName = error->myAlgo->GetName();
1628 errStruct.hasBadMesh = error->HasBadElems();
1631 error_array->length( nbErr );
1634 catch ( SALOME_Exception& S_ex ) {
1635 INFOS( "catch exception "<< S_ex.what() );
1638 return error_array._retn();
1641 //================================================================================
1643 * \brief Return mesh elements preventing computation of a subshape
1645 //================================================================================
1647 SMESH::MeshPreviewStruct*
1648 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1649 CORBA::Short theSubShapeID )
1650 throw ( SALOME::SALOME_Exception )
1652 Unexpect aCatch(SALOME_SalomeException);
1653 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1655 if ( CORBA::is_nil( theMesh ) )
1656 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1658 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1661 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1663 // mesh implementation
1664 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1665 // submesh by subshape id
1666 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1669 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1670 if ( error && error->HasBadElems() )
1672 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1673 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1675 // get nodes of elements and count elements
1676 TNode2LocalIDMap mapNode2LocalID;
1677 list< TNodeLocalID > connectivity;
1678 int i, nbElements = 0, nbConnNodes = 0;
1680 const list<const SMDS_MeshElement*>& badElems =
1681 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1682 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1683 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1684 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1686 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1687 while ( nIt->more() )
1688 connectivity.push_back
1689 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1691 // fill node coords and assign local ids to the nodes
1692 int nbNodes = mapNode2LocalID.size();
1693 result->nodesXYZ.length( nbNodes );
1694 TNodeLocalID node2ID = mapNode2LocalID.begin();
1695 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1696 node2ID->second = i;
1697 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1698 result->nodesXYZ[i].x = node->X();
1699 result->nodesXYZ[i].y = node->Y();
1700 result->nodesXYZ[i].z = node->Z();
1702 // fill connectivity
1703 result->elementConnectivities.length( nbConnNodes );
1704 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1705 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1706 result->elementConnectivities[i] = (*connIt)->second;
1708 // fill element types
1709 result->elementTypes.length( nbElements );
1710 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1712 const SMDS_MeshElement* elem = *elemIt;
1713 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1714 result->elementTypes[i].isPoly = elem->IsPoly();
1715 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1721 catch ( SALOME_Exception& S_ex ) {
1722 INFOS( "catch exception "<< S_ex.what() );
1725 return result._retn();
1728 //================================================================================
1730 * \brief Create a group of elements preventing computation of a sub-shape
1732 //================================================================================
1734 SMESH::ListOfGroups*
1735 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1736 CORBA::Short theSubShapeID,
1737 const char* theGroupName )
1738 throw ( SALOME::SALOME_Exception )
1740 Unexpect aCatch(SALOME_SalomeException);
1742 SMESH::ListOfGroups_var groups;
1744 if ( CORBA::is_nil( theMesh ) )
1745 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1748 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1750 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1751 TPythonDump() << groups << " = " << this
1752 << ".MakeGroupsOfBadInputElements( "
1753 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1756 catch ( SALOME_Exception& S_ex ) {
1757 INFOS( "catch exception "<< S_ex.what() );
1759 return groups._retn();
1762 //================================================================================
1764 * \brief Returns errors of hypotheses definition
1765 * \param theMesh - the mesh
1766 * \param theSubObject - the main or sub- shape
1767 * \retval SMESH::algo_error_array* - sequence of errors
1769 //================================================================================
1771 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1772 GEOM::GEOM_Object_ptr theSubObject )
1773 throw ( SALOME::SALOME_Exception )
1775 Unexpect aCatch(SALOME_SalomeException);
1776 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1778 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1779 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1781 if ( CORBA::is_nil( theMesh ) )
1782 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1784 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1786 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1787 ASSERT( meshServant );
1788 if ( meshServant ) {
1789 TopoDS_Shape myLocShape;
1790 if(theMesh->HasShapeToMesh())
1791 myLocShape = GeomObjectToShape( theSubObject );
1793 myLocShape = SMESH_Mesh::PseudoShape();
1795 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1796 list< ::SMESH_Gen::TAlgoStateError > error_list;
1797 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1798 // call ::SMESH_Gen::GetAlgoState()
1799 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1800 error_array->length( error_list.size() );
1802 for ( error = error_list.begin(); error != error_list.end(); ++error )
1804 // fill AlgoStateError structure
1805 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1806 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1807 errStruct.algoDim = error->_algoDim;
1808 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1809 errStruct.algoName = "";
1810 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1811 if ( !algoSO->_is_nil() ) {
1812 CORBA::String_var algoName = algoSO->GetName();
1813 errStruct.algoName = algoName.in();
1818 catch ( SALOME_Exception& S_ex ) {
1819 INFOS( "catch exception "<< S_ex.what() );
1821 return error_array._retn();
1824 //=============================================================================
1826 * SMESH_Gen_i::GetSubShapesId
1828 * Get sub-shapes unique ID's list
1830 //=============================================================================
1833 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1834 const SMESH::object_array& theListOfSubShapeObject )
1835 throw ( SALOME::SALOME_Exception )
1837 Unexpect aCatch(SALOME_SalomeException);
1838 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1840 SMESH::long_array_var shapesId = new SMESH::long_array;
1843 if ( CORBA::is_nil( theMainShapeObject ) )
1844 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1848 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1849 TopTools_IndexedMapOfShape myIndexToShape;
1850 TopExp::MapShapes(myMainShape,myIndexToShape);
1852 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1854 GEOM::GEOM_Object_var aShapeObject
1855 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1856 if ( CORBA::is_nil( aShapeObject ) )
1857 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1858 SALOME::BAD_PARAM );
1860 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1861 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1863 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1864 setId.insert(myIndexToShape.FindIndex(F));
1865 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1867 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1869 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1870 setId.insert(myIndexToShape.FindIndex(E));
1871 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1873 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1875 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1876 setId.insert(myIndexToShape.FindIndex(V));
1877 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1880 shapesId->length(setId.size());
1881 set<int>::iterator iind;
1883 for (iind = setId.begin(); iind != setId.end(); iind++)
1885 if(MYDEBUG) SCRUTE((*iind));
1886 shapesId[i] = (*iind);
1887 if(MYDEBUG) SCRUTE(shapesId[i]);
1891 catch (SALOME_Exception& S_ex)
1893 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1896 return shapesId._retn();
1899 //=============================================================================
1901 * SMESH_Gen_i::Compute
1903 * Compute mesh on a shape
1905 //=============================================================================
1907 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1908 GEOM::GEOM_Object_ptr theShapeObject )
1909 throw ( SALOME::SALOME_Exception )
1912 Unexpect aCatch(SALOME_SalomeException);
1913 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1915 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1916 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1917 SALOME::BAD_PARAM );
1919 if ( CORBA::is_nil( theMesh ) )
1920 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1921 SALOME::BAD_PARAM );
1923 // Update Python script
1924 TPythonDump() << "isDone = " << this << ".Compute( "
1925 << theMesh << ", " << theShapeObject << ")";
1929 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1930 ASSERT( meshServant );
1931 if ( meshServant ) {
1932 meshServant->Load();
1933 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
1934 meshServant->CheckGeomModif();
1935 // get local TopoDS_Shape
1936 TopoDS_Shape myLocShape;
1937 if(theMesh->HasShapeToMesh())
1938 myLocShape = GeomObjectToShape( theShapeObject );
1940 myLocShape = SMESH_Mesh::PseudoShape();
1941 // call implementation compute
1942 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1943 myGen.PrepareCompute( myLocMesh, myLocShape );
1944 int how = ::SMESH_Gen::COMPACT_MESH;
1945 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
1946 how |= ::SMESH_Gen::SHAPE_ONLY;
1947 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
1948 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1949 myLocMesh.GetMeshDS()->Modified();
1950 UpdateIcons( theMesh );
1954 catch ( std::bad_alloc ) {
1955 INFOS( "Compute(): lack of memory" );
1957 catch ( SALOME_Exception& S_ex ) {
1958 INFOS( "Compute(): catch exception "<< S_ex.what() );
1961 INFOS( "Compute(): unknown exception " );
1966 //=============================================================================
1968 * SMESH_Gen_i::CancelCompute
1970 * Cancel Compute mesh on a shape
1972 //=============================================================================
1974 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
1975 GEOM::GEOM_Object_ptr theShapeObject )
1977 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1978 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1979 TopoDS_Shape myLocShape;
1980 if(theMesh->HasShapeToMesh())
1981 myLocShape = GeomObjectToShape( theShapeObject );
1983 myLocShape = SMESH_Mesh::PseudoShape();
1984 myGen.CancelCompute( myLocMesh, myLocShape);
1987 //=============================================================================
1989 * SMESH_Gen_i::Precompute
1991 * Compute mesh as preview till indicated dimension on shape
1993 //=============================================================================
1995 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
1996 GEOM::GEOM_Object_ptr theShapeObject,
1997 SMESH::Dimension theDimension,
1998 SMESH::long_array& theShapesId)
1999 throw ( SALOME::SALOME_Exception )
2001 Unexpect aCatch(SALOME_SalomeException);
2002 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2004 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2005 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2006 SALOME::BAD_PARAM );
2008 if ( CORBA::is_nil( theMesh ) )
2009 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2010 SALOME::BAD_PARAM );
2012 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2015 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2016 meshServant->Load();
2017 ASSERT( meshServant );
2018 if ( meshServant ) {
2019 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2020 meshServant->CheckGeomModif();
2021 // get local TopoDS_Shape
2022 TopoDS_Shape myLocShape;
2023 if(theMesh->HasShapeToMesh())
2024 myLocShape = GeomObjectToShape( theShapeObject );
2026 return result._retn();;
2028 // call implementation compute
2029 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2031 ::MeshDimension aDim = (MeshDimension)theDimension;
2032 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2034 int nbShapeId = shapeIds.size();
2035 theShapesId.length( nbShapeId );
2036 // iterates on shapes and collect mesh entities into mesh preview
2037 TSetOfInt::const_iterator idIt = shapeIds.begin();
2038 TSetOfInt::const_iterator idEnd = shapeIds.end();
2039 std::map< int, int > mapOfShIdNb;
2040 std::set< SMESH_TLink > setOfEdge;
2041 std::list< SMDSAbs_ElementType > listOfElemType;
2042 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2043 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2044 TNode2LocalIDMap mapNode2LocalID;
2045 list< TNodeLocalID > connectivity;
2046 int i, nbConnNodes = 0;
2047 std::set< const SMESH_subMesh* > setOfVSubMesh;
2048 // iterates on shapes
2049 for ( ; idIt != idEnd; idIt++ )
2051 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2053 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2054 if ( !sm || !sm->IsMeshComputed() )
2057 const TopoDS_Shape& aSh = sm->GetSubShape();
2058 const int shDim = myGen.GetShapeDim( aSh );
2059 if ( shDim < 1 || shDim > theDimension )
2062 mapOfShIdNb[ *idIt ] = 0;
2063 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2065 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2066 if ( !smDS ) continue;
2068 if ( theDimension == SMESH::DIM_2D )
2070 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2071 while ( faceIt->more() )
2073 const SMDS_MeshElement* face = faceIt->next();
2074 int aNbNode = face->NbNodes();
2076 aNbNode /= 2; // do not take into account additional middle nodes
2078 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2079 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2081 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2082 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2084 listOfElemType.push_back( SMDSAbs_Edge );
2085 connectivity.push_back
2086 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2087 connectivity.push_back
2088 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2094 else if ( theDimension == SMESH::DIM_1D )
2096 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2097 while ( nodeIt->more() )
2099 listOfElemType.push_back( SMDSAbs_Node );
2100 connectivity.push_back
2101 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2103 // add corner nodes by first vertex from edge
2104 SMESH_subMeshIteratorPtr edgeSmIt =
2105 sm->getDependsOnIterator(/*includeSelf*/false,
2106 /*complexShapeFirst*/false);
2107 while ( edgeSmIt->more() )
2109 SMESH_subMesh* vertexSM = edgeSmIt->next();
2110 // check that vertex is not already treated
2111 if ( !setOfVSubMesh.insert( vertexSM ).second )
2113 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2116 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2117 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2118 while ( nodeIt->more() )
2120 listOfElemType.push_back( SMDSAbs_Node );
2121 connectivity.push_back
2122 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2128 // fill node coords and assign local ids to the nodes
2129 int nbNodes = mapNode2LocalID.size();
2130 result->nodesXYZ.length( nbNodes );
2131 TNodeLocalID node2ID = mapNode2LocalID.begin();
2132 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2133 node2ID->second = i;
2134 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2135 result->nodesXYZ[i].x = node->X();
2136 result->nodesXYZ[i].y = node->Y();
2137 result->nodesXYZ[i].z = node->Z();
2139 // fill connectivity
2140 result->elementConnectivities.length( nbConnNodes );
2141 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2142 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2143 result->elementConnectivities[i] = (*connIt)->second;
2146 // fill element types
2147 result->elementTypes.length( listOfElemType.size() );
2148 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2149 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2150 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2152 SMDSAbs_ElementType elemType = *typeIt;
2153 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2154 result->elementTypes[i].isPoly = false;
2155 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2158 // correct number of shapes
2159 theShapesId.length( mapOfShIdNb.size() );
2163 catch ( std::bad_alloc ) {
2164 INFOS( "Precompute(): lack of memory" );
2166 catch ( SALOME_Exception& S_ex ) {
2167 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2170 INFOS( "Precompute(): unknown exception " );
2172 return result._retn();
2176 //=============================================================================
2178 * SMESH_Gen_i::Evaluate
2180 * Evaluate mesh on a shape
2182 //=============================================================================
2184 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2185 GEOM::GEOM_Object_ptr theShapeObject)
2186 // SMESH::long_array& theNbElems)
2187 throw ( SALOME::SALOME_Exception )
2189 Unexpect aCatch(SALOME_SalomeException);
2190 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2192 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2193 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2194 SALOME::BAD_PARAM );
2196 if ( CORBA::is_nil( theMesh ) )
2197 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2198 SALOME::BAD_PARAM );
2200 SMESH::long_array_var nbels = new SMESH::long_array;
2201 nbels->length(SMESH::Entity_Last);
2202 int i = SMESH::Entity_Node;
2203 for (; i < SMESH::Entity_Last; i++)
2206 // Update Python script
2207 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2208 << theMesh << ", " << theShapeObject << ")";
2212 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2213 ASSERT( meshServant );
2214 if ( meshServant ) {
2215 meshServant->Load();
2216 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2217 meshServant->CheckGeomModif();
2218 // get local TopoDS_Shape
2219 TopoDS_Shape myLocShape;
2220 if(theMesh->HasShapeToMesh())
2221 myLocShape = GeomObjectToShape( theShapeObject );
2223 myLocShape = SMESH_Mesh::PseudoShape();
2224 // call implementation compute
2225 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2226 MapShapeNbElems aResMap;
2227 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2228 MapShapeNbElemsItr anIt = aResMap.begin();
2229 for(; anIt!=aResMap.end(); anIt++) {
2230 const vector<int>& aVec = (*anIt).second;
2231 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2232 int nbElem = aVec[i];
2233 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2235 SMESH_subMesh* sm = anIt->first;
2236 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2237 const SMESH_Algo* algo = sm->GetAlgo();
2238 if ( (algo && !error.get()) || error->IsOK() )
2239 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2243 nbels[i] += aVec[i];
2247 return nbels._retn();
2250 catch ( std::bad_alloc ) {
2251 INFOS( "Evaluate(): lack of memory" );
2253 catch ( SALOME_Exception& S_ex ) {
2254 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2257 INFOS( "Evaluate(): unknown exception " );
2260 return nbels._retn();
2263 //================================================================================
2265 * \brief Return geometrical object the given element is built on
2266 * \param theMesh - the mesh the element is in
2267 * \param theElementID - the element ID
2268 * \param theGeomName - the name of the result geom object if it is not yet published
2269 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2271 //================================================================================
2273 GEOM::GEOM_Object_ptr
2274 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2275 CORBA::Long theElementID,
2276 const char* theGeomName)
2277 throw ( SALOME::SALOME_Exception )
2279 Unexpect aCatch(SALOME_SalomeException);
2281 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2282 if ( !geom->_is_nil() ) {
2283 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2284 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2286 // try to find the corresponding SObject
2287 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2288 if ( SObj->_is_nil() ) // submesh can be not found even if published
2290 // try to find published submesh
2291 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2292 if ( !geom->IsMainShape() && list->length() == 1 ) {
2293 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2294 SALOMEDS::ChildIterator_wrap it;
2295 if ( !mainSO->_is_nil() ) {
2296 it = getStudyServant()->NewChildIterator( mainSO );
2298 if ( !it->_is_nil() ) {
2299 for ( it->InitEx(true); it->More(); it->Next() ) {
2300 SALOMEDS::SObject_wrap so = it->Value();
2301 CORBA::Object_var obj = SObjectToObject( so );
2302 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2303 if ( !subGeom->_is_nil() ) {
2304 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2305 if ( subList->length() == 1 && list[0] == subList[0] ) {
2315 if ( SObj->_is_nil() ) // publish a new subshape
2316 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2318 // return only published geometry
2319 if ( !SObj->_is_nil() ) {
2320 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2321 CORBA::Object_var obj = SObjectToObject( SObj );
2322 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2326 return GEOM::GEOM_Object::_nil();
2329 //================================================================================
2331 * \brief Return geometrical object the given element is built on.
2332 * \param theMesh - the mesh the element is in
2333 * \param theElementID - the element ID
2334 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2336 //================================================================================
2338 GEOM::GEOM_Object_ptr
2339 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2340 CORBA::Long theElementID)
2341 throw ( SALOME::SALOME_Exception )
2343 Unexpect aCatch(SALOME_SalomeException);
2344 if ( CORBA::is_nil( theMesh ) )
2345 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2347 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2348 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2350 // get a core mesh DS
2351 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2352 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2354 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2355 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2356 // find the element in mesh
2357 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2358 // find a shape id by the element
2359 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2360 // get a geom object by the shape id
2361 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2362 if ( geom->_is_nil() ) {
2363 // try to find a published sub-shape
2364 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2365 SALOMEDS::ChildIterator_wrap it;
2366 if ( !mainSO->_is_nil() ) {
2367 it = getStudyServant()->NewChildIterator( mainSO );
2369 if ( !it->_is_nil() ) {
2370 for ( it->InitEx(true); it->More(); it->Next() ) {
2371 SALOMEDS::SObject_wrap so = it->Value();
2372 CORBA::Object_var obj = SObjectToObject( so );
2373 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2374 if ( !subGeom->_is_nil() ) {
2375 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2376 if ( subList->length() == 1 && shapeID == subList[0] ) {
2384 if ( geom->_is_nil() ) {
2386 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2387 if ( !op->_is_nil() )
2388 geom = op->GetSubShape( mainShape, shapeID );
2393 if ( !geom->_is_nil() ) {
2394 GeomObjectToShape( geom ); // let geom client remember the found shape
2395 return geom._retn();
2400 return GEOM::GEOM_Object::_nil();
2403 //================================================================================
2405 * SMESH_Gen_i::Concatenate
2407 * Concatenate the given meshes into one mesh
2409 //================================================================================
2411 SMESH::SMESH_Mesh_ptr
2412 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2413 CORBA::Boolean theUniteIdenticalGroups,
2414 CORBA::Boolean theMergeNodesAndElements,
2415 CORBA::Double theMergeTolerance)
2416 throw ( SALOME::SALOME_Exception )
2418 return ConcatenateCommon(theMeshesArray,
2419 theUniteIdenticalGroups,
2420 theMergeNodesAndElements,
2425 //================================================================================
2427 * SMESH_Gen_i::ConcatenateWithGroups
2429 * Concatenate the given meshes into one mesh
2430 * Create the groups of all elements from initial meshes
2432 //================================================================================
2434 SMESH::SMESH_Mesh_ptr
2435 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2436 CORBA::Boolean theUniteIdenticalGroups,
2437 CORBA::Boolean theMergeNodesAndElements,
2438 CORBA::Double theMergeTolerance)
2439 throw ( SALOME::SALOME_Exception )
2441 return ConcatenateCommon(theMeshesArray,
2442 theUniteIdenticalGroups,
2443 theMergeNodesAndElements,
2448 //================================================================================
2450 * SMESH_Gen_i::ConcatenateCommon
2452 * Concatenate the given meshes into one mesh
2454 //================================================================================
2456 SMESH::SMESH_Mesh_ptr
2457 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2458 CORBA::Boolean theUniteIdenticalGroups,
2459 CORBA::Boolean theMergeNodesAndElements,
2460 CORBA::Double theMergeTolerance,
2461 CORBA::Boolean theCommonGroups)
2462 throw ( SALOME::SALOME_Exception )
2464 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2465 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2468 SMESH::SMESH_Mesh_var newMesh = CreateEmptyMesh();
2469 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2470 if ( !newImpl ) return newMesh._retn();
2472 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2473 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2475 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2476 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2477 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2478 TGroupsMap groupsMap;
2479 TListOfNewGroups listOfNewGroups;
2481 ::SMESH_MeshEditor newEditor( &locMesh );
2482 ::SMESH_MeshEditor::ElemFeatures elemType;
2484 // loop on sub-meshes
2485 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2487 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2488 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2489 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2490 if ( !initImpl ) continue;
2493 // assure that IDs increments by one during iteration
2494 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2495 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2496 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2497 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2499 initMeshDS->Modified();
2500 initMeshDS->CompactMesh();
2503 // remember nb of elements before filling in
2504 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2508 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2509 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2510 while ( elemIt->more() )
2512 SMESH_NodeXYZ node = elemIt->next();
2513 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2518 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2519 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2520 while ( elemIt->more() )
2522 const SMDS_MeshElement* elem = elemIt->next();
2523 elemType.myNodes.resize( elem->NbNodes() );
2525 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2526 for ( int k = 0; itNodes->more(); k++)
2528 const SMDS_MeshNode* node = itNodes->next();
2529 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2532 // creates a corresponding element on existent nodes in new mesh
2533 newElems[ elem->GetID() ] =
2534 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2536 newEditor.ClearLastCreated(); // forget the history
2539 // create groups of just added elements
2540 SMESH::SMESH_Group_var newGroup;
2541 SMESH::ElementType groupType;
2542 if ( theCommonGroups )
2545 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2546 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2547 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2548 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2551 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2553 for( groupType = SMESH::NODE;
2554 groupType < SMESH::NB_ELEMENT_TYPES;
2555 groupType = (SMESH::ElementType)( groupType + 1 ))
2557 if ( curState[ groupType ] <= prevState[ groupType ])
2558 continue; // no elements of groupType added from the i-th mesh
2560 // make a group name
2561 std::string groupName = "Gr";
2562 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2564 CORBA::String_var name = meshSO->GetName();
2568 groupName += typeNames[ groupType ];
2570 // make and fill a group
2571 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2572 std::vector< const SMDS_MeshElement* > & elemVec =
2573 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2574 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2576 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2578 for ( size_t j = 0; j < elemVec.size(); ++j )
2580 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2581 grpDS->Add( elemVec[j] );
2585 listOfNewGroups.clear();
2586 listOfNewGroups.push_back( newGroup );
2587 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2592 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2596 SMESH::SMESH_GroupBase_ptr group;
2597 CORBA::String_var groupName;
2598 SMESH::long_array_var newIDs = new SMESH::long_array();
2600 // loop on groups of a source mesh
2601 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2602 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2604 group = listOfGroups[iG];
2605 groupType = group->GetType();
2606 groupName = group->GetName();
2607 std::string name = groupName.in();
2609 // convert a list of IDs
2610 newIDs->length( group->Size() );
2611 std::vector< const SMDS_MeshElement* > & elemVec =
2612 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2613 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2615 while ( itGrElems->more() )
2617 const SMDS_MeshElement* elem = itGrElems->next();
2618 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2620 newIDs[ nbElems++ ] = newElem->GetID();
2622 newIDs->length( nbElems );
2624 // check that a current group name and type don't have identical ones in final mesh
2625 listOfNewGroups.clear();
2626 TNameAndType nameAndType( name, groupType );
2627 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2628 if ( anIter == groupsMap.end() )
2630 // add a new group in the mesh
2631 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2632 newGroup->Add( newIDs );
2634 listOfNewGroups.push_back( newGroup );
2635 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2637 else if ( theUniteIdenticalGroups )
2639 // unite identical groups
2640 TListOfNewGroups& aNewGroups = anIter->second;
2641 aNewGroups.front()->Add( newIDs );
2645 // rename identical groups
2646 newGroup = newImpl->CreateGroup( groupType, groupName );
2647 newGroup->Add( newIDs );
2649 TListOfNewGroups& newGroups = anIter->second;
2650 std::string newGroupName;
2651 if ( newGroups.size() == 1 )
2653 newGroupName = name + "_1";
2654 newGroups.front()->SetName( newGroupName.c_str() );
2656 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2657 newGroup->SetName( newGroupName.c_str() );
2658 newGroups.push_back( newGroup );
2661 } // if an IDSource is a mesh
2664 if ( theMergeNodesAndElements ) // merge nodes
2666 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2667 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2668 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2669 /*SeparateCornersAndMedium=*/ false );
2670 newEditor.MergeNodes( groupsOfNodes );
2672 newEditor.MergeEqualElements();
2675 // Update Python script
2676 pythonDump << newMesh << " = " << this
2677 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "("
2678 << theMeshesArray << ", "
2679 << theUniteIdenticalGroups << ", "
2680 << theMergeNodesAndElements << ", "
2681 << TVar( theMergeTolerance ) << ")";
2683 pPythonDump.reset(); // enable python dump from GetGroups()
2685 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2686 if ( !newMesh->_is_nil() )
2688 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2691 // IPAL21468 Change icon of compound because it need not be computed.
2692 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2693 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2695 newMeshDS->Modified();
2697 return newMesh._retn();
2700 //================================================================================
2702 * \brief Create a mesh by copying a part of another mesh
2703 * \param meshPart - a part of mesh to copy
2704 * \param toCopyGroups - to create in the new mesh groups
2705 * the copied elements belongs to
2706 * \param toKeepIDs - to preserve IDs of the copied elements or not
2707 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2709 //================================================================================
2711 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2712 const char* meshName,
2713 CORBA::Boolean toCopyGroups,
2714 CORBA::Boolean toKeepIDs)
2716 Unexpect aCatch(SALOME_SalomeException);
2718 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2720 // 1. Get source mesh
2722 if ( CORBA::is_nil( meshPart ))
2723 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2725 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2726 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2728 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2730 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2732 // 2. Make a new mesh
2734 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2735 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2737 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2738 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2739 if ( !meshSO->_is_nil() )
2741 SetName( meshSO, meshName, "Mesh" );
2742 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2744 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2745 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2746 ::SMESH_MeshEditor::ElemFeatures elemType;
2748 // 3. Get elements to copy
2750 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2751 TIDSortedElemSet srcElems;
2752 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2753 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2756 srcElemIt = srcMeshDS->elementsIterator();
2757 srcNodeIt = srcMeshDS->nodesIterator();
2761 SMESH::long_array_var ids = meshPart->GetIDs();
2762 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2764 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2765 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2766 srcElems.insert( elem );
2770 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2771 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2772 srcElems.insert( elem );
2774 if ( srcElems.empty() )
2775 return newMesh._retn();
2777 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2778 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2783 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2784 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2785 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2787 const SMDS_MeshNode *nSrc, *nTgt;
2788 vector< const SMDS_MeshNode* > nodes;
2789 while ( srcElemIt->more() )
2791 const SMDS_MeshElement * elem = srcElemIt->next();
2793 nodes.resize( elem->NbNodes());
2794 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2796 for ( iN = 0; nIt->more(); ++iN )
2798 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2799 nTgt = newMeshDS->FindNode( nSrc->GetID());
2801 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2806 for ( iN = 0; nIt->more(); ++iN )
2808 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2809 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2811 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2812 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2816 if ( elem->GetType() != SMDSAbs_Node )
2818 elemType.Init( elem, /*basicOnly=*/false );
2819 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2821 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2822 if ( toCopyGroups && !toKeepIDs )
2823 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2825 } // while ( srcElemIt->more() )
2827 // 4(b). Copy free nodes
2829 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2831 while ( srcNodeIt->more() )
2833 nSrc = srcNodeIt->next();
2834 if ( nSrc->NbInverseElements() == 0 )
2837 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2839 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2846 int nbNewGroups = 0;
2849 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2850 while ( gIt->more() )
2852 SMESH_Group* group = gIt->next();
2853 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2855 // Check group type. We copy nodal groups containing nodes of copied element
2856 SMDSAbs_ElementType groupType = groupDS->GetType();
2857 if ( groupType != SMDSAbs_Node &&
2858 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2859 continue; // group type differs from types of meshPart
2861 // Find copied elements in the group
2862 vector< const SMDS_MeshElement* > groupElems;
2863 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2866 const SMDS_MeshElement* foundElem;
2867 if ( groupType == SMDSAbs_Node )
2869 while ( eIt->more() )
2870 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2871 groupElems.push_back( foundElem );
2875 while ( eIt->more() )
2876 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2877 groupElems.push_back( foundElem );
2882 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2883 if ( e2eMap.empty() ) continue;
2884 int minID = e2eMap.begin()->first->GetID();
2885 int maxID = e2eMap.rbegin()->first->GetID();
2886 TE2EMap::iterator e2e;
2887 while ( eIt->more() && groupElems.size() < e2eMap.size())
2889 const SMDS_MeshElement* e = eIt->next();
2890 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2891 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2892 groupElems.push_back( e2e->second );
2896 if ( !groupElems.empty() )
2898 SMESH::SMESH_Group_var newGroupObj =
2899 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2900 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2902 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2903 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2904 for ( unsigned i = 0; i < groupElems.size(); ++i )
2905 smdsGroup.Add( groupElems[i] );
2913 newMeshDS->Modified();
2915 *pyDump << newMesh << " = " << this
2916 << ".CopyMesh( " << meshPart << ", "
2917 << "'" << meshName << "', "
2918 << toCopyGroups << ", "
2919 << toKeepIDs << ")";
2921 delete pyDump; pyDump = 0; // allow dump in GetGroups()
2923 if ( nbNewGroups > 0 ) // dump created groups
2924 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2926 return newMesh._retn();
2929 //================================================================================
2931 * \brief Get version of MED format being used.
2933 //================================================================================
2935 char* SMESH_Gen_i::GetMEDFileVersion()
2937 MED::TInt majeur, mineur, release;
2938 majeur = mineur = release = 0;
2939 MED::GetVersionRelease(majeur, mineur, release);
2940 std::ostringstream version;
2941 version << majeur << "." << mineur << "." << release;
2942 return CORBA::string_dup( version.str().c_str() );
2945 //================================================================================
2947 * SMESH_Gen_i::GetMEDVersion
2949 * Get MED version of the file by its name
2951 //================================================================================
2952 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
2954 std::string version = MED::GetMEDVersion( theFileName );
2955 return CORBA::string_dup( version.c_str() );
2958 //================================================================================
2960 * SMESH_Gen_i::CheckCompatibility
2962 * Check compatibility of file with MED format being used.
2964 //================================================================================
2965 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
2967 return MED::CheckCompatibility( theFileName );
2970 //================================================================================
2972 * SMESH_Gen_i::GetMeshNames
2974 * Get names of meshes defined in file with the specified name
2976 //================================================================================
2977 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
2979 SMESH::string_array_var aResult = new SMESH::string_array();
2980 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
2982 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
2984 aResult->length( aNbMeshes );
2985 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
2986 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
2987 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
2990 return aResult._retn();
2993 //=============================================================================
2997 * Save SMESH module's data
2999 //=============================================================================
3000 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
3004 if (!myStudyContext)
3007 // Store study contents as a set of python commands
3010 SALOMEDS::Study_var aStudy = getStudyServant();
3012 // Declare a byte stream
3013 SALOMEDS::TMPFile_var aStreamFile;
3015 // Obtain a temporary dir
3016 TCollection_AsciiString tmpDir =
3017 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
3019 // Create a sequence of files processed
3020 SALOMEDS_Tool::ListOfFiles aFileSeq;
3021 aFileSeq.reserve( NUM_TMP_FILES );
3023 TCollection_AsciiString aStudyName( "" );
3025 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
3027 // Set names of temporary files
3028 TCollection_AsciiString filename =
3029 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
3030 TCollection_AsciiString meshfile =
3031 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
3032 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
3033 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
3034 filename = tmpDir + filename;
3035 meshfile = tmpDir + meshfile;
3038 HDFdataset* aDataset;
3039 HDFgroup* aTopGroup;
3041 HDFgroup* aSubGroup;
3042 HDFgroup* aSubSubGroup;
3043 hdf_size aSize[ 1 ];
3046 //Remove the files if they exist: BugID: 11225
3047 #ifndef WIN32 /* unix functionality */
3048 TCollection_AsciiString cmd("rm -f \"");
3050 TCollection_AsciiString cmd("del /F \"");
3057 system(cmd.ToCString());
3059 // MED writer to be used by storage process
3060 DriverMED_W_SMESHDS_Mesh myWriter;
3061 myWriter.SetFile( meshfile.ToCString() );
3064 // SetStoreName() to groups before storing hypotheses to let them refer to
3065 // groups using "store name", which is "Group <group_persistent_id>"
3067 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
3068 for ( ; itBig->More(); itBig->Next() ) {
3069 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3070 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3071 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3072 if ( !CORBA::is_nil( anObject ) ) {
3073 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3074 if ( !myMesh->_is_nil() ) {
3075 myMesh->Load(); // load from study file if not yet done
3076 TPythonDump pd; // not to dump GetGroups()
3077 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
3078 pd << ""; // to avoid optimizing pd out
3079 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
3081 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
3084 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
3085 int anId = myStudyContext->findId( string( objStr.in() ) );
3087 sprintf( grpName, "Group %d", anId );
3088 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
3089 aGrpBaseDS->SetStoreName( grpName );
3099 // ---> create HDF file
3100 aFile = new HDFfile( (char*) filename.ToCString() );
3101 aFile->CreateOnDisk();
3103 // --> iterator for top-level objects
3104 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
3105 for ( ; itBig->More(); itBig->Next() ) {
3106 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3108 // --> hypotheses root branch (only one for the study)
3109 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
3110 // create hypotheses root HDF group
3111 aTopGroup = new HDFgroup( "Hypotheses", aFile );
3112 aTopGroup->CreateOnDisk();
3114 // iterator for all hypotheses
3115 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
3116 for ( ; it->More(); it->Next() ) {
3117 SALOMEDS::SObject_wrap mySObject = it->Value();
3118 CORBA::Object_var anObject = SObjectToObject( mySObject );
3119 if ( !CORBA::is_nil( anObject ) ) {
3120 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3121 if ( !myHyp->_is_nil() ) {
3122 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3124 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
3125 std::string hypname = hn.in();
3126 std::string libname = ln.in();
3128 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3129 // WIN32 and ".so" for X-system) must be deleted
3130 int libname_len = libname.length();
3132 if( libname_len > 4 )
3133 libname.resize( libname_len - 4 );
3135 // PAL17753 (Regression: missing hypothesis in restored study)
3136 // "lib" also should be removed from the beginning
3137 //if( libname_len > 3 )
3138 //libname.resize( libname_len - 3 );
3139 if( libname_len > 6 )
3140 libname = libname.substr( 3, libname_len - 3 - 3 );
3142 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3143 CORBA::String_var hypdata = myImpl->SaveTo();
3144 int id = myStudyContext->findId( string( objStr.in() ));
3146 // for each hypothesis create HDF group basing on its id
3147 char hypGrpName[30];
3148 sprintf( hypGrpName, "Hypothesis %d", id );
3149 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3150 aGroup->CreateOnDisk();
3151 // --> type name of hypothesis
3152 aSize[ 0 ] = hypname.length() + 1;
3153 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3154 aDataset->CreateOnDisk();
3155 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3156 aDataset->CloseOnDisk();
3157 // --> server plugin library name of hypothesis
3158 aSize[ 0 ] = libname.length() + 1;
3159 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3160 aDataset->CreateOnDisk();
3161 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3162 aDataset->CloseOnDisk();
3163 // --> persistent data of hypothesis
3164 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
3165 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3166 aDataset->CreateOnDisk();
3167 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
3168 aDataset->CloseOnDisk();
3169 // close hypothesis HDF group
3170 aGroup->CloseOnDisk();
3175 // close hypotheses root HDF group
3176 aTopGroup->CloseOnDisk();
3178 // --> algorithms root branch (only one for the study)
3179 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
3180 // create algorithms root HDF group
3181 aTopGroup = new HDFgroup( "Algorithms", aFile );
3182 aTopGroup->CreateOnDisk();
3184 // iterator for all algorithms
3185 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
3186 for ( ; it->More(); it->Next() ) {
3187 SALOMEDS::SObject_wrap mySObject = it->Value();
3188 CORBA::Object_var anObject = SObjectToObject( mySObject );
3189 if ( !CORBA::is_nil( anObject ) ) {
3190 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3191 if ( !myHyp->_is_nil() ) {
3192 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3194 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
3195 std::string hypname = hn.in();
3196 std::string libname = ln.in();
3198 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3199 // WIN32 and ".so" for X-system) must be deleted
3200 int libname_len = libname.length();
3202 if( libname_len > 4 )
3203 libname.resize( libname_len - 4 );
3205 // PAL17753 (Regression: missing hypothesis in restored study)
3206 // "lib" also should be removed from the beginning
3207 //if( libname_len > 3 )
3208 //libname.resize( libname_len - 3 );
3209 if( libname_len > 6 )
3210 libname = libname.substr( 3, libname_len - 3 - 3 );
3212 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3213 CORBA::String_var hypdata = myImpl->SaveTo();
3214 int id = myStudyContext->findId( string( objStr.in() ) );
3216 // for each algorithm create HDF group basing on its id
3217 char hypGrpName[30];
3218 sprintf( hypGrpName, "Algorithm %d", id );
3219 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3220 aGroup->CreateOnDisk();
3221 // --> type name of algorithm
3222 aSize[0] = hypname.length() + 1;
3223 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3224 aDataset->CreateOnDisk();
3225 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3226 aDataset->CloseOnDisk();
3227 // --> server plugin library name of hypothesis
3228 aSize[0] = libname.length() + 1;
3229 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3230 aDataset->CreateOnDisk();
3231 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3232 aDataset->CloseOnDisk();
3233 // --> persistent data of algorithm
3234 aSize[0] = strlen( hypdata.in() ) + 1;
3235 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3236 aDataset->CreateOnDisk();
3237 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
3238 aDataset->CloseOnDisk();
3239 // close algorithm HDF group
3240 aGroup->CloseOnDisk();
3245 // close algorithms root HDF group
3246 aTopGroup->CloseOnDisk();
3248 // --> mesh objects roots branches
3249 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3250 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3251 if ( !CORBA::is_nil( anObject ) ) {
3252 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3253 if ( !myMesh->_is_nil() ) {
3254 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
3256 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3257 int id = myStudyContext->findId( string( objStr.in() ) );
3258 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
3259 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
3260 bool hasShape = myLocMesh.HasShapeToMesh();
3262 // for each mesh open the HDF group basing on its id
3263 char meshGrpName[ 30 ];
3264 sprintf( meshGrpName, "Mesh %d", id );
3265 aTopGroup = new HDFgroup( meshGrpName, aFile );
3266 aTopGroup->CreateOnDisk();
3268 // --> put dataset to hdf file which is a flag that mesh has data
3269 string strHasData = "0";
3270 // check if the mesh is not empty
3271 if ( mySMESHDSMesh->NbNodes() > 0 ) {
3272 // write mesh data to med file
3273 myWriter.SetMesh( mySMESHDSMesh );
3274 myWriter.SetMeshId( id );
3277 aSize[ 0 ] = strHasData.length() + 1;
3278 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
3279 aDataset->CreateOnDisk();
3280 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
3281 aDataset->CloseOnDisk();
3284 // for each mesh open the HDF group basing on its auto color parameter
3285 char meshAutoColorName[ 30 ];
3286 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
3288 anAutoColor[0] = myImpl->GetAutoColor();
3290 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
3291 aDataset->CreateOnDisk();
3292 aDataset->WriteOnDisk( anAutoColor );
3293 aDataset->CloseOnDisk();
3295 // issue 0020693. Store _isModified flag
3296 int isModified = myLocMesh.GetIsModified();
3298 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
3299 aDataset->CreateOnDisk();
3300 aDataset->WriteOnDisk( &isModified );
3301 aDataset->CloseOnDisk();
3303 // issue 20918. Store Persistent Id of SMESHDS_Mesh
3304 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
3306 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
3307 aDataset->CreateOnDisk();
3308 aDataset->WriteOnDisk( &meshPersistentId );
3309 aDataset->CloseOnDisk();
3311 // write reference on a shape if exists
3312 SALOMEDS::SObject_wrap myRef;
3313 bool shapeRefFound = false;
3314 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
3316 SALOMEDS::SObject_wrap myShape;
3317 bool ok = myRef->ReferencedObject( myShape.inout() );
3319 CORBA::Object_var shapeObj = myShape->GetObject();
3320 shapeRefFound = (! CORBA::is_nil( shapeObj ));
3321 CORBA::String_var myRefOnObject = myShape->GetID();
3322 if ( shapeRefFound && myRefOnObject.in()[0] ) {
3323 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
3324 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
3325 aDataset->CreateOnDisk();
3326 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
3327 aDataset->CloseOnDisk();
3332 // write applied hypotheses if exist
3333 SALOMEDS::SObject_wrap myHypBranch;
3334 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
3335 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
3336 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
3338 if ( found && (shapeRefFound || !hasShape) ) {
3339 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
3340 aGroup->CreateOnDisk();
3342 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
3344 for ( ; it->More(); it->Next() ) {
3345 SALOMEDS::SObject_wrap mySObject = it->Value();
3346 SALOMEDS::SObject_wrap myRefOnHyp;
3347 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
3349 // san - it is impossible to recover applied hypotheses
3350 // using their entries within Load() method,
3351 // for there are no AttributeIORs in the study when Load() is working.
3352 // Hence, it is better to store persistent IDs of hypotheses as references to them
3354 //string myRefOnObject = myRefOnHyp->GetID();
3355 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3356 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3357 int id = myStudyContext->findId( string( objStr.in() ) );
3358 //if ( myRefOnObject.length() > 0 ) {
3359 //aSize[ 0 ] = myRefOnObject.length() + 1;
3360 char hypName[ 30 ], hypId[ 30 ];
3361 sprintf( hypName, "Hyp %d", ++hypNb );
3362 sprintf( hypId, "%d", id );
3363 aSize[ 0 ] = strlen( hypId ) + 1;
3364 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
3365 aDataset->CreateOnDisk();
3366 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3367 aDataset->WriteOnDisk( hypId );
3368 aDataset->CloseOnDisk();
3372 aGroup->CloseOnDisk();
3375 // write applied algorithms if exist
3376 SALOMEDS::SObject_wrap myAlgoBranch;
3377 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3378 myAlgoBranch.inout() );
3379 if ( found && !shapeRefFound && hasShape) { // remove applied algos
3380 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
3382 if ( found && (shapeRefFound || !hasShape)) {
3383 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3384 aGroup->CreateOnDisk();
3386 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
3388 for ( ; it->More(); it->Next() ) {
3389 SALOMEDS::SObject_wrap mySObject = it->Value();
3390 SALOMEDS::SObject_wrap myRefOnAlgo;
3391 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
3393 // san - it is impossible to recover applied algorithms
3394 // using their entries within Load() method,
3395 // for there are no AttributeIORs in the study when Load() is working.
3396 // Hence, it is better to store persistent IDs of algorithms as references to them
3398 //string myRefOnObject = myRefOnAlgo->GetID();
3399 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3400 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3401 int id = myStudyContext->findId( string( objStr.in() ) );
3402 //if ( myRefOnObject.length() > 0 ) {
3403 //aSize[ 0 ] = myRefOnObject.length() + 1;
3404 char algoName[ 30 ], algoId[ 30 ];
3405 sprintf( algoName, "Algo %d", ++algoNb );
3406 sprintf( algoId, "%d", id );
3407 aSize[ 0 ] = strlen( algoId ) + 1;
3408 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
3409 aDataset->CreateOnDisk();
3410 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3411 aDataset->WriteOnDisk( algoId );
3412 aDataset->CloseOnDisk();
3416 aGroup->CloseOnDisk();
3419 // --> submesh objects sub-branches
3421 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
3422 SALOMEDS::SObject_wrap mySubmeshBranch;
3423 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
3425 if ( found ) // check if there is shape reference in submeshes
3427 bool hasShapeRef = false;
3428 SALOMEDS::ChildIterator_wrap itSM =
3429 aStudy->NewChildIterator( mySubmeshBranch );
3430 for ( ; itSM->More(); itSM->Next() ) {
3431 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
3432 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3433 mySubRef->ReferencedObject( myShape.inout() );
3434 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
3437 { // remove one submesh
3438 if ( shapeRefFound )
3439 { // unassign hypothesis
3440 SMESH::SMESH_subMesh_var mySubMesh =
3441 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
3442 if ( !mySubMesh->_is_nil() ) {
3443 int shapeID = mySubMesh->GetId();
3444 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
3445 const list<const SMESHDS_Hypothesis*>& hypList =
3446 mySMESHDSMesh->GetHypothesis( S );
3447 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
3448 while ( hyp != hypList.end() ) {
3449 int hypID = (*hyp++)->GetID(); // goto next hyp here because
3450 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
3454 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
3456 } // loop on submeshes of a type
3457 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
3458 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
3461 } // end check if there is shape reference in submeshes
3463 char name_meshgroup[ 30 ];
3464 if ( i == GetSubMeshOnVertexTag() )
3465 strcpy( name_meshgroup, "SubMeshes On Vertex" );
3466 else if ( i == GetSubMeshOnEdgeTag() )
3467 strcpy( name_meshgroup, "SubMeshes On Edge" );
3468 else if ( i == GetSubMeshOnWireTag() )
3469 strcpy( name_meshgroup, "SubMeshes On Wire" );
3470 else if ( i == GetSubMeshOnFaceTag() )
3471 strcpy( name_meshgroup, "SubMeshes On Face" );
3472 else if ( i == GetSubMeshOnShellTag() )
3473 strcpy( name_meshgroup, "SubMeshes On Shell" );
3474 else if ( i == GetSubMeshOnSolidTag() )
3475 strcpy( name_meshgroup, "SubMeshes On Solid" );
3476 else if ( i == GetSubMeshOnCompoundTag() )
3477 strcpy( name_meshgroup, "SubMeshes On Compound" );
3479 // for each type of submeshes create container HDF group
3480 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
3481 aGroup->CreateOnDisk();
3483 // iterator for all submeshes of given type
3484 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
3485 for ( ; itSM->More(); itSM->Next() ) {
3486 SALOMEDS::SObject_wrap mySObject = itSM->Value();
3487 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
3488 if ( !CORBA::is_nil( anSubObject ))
3490 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
3491 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
3492 int subid = myStudyContext->findId( string( objStr.in() ) );
3494 // for each mesh open the HDF group basing on its id
3495 char submeshGrpName[ 30 ];
3496 sprintf( submeshGrpName, "SubMesh %d", subid );
3497 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
3498 aSubGroup->CreateOnDisk();
3500 // write reference on a shape, already checked if it exists
3501 SALOMEDS::SObject_wrap mySubRef, myShape;
3502 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3503 mySubRef->ReferencedObject( myShape.inout() );
3504 string myRefOnObject = myShape->GetID();
3505 if ( myRefOnObject.length() > 0 ) {
3506 aSize[ 0 ] = myRefOnObject.length() + 1;
3507 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
3508 aDataset->CreateOnDisk();
3509 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3510 aDataset->CloseOnDisk();
3513 // write applied hypotheses if exist
3514 SALOMEDS::SObject_wrap mySubHypBranch;
3515 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
3516 mySubHypBranch.inout() );
3518 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
3519 aSubSubGroup->CreateOnDisk();
3521 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
3523 for ( ; it->More(); it->Next() ) {
3524 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3525 SALOMEDS::SObject_wrap myRefOnHyp;
3526 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
3528 //string myRefOnObject = myRefOnHyp->GetID();
3529 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3530 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3531 int id = myStudyContext->findId( string( objStr.in() ) );
3532 //if ( myRefOnObject.length() > 0 ) {
3533 //aSize[ 0 ] = myRefOnObject.length() + 1;
3534 char hypName[ 30 ], hypId[ 30 ];
3535 sprintf( hypName, "Hyp %d", ++hypNb );
3536 sprintf( hypId, "%d", id );
3537 aSize[ 0 ] = strlen( hypId ) + 1;
3538 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
3539 aDataset->CreateOnDisk();
3540 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3541 aDataset->WriteOnDisk( hypId );
3542 aDataset->CloseOnDisk();
3546 aSubSubGroup->CloseOnDisk();
3549 // write applied algorithms if exist
3550 SALOMEDS::SObject_wrap mySubAlgoBranch;
3551 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3552 mySubAlgoBranch.inout() );
3554 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3555 aSubSubGroup->CreateOnDisk();
3557 SALOMEDS::ChildIterator_wrap it =
3558 aStudy->NewChildIterator( mySubAlgoBranch );
3560 for ( ; it->More(); it->Next() ) {
3561 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3562 SALOMEDS::SObject_wrap myRefOnAlgo;
3563 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
3565 //string myRefOnObject = myRefOnAlgo->GetID();
3566 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3567 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3568 int id = myStudyContext->findId( string( objStr.in() ) );
3569 //if ( myRefOnObject.length() > 0 ) {
3570 //aSize[ 0 ] = myRefOnObject.length() + 1;
3571 char algoName[ 30 ], algoId[ 30 ];
3572 sprintf( algoName, "Algo %d", ++algoNb );
3573 sprintf( algoId, "%d", id );
3574 aSize[ 0 ] = strlen( algoId ) + 1;
3575 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
3576 aDataset->CreateOnDisk();
3577 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3578 aDataset->WriteOnDisk( algoId );
3579 aDataset->CloseOnDisk();
3583 aSubSubGroup->CloseOnDisk();
3585 // close submesh HDF group
3586 aSubGroup->CloseOnDisk();
3589 // close container of submeshes by type HDF group
3590 aGroup->CloseOnDisk();
3593 // All sub-meshes will be stored in MED file
3594 // .. will NOT (PAL 12992)
3595 //if ( shapeRefFound )
3596 //myWriter.AddAllSubMeshes();
3598 // store submesh order if any
3599 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
3600 if ( theOrderIds.size() ) {
3601 char order_list[ 30 ];
3602 strcpy( order_list, "Mesh Order" );
3603 // count number of submesh ids
3605 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
3606 for ( ; idIt != theOrderIds.end(); idIt++ )
3607 nbIDs += (*idIt).size();
3608 // number of values = number of IDs +
3609 // number of lists (for separators) - 1
3610 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
3611 idIt = theOrderIds.begin();
3612 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
3613 const TListOfInt& idList = *idIt;
3614 if (idIt != theOrderIds.begin()) // not first list
3615 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
3616 // dump submesh ids from current list
3617 TListOfInt::const_iterator id_smId = idList.begin();
3618 for( ; id_smId != idList.end(); id_smId++ )
3619 smIDs[ i++ ] = *id_smId;
3622 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
3624 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
3625 aDataset->CreateOnDisk();
3626 aDataset->WriteOnDisk( smIDs );
3627 aDataset->CloseOnDisk();
3632 // groups root sub-branch
3633 SALOMEDS::SObject_wrap myGroupsBranch;
3634 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
3635 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
3637 char name_group[ 30 ];
3638 if ( i == GetNodeGroupsTag() )
3639 strcpy( name_group, "Groups of Nodes" );
3640 else if ( i == GetEdgeGroupsTag() )
3641 strcpy( name_group, "Groups of Edges" );
3642 else if ( i == GetFaceGroupsTag() )
3643 strcpy( name_group, "Groups of Faces" );
3644 else if ( i == GetVolumeGroupsTag() )
3645 strcpy( name_group, "Groups of Volumes" );
3646 else if ( i == Get0DElementsGroupsTag() )
3647 strcpy( name_group, "Groups of 0D Elements" );
3648 else if ( i == GetBallElementsGroupsTag() )
3649 strcpy( name_group, "Groups of Balls" );
3651 aGroup = new HDFgroup( name_group, aTopGroup );
3652 aGroup->CreateOnDisk();
3654 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
3655 for ( ; it->More(); it->Next() ) {
3656 SALOMEDS::SObject_wrap mySObject = it->Value();
3657 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
3658 if ( !CORBA::is_nil( aSubObject ) ) {
3659 SMESH_GroupBase_i* myGroupImpl =
3660 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
3663 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
3667 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
3668 int anId = myStudyContext->findId( string( objStr.in() ) );
3670 // For each group, create a dataset named "Group <group_persistent_id>"
3671 // and store the group's user name into it
3672 const char* grpName = aGrpBaseDS->GetStoreName();
3673 CORBA::String_var aUserName = myGroupImpl->GetName();
3674 aSize[ 0 ] = strlen( aUserName ) + 1;
3676 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
3677 aDataset->CreateOnDisk();
3678 aDataset->WriteOnDisk( aUserName );
3679 aDataset->CloseOnDisk();
3682 // For each group, create a dataset named "Group <group_persistent_id> Color"
3683 // and store the group's color into it
3684 char grpColorName[ 30 ];
3685 sprintf( grpColorName, "ColorGroup %d", anId );
3686 SALOMEDS::Color aColor = myGroupImpl->GetColor();
3688 anRGB[ 0 ] = aColor.R;
3689 anRGB[ 1 ] = aColor.G;
3690 anRGB[ 2 ] = aColor.B;
3692 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
3693 aDataset->CreateOnDisk();
3694 aDataset->WriteOnDisk( anRGB );
3695 aDataset->CloseOnDisk();
3697 // Pass SMESHDS_Group to MED writer
3698 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
3700 myWriter.AddGroup( aGrpDS );
3702 // write reference on a shape if exists
3703 SMESHDS_GroupOnGeom* aGeomGrp =
3704 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
3706 SALOMEDS::SObject_wrap mySubRef, myShape;
3707 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
3708 mySubRef->ReferencedObject( myShape.inout() ) &&
3709 !CORBA::is_nil( myShape->GetObject() ))
3711 CORBA::String_var myRefOnObject = myShape->GetID();
3712 if ( myRefOnObject.in()[0] ) {
3713 char aRefName[ 30 ];
3714 sprintf( aRefName, "Ref on shape %d", anId);
3715 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
3716 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
3717 aDataset->CreateOnDisk();
3718 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
3719 aDataset->CloseOnDisk();
3722 else // shape ref is invalid:
3724 // save a group on geometry as ordinary group
3725 myWriter.AddGroup( aGeomGrp );
3728 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
3729 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
3731 std::string str = aFilterGrp_i->FilterToString();
3732 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
3733 aSize[ 0 ] = str.length() + 1;
3734 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
3735 aDataset->CreateOnDisk();
3736 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
3737 aDataset->CloseOnDisk();
3741 aGroup->CloseOnDisk();
3745 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
3747 // Flush current mesh information into MED file
3750 // save info on nb of elements
3751 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
3753 // maybe a shape was deleted in the study
3754 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
3755 TopoDS_Shape nullShape;
3756 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
3759 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
3764 aGroup = new HDFgroup( "Submeshes", aTopGroup );
3765 aGroup->CreateOnDisk();
3767 // each element belongs to one or none submesh,
3768 // so for each node/element, we store a submesh ID
3770 // Store submesh IDs
3771 for ( int isNode = 0; isNode < 2; ++isNode )
3773 SMDS_ElemIteratorPtr eIt =
3774 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
3775 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
3778 std::vector<int> smIDs; smIDs.reserve( nbElems );
3779 while ( eIt->more() )
3780 if ( const SMDS_MeshElement* e = eIt->next())
3781 smIDs.push_back( e->getshapeId() );
3783 aSize[ 0 ] = nbElems;
3784 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3785 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3786 aDataset->CreateOnDisk();
3787 aDataset->WriteOnDisk( & smIDs[0] );
3788 aDataset->CloseOnDisk();
3791 aGroup->CloseOnDisk();
3793 // Store node positions on sub-shapes (SMDS_Position):
3794 // ----------------------------------------------------
3796 aGroup = new HDFgroup( "Node Positions", aTopGroup );
3797 aGroup->CreateOnDisk();
3799 // in aGroup, create 5 datasets to contain:
3800 // "Nodes on Edges" - ID of node on edge
3801 // "Edge positions" - U parameter on node on edge
3802 // "Nodes on Faces" - ID of node on face
3803 // "Face U positions" - U parameter of node on face
3804 // "Face V positions" - V parameter of node on face
3806 // Find out nb of nodes on edges and faces
3807 // Collect corresponding sub-meshes
3808 int nbEdgeNodes = 0, nbFaceNodes = 0;
3809 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
3810 // loop on SMESHDS_SubMesh'es
3811 while ( smIt->more() )
3813 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
3814 if ( aSubMesh->IsComplexSubmesh() )
3815 continue; // submesh containing other submeshs
3816 int nbNodes = aSubMesh->NbNodes();
3817 if ( nbNodes == 0 ) continue;
3819 int aShapeID = aSubMesh->GetID();
3820 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
3822 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
3823 // write only SMDS_FacePosition and SMDS_EdgePosition
3824 switch ( aShapeType ) {
3826 nbFaceNodes += nbNodes;
3827 aFaceSM.push_back( aSubMesh );
3830 nbEdgeNodes += nbNodes;
3831 aEdgeSM.push_back( aSubMesh );
3837 // Treat positions on edges or faces
3838 for ( int onFace = 0; onFace < 2; onFace++ )
3840 // Create arrays to store in datasets
3841 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
3842 if (!nbNodes) continue;
3843 int* aNodeIDs = new int [ nbNodes ];
3844 double* aUPos = new double [ nbNodes ];
3845 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
3848 // loop on sub-meshes
3849 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
3850 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
3851 for ( ; itSM != pListSM->end(); itSM++ )
3853 SMESHDS_SubMesh* aSubMesh = (*itSM);
3855 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
3856 // loop on nodes in aSubMesh
3857 while ( itNode->more() )
3860 const SMDS_MeshNode* node = itNode->next();
3861 aNodeIDs [ iNode ] = node->GetID();
3864 const SMDS_PositionPtr pos = node->GetPosition();
3865 if ( onFace ) { // on FACE
3866 SMDS_FacePositionPtr fPos = pos;
3868 aUPos[ iNode ] = fPos->GetUParameter();
3869 aVPos[ iNode ] = fPos->GetVParameter();
3876 SMDS_EdgePositionPtr ePos = pos;
3878 aUPos[ iNode ] = ePos->GetUParameter();
3884 } // loop on nodes in aSubMesh
3885 } // loop on sub-meshes
3890 aSize[ 0 ] = nbNodes;
3892 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
3893 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3894 aDataset->CreateOnDisk();
3895 aDataset->WriteOnDisk( aNodeIDs );
3896 aDataset->CloseOnDisk();
3899 aDSName = ( onFace ? "Face U positions" : "Edge positions");
3900 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
3901 aDataset->CreateOnDisk();
3902 aDataset->WriteOnDisk( aUPos );
3903 aDataset->CloseOnDisk();
3906 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
3907 aDataset->CreateOnDisk();
3908 aDataset->WriteOnDisk( aVPos );
3909 aDataset->CloseOnDisk();
3914 if ( aVPos ) delete [] aVPos;
3916 } // treat positions on edges or faces
3918 // close "Node Positions" group
3919 aGroup->CloseOnDisk();
3921 } // if ( there are submeshes in SMESHDS_Mesh )
3924 // close mesh HDF group
3925 aTopGroup->CloseOnDisk();
3933 aFile->CloseOnDisk();
3936 // Convert temporary files to stream
3937 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
3939 // Remove temporary files and directory
3941 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
3943 return aStreamFile._retn();
3946 //=============================================================================
3948 * SMESH_Gen_i::SaveASCII
3950 * Save SMESH module's data in ASCII format
3952 //=============================================================================
3954 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
3956 bool isMultiFile ) {
3957 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
3958 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
3959 return aStreamFile._retn();
3961 //after usual saving needs to encipher binary to text string
3962 //Any binary symbol will be represent as "|xx" () hexadecimal format number
3963 int size = aStreamFile.in().length();
3964 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
3965 for ( int i = 0; i < size; i++ )
3966 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
3968 buffer[size * 3] = '\0';
3970 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
3972 return anAsciiStreamFile._retn();
3975 //=============================================================================
3977 * SMESH_Gen_i::loadGeomData
3979 * Load GEOM module data
3981 //=============================================================================
3983 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
3985 if ( theCompRoot->_is_nil() )
3988 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
3989 aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
3992 //=============================================================================
3996 * Load SMESH module's data
3998 //=============================================================================
4000 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
4001 const SALOMEDS::TMPFile& theStream,
4005 if (!myStudyContext)
4007 SALOMEDS::Study_var aStudy = getStudyServant();
4008 /* if( !theComponent->_is_nil() )
4010 if( !aStudy->FindComponent( "GEOM" )->_is_nil() )
4011 loadGeomData( aStudy->FindComponent( "GEOM" ) );
4014 // Get temporary files location
4015 TCollection_AsciiString tmpDir =
4016 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
4018 // Convert the stream into sequence of files to process
4019 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
4022 TCollection_AsciiString aStudyName( "" );
4023 if ( isMultiFile ) {
4024 CORBA::WString_var url = aStudy->URL();
4025 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
4027 // Set names of temporary files
4028 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
4029 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
4033 HDFdataset* aDataset;
4034 HDFgroup* aTopGroup;
4036 HDFgroup* aSubGroup;
4037 HDFgroup* aSubSubGroup;
4040 // ---> open HDF file
4041 aFile = new HDFfile( (char*) filename.ToCString() );
4043 aFile->OpenOnDisk( HDF_RDONLY );
4045 catch ( HDFexception ) {
4046 INFOS( "Load(): " << filename << " not found!" );
4050 TPythonDump pd; // prevent dump during loading
4052 // DriverMED_R_SMESHDS_Mesh myReader;
4053 // myReader.SetFile( meshfile.ToCString() );
4055 // For PAL13473 ("Repetitive mesh") implementation.
4056 // New dependencies between SMESH objects are established:
4057 // now hypotheses can refer to meshes, shapes and other hypotheses.
4058 // To keep data consistent, the following order of data restoration
4060 // 1. Create hypotheses
4061 // 2. Create all meshes
4062 // 3. Load hypotheses' data
4065 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
4066 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
4067 list< SMESH::Filter_var > filters;
4069 // get total number of top-level groups
4070 int aNbGroups = aFile->nInternalObjects();
4071 if ( aNbGroups > 0 ) {
4072 // --> in first turn we should read&create hypotheses
4073 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
4074 // open hypotheses root HDF group
4075 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4076 aTopGroup->OpenOnDisk();
4078 // get number of hypotheses
4079 int aNbObjects = aTopGroup->nInternalObjects();
4080 for ( int j = 0; j < aNbObjects; j++ ) {
4081 // try to identify hypothesis
4082 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4083 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4085 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
4086 // open hypothesis group
4087 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4088 aGroup->OpenOnDisk();
4090 // --> get hypothesis id
4091 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
4096 // get number of datasets
4097 int aNbSubObjects = aGroup->nInternalObjects();
4098 for ( int k = 0; k < aNbSubObjects; k++ ) {
4100 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4101 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4102 // --> get hypothesis name
4103 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4104 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4105 aDataset->OpenOnDisk();
4106 size = aDataset->GetSize();
4107 char* hypname_str = new char[ size ];
4108 aDataset->ReadFromDisk( hypname_str );
4109 hypname = string( hypname_str );
4110 delete [] hypname_str;
4111 aDataset->CloseOnDisk();
4113 // --> get hypothesis plugin library name
4114 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4115 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4116 aDataset->OpenOnDisk();
4117 size = aDataset->GetSize();
4118 char* libname_str = new char[ size ];
4119 aDataset->ReadFromDisk( libname_str );
4120 if(MYDEBUG) SCRUTE( libname_str );
4121 libname = string( libname_str );
4122 delete [] libname_str;
4123 aDataset->CloseOnDisk();
4125 // --> get hypothesis data
4126 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4127 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4128 aDataset->OpenOnDisk();
4129 size = aDataset->GetSize();
4130 char* hypdata_str = new char[ size ];
4131 aDataset->ReadFromDisk( hypdata_str );
4132 hypdata = string( hypdata_str );
4133 delete [] hypdata_str;
4134 aDataset->CloseOnDisk();
4137 // close hypothesis HDF group
4138 aGroup->CloseOnDisk();
4140 // --> restore hypothesis from data
4141 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4142 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
4143 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4144 SMESH::SMESH_Hypothesis_var myHyp;
4146 try { // protect persistence mechanism against exceptions
4147 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4150 INFOS( "Exception during hypothesis creation" );
4153 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4155 // myImpl->LoadFrom( hypdata.c_str() );
4156 hypDataList.push_back( make_pair( myImpl, hypdata ));
4157 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4158 int newId = myStudyContext->findId( iorString.in() );
4159 myStudyContext->mapOldToNew( id, newId );
4162 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4166 // close hypotheses root HDF group
4167 aTopGroup->CloseOnDisk();
4171 // --> then we should read&create algorithms
4172 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
4173 // open algorithms root HDF group
4174 aTopGroup = new HDFgroup( "Algorithms", aFile );
4175 aTopGroup->OpenOnDisk();
4177 // get number of algorithms
4178 int aNbObjects = aTopGroup->nInternalObjects();
4179 for ( int j = 0; j < aNbObjects; j++ ) {
4180 // try to identify algorithm
4181 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4182 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4184 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
4185 // open algorithm group
4186 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4187 aGroup->OpenOnDisk();
4189 // --> get algorithm id
4190 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
4195 // get number of datasets
4196 int aNbSubObjects = aGroup->nInternalObjects();
4197 for ( int k = 0; k < aNbSubObjects; k++ ) {
4199 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4200 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4201 // --> get algorithm name
4202 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4203 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4204 aDataset->OpenOnDisk();
4205 size = aDataset->GetSize();
4206 char* hypname_str = new char[ size ];
4207 aDataset->ReadFromDisk( hypname_str );
4208 hypname = string( hypname_str );
4209 delete [] hypname_str;
4210 aDataset->CloseOnDisk();
4212 // --> get algorithm plugin library name
4213 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4214 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4215 aDataset->OpenOnDisk();
4216 size = aDataset->GetSize();
4217 char* libname_str = new char[ size ];
4218 aDataset->ReadFromDisk( libname_str );
4219 if(MYDEBUG) SCRUTE( libname_str );
4220 libname = string( libname_str );
4221 delete [] libname_str;
4222 aDataset->CloseOnDisk();
4224 // --> get algorithm data
4225 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4226 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4227 aDataset->OpenOnDisk();
4228 size = aDataset->GetSize();
4229 char* hypdata_str = new char[ size ];
4230 aDataset->ReadFromDisk( hypdata_str );
4231 if(MYDEBUG) SCRUTE( hypdata_str );
4232 hypdata = string( hypdata_str );
4233 delete [] hypdata_str;
4234 aDataset->CloseOnDisk();
4237 // close algorithm HDF group
4238 aGroup->CloseOnDisk();
4240 // --> restore algorithm from data
4241 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4242 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
4243 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4244 SMESH::SMESH_Hypothesis_var myHyp;
4246 try { // protect persistence mechanism against exceptions
4247 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4250 INFOS( "Exception during hypothesis creation" );
4253 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4255 //myImpl->LoadFrom( hypdata.c_str() );
4256 hypDataList.push_back( make_pair( myImpl, hypdata ));
4257 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4258 int newId = myStudyContext->findId( iorString.in() );
4259 myStudyContext->mapOldToNew( id, newId );
4262 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4266 // close algorithms root HDF group
4267 aTopGroup->CloseOnDisk();
4271 // --> the rest groups should be meshes
4272 for ( int i = 0; i < aNbGroups; i++ ) {
4273 // identify next group
4274 char meshName[ HDF_NAME_MAX_LEN+1 ];
4275 aFile->InternalObjectIndentify( i, meshName );
4277 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
4279 int id = atoi( string( meshName ).substr( 4 ).c_str() );
4283 // open mesh HDF group
4284 aTopGroup = new HDFgroup( meshName, aFile );
4285 aTopGroup->OpenOnDisk();
4287 // get number of child HDF objects
4288 int aNbObjects = aTopGroup->nInternalObjects();
4289 if ( aNbObjects > 0 ) {
4291 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
4292 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
4293 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
4294 if ( !myNewMeshImpl )
4296 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
4298 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
4299 int newId = myStudyContext->findId( iorString.in() );
4300 myStudyContext->mapOldToNew( id, newId );
4303 // try to read and set auto color flag
4304 char aMeshAutoColorName[ 30 ];
4305 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
4306 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
4308 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
4309 aDataset->OpenOnDisk();
4310 size = aDataset->GetSize();
4311 int* anAutoColor = new int[ size ];
4312 aDataset->ReadFromDisk( anAutoColor );
4313 aDataset->CloseOnDisk();
4314 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
4315 delete [] anAutoColor;
4318 // try to read and set reference to shape
4319 GEOM::GEOM_Object_var aShapeObject;
4320 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
4321 // load mesh "Ref on shape" - it's an entry to SObject
4322 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
4323 aDataset->OpenOnDisk();
4324 size = aDataset->GetSize();
4325 char* refFromFile = new char[ size ];
4326 aDataset->ReadFromDisk( refFromFile );
4327 aDataset->CloseOnDisk();
4328 if ( strlen( refFromFile ) > 0 ) {
4329 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
4331 // Make sure GEOM data are loaded first
4332 //loadGeomData( shapeSO->GetFatherComponent() );
4334 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4335 if ( !CORBA::is_nil( shapeObject ) ) {
4336 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4337 if ( !aShapeObject->_is_nil() )
4338 myNewMeshImpl->SetShape( aShapeObject );
4341 delete [] refFromFile;
4344 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
4345 if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
4347 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
4348 aDataset->OpenOnDisk();
4349 size = aDataset->GetSize();
4350 int* meshPersistentId = new int[ size ];
4351 aDataset->ReadFromDisk( meshPersistentId );
4352 aDataset->CloseOnDisk();
4353 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
4354 delete [] meshPersistentId;
4360 // As all object that can be referred by hypothesis are created,
4361 // we can restore hypothesis data
4363 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
4364 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4366 SMESH_Hypothesis_i* hyp = hyp_data->first;
4367 string & data = hyp_data->second;
4368 hyp->LoadFrom( data.c_str() );
4371 // Restore the rest mesh data
4373 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
4374 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4376 aTopGroup = meshi_group->second;
4377 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4378 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4379 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4381 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
4382 bool hasData = false;
4385 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
4386 int newId = myStudyContext->findId( iorString.in() );
4387 int id = myStudyContext->getOldId( newId );
4389 // try to find mesh data dataset
4390 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
4391 // load mesh "has data" flag
4392 aDataset = new HDFdataset( "Has data", aTopGroup );
4393 aDataset->OpenOnDisk();
4394 size = aDataset->GetSize();
4395 char* strHasData = new char[ size ];
4396 aDataset->ReadFromDisk( strHasData );
4397 aDataset->CloseOnDisk();
4398 if ( strcmp( strHasData, "1") == 0 ) {
4399 // read mesh data from MED file
4400 // myReader.SetMesh( mySMESHDSMesh );
4401 // myReader.SetMeshId( id );
4402 // myReader.Perform();
4405 delete [] strHasData;
4408 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
4409 // nodes and elements are not yet put into sub-meshes)
4410 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4411 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4412 aGroup->OpenOnDisk();
4413 // get number of applied algorithms
4414 int aNbSubObjects = aGroup->nInternalObjects();
4415 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
4416 for ( int j = 0; j < aNbSubObjects; j++ ) {
4417 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4418 aGroup->InternalObjectIndentify( j, name_dataset );
4419 // check if it is an algorithm
4420 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
4421 aDataset = new HDFdataset( name_dataset, aGroup );
4422 aDataset->OpenOnDisk();
4423 size = aDataset->GetSize();
4424 char* refFromFile = new char[ size ];
4425 aDataset->ReadFromDisk( refFromFile );
4426 aDataset->CloseOnDisk();
4427 // san - it is impossible to recover applied algorithms using their entries within Load() method
4428 //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
4429 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4430 int id = atoi( refFromFile );
4431 delete [] refFromFile;
4432 string anIOR = myStudyContext->getIORbyOldId( id );
4433 if ( !anIOR.empty() ) {
4434 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4435 if ( !CORBA::is_nil( hypObject ) ) {
4436 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4437 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4438 || !myNewMeshImpl->HasShapeToMesh()) )
4439 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4444 aGroup->CloseOnDisk();
4447 // try to get applied hypotheses
4448 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4449 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4450 aGroup->OpenOnDisk();
4451 // get number of applied hypotheses
4452 int aNbSubObjects = aGroup->nInternalObjects();
4453 for ( int j = 0; j < aNbSubObjects; j++ ) {
4454 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4455 aGroup->InternalObjectIndentify( j, name_dataset );
4456 // check if it is a hypothesis
4457 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4458 aDataset = new HDFdataset( name_dataset, aGroup );
4459 aDataset->OpenOnDisk();
4460 size = aDataset->GetSize();
4461 char* refFromFile = new char[ size ];
4462 aDataset->ReadFromDisk( refFromFile );
4463 aDataset->CloseOnDisk();
4464 // san - it is impossible to recover applied hypotheses using their entries within Load() method
4465 //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
4466 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4467 int id = atoi( refFromFile );
4468 delete [] refFromFile;
4469 string anIOR = myStudyContext->getIORbyOldId( id );
4470 if ( !anIOR.empty() ) {
4471 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4472 if ( !CORBA::is_nil( hypObject ) ) {
4473 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4474 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4475 || !myNewMeshImpl->HasShapeToMesh()) )
4476 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4481 aGroup->CloseOnDisk();
4484 // --> try to find SUB-MESHES containers for each type of submesh
4485 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
4486 const char* name_meshgroup = 0;
4487 if ( j == GetSubMeshOnVertexTag() )
4488 name_meshgroup = "SubMeshes On Vertex";
4489 else if ( j == GetSubMeshOnEdgeTag() )
4490 name_meshgroup = "SubMeshes On Edge";
4491 else if ( j == GetSubMeshOnWireTag() )
4492 name_meshgroup = "SubMeshes On Wire";
4493 else if ( j == GetSubMeshOnFaceTag() )
4494 name_meshgroup = "SubMeshes On Face";
4495 else if ( j == GetSubMeshOnShellTag() )
4496 name_meshgroup = "SubMeshes On Shell";
4497 else if ( j == GetSubMeshOnSolidTag() )
4498 name_meshgroup = "SubMeshes On Solid";
4499 else if ( j == GetSubMeshOnCompoundTag() )
4500 name_meshgroup = "SubMeshes On Compound";
4502 // try to get submeshes container HDF group
4503 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
4504 // open submeshes containers HDF group
4505 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4506 aGroup->OpenOnDisk();
4508 // get number of submeshes
4509 int aNbSubMeshes = aGroup->nInternalObjects();
4510 for ( int k = 0; k < aNbSubMeshes; k++ ) {
4512 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
4513 aGroup->InternalObjectIndentify( k, name_submeshgroup );
4514 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
4515 // --> get submesh id
4516 int subid = atoi( name_submeshgroup + 7 );
4519 // open submesh HDF group
4520 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
4521 aSubGroup->OpenOnDisk();
4523 // try to read and set reference to subshape
4524 GEOM::GEOM_Object_var aSubShapeObject;
4525 SMESH::SMESH_subMesh_var aSubMesh;
4527 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
4528 // load submesh "Ref on shape" - it's an entry to SObject
4529 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
4530 aDataset->OpenOnDisk();
4531 size = aDataset->GetSize();
4532 char* refFromFile = new char[ size ];
4533 aDataset->ReadFromDisk( refFromFile );
4534 aDataset->CloseOnDisk();
4535 if ( strlen( refFromFile ) > 0 ) {
4536 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
4537 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
4538 if ( !CORBA::is_nil( subShapeObject ) ) {
4539 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
4540 if ( !aSubShapeObject->_is_nil() )
4541 aSubMesh = SMESH::SMESH_subMesh::_duplicate
4542 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
4543 if ( aSubMesh->_is_nil() )
4545 string iorSubString = GetORB()->object_to_string( aSubMesh );
4546 int newSubId = myStudyContext->findId( iorSubString );
4547 myStudyContext->mapOldToNew( subid, newSubId );
4550 delete [] refFromFile;
4553 if ( aSubMesh->_is_nil() )
4556 // try to get applied algorithms
4557 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4558 // open "applied algorithms" HDF group
4559 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4560 aSubSubGroup->OpenOnDisk();
4561 // get number of applied algorithms
4562 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4563 for ( int l = 0; l < aNbSubObjects; l++ ) {
4564 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4565 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4566 // check if it is an algorithm
4567 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
4568 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4569 aDataset->OpenOnDisk();
4570 size = aDataset->GetSize();
4571 char* refFromFile = new char[ size ];
4572 aDataset->ReadFromDisk( refFromFile );
4573 aDataset->CloseOnDisk();
4575 int id = atoi( refFromFile );
4576 string anIOR = myStudyContext->getIORbyOldId( id );
4577 if ( !anIOR.empty() ) {
4578 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4579 if ( !CORBA::is_nil( hypObject ) ) {
4580 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4581 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4582 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4585 delete [] refFromFile;
4588 // close "applied algorithms" HDF group
4589 aSubSubGroup->CloseOnDisk();
4592 // try to get applied hypotheses
4593 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4594 // open "applied hypotheses" HDF group
4595 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4596 aSubSubGroup->OpenOnDisk();
4597 // get number of applied hypotheses
4598 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4599 for ( int l = 0; l < aNbSubObjects; l++ ) {
4600 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4601 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4602 // check if it is a hypothesis
4603 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4604 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4605 aDataset->OpenOnDisk();
4606 size = aDataset->GetSize();
4607 char* refFromFile = new char[ size ];
4608 aDataset->ReadFromDisk( refFromFile );
4609 aDataset->CloseOnDisk();
4611 int id = atoi( refFromFile );
4612 string anIOR = myStudyContext->getIORbyOldId( id );
4613 if ( !anIOR.empty() ) {
4614 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4615 if ( !CORBA::is_nil( hypObject ) ) {
4616 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4617 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4618 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4621 delete [] refFromFile;
4624 // close "APPLIED HYPOTHESES" hdf group
4625 aSubSubGroup->CloseOnDisk();
4628 // close SUB-MESH hdf group
4629 aSubGroup->CloseOnDisk();
4632 // close SUB-MESHES containers hdf group
4633 aGroup->CloseOnDisk();
4637 // try to get GROUPS
4638 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
4639 char name_group[ 30 ];
4640 if ( ii == GetNodeGroupsTag() )
4641 strcpy( name_group, "Groups of Nodes" );
4642 else if ( ii == GetEdgeGroupsTag() )
4643 strcpy( name_group, "Groups of Edges" );
4644 else if ( ii == GetFaceGroupsTag() )
4645 strcpy( name_group, "Groups of Faces" );
4646 else if ( ii == GetVolumeGroupsTag() )
4647 strcpy( name_group, "Groups of Volumes" );
4648 else if ( ii == Get0DElementsGroupsTag() )
4649 strcpy( name_group, "Groups of 0D Elements" );
4650 else if ( ii == GetBallElementsGroupsTag() )
4651 strcpy( name_group, "Groups of Balls" );
4653 if ( aTopGroup->ExistInternalObject( name_group ) ) {
4654 aGroup = new HDFgroup( name_group, aTopGroup );
4655 aGroup->OpenOnDisk();
4656 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
4657 // within aGroup->ExistInternalObject( name )
4658 std::vector< std::string > subNames;
4659 TColStd_MapOfAsciiString mapOfNames;
4660 aGroup->GetAllObjects( subNames );
4661 for ( size_t iN = 0; iN < subNames.size(); ++iN )
4662 mapOfNames.Add( subNames[ iN ].c_str() );
4664 for ( size_t j = 0; j < subNames.size(); j++ ) {
4665 const std::string& name_dataset = subNames[ j ];
4666 // check if it is a group
4667 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
4669 int subid = atoi( name_dataset.substr( 5 ).c_str() );
4672 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
4673 aDataset->OpenOnDisk();
4675 // Retrieve actual group name
4676 size = aDataset->GetSize();
4677 char* nameFromFile = new char[ size ];
4678 aDataset->ReadFromDisk( nameFromFile );
4679 aDataset->CloseOnDisk();
4681 // Try to find a shape reference
4682 TopoDS_Shape aShape;
4683 char aRefName[ 30 ];
4684 sprintf( aRefName, "Ref on shape %d", subid);
4685 if ( mapOfNames.Contains( aRefName ))
4687 // load mesh "Ref on shape" - it's an entry to SObject
4688 aDataset = new HDFdataset( aRefName, aGroup );
4689 aDataset->OpenOnDisk();
4690 size = aDataset->GetSize();
4691 char* refFromFile = new char[ size ];
4692 aDataset->ReadFromDisk( refFromFile );
4693 aDataset->CloseOnDisk();
4694 if ( strlen( refFromFile ) > 0 ) {
4695 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
4696 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4697 if ( !CORBA::is_nil( shapeObject ) ) {
4698 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4699 if ( !aShapeObject->_is_nil() )
4700 aShape = GeomObjectToShape( aShapeObject );
4703 delete [] refFromFile;
4705 // Try to read a filter of SMESH_GroupOnFilter
4706 SMESH::Filter_var filter;
4707 SMESH_PredicatePtr predicate;
4708 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
4709 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
4711 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
4712 aDataset->OpenOnDisk();
4713 size = aDataset->GetSize();
4714 char* persistStr = new char[ size ];
4715 aDataset->ReadFromDisk( persistStr );
4716 aDataset->CloseOnDisk();
4717 if ( strlen( persistStr ) > 0 ) {
4718 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
4719 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
4720 filters.push_back( filter );
4722 delete [] persistStr;
4725 // Create group servant
4726 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
4727 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
4728 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape, predicate ) );
4729 delete [] nameFromFile;
4730 // Obtain a SMESHDS_Group object
4731 if ( aNewGroup->_is_nil() )
4734 string iorSubString = GetORB()->object_to_string( aNewGroup );
4735 int newSubId = myStudyContext->findId( iorSubString );
4736 myStudyContext->mapOldToNew( subid, newSubId );
4738 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
4742 if ( SMESH_GroupOnFilter_i* aFilterGroup =
4743 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
4745 aFilterGroup->SetFilter( filter );
4746 filter->UnRegister();
4748 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
4749 if ( !aGroupBaseDS )
4752 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
4755 // Read color of the group
4756 char aGroupColorName[ 30 ];
4757 sprintf( aGroupColorName, "ColorGroup %d", subid);
4758 if ( mapOfNames.Contains( aGroupColorName ))
4760 aDataset = new HDFdataset( aGroupColorName, aGroup );
4761 aDataset->OpenOnDisk();
4762 size = aDataset->GetSize();
4763 double* anRGB = new double[ size ];
4764 aDataset->ReadFromDisk( anRGB );
4765 aDataset->CloseOnDisk();
4766 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
4767 aGroupBaseDS->SetColor( aColor );
4772 aGroup->CloseOnDisk();
4776 // instead of reading mesh data, we read only brief information of all
4777 // objects: mesh, groups, sub-meshes (issue 0021208 )
4780 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, id,
4781 meshfile.ToCString(), filename.ToCString(),
4785 // read Sub-Mesh ORDER if any
4786 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
4787 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
4788 aDataset->OpenOnDisk();
4789 size = aDataset->GetSize();
4790 int* smIDs = new int[ size ];
4791 aDataset->ReadFromDisk( smIDs );
4792 aDataset->CloseOnDisk();
4793 TListOfListOfInt anOrderIds;
4794 anOrderIds.push_back( TListOfInt() );
4795 for ( int i = 0; i < size; i++ )
4796 if ( smIDs[ i ] < 0 ) // is separator
4797 anOrderIds.push_back( TListOfInt() );
4799 anOrderIds.back().push_back(smIDs[ i ]);
4801 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
4806 // update hyps needing full mesh data restored (issue 20918)
4807 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4809 SMESH_Hypothesis_i* hyp = hyp_data->first;
4810 hyp->UpdateAsMeshesRestored();
4813 // notify algos on completed restoration to set sub-mesh event listeners
4814 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4816 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4817 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4819 TopoDS_Shape myLocShape;
4820 if(myLocMesh.HasShapeToMesh())
4821 myLocShape = myLocMesh.GetShapeToMesh();
4823 myLocShape = SMESH_Mesh::PseudoShape();
4825 myLocMesh.GetSubMesh(myLocShape)->
4826 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
4829 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
4830 list< SMESH::Filter_var >::iterator f = filters.begin();
4831 for ( ; f != filters.end(); ++f )
4832 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
4833 fi->FindBaseObjects();
4838 aTopGroup->CloseOnDisk();
4841 aFile->CloseOnDisk();
4844 // Remove temporary files created from the stream
4847 SMESH_File meshFile( meshfile.ToCString() );
4848 if ( !meshFile ) // no meshfile exists
4850 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
4854 Engines::Container_var container = GetContainerRef();
4855 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
4857 container_i->registerTemporaryFile( filename.ToCString() );
4858 container_i->registerTemporaryFile( meshfile.ToCString() );
4859 container_i->registerTemporaryFile( tmpDir.ToCString() );
4863 pd << ""; // prevent optimizing pd out
4865 // creation of tree nodes for all data objects in the study
4866 // to support tree representation customization and drag-n-drop:
4867 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
4868 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
4869 useCaseBuilder->SetRootCurrent();
4870 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
4871 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
4872 for (it->InitEx(true); it->More(); it->Next()) {
4873 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
4880 //=============================================================================
4882 * SMESH_Gen_i::LoadASCII
4884 * Load SMESH module's data in ASCII format
4886 //=============================================================================
4888 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
4889 const SALOMEDS::TMPFile& theStream,
4891 bool isMultiFile ) {
4892 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
4893 return Load( theComponent, theStream, theURL, isMultiFile );
4895 //before call main ::Load method it's need for decipher text format to
4896 //binary ( "|xx" => x' )
4897 int size = theStream.length();
4898 if ( int((size / 3 )*3) != size ) //error size of buffer
4901 int real_size = int(size / 3);
4903 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
4906 unsigned int c = -1;
4907 for ( int i = 0; i < real_size; i++ )
4909 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
4910 sscanf( tmp, "%x", &c );
4911 sprintf( (char*)&(buffer[i]), "%c", (char)c );
4914 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
4916 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
4919 //=============================================================================
4921 * SMESH_Gen_i::Close
4923 * Clears study-connected data when it is closed
4925 //=============================================================================
4927 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
4929 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
4931 // Clear study contexts data
4932 delete myStudyContext;
4935 // remove the tmp files meshes are loaded from
4936 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
4941 //=============================================================================
4943 * SMESH_Gen_i::ComponentDataType
4945 * Get component data type
4947 //=============================================================================
4949 char* SMESH_Gen_i::ComponentDataType()
4951 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
4952 return CORBA::string_dup( "SMESH" );
4956 //=============================================================================
4958 * SMESH_Gen_i::IORToLocalPersistentID
4960 * Transform data from transient form to persistent
4962 //=============================================================================
4964 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
4965 const char* IORString,
4966 CORBA::Boolean /*isMultiFile*/,
4967 CORBA::Boolean /*isASCII*/ )
4969 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
4971 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
4972 int anId = myStudyContext->findId( IORString );
4974 if(MYDEBUG) MESSAGE( "VSR " << anId )
4976 sprintf( strId, "%d", anId );
4977 return CORBA::string_dup( strId );
4980 return CORBA::string_dup( "" );
4983 //=============================================================================
4985 * SMESH_Gen_i::LocalPersistentIDToIOR
4987 * Transform data from persistent form to transient
4989 //=============================================================================
4991 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
4992 const char* aLocalPersistentID,
4993 CORBA::Boolean /*isMultiFile*/,
4994 CORBA::Boolean /*isASCII*/ )
4996 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
4998 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
4999 int anId = atoi( aLocalPersistentID );
5000 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
5002 return CORBA::string_dup( "" );
5005 //=======================================================================
5006 //function : RegisterObject
5008 //=======================================================================
5010 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
5012 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5013 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
5014 return myStudyContext->addObject( string( iorString.in() ) );
5019 //================================================================================
5021 * \brief Return id of registered object
5022 * \param theObject - the Object
5023 * \retval int - Object id
5025 //================================================================================
5027 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
5029 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5030 string iorString = GetORB()->object_to_string( theObject );
5031 return myStudyContext->findId( iorString );
5036 //=============================================================================
5038 * SMESH_Gen_i::SetName
5040 * Set a new object name
5042 //=============================================================================
5043 void SMESH_Gen_i::SetName(const char* theIOR,
5044 const char* theName)
5046 if ( theIOR && strcmp( theIOR, "" ) ) {
5047 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
5048 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
5049 if ( !aSO->_is_nil() ) {
5050 SetName( aSO, theName );
5055 // Version information
5056 char* SMESH_Gen_i::getVersion()
5058 #if SMESH_DEVELOPMENT
5059 return CORBA::string_dup(SMESH_VERSION_STR"dev");
5061 return CORBA::string_dup(SMESH_VERSION_STR);
5065 //=================================================================================
5066 // function : Move()
5067 // purpose : Moves objects to the specified position.
5068 // Is used in the drag-n-drop functionality.
5069 //=================================================================================
5070 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
5071 SALOMEDS::SObject_ptr where,
5074 if ( CORBA::is_nil( where ) ) return;
5076 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
5077 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
5078 SALOMEDS::SComponent_var father = where->GetFatherComponent();
5079 std::string dataType = father->ComponentDataType();
5080 if ( dataType != "SMESH" ) return; // not a SMESH component
5082 SALOMEDS::SObject_var objAfter;
5083 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
5084 // insert at given row -> find insertion position
5085 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
5087 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
5088 if ( i == row && useCaseIt->More() ) {
5089 objAfter = useCaseIt->Value();
5093 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
5094 SALOMEDS::SObject_var sobj = what[i];
5095 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
5096 // insert the object to the use case tree
5097 if ( !CORBA::is_nil( objAfter ) )
5098 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
5100 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
5103 //================================================================================
5105 * \brief Returns true if algorithm can be used to mesh a given geometry
5106 * \param [in] theAlgoType - the algorithm type
5107 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
5108 * \param [in] theGeomObject - the geometry to mesh
5109 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
5110 * else, returns \c True if at least one shape is meshable
5111 * \return CORBA::Boolean - can or can't
5113 //================================================================================
5115 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
5116 const char* theLibName,
5117 GEOM::GEOM_Object_ptr theGeomObject,
5118 CORBA::Boolean toCheckAll)
5122 std::string aPlatformLibName;
5123 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
5124 GenericHypothesisCreator_i* aCreator =
5125 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
5128 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
5129 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll );
5136 SMESH_CATCH( SMESH::doNothing );
5139 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
5144 //=================================================================================
5145 // function : GetInsideSphere
5146 // purpose : Collect indices of elements, which are located inside the sphere
5147 //=================================================================================
5148 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
5149 SMESH::ElementType theElemType,
5155 SMESH::long_array_var aResult = new SMESH::long_array();
5156 if ( meshPart->_is_nil() )
5157 return aResult._retn();
5159 // 1. Create geometrical object
5160 gp_Pnt aP( theX, theY, theZ );
5161 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
5163 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5165 if ( lst.size() > 0 ) {
5166 aResult->length( lst.size() );
5167 for ( size_t i = 0; i < lst.size(); i++ ) {
5168 aResult[i] = lst[i];
5171 return aResult._retn();
5174 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
5175 SMESH::ElementType theElemType,
5176 CORBA::Double theX1,
5177 CORBA::Double theY1,
5178 CORBA::Double theZ1,
5179 CORBA::Double theX2,
5180 CORBA::Double theY2,
5181 CORBA::Double theZ2) {
5182 SMESH::long_array_var aResult = new SMESH::long_array();
5183 if( meshPart->_is_nil() )
5184 return aResult._retn();
5186 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
5188 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5190 if( lst.size() > 0 ) {
5191 aResult->length( lst.size() );
5192 for ( size_t i = 0; i < lst.size(); i++ ) {
5193 aResult[i] = lst[i];
5196 return aResult._retn();
5199 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
5200 SMESH::ElementType theElemType,
5204 CORBA::Double theDX,
5205 CORBA::Double theDY,
5206 CORBA::Double theDZ,
5208 CORBA::Double theR ){
5209 SMESH::long_array_var aResult = new SMESH::long_array();
5210 if( meshPart->_is_nil() )
5211 return aResult._retn();
5213 gp_Pnt aP( theX, theY, theZ );
5214 gp_Vec aV( theDX, theDY, theDZ );
5215 gp_Ax2 anAxes (aP, aV);
5217 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
5219 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5221 if( lst.size() > 0 ) {
5222 aResult->length( lst.size() );
5223 for ( size_t i = 0; i < lst.size(); i++ ) {
5224 aResult[i] = lst[i];
5227 return aResult._retn();
5230 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5231 SMESH::ElementType theElemType,
5232 GEOM::GEOM_Object_ptr theGeom,
5233 CORBA::Double theTolerance ) {
5234 SMESH::long_array_var aResult = new SMESH::long_array();
5235 if( meshPart->_is_nil() || theGeom->_is_nil() )
5236 return aResult._retn();
5238 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
5240 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
5242 if( lst.size() > 0 ) {
5243 aResult->length( lst.size() );
5244 for ( size_t i = 0; i < lst.size(); i++ ) {
5245 aResult[i] = lst[i];
5248 return aResult._retn();
5253 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5254 SMESH::ElementType theElemType,
5255 TopoDS_Shape& aShape,
5256 double* theTolerance) {
5258 std::vector<long> res;
5259 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
5261 if ( mesh->_is_nil() )
5264 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
5268 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
5273 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
5274 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
5275 anElementsOnShape->SetAllNodes( true );
5276 anElementsOnShape->SetMesh( meshDS );
5277 anElementsOnShape->SetShape( aShape, aType );
5280 anElementsOnShape->SetTolerance(*theTolerance);
5282 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
5283 if ( !msource->_is_nil() ) { // Mesh case
5284 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
5286 while ( elemIt->more() ) {
5287 const SMDS_MeshElement* anElem = elemIt->next();
5288 long anId = anElem->GetID();
5289 if ( anElementsOnShape->IsSatisfy( anId ) )
5290 res.push_back( anId );
5294 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
5295 if ( !gsource->_is_nil() ) {
5296 if(theElemType == SMESH::NODE) {
5297 SMESH::long_array_var nodes = gsource->GetNodeIDs();
5298 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
5299 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
5300 long anId = node->GetID();
5301 if ( anElementsOnShape->IsSatisfy( anId ) )
5302 res.push_back( anId );
5305 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
5306 SMESH::long_array_var elems = gsource->GetListOfID();
5307 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
5308 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
5309 long anId = elem->GetID();
5310 if ( anElementsOnShape->IsSatisfy( anId ) )
5311 res.push_back( anId );
5316 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
5317 if ( !smsource->_is_nil() ) {
5318 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
5319 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
5320 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
5322 long anId = elem->GetID();
5323 if ( anElementsOnShape->IsSatisfy( anId ) )
5324 res.push_back( anId );
5332 //=============================================================================
5334 * SMESHEngine_factory
5336 * C factory, accessible with dlsym, after dlopen
5338 //=============================================================================
5342 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
5343 PortableServer::POA_ptr poa,
5344 PortableServer::ObjectId* contId,
5345 const char* instanceName,
5346 const char* interfaceName )
5348 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
5349 if(MYDEBUG) SCRUTE(interfaceName);
5350 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
5351 return aSMESHGen->getId() ;