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>
142 using SMESH::TPythonDump;
145 #define NUM_TMP_FILES 2
148 static int MYDEBUG = 0;
150 static int MYDEBUG = 0;
153 // Static variables definition
154 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
155 CORBA::ORB_var SMESH_Gen_i::myOrb;
156 PortableServer::POA_var SMESH_Gen_i::myPoa;
157 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
158 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
159 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
162 const int nbElemPerDiagonal = 10;
164 //=============================================================================
166 * GetServant [ static ]
168 * Get servant of the CORBA object
170 //=============================================================================
172 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
174 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
177 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
180 catch (PortableServer::POA::ObjectNotActive &ex)
182 INFOS("GetServant: ObjectNotActive");
185 catch (PortableServer::POA::WrongAdapter &ex)
187 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
190 catch (PortableServer::POA::WrongPolicy &ex)
192 INFOS("GetServant: WrongPolicy");
197 INFOS( "GetServant - Unknown exception was caught!!!" );
202 //=============================================================================
204 * SObjectToObject [ static ]
206 * Get CORBA object corresponding to the SALOMEDS::SObject
208 //=============================================================================
210 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
212 SALOMEDS::GenericAttribute_wrap anAttr;
213 CORBA::Object_var anObj;
214 if ( !theSObject->_is_nil() ) {
216 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
217 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
218 CORBA::String_var aValue = anIOR->Value();
219 if( strcmp( aValue, "" ) != 0 )
220 anObj = GetORB()->string_to_object( aValue );
224 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
230 //=============================================================================
234 * Get SALOME_NamingService object
236 //=============================================================================
238 SALOME_NamingService* SMESH_Gen_i::GetNS()
240 if ( myNS == NULL ) {
241 myNS = SINGLETON_<SALOME_NamingService>::Instance();
242 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
243 myNS->init_orb( GetORB() );
248 //=============================================================================
252 * Get SALOME_LifeCycleCORBA object
254 //=============================================================================
255 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC() {
256 if ( myLCC == NULL ) {
257 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
263 //=============================================================================
265 * GetGeomEngine [ static ]
267 * Get GEOM::GEOM_Gen reference
269 //=============================================================================
270 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine() {
271 //CCRT GEOM::GEOM_Gen_var aGeomEngine =
272 //CCRT GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
273 //CCRT return aGeomEngine._retn();
274 if(CORBA::is_nil(myGeomGen))
276 Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
277 myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
282 //=============================================================================
284 * SMESH_Gen_i::SMESH_Gen_i
286 * Default constructor: not for use
288 //=============================================================================
290 SMESH_Gen_i::SMESH_Gen_i()
294 //=============================================================================
296 * SMESH_Gen_i::SMESH_Gen_i
298 * Standard constructor, used with Container
300 //=============================================================================
302 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
303 PortableServer::POA_ptr poa,
304 PortableServer::ObjectId* contId,
305 const char* instanceName,
306 const char* interfaceName )
307 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
310 myOrb = CORBA::ORB::_duplicate(orb);
311 myPoa = PortableServer::POA::_duplicate(poa);
314 _id = myPoa->activate_object( _thisObj );
316 myIsEmbeddedMode = false;
317 myShapeReader = NULL; // shape reader
319 myIsHistoricalPythonDump = true;
320 myToForgetMeshDataOnHypModif = false;
322 // set it in standalone mode only
323 //OSD::SetSignal( true );
325 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
326 // find out mode (embedded or standalone) here else
327 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
328 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
329 if ( SALOME_NamingService* ns = GetNS() )
331 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
332 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
333 if ( !session->_is_nil() )
335 CORBA::String_var str_host = session->getHostname();
336 CORBA::Long s_pid = session->getPID();
337 string my_host = Kernel_Utils::GetHostname();
339 long my_pid = (long)_getpid();
341 long my_pid = (long) getpid();
343 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
348 //=============================================================================
350 * SMESH_Gen_i::~SMESH_Gen_i
354 //=============================================================================
356 SMESH_Gen_i::~SMESH_Gen_i()
358 // delete hypothesis creators
359 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
360 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
362 // same creator can be mapped under different names
363 GenericHypothesisCreator_i* creator = (*itHyp).second;
367 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
368 if ( creator == (*itHyp2).second )
369 (*itHyp2).second = 0;
371 myHypCreatorMap.clear();
373 // Clear study contexts data
374 map<int, StudyContext*>::iterator it;
375 for ( it = myStudyContextMap.begin(); it != myStudyContextMap.end(); ++it ) {
378 myStudyContextMap.clear();
379 // delete shape reader
381 delete myShapeReader;
383 //=============================================================================
385 * SMESH_Gen_i::getHypothesisCreator
387 * Get hypothesis creator
389 //=============================================================================
390 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
391 const char* theLibName,
392 std::string& thePlatformLibName)
393 throw (SALOME::SALOME_Exception)
395 std::string aPlatformLibName;
396 /* It's Need to translate lib name for WIN32 or X platform */
397 if ( theLibName && theLibName[0] != '\0' )
399 int libNameLen = strlen(theLibName);
400 //check for old format "libXXXXXXX.so"
401 if (libNameLen > 7 &&
402 !strncmp( theLibName, "lib", 3 ) &&
403 !strcmp( theLibName+libNameLen-3, ".so" ))
407 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
408 #elif defined(__APPLE__)
409 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
411 aPlatformLibName = theLibName;
416 //try to use new format
418 aPlatformLibName = theLibName;
419 aPlatformLibName += ".dll";
420 #elif defined(__APPLE__)
421 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
423 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
427 thePlatformLibName = aPlatformLibName;
429 Unexpect aCatch(SALOME_SalomeException);
430 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
432 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
433 GenericHypothesisCreator_i* aCreator;
436 // check, if creator for this hypothesis type already exists
437 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
439 // load plugin library
440 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
441 LibHandle libHandle = LoadLib( aPlatformLibName.c_str() );
444 // report any error, if occurred
446 const char* anError = dlerror();
447 throw(SALOME_Exception(anError));
449 throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
453 // get method, returning hypothesis creator
454 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
455 GetHypothesisCreator procHandle =
456 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
459 throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
460 UnLoadLib(libHandle);
463 // get hypothesis creator
464 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
465 aCreator = procHandle(theHypName);
468 throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
470 // map hypothesis creator to a hypothesis name
471 myHypCreatorMap[string(theHypName)] = aCreator;
476 return myHypCreatorMap[string(theHypName)];
479 catch (SALOME_Exception& S_ex)
481 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
486 //=============================================================================
488 * SMESH_Gen_i::createHypothesis
490 * Create hypothesis of given type
492 //=============================================================================
493 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
494 const char* theLibName)
496 SMESH_Hypothesis_i* myHypothesis_i = 0;
497 SMESH::SMESH_Hypothesis_var hypothesis_i;
498 std::string aPlatformLibName;
499 GenericHypothesisCreator_i* aCreator =
500 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
502 // create a new hypothesis object, store its ref. in studyContext
503 myHypothesis_i = aCreator->Create(myPoa, GetCurrentStudyID(), &myGen);
506 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
507 CORBA::String_var hypName = myHypothesis_i->GetName();
508 myHypCreatorMap[ hypName.in() ] = aCreator;
510 // activate the CORBA servant of hypothesis
511 hypothesis_i = myHypothesis_i->_this();
512 int nextId = RegisterObject( hypothesis_i );
513 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
514 else { nextId = 0; } // avoid "unused variable" warning in release mode
516 return hypothesis_i._retn();
519 //=============================================================================
521 * SMESH_Gen_i::createMesh
523 * Create empty mesh on shape
525 //=============================================================================
526 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
527 throw ( SALOME::SALOME_Exception )
529 Unexpect aCatch(SALOME_SalomeException);
530 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
532 // Get or create the GEOM_Client instance
534 // create a new mesh object servant, store it in a map in study context
535 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this, GetCurrentStudyID() );
536 // create a new mesh object
537 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
538 meshServant->SetImpl( myGen.CreateMesh( GetCurrentStudyID(), myIsEmbeddedMode ));
540 // activate the CORBA servant of Mesh
541 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
542 int nextId = RegisterObject( mesh );
543 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
544 else { nextId = 0; } // avoid "unused variable" warning in release mode
547 catch (SALOME_Exception& S_ex) {
548 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
550 return SMESH::SMESH_Mesh::_nil();
553 //=============================================================================
555 * SMESH_Gen_i::GetShapeReader
559 //=============================================================================
560 GEOM_Client* SMESH_Gen_i::GetShapeReader()
562 // create shape reader if necessary
563 if ( !myShapeReader )
564 myShapeReader = new GEOM_Client(GetContainerRef());
565 ASSERT( myShapeReader );
566 return myShapeReader;
569 //=============================================================================
571 * SMESH_Gen_i::SetGeomEngine
573 * Set GEOM::GEOM_Gen reference
575 //=============================================================================
576 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
577 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
579 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
580 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
581 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
585 //=============================================================================
587 * SMESH_Gen_i::SetEmbeddedMode
591 //=============================================================================
593 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
595 myIsEmbeddedMode = theMode;
597 if ( !myIsEmbeddedMode ) {
598 //PAL10867: disable signals catching with "noexcepthandler" option
599 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
600 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
605 char* envDisableFPE = getenv("DISABLE_FPE");
606 if (envDisableFPE && atoi(envDisableFPE))
611 OSD::SetSignal( raiseFPE );
613 // else OSD::SetSignal() is called in GUI
617 //=============================================================================
619 * SMESH_Gen_i::IsEmbeddedMode
623 //=============================================================================
625 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
627 return myIsEmbeddedMode;
630 //=============================================================================
632 * SMESH_Gen_i::SetCurrentStudy
636 //=============================================================================
638 void SMESH_Gen_i::SetCurrentStudy( SALOMEDS::Study_ptr theStudy )
640 setCurrentStudy( theStudy );
643 void SMESH_Gen_i::setCurrentStudy( SALOMEDS::Study_ptr theStudy,
644 bool theStudyIsBeingClosed)
646 int curStudyId = GetCurrentStudyID();
647 MESSAGE("curStudyId " << curStudyId);
648 myCurrentStudy = SALOMEDS::Study::_duplicate( theStudy );
649 // create study context, if it doesn't exist and set current study
650 int studyId = GetCurrentStudyID();
651 MESSAGE("studyId " << studyId);
652 if ( myStudyContextMap.find( studyId ) == myStudyContextMap.end() )
653 myStudyContextMap[ studyId ] = new StudyContext;
655 // myCurrentStudy may be nil
656 if ( !theStudyIsBeingClosed && !CORBA::is_nil( myCurrentStudy ) ) {
657 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
658 SALOMEDS::SComponent_wrap GEOM_var = myCurrentStudy->FindComponent( "GEOM" );
659 if( !GEOM_var->_is_nil() )
660 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
661 // NPAL16168, issue 0020210
662 // Let meshes update their data depending on GEOM groups that could change
663 if ( curStudyId != studyId )
665 MESSAGE("curStudyId " << curStudyId << " studyId " << studyId);
666 CORBA::String_var compDataType = ComponentDataType();
667 SALOMEDS::SComponent_wrap me = myCurrentStudy->FindComponent( compDataType.in() );
668 if ( !me->_is_nil() ) {
669 SALOMEDS::ChildIterator_wrap anIter = myCurrentStudy->NewChildIterator( me );
670 for ( ; anIter->More(); anIter->Next() ) {
671 SALOMEDS::SObject_wrap so = anIter->Value();
672 CORBA::Object_var ior = SObjectToObject( so );
673 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
674 mesh->CheckGeomModif();
681 //=============================================================================
683 * SMESH_Gen_i::GetCurrentStudy
687 //=============================================================================
689 SALOMEDS::Study_ptr SMESH_Gen_i::GetCurrentStudy()
691 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetCurrentStudy: study Id = " << GetCurrentStudyID() );
692 if ( GetCurrentStudyID() < 0 )
693 return SALOMEDS::Study::_nil();
694 return SALOMEDS::Study::_duplicate( myCurrentStudy );
697 //=============================================================================
699 * SMESH_Gen_i::GetCurrentStudyContext
701 * Get current study context
703 //=============================================================================
704 StudyContext* SMESH_Gen_i::GetCurrentStudyContext()
706 if ( !CORBA::is_nil( myCurrentStudy ) &&
707 myStudyContextMap.find( GetCurrentStudyID() ) != myStudyContextMap.end() )
708 return myStudyContextMap[ myCurrentStudy->StudyId() ];
713 //=============================================================================
715 * SMESH_Gen_i::CreateHypothesis
717 * Create hypothesis/algorothm of given type and publish it in the study
719 //=============================================================================
721 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
722 const char* theLibName )
723 throw ( SALOME::SALOME_Exception )
725 Unexpect aCatch(SALOME_SalomeException);
726 // Create hypothesis/algorithm
727 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
729 // Publish hypothesis/algorithm in the study
730 if ( CanPublishInStudy( hyp ) ) {
731 SALOMEDS::SObject_wrap aSO = PublishHypothesis( myCurrentStudy, hyp );
732 if ( !aSO->_is_nil() ) {
733 // Update Python script
734 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
735 << theHypName << "', '" << theLibName << "')";
742 //================================================================================
744 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
745 * existing on the given geometry or to size of the geometry.
746 * \param theHypType - hypothesis type name
747 * \param theLibName - plugin library name
748 * \param theMesh - The mesh of interest
749 * \param theGeom - The shape to get parameter values from
750 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
751 * in a study and used to compute the mesh, or a temporary one created just to pass
754 //================================================================================
756 SMESH::SMESH_Hypothesis_ptr
757 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
758 const char* theLibName,
759 SMESH::SMESH_Mesh_ptr theMesh,
760 GEOM::GEOM_Object_ptr theGeom,
761 CORBA::Boolean byMesh)
762 throw ( SALOME::SALOME_Exception )
764 Unexpect aCatch(SALOME_SalomeException);
765 if ( byMesh && CORBA::is_nil( theMesh ) )
766 return SMESH::SMESH_Hypothesis::_nil();
767 if ( byMesh && CORBA::is_nil( theGeom ) )
768 return SMESH::SMESH_Hypothesis::_nil();
770 // -----------------------------------------------
771 // find hypothesis used to mesh theGeom
772 // -----------------------------------------------
774 // get mesh and shape
775 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
776 TopoDS_Shape shape = GeomObjectToShape( theGeom );
777 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
778 return SMESH::SMESH_Hypothesis::_nil();
779 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
781 // create a temporary hypothesis to know its dimension
782 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
783 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
785 return SMESH::SMESH_Hypothesis::_nil();
786 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
789 // look for a hypothesis of theHypType used to mesh the shape
790 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
793 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
794 int nbLocalHyps = aHypList->length();
795 for ( int i = 0; i < nbLocalHyps; i++ ) {
796 CORBA::String_var hypName = aHypList[i]->GetName();
797 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
798 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
800 // check super shapes
801 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
802 while ( nbLocalHyps == 0 && itShape.More() ) {
803 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
804 if ( ! CORBA::is_nil( geomObj )) {
805 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
806 nbLocalHyps = aHypList->length();
807 for ( int i = 0; i < nbLocalHyps; i++ )
808 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
809 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
815 // let the temporary hypothesis find out somehow parameter values by mesh
816 if ( hyp->SetParametersByMesh( mesh, shape ))
817 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
822 diagonal = mesh->GetShapeDiagonalSize();
824 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
825 ::SMESH_Hypothesis::TDefaults dflts;
826 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
827 dflts._nbSegments = myGen.GetDefaultNbSegments();
828 dflts._shape = &shape;
829 // let the temporary hypothesis initialize it's values
830 if ( hyp->SetParametersByDefaults( dflts, mesh ))
831 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
834 return SMESH::SMESH_Hypothesis::_nil();
837 //=============================================================================
839 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
840 * \param [in] theHyp - the hypothesis of interest
841 * \param [out] theMesh - the sole mesh using \a theHyp
842 * \param [out] theShape - the sole geometry \a theHyp is assigned to
843 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
845 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
846 * considered as SAME sub-mesh => result is \c true.
847 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
848 * a shape to which an hyp being edited is assigned.
850 //=============================================================================
852 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
853 SMESH::SMESH_Mesh_out theMesh,
854 GEOM::GEOM_Object_out theShape)
856 if ( GetCurrentStudyID() < 0 || CORBA::is_nil( theHyp ))
859 // get Mesh component SO
860 CORBA::String_var compDataType = ComponentDataType();
861 SALOMEDS::SComponent_wrap comp = myCurrentStudy->FindComponent( compDataType.in() );
862 if ( CORBA::is_nil( comp ))
865 // look for child SO of meshes
866 SMESH::SMESH_Mesh_var foundMesh;
867 TopoDS_Shape foundShape;
869 SALOMEDS::ChildIterator_wrap meshIter = myCurrentStudy->NewChildIterator( comp );
870 for ( ; meshIter->More() && isSole; meshIter->Next() )
872 SALOMEDS::SObject_wrap curSO = meshIter->Value();
873 CORBA::Object_var obj = SObjectToObject( curSO );
874 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
878 // look for a sole shape where theHyp is assigned
879 bool isHypFound = false;
880 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
881 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
882 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
884 const THypList& hyps = s2hypsIt.Value();
885 THypList::const_iterator h = hyps.begin();
886 for ( ; h != hyps.end(); ++h )
887 if ( (*h)->GetID() == theHyp->GetId() )
889 if ( h != hyps.end()) // theHyp found
892 if ( ! foundShape.IsNull() &&
893 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
895 foundShape.Nullify();
899 foundShape = s2hypsIt.Key();
901 } // loop on assigned hyps
903 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
905 if ( !foundMesh->_is_nil() ) // not a sole mesh
907 if ( !foundMesh->HasShapeToMesh() ||
908 !mesh_i ->HasShapeToMesh() )
910 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
914 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
915 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
916 isSole = s1->IsSame( s2 );
919 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
925 ! foundMesh->_is_nil() &&
926 ! foundShape.IsNull() )
928 theMesh = foundMesh._retn();
929 theShape = ShapeToGeomObject( foundShape );
930 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
935 //=============================================================================
937 * Sets number of segments per diagonal of boundary box of geometry by which
938 * default segment length of appropriate 1D hypotheses is defined
940 //=============================================================================
942 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
943 throw ( SALOME::SALOME_Exception )
945 if ( theNbSegments > 0 )
946 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
948 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
950 //=============================================================================
952 * \brief Sets default number of segments per edge
954 //=============================================================================
955 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
956 throw ( SALOME::SALOME_Exception )
958 if ( theNbSegments > 0 )
959 myGen.SetDefaultNbSegments( int(theNbSegments) );
961 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
964 //=============================================================================
968 //=============================================================================
970 void SMESH_Gen_i::SetOption(const char* name, const char* value)
972 if ( name && value && strlen( value ) > 0 )
975 if ( strcmp(name, "historical_python_dump") == 0 )
977 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
978 msgToGUI = "preferences/SMESH/historical_python_dump/";
979 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
981 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
983 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
984 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
985 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
987 else if ( strcmp(name, "default_grp_color") == 0 )
991 // color must be presented as a string of following form:
992 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
994 for ( size_t i = 0; i < str.length()/2; i++ )
995 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
996 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
998 else if ( value ) { // rgb color ("255,170,0", for example)
999 string tempValue( value );
1000 char* colorValue = strtok( &tempValue[0], "," );
1001 while ( colorValue != NULL ) {
1002 int c_value = atoi( colorValue );
1003 if ( c_value >= 0 && c_value <= 255 )
1004 color.push_back( c_value );
1005 colorValue = strtok( NULL, "," );
1008 if ( color.size() == 3 ) { // color must have three valid component
1009 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1010 myDefaultGroupColor = value;
1011 msgToGUI = "preferences/SMESH/default_grp_color/";
1016 // update preferences in case if SetOption() is invoked from python console
1017 if ( !msgToGUI.empty() )
1019 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1020 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1021 if ( !CORBA::is_nil( session ) )
1022 session->emitMessageOneWay(msgToGUI.c_str());
1027 //=============================================================================
1029 Return an option value
1031 //=============================================================================
1033 char* SMESH_Gen_i::GetOption(const char* name)
1037 if ( strcmp(name, "historical_python_dump") == 0 )
1039 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1041 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1043 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1045 if ( strcmp(name, "default_grp_color") == 0 )
1047 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1050 return CORBA::string_dup( "" );
1053 //=============================================================================
1055 * SMESH_Gen_i::CreateMesh
1057 * Create empty mesh on a shape and publish it in the study
1059 //=============================================================================
1061 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1062 throw ( SALOME::SALOME_Exception )
1064 Unexpect aCatch(SALOME_SalomeException);
1065 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1067 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1069 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1070 ASSERT( meshServant );
1071 meshServant->SetShape( theShapeObject );
1073 // publish mesh in the study
1074 if ( CanPublishInStudy( mesh ) ) {
1075 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1076 aStudyBuilder->NewCommand(); // There is a transaction
1077 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1078 aStudyBuilder->CommitCommand();
1079 if ( !aSO->_is_nil() ) {
1080 // Update Python script
1081 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1085 return mesh._retn();
1088 //=============================================================================
1090 * SMESH_Gen_i::CreateEmptyMesh
1094 //=============================================================================
1096 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1097 throw ( SALOME::SALOME_Exception )
1099 Unexpect aCatch(SALOME_SalomeException);
1100 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1102 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1104 // publish mesh in the study
1105 if ( CanPublishInStudy( mesh ) ) {
1106 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1107 aStudyBuilder->NewCommand(); // There is a transaction
1108 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1109 aStudyBuilder->CommitCommand();
1110 if ( !aSO->_is_nil() ) {
1111 // Update Python script
1112 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1116 return mesh._retn();
1121 //================================================================================
1123 * \brief Throws an exception in case if the file can't be read
1125 //================================================================================
1127 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1129 SMESH_File f ( theFileName );
1132 if ( !f.error().empty() )
1133 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1135 THROW_SALOME_CORBA_EXCEPTION
1136 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1137 SALOME::BAD_PARAM );
1142 //=============================================================================
1144 * SMESH_Gen_i::CreateMeshFromUNV
1146 * Create mesh and import data from UNV file
1148 //=============================================================================
1150 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1151 throw ( SALOME::SALOME_Exception )
1153 Unexpect aCatch(SALOME_SalomeException);
1155 checkFileReadable( theFileName );
1157 SMESH::SMESH_Mesh_var aMesh = createMesh();
1159 // publish mesh in the study
1160 if ( CanPublishInStudy( aMesh ) ) {
1161 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1162 aStudyBuilder->NewCommand(); // There is a transaction
1163 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, aMesh.in(), aFileName.c_str() );
1164 aStudyBuilder->CommitCommand();
1165 if ( !aSO->_is_nil() ) {
1166 // Update Python script
1167 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1171 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1173 aServant->ImportUNVFile( theFileName );
1175 // Dump creation of groups
1176 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1178 aServant->GetImpl().GetMeshDS()->Modified();
1179 return aMesh._retn();
1182 //=============================================================================
1184 * SMESH_Gen_i::CreateMeshFromMED
1186 * Create mesh and import data from MED file
1188 //=============================================================================
1190 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1191 SMESH::DriverMED_ReadStatus& theStatus,
1192 const char* theCommandNameForPython,
1193 const char* theFileNameForPython)
1196 char bname[ _MAX_FNAME ];
1197 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1198 string aFileName = bname;
1200 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1202 // Retrieve mesh names from the file
1203 DriverMED_R_SMESHDS_Mesh myReader;
1204 myReader.SetFile( theFileName );
1205 myReader.SetMeshId( -1 );
1206 Driver_Mesh::Status aStatus;
1207 list<string> aNames = myReader.GetMeshNames(aStatus);
1208 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1209 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1211 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1214 TPythonDump aPythonDump;
1215 aPythonDump << "([";
1217 if (theStatus == SMESH::DRS_OK) {
1218 SALOMEDS::StudyBuilder_var aStudyBuilder;
1219 if ( GetCurrentStudyID() > -1 )
1221 aStudyBuilder = myCurrentStudy->NewBuilder();
1222 aStudyBuilder->NewCommand(); // There is a transaction
1224 aResult->length( aNames.size() );
1227 // Iterate through all meshes and create mesh objects
1228 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1231 if (i > 0) aPythonDump << ", ";
1234 SMESH::SMESH_Mesh_var mesh = createMesh();
1236 // publish mesh in the study
1237 SALOMEDS::SObject_wrap aSO;
1238 if ( CanPublishInStudy( mesh ) )
1239 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1240 // - as names of meshes are stored in MED file, we use them for data publishing
1241 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1242 aSO = PublishMesh( myCurrentStudy, mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1245 if ( !aSO->_is_nil() ) {
1248 aPythonDump << "mesh_" << i;
1251 // Read mesh data (groups are published automatically by ImportMEDFile())
1252 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1253 ASSERT( meshServant );
1254 SMESH::DriverMED_ReadStatus status1 =
1255 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1256 if (status1 > theStatus)
1257 theStatus = status1;
1259 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1260 meshServant->GetImpl().GetMeshDS()->Modified();
1262 if ( !aStudyBuilder->_is_nil() )
1263 aStudyBuilder->CommitCommand();
1266 // Update Python script
1267 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1269 // Dump creation of groups
1270 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1271 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1273 return aResult._retn();
1276 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1277 SMESH::DriverMED_ReadStatus& theStatus)
1278 throw ( SALOME::SALOME_Exception )
1280 Unexpect aCatch(SALOME_SalomeException);
1281 checkFileReadable( theFileName );
1283 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1287 //=============================================================================
1289 * SMESH_Gen_i::CreateMeshFromSAUV
1291 * Create mesh and import data from SAUV file
1293 //=============================================================================
1295 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1296 SMESH::DriverMED_ReadStatus& theStatus)
1297 throw ( SALOME::SALOME_Exception )
1299 Unexpect aCatch(SALOME_SalomeException);
1300 checkFileReadable( theFileName );
1302 std::string sauvfilename(theFileName);
1303 std::string medfilename(theFileName);
1304 medfilename += ".med";
1307 cmd = "%PYTHONBIN% ";
1312 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1314 system(cmd.c_str());
1315 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1317 cmd = "%PYTHONBIN% ";
1322 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1324 system(cmd.c_str());
1328 //=============================================================================
1330 * SMESH_Gen_i::CreateMeshFromSTL
1332 * Create mesh and import data from STL file
1334 //=============================================================================
1336 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1337 throw ( SALOME::SALOME_Exception )
1339 Unexpect aCatch(SALOME_SalomeException);
1340 checkFileReadable( theFileName );
1342 SMESH::SMESH_Mesh_var aMesh = createMesh();
1345 char bname[ _MAX_FNAME ];
1346 _splitpath( theFileName, NULL, NULL, bname, NULL );
1347 string aFileName = bname;
1349 string aFileName = basename( const_cast<char *>(theFileName) );
1351 // publish mesh in the study
1352 if ( CanPublishInStudy( aMesh ) ) {
1353 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1354 aStudyBuilder->NewCommand(); // There is a transaction
1355 SALOMEDS::SObject_wrap aSO = PublishInStudy
1356 ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1357 aStudyBuilder->CommitCommand();
1358 if ( !aSO->_is_nil() ) {
1359 // Update Python script
1360 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1364 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1366 aServant->ImportSTLFile( theFileName );
1367 aServant->GetImpl().GetMeshDS()->Modified();
1368 return aMesh._retn();
1371 //================================================================================
1373 * \brief Create meshes and import data from the CGSN file
1375 //================================================================================
1377 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1378 SMESH::DriverMED_ReadStatus& theStatus)
1379 throw ( SALOME::SALOME_Exception )
1381 Unexpect aCatch(SALOME_SalomeException);
1382 checkFileReadable( theFileName );
1384 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1387 // Retrieve nb meshes from the file
1388 DriverCGNS_Read myReader;
1389 myReader.SetFile( theFileName );
1390 Driver_Mesh::Status aStatus;
1391 int nbMeshes = myReader.GetNbMeshes(aStatus);
1392 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1394 aResult->length( nbMeshes );
1396 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1399 TPythonDump aPythonDump;
1400 aPythonDump << "([";
1402 if (theStatus == SMESH::DRS_OK)
1404 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1405 aStudyBuilder->NewCommand(); // There is a transaction
1409 // Iterate through all meshes and create mesh objects
1410 for ( ; i < nbMeshes; ++i )
1413 if (i > 0) aPythonDump << ", ";
1416 SMESH::SMESH_Mesh_var mesh = createMesh();
1417 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1419 // Read mesh data (groups are published automatically by ImportMEDFile())
1420 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1421 ASSERT( meshServant );
1423 SMESH::DriverMED_ReadStatus status1 =
1424 meshServant->ImportCGNSFile( theFileName, i, meshName );
1425 if (status1 > theStatus)
1426 theStatus = status1;
1428 meshServant->GetImpl().GetMeshDS()->Modified();
1429 // publish mesh in the study
1430 SALOMEDS::SObject_wrap aSO;
1431 if ( CanPublishInStudy( mesh ) )
1432 aSO = PublishMesh( myCurrentStudy, mesh.in(), meshName.c_str() );
1435 if ( !aSO->_is_nil() ) {
1439 aPythonDump << "mesh_" << i;
1442 aStudyBuilder->CommitCommand();
1445 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1447 // Dump creation of groups
1448 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1449 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1451 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1454 return aResult._retn();
1457 //================================================================================
1459 * \brief Create a mesh and import data from a GMF file
1461 //================================================================================
1463 SMESH::SMESH_Mesh_ptr
1464 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1465 CORBA::Boolean theMakeRequiredGroups,
1466 SMESH::ComputeError_out theError)
1467 throw ( SALOME::SALOME_Exception )
1469 Unexpect aCatch(SALOME_SalomeException);
1470 checkFileReadable( theFileName );
1472 SMESH::SMESH_Mesh_var aMesh = createMesh();
1474 char bname[ _MAX_FNAME ];
1475 _splitpath( theFileName, NULL, NULL, bname, NULL );
1476 string aFileName = bname;
1478 string aFileName = basename( const_cast<char *>(theFileName) );
1480 // publish mesh in the study
1481 if ( CanPublishInStudy( aMesh ) ) {
1482 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1483 aStudyBuilder->NewCommand(); // There is a transaction
1484 SALOMEDS::SObject_wrap aSO = PublishInStudy
1485 ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1486 aStudyBuilder->CommitCommand();
1487 if ( !aSO->_is_nil() ) {
1488 // Update Python script
1489 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1490 << theFileName << "', "
1491 << theMakeRequiredGroups << " )";
1494 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1496 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1497 aServant->GetImpl().GetMeshDS()->Modified();
1498 return aMesh._retn();
1502 //=============================================================================
1504 * SMESH_Gen_i::IsReadyToCompute
1506 * Returns true if mesh contains enough data to be computed
1508 //=============================================================================
1510 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1511 GEOM::GEOM_Object_ptr theShapeObject )
1512 throw ( SALOME::SALOME_Exception )
1514 Unexpect aCatch(SALOME_SalomeException);
1515 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1517 if ( CORBA::is_nil( theShapeObject ) )
1518 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1519 SALOME::BAD_PARAM );
1521 if ( CORBA::is_nil( theMesh ) )
1522 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1523 SALOME::BAD_PARAM );
1527 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1528 ASSERT( meshServant );
1529 if ( meshServant ) {
1530 // get local TopoDS_Shape
1531 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1532 // call implementation
1533 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1534 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1537 catch ( SALOME_Exception& S_ex ) {
1538 INFOS( "catch exception "<< S_ex.what() );
1543 //================================================================================
1545 * \brief Find SObject for an algo
1547 //================================================================================
1549 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1552 if ( !myCurrentStudy->_is_nil() ) {
1553 // find algo in the study
1554 CORBA::String_var compDataType = ComponentDataType();
1555 SALOMEDS::SComponent_wrap father = myCurrentStudy->FindComponent( compDataType.in() );
1556 if ( !father->_is_nil() ) {
1557 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( father );
1558 for ( ; itBig->More(); itBig->Next() ) {
1559 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1560 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1561 SALOMEDS::ChildIterator_wrap algoIt = myCurrentStudy->NewChildIterator( gotBranch );
1562 for ( ; algoIt->More(); algoIt->Next() ) {
1563 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1564 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1565 if ( !CORBA::is_nil( algoIOR )) {
1566 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1567 if ( impl && impl->GetImpl() == algo )
1568 return algoSO._retn();
1570 } // loop on algo SO's
1573 } // SMESH component iterator
1577 return SALOMEDS::SObject::_nil();
1580 //================================================================================
1582 * \brief Return errors of mesh computation
1584 //================================================================================
1586 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1587 GEOM::GEOM_Object_ptr theSubObject )
1588 throw ( SALOME::SALOME_Exception )
1590 Unexpect aCatch(SALOME_SalomeException);
1591 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1593 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1594 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1596 if ( CORBA::is_nil( theMesh ) )
1597 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1599 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1601 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1604 if(theMesh->HasShapeToMesh())
1605 shape = GeomObjectToShape( theSubObject );
1607 shape = SMESH_Mesh::PseudoShape();
1609 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1611 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1614 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1615 const bool includeSelf = true, complexShapeFirst = true;
1616 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1618 while ( smIt->more() )
1621 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1623 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1624 if ( error && !error->IsOK() )
1626 if ( !( error->myAlgo ) &&
1627 !( error->myAlgo = sm->GetAlgo() ))
1629 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1630 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1631 errStruct.comment = error->myComment.c_str();
1632 errStruct.subShapeID = sm->GetId();
1633 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1634 if ( !algoSO->_is_nil() ) {
1635 CORBA::String_var algoName = algoSO->GetName();
1636 errStruct.algoName = algoName;
1639 errStruct.algoName = error->myAlgo->GetName();
1641 errStruct.hasBadMesh = error->HasBadElems();
1644 error_array->length( nbErr );
1647 catch ( SALOME_Exception& S_ex ) {
1648 INFOS( "catch exception "<< S_ex.what() );
1651 return error_array._retn();
1654 //================================================================================
1656 * \brief Return mesh elements preventing computation of a subshape
1658 //================================================================================
1660 SMESH::MeshPreviewStruct*
1661 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1662 CORBA::Short theSubShapeID )
1663 throw ( SALOME::SALOME_Exception )
1665 Unexpect aCatch(SALOME_SalomeException);
1666 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1668 if ( CORBA::is_nil( theMesh ) )
1669 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1671 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1674 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1676 // mesh implementation
1677 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1678 // submesh by subshape id
1679 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1682 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1683 if ( error && error->HasBadElems() )
1685 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1686 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1688 // get nodes of elements and count elements
1689 TNode2LocalIDMap mapNode2LocalID;
1690 list< TNodeLocalID > connectivity;
1691 int i, nbElements = 0, nbConnNodes = 0;
1693 const list<const SMDS_MeshElement*>& badElems =
1694 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1695 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1696 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1697 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1699 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1700 while ( nIt->more() )
1701 connectivity.push_back
1702 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1704 // fill node coords and assign local ids to the nodes
1705 int nbNodes = mapNode2LocalID.size();
1706 result->nodesXYZ.length( nbNodes );
1707 TNodeLocalID node2ID = mapNode2LocalID.begin();
1708 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1709 node2ID->second = i;
1710 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1711 result->nodesXYZ[i].x = node->X();
1712 result->nodesXYZ[i].y = node->Y();
1713 result->nodesXYZ[i].z = node->Z();
1715 // fill connectivity
1716 result->elementConnectivities.length( nbConnNodes );
1717 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1718 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1719 result->elementConnectivities[i] = (*connIt)->second;
1721 // fill element types
1722 result->elementTypes.length( nbElements );
1723 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1725 const SMDS_MeshElement* elem = *elemIt;
1726 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1727 result->elementTypes[i].isPoly = elem->IsPoly();
1728 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1734 catch ( SALOME_Exception& S_ex ) {
1735 INFOS( "catch exception "<< S_ex.what() );
1738 return result._retn();
1741 //================================================================================
1743 * \brief Create a group of elements preventing computation of a sub-shape
1745 //================================================================================
1747 SMESH::ListOfGroups*
1748 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1749 CORBA::Short theSubShapeID,
1750 const char* theGroupName )
1751 throw ( SALOME::SALOME_Exception )
1753 Unexpect aCatch(SALOME_SalomeException);
1755 SMESH::ListOfGroups_var groups;
1757 if ( CORBA::is_nil( theMesh ) )
1758 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1761 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1763 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1764 TPythonDump() << groups << " = " << this
1765 << ".MakeGroupsOfBadInputElements( "
1766 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1769 catch ( SALOME_Exception& S_ex ) {
1770 INFOS( "catch exception "<< S_ex.what() );
1772 return groups._retn();
1775 //================================================================================
1777 * \brief Returns errors of hypotheses definition
1778 * \param theMesh - the mesh
1779 * \param theSubObject - the main or sub- shape
1780 * \retval SMESH::algo_error_array* - sequence of errors
1782 //================================================================================
1784 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1785 GEOM::GEOM_Object_ptr theSubObject )
1786 throw ( SALOME::SALOME_Exception )
1788 Unexpect aCatch(SALOME_SalomeException);
1789 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1791 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1792 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1794 if ( CORBA::is_nil( theMesh ) )
1795 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1797 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1799 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1800 ASSERT( meshServant );
1801 if ( meshServant ) {
1802 TopoDS_Shape myLocShape;
1803 if(theMesh->HasShapeToMesh())
1804 myLocShape = GeomObjectToShape( theSubObject );
1806 myLocShape = SMESH_Mesh::PseudoShape();
1808 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1809 list< ::SMESH_Gen::TAlgoStateError > error_list;
1810 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1811 // call ::SMESH_Gen::GetAlgoState()
1812 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1813 error_array->length( error_list.size() );
1815 for ( error = error_list.begin(); error != error_list.end(); ++error )
1817 // fill AlgoStateError structure
1818 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1819 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1820 errStruct.algoDim = error->_algoDim;
1821 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1822 errStruct.algoName = "";
1823 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1824 if ( !algoSO->_is_nil() ) {
1825 CORBA::String_var algoName = algoSO->GetName();
1826 errStruct.algoName = algoName.in();
1831 catch ( SALOME_Exception& S_ex ) {
1832 INFOS( "catch exception "<< S_ex.what() );
1834 return error_array._retn();
1837 //=============================================================================
1839 * SMESH_Gen_i::GetSubShapesId
1841 * Get sub-shapes unique ID's list
1843 //=============================================================================
1846 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1847 const SMESH::object_array& theListOfSubShapeObject )
1848 throw ( SALOME::SALOME_Exception )
1850 Unexpect aCatch(SALOME_SalomeException);
1851 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1853 SMESH::long_array_var shapesId = new SMESH::long_array;
1856 if ( CORBA::is_nil( theMainShapeObject ) )
1857 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1861 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1862 TopTools_IndexedMapOfShape myIndexToShape;
1863 TopExp::MapShapes(myMainShape,myIndexToShape);
1865 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1867 GEOM::GEOM_Object_var aShapeObject
1868 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1869 if ( CORBA::is_nil( aShapeObject ) )
1870 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1871 SALOME::BAD_PARAM );
1873 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1874 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1876 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1877 setId.insert(myIndexToShape.FindIndex(F));
1878 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1880 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1882 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1883 setId.insert(myIndexToShape.FindIndex(E));
1884 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1886 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1888 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1889 setId.insert(myIndexToShape.FindIndex(V));
1890 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1893 shapesId->length(setId.size());
1894 set<int>::iterator iind;
1896 for (iind = setId.begin(); iind != setId.end(); iind++)
1898 if(MYDEBUG) SCRUTE((*iind));
1899 shapesId[i] = (*iind);
1900 if(MYDEBUG) SCRUTE(shapesId[i]);
1904 catch (SALOME_Exception& S_ex)
1906 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1909 return shapesId._retn();
1912 //=============================================================================
1914 * SMESH_Gen_i::Compute
1916 * Compute mesh on a shape
1918 //=============================================================================
1920 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1921 GEOM::GEOM_Object_ptr theShapeObject )
1922 throw ( SALOME::SALOME_Exception )
1925 Unexpect aCatch(SALOME_SalomeException);
1926 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1928 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1929 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1930 SALOME::BAD_PARAM );
1932 if ( CORBA::is_nil( theMesh ) )
1933 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1934 SALOME::BAD_PARAM );
1936 // Update Python script
1937 TPythonDump() << "isDone = " << this << ".Compute( "
1938 << theMesh << ", " << theShapeObject << ")";
1942 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1943 ASSERT( meshServant );
1944 if ( meshServant ) {
1945 meshServant->Load();
1946 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1947 meshServant->CheckGeomModif();
1948 // get local TopoDS_Shape
1949 TopoDS_Shape myLocShape;
1950 if(theMesh->HasShapeToMesh())
1951 myLocShape = GeomObjectToShape( theShapeObject );
1953 myLocShape = SMESH_Mesh::PseudoShape();
1954 // call implementation compute
1955 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1956 myGen.PrepareCompute( myLocMesh, myLocShape );
1957 int how = ::SMESH_Gen::COMPACT_MESH;
1958 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
1959 how |= ::SMESH_Gen::SHAPE_ONLY;
1960 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
1961 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1962 myLocMesh.GetMeshDS()->Modified();
1966 catch ( std::bad_alloc ) {
1967 INFOS( "Compute(): lack of memory" );
1969 catch ( SALOME_Exception& S_ex ) {
1970 INFOS( "Compute(): catch exception "<< S_ex.what() );
1973 INFOS( "Compute(): unknown exception " );
1978 //=============================================================================
1980 * SMESH_Gen_i::CancelCompute
1982 * Cancel Compute mesh on a shape
1984 //=============================================================================
1986 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
1987 GEOM::GEOM_Object_ptr theShapeObject )
1989 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1990 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1991 TopoDS_Shape myLocShape;
1992 if(theMesh->HasShapeToMesh())
1993 myLocShape = GeomObjectToShape( theShapeObject );
1995 myLocShape = SMESH_Mesh::PseudoShape();
1996 myGen.CancelCompute( myLocMesh, myLocShape);
1999 //=============================================================================
2001 * SMESH_Gen_i::Precompute
2003 * Compute mesh as preview till indicated dimension on shape
2005 //=============================================================================
2007 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2008 GEOM::GEOM_Object_ptr theShapeObject,
2009 SMESH::Dimension theDimension,
2010 SMESH::long_array& theShapesId)
2011 throw ( SALOME::SALOME_Exception )
2013 Unexpect aCatch(SALOME_SalomeException);
2014 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2016 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2017 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2018 SALOME::BAD_PARAM );
2020 if ( CORBA::is_nil( theMesh ) )
2021 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2022 SALOME::BAD_PARAM );
2024 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2027 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2028 meshServant->Load();
2029 ASSERT( meshServant );
2030 if ( meshServant ) {
2031 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
2032 meshServant->CheckGeomModif();
2033 // get local TopoDS_Shape
2034 TopoDS_Shape myLocShape;
2035 if(theMesh->HasShapeToMesh())
2036 myLocShape = GeomObjectToShape( theShapeObject );
2038 return result._retn();;
2040 // call implementation compute
2041 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2043 ::MeshDimension aDim = (MeshDimension)theDimension;
2044 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2046 int nbShapeId = shapeIds.size();
2047 theShapesId.length( nbShapeId );
2048 // iterates on shapes and collect mesh entities into mesh preview
2049 TSetOfInt::const_iterator idIt = shapeIds.begin();
2050 TSetOfInt::const_iterator idEnd = shapeIds.end();
2051 std::map< int, int > mapOfShIdNb;
2052 std::set< SMESH_TLink > setOfEdge;
2053 std::list< SMDSAbs_ElementType > listOfElemType;
2054 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2055 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2056 TNode2LocalIDMap mapNode2LocalID;
2057 list< TNodeLocalID > connectivity;
2058 int i, nbConnNodes = 0;
2059 std::set< const SMESH_subMesh* > setOfVSubMesh;
2060 // iterates on shapes
2061 for ( ; idIt != idEnd; idIt++ )
2063 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2065 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2066 if ( !sm || !sm->IsMeshComputed() )
2069 const TopoDS_Shape& aSh = sm->GetSubShape();
2070 const int shDim = myGen.GetShapeDim( aSh );
2071 if ( shDim < 1 || shDim > theDimension )
2074 mapOfShIdNb[ *idIt ] = 0;
2075 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2077 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2078 if ( !smDS ) continue;
2080 if ( theDimension == SMESH::DIM_2D )
2082 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2083 while ( faceIt->more() )
2085 const SMDS_MeshElement* face = faceIt->next();
2086 int aNbNode = face->NbNodes();
2088 aNbNode /= 2; // do not take into account additional middle nodes
2090 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2091 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2093 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2094 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2096 listOfElemType.push_back( SMDSAbs_Edge );
2097 connectivity.push_back
2098 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2099 connectivity.push_back
2100 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2106 else if ( theDimension == SMESH::DIM_1D )
2108 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2109 while ( nodeIt->more() )
2111 listOfElemType.push_back( SMDSAbs_Node );
2112 connectivity.push_back
2113 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2115 // add corner nodes by first vertex from edge
2116 SMESH_subMeshIteratorPtr edgeSmIt =
2117 sm->getDependsOnIterator(/*includeSelf*/false,
2118 /*complexShapeFirst*/false);
2119 while ( edgeSmIt->more() )
2121 SMESH_subMesh* vertexSM = edgeSmIt->next();
2122 // check that vertex is not already treated
2123 if ( !setOfVSubMesh.insert( vertexSM ).second )
2125 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2128 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2129 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2130 while ( nodeIt->more() )
2132 listOfElemType.push_back( SMDSAbs_Node );
2133 connectivity.push_back
2134 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2140 // fill node coords and assign local ids to the nodes
2141 int nbNodes = mapNode2LocalID.size();
2142 result->nodesXYZ.length( nbNodes );
2143 TNodeLocalID node2ID = mapNode2LocalID.begin();
2144 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2145 node2ID->second = i;
2146 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2147 result->nodesXYZ[i].x = node->X();
2148 result->nodesXYZ[i].y = node->Y();
2149 result->nodesXYZ[i].z = node->Z();
2151 // fill connectivity
2152 result->elementConnectivities.length( nbConnNodes );
2153 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2154 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2155 result->elementConnectivities[i] = (*connIt)->second;
2158 // fill element types
2159 result->elementTypes.length( listOfElemType.size() );
2160 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2161 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2162 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2164 SMDSAbs_ElementType elemType = *typeIt;
2165 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2166 result->elementTypes[i].isPoly = false;
2167 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2170 // correct number of shapes
2171 theShapesId.length( mapOfShIdNb.size() );
2175 catch ( std::bad_alloc ) {
2176 INFOS( "Precompute(): lack of memory" );
2178 catch ( SALOME_Exception& S_ex ) {
2179 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2182 INFOS( "Precompute(): unknown exception " );
2184 return result._retn();
2188 //=============================================================================
2190 * SMESH_Gen_i::Evaluate
2192 * Evaluate mesh on a shape
2194 //=============================================================================
2196 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2197 GEOM::GEOM_Object_ptr theShapeObject)
2198 // SMESH::long_array& theNbElems)
2199 throw ( SALOME::SALOME_Exception )
2201 Unexpect aCatch(SALOME_SalomeException);
2202 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2204 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2205 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2206 SALOME::BAD_PARAM );
2208 if ( CORBA::is_nil( theMesh ) )
2209 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2210 SALOME::BAD_PARAM );
2212 SMESH::long_array_var nbels = new SMESH::long_array;
2213 nbels->length(SMESH::Entity_Last);
2214 int i = SMESH::Entity_Node;
2215 for (; i < SMESH::Entity_Last; i++)
2218 // Update Python script
2219 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2220 << theMesh << ", " << theShapeObject << ")";
2224 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2225 ASSERT( meshServant );
2226 if ( meshServant ) {
2227 meshServant->Load();
2228 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
2229 meshServant->CheckGeomModif();
2230 // get local TopoDS_Shape
2231 TopoDS_Shape myLocShape;
2232 if(theMesh->HasShapeToMesh())
2233 myLocShape = GeomObjectToShape( theShapeObject );
2235 myLocShape = SMESH_Mesh::PseudoShape();
2236 // call implementation compute
2237 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2238 MapShapeNbElems aResMap;
2239 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2240 MapShapeNbElemsItr anIt = aResMap.begin();
2241 for(; anIt!=aResMap.end(); anIt++) {
2242 const vector<int>& aVec = (*anIt).second;
2243 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2244 int nbElem = aVec[i];
2245 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2247 SMESH_subMesh* sm = anIt->first;
2248 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2249 const SMESH_Algo* algo = sm->GetAlgo();
2250 if ( (algo && !error.get()) || error->IsOK() )
2251 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2255 nbels[i] += aVec[i];
2259 return nbels._retn();
2262 catch ( std::bad_alloc ) {
2263 INFOS( "Evaluate(): lack of memory" );
2265 catch ( SALOME_Exception& S_ex ) {
2266 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2269 INFOS( "Evaluate(): unknown exception " );
2272 return nbels._retn();
2275 //================================================================================
2277 * \brief Return geometrical object the given element is built on
2278 * \param theMesh - the mesh the element is in
2279 * \param theElementID - the element ID
2280 * \param theGeomName - the name of the result geom object if it is not yet published
2281 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2283 //================================================================================
2285 GEOM::GEOM_Object_ptr
2286 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2287 CORBA::Long theElementID,
2288 const char* theGeomName)
2289 throw ( SALOME::SALOME_Exception )
2291 Unexpect aCatch(SALOME_SalomeException);
2293 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2294 if ( !geom->_is_nil() ) {
2295 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2296 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2298 // try to find the corresponding SObject
2299 SALOMEDS::SObject_wrap SObj = ObjectToSObject( myCurrentStudy, geom.in() );
2300 if ( SObj->_is_nil() ) // submesh can be not found even if published
2302 // try to find published submesh
2303 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2304 if ( !geom->IsMainShape() && list->length() == 1 ) {
2305 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2306 SALOMEDS::ChildIterator_wrap it;
2307 if ( !mainSO->_is_nil() ) {
2308 it = myCurrentStudy->NewChildIterator( mainSO );
2310 if ( !it->_is_nil() ) {
2311 for ( it->InitEx(true); it->More(); it->Next() ) {
2312 SALOMEDS::SObject_wrap so = it->Value();
2313 CORBA::Object_var obj = SObjectToObject( so );
2314 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2315 if ( !subGeom->_is_nil() ) {
2316 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2317 if ( subList->length() == 1 && list[0] == subList[0] ) {
2327 if ( SObj->_is_nil() ) // publish a new subshape
2328 SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
2330 // return only published geometry
2331 if ( !SObj->_is_nil() ) {
2332 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2333 CORBA::Object_var obj = SObjectToObject( SObj );
2334 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2338 return GEOM::GEOM_Object::_nil();
2341 //================================================================================
2343 * \brief Return geometrical object the given element is built on.
2344 * \param theMesh - the mesh the element is in
2345 * \param theElementID - the element ID
2346 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2348 //================================================================================
2350 GEOM::GEOM_Object_ptr
2351 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2352 CORBA::Long theElementID)
2353 throw ( SALOME::SALOME_Exception )
2355 Unexpect aCatch(SALOME_SalomeException);
2356 if ( CORBA::is_nil( theMesh ) )
2357 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2359 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2360 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2362 // get a core mesh DS
2363 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2364 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2366 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2367 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2368 // find the element in mesh
2369 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2370 // find a shape id by the element
2371 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2372 // get a geom object by the shape id
2373 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2374 if ( geom->_is_nil() ) {
2375 // try to find a published sub-shape
2376 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2377 SALOMEDS::ChildIterator_wrap it;
2378 if ( !mainSO->_is_nil() ) {
2379 it = myCurrentStudy->NewChildIterator( mainSO );
2381 if ( !it->_is_nil() ) {
2382 for ( it->InitEx(true); it->More(); it->Next() ) {
2383 SALOMEDS::SObject_wrap so = it->Value();
2384 CORBA::Object_var obj = SObjectToObject( so );
2385 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2386 if ( !subGeom->_is_nil() ) {
2387 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2388 if ( subList->length() == 1 && shapeID == subList[0] ) {
2396 if ( geom->_is_nil() ) {
2398 GEOM::GEOM_IShapesOperations_wrap op =
2399 geomGen->GetIShapesOperations( GetCurrentStudyID() );
2400 if ( !op->_is_nil() )
2401 geom = op->GetSubShape( mainShape, shapeID );
2406 if ( !geom->_is_nil() ) {
2407 GeomObjectToShape( geom ); // let geom client remember the found shape
2408 return geom._retn();
2413 return GEOM::GEOM_Object::_nil();
2416 //================================================================================
2418 * SMESH_Gen_i::Concatenate
2420 * Concatenate the given meshes into one mesh
2422 //================================================================================
2424 SMESH::SMESH_Mesh_ptr
2425 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2426 CORBA::Boolean theUniteIdenticalGroups,
2427 CORBA::Boolean theMergeNodesAndElements,
2428 CORBA::Double theMergeTolerance)
2429 throw ( SALOME::SALOME_Exception )
2431 return ConcatenateCommon(theMeshesArray,
2432 theUniteIdenticalGroups,
2433 theMergeNodesAndElements,
2438 //================================================================================
2440 * SMESH_Gen_i::ConcatenateWithGroups
2442 * Concatenate the given meshes into one mesh
2443 * Create the groups of all elements from initial meshes
2445 //================================================================================
2447 SMESH::SMESH_Mesh_ptr
2448 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2449 CORBA::Boolean theUniteIdenticalGroups,
2450 CORBA::Boolean theMergeNodesAndElements,
2451 CORBA::Double theMergeTolerance)
2452 throw ( SALOME::SALOME_Exception )
2454 return ConcatenateCommon(theMeshesArray,
2455 theUniteIdenticalGroups,
2456 theMergeNodesAndElements,
2461 //================================================================================
2463 * SMESH_Gen_i::ConcatenateCommon
2465 * Concatenate the given meshes into one mesh
2467 //================================================================================
2469 SMESH::SMESH_Mesh_ptr
2470 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2471 CORBA::Boolean theUniteIdenticalGroups,
2472 CORBA::Boolean theMergeNodesAndElements,
2473 CORBA::Double theMergeTolerance,
2474 CORBA::Boolean theCommonGroups)
2475 throw ( SALOME::SALOME_Exception )
2477 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2478 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2481 SMESH::SMESH_Mesh_var newMesh = CreateEmptyMesh();
2482 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2483 if ( !newImpl ) return newMesh._retn();
2485 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2486 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2488 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2489 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2490 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2491 TGroupsMap groupsMap;
2492 TListOfNewGroups listOfNewGroups;
2494 ::SMESH_MeshEditor newEditor( &locMesh );
2495 ::SMESH_MeshEditor::ElemFeatures elemType;
2497 // loop on sub-meshes
2498 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2500 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2501 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2502 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2503 if ( !initImpl ) continue;
2506 // assure that IDs increments by one during iteration
2507 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2508 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2509 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2510 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2512 initMeshDS->Modified();
2513 initMeshDS->CompactMesh();
2516 // remember nb of elements before filling in
2517 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2521 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2522 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2523 while ( elemIt->more() )
2525 SMESH_NodeXYZ node = elemIt->next();
2526 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2531 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2532 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2533 while ( elemIt->more() )
2535 const SMDS_MeshElement* elem = elemIt->next();
2536 elemType.myNodes.resize( elem->NbNodes() );
2538 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2539 for ( int k = 0; itNodes->more(); k++)
2541 const SMDS_MeshNode* node = itNodes->next();
2542 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2545 // creates a corresponding element on existent nodes in new mesh
2546 newElems[ elem->GetID() ] =
2547 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2549 newEditor.ClearLastCreated(); // forget the history
2552 // create groups of just added elements
2553 SMESH::SMESH_Group_var newGroup;
2554 SMESH::ElementType groupType;
2555 if ( theCommonGroups )
2558 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2559 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2560 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2561 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2564 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2566 for( groupType = SMESH::NODE;
2567 groupType < SMESH::NB_ELEMENT_TYPES;
2568 groupType = (SMESH::ElementType)( groupType + 1 ))
2570 if ( curState[ groupType ] <= prevState[ groupType ])
2571 continue; // no elements of groupType added from the i-th mesh
2573 // make a group name
2574 std::string groupName = "Gr";
2575 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( myCurrentStudy, theMeshesArray[i] );
2577 CORBA::String_var name = meshSO->GetName();
2581 groupName += typeNames[ groupType ];
2583 // make and fill a group
2584 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2585 std::vector< const SMDS_MeshElement* > & elemVec =
2586 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2587 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2589 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2591 for ( size_t j = 0; j < elemVec.size(); ++j )
2593 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2594 grpDS->Add( elemVec[j] );
2598 listOfNewGroups.clear();
2599 listOfNewGroups.push_back( newGroup );
2600 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2605 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2609 SMESH::SMESH_GroupBase_ptr group;
2610 CORBA::String_var groupName;
2611 SMESH::long_array_var newIDs = new SMESH::long_array();
2613 // loop on groups of a source mesh
2614 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2615 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2617 group = listOfGroups[iG];
2618 groupType = group->GetType();
2619 groupName = group->GetName();
2620 std::string name = groupName.in();
2622 // convert a list of IDs
2623 newIDs->length( group->Size() );
2624 std::vector< const SMDS_MeshElement* > & elemVec =
2625 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2626 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2628 while ( itGrElems->more() )
2630 const SMDS_MeshElement* elem = itGrElems->next();
2631 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2633 newIDs[ nbElems++ ] = newElem->GetID();
2635 newIDs->length( nbElems );
2637 // check that a current group name and type don't have identical ones in final mesh
2638 listOfNewGroups.clear();
2639 TNameAndType nameAndType( name, groupType );
2640 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2641 if ( anIter == groupsMap.end() )
2643 // add a new group in the mesh
2644 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2645 newGroup->Add( newIDs );
2647 listOfNewGroups.push_back( newGroup );
2648 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2650 else if ( theUniteIdenticalGroups )
2652 // unite identical groups
2653 TListOfNewGroups& aNewGroups = anIter->second;
2654 aNewGroups.front()->Add( newIDs );
2658 // rename identical groups
2659 newGroup = newImpl->CreateGroup( groupType, groupName );
2660 newGroup->Add( newIDs );
2662 TListOfNewGroups& newGroups = anIter->second;
2663 std::string newGroupName;
2664 if ( newGroups.size() == 1 )
2666 newGroupName = name + "_1";
2667 newGroups.front()->SetName( newGroupName.c_str() );
2669 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2670 newGroup->SetName( newGroupName.c_str() );
2671 newGroups.push_back( newGroup );
2674 } // if an IDSource is a mesh
2677 if ( theMergeNodesAndElements ) // merge nodes
2679 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2680 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2681 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2682 /*SeparateCornersAndMedium=*/ false );
2683 newEditor.MergeNodes( groupsOfNodes );
2685 newEditor.MergeEqualElements();
2688 // Update Python script
2689 pythonDump << newMesh << " = " << this
2690 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "("
2691 << theMeshesArray << ", "
2692 << theUniteIdenticalGroups << ", "
2693 << theMergeNodesAndElements << ", "
2694 << TVar( theMergeTolerance ) << ")";
2696 pPythonDump.reset(); // enable python dump from GetGroups()
2698 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2699 if ( !newMesh->_is_nil() )
2701 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2704 // IPAL21468 Change icon of compound because it need not be computed.
2705 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( myCurrentStudy, newMesh );
2706 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2708 newMeshDS->Modified();
2710 return newMesh._retn();
2713 //================================================================================
2715 * \brief Create a mesh by copying a part of another mesh
2716 * \param meshPart - a part of mesh to copy
2717 * \param toCopyGroups - to create in the new mesh groups
2718 * the copied elements belongs to
2719 * \param toKeepIDs - to preserve IDs of the copied elements or not
2720 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2722 //================================================================================
2724 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2725 const char* meshName,
2726 CORBA::Boolean toCopyGroups,
2727 CORBA::Boolean toKeepIDs)
2729 Unexpect aCatch(SALOME_SalomeException);
2731 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2733 // 1. Get source mesh
2735 if ( CORBA::is_nil( meshPart ))
2736 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2738 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2739 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2741 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2743 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2745 // 2. Make a new mesh
2747 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2748 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2750 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2751 SALOMEDS::SObject_wrap meshSO = ObjectToSObject(myCurrentStudy, newMesh );
2752 if ( !meshSO->_is_nil() )
2754 SetName( meshSO, meshName, "Mesh" );
2755 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2757 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2758 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2759 ::SMESH_MeshEditor::ElemFeatures elemType;
2761 // 3. Get elements to copy
2763 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2764 TIDSortedElemSet srcElems;
2765 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2766 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2769 srcElemIt = srcMeshDS->elementsIterator();
2770 srcNodeIt = srcMeshDS->nodesIterator();
2774 SMESH::long_array_var ids = meshPart->GetIDs();
2775 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2777 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2778 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2779 srcElems.insert( elem );
2783 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2784 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2785 srcElems.insert( elem );
2787 if ( srcElems.empty() )
2788 return newMesh._retn();
2790 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2791 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2796 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2797 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2798 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2800 const SMDS_MeshNode *nSrc, *nTgt;
2801 vector< const SMDS_MeshNode* > nodes;
2802 while ( srcElemIt->more() )
2804 const SMDS_MeshElement * elem = srcElemIt->next();
2806 nodes.resize( elem->NbNodes());
2807 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2809 for ( iN = 0; nIt->more(); ++iN )
2811 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2812 nTgt = newMeshDS->FindNode( nSrc->GetID());
2814 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2819 for ( iN = 0; nIt->more(); ++iN )
2821 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2822 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2824 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2825 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2829 if ( elem->GetType() != SMDSAbs_Node )
2831 elemType.Init( elem, /*basicOnly=*/false );
2832 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2834 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2835 if ( toCopyGroups && !toKeepIDs )
2836 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2838 } // while ( srcElemIt->more() )
2840 // 4(b). Copy free nodes
2842 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2844 while ( srcNodeIt->more() )
2846 nSrc = srcNodeIt->next();
2847 if ( nSrc->NbInverseElements() == 0 )
2850 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2852 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2859 int nbNewGroups = 0;
2862 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2863 while ( gIt->more() )
2865 SMESH_Group* group = gIt->next();
2866 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2868 // Check group type. We copy nodal groups containing nodes of copied element
2869 SMDSAbs_ElementType groupType = groupDS->GetType();
2870 if ( groupType != SMDSAbs_Node &&
2871 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2872 continue; // group type differs from types of meshPart
2874 // Find copied elements in the group
2875 vector< const SMDS_MeshElement* > groupElems;
2876 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2879 const SMDS_MeshElement* foundElem;
2880 if ( groupType == SMDSAbs_Node )
2882 while ( eIt->more() )
2883 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2884 groupElems.push_back( foundElem );
2888 while ( eIt->more() )
2889 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2890 groupElems.push_back( foundElem );
2895 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2896 if ( e2eMap.empty() ) continue;
2897 int minID = e2eMap.begin()->first->GetID();
2898 int maxID = e2eMap.rbegin()->first->GetID();
2899 TE2EMap::iterator e2e;
2900 while ( eIt->more() && groupElems.size() < e2eMap.size())
2902 const SMDS_MeshElement* e = eIt->next();
2903 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2904 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2905 groupElems.push_back( e2e->second );
2909 if ( !groupElems.empty() )
2911 SMESH::SMESH_Group_var newGroupObj =
2912 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2913 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2915 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2916 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2917 for ( unsigned i = 0; i < groupElems.size(); ++i )
2918 smdsGroup.Add( groupElems[i] );
2926 newMeshDS->Modified();
2928 *pyDump << newMesh << " = " << this
2929 << ".CopyMesh( " << meshPart << ", "
2930 << "'" << meshName << "', "
2931 << toCopyGroups << ", "
2932 << toKeepIDs << ")";
2934 delete pyDump; pyDump = 0; // allow dump in GetGroups()
2936 if ( nbNewGroups > 0 ) // dump created groups
2937 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2939 return newMesh._retn();
2942 //================================================================================
2944 * SMESH_Gen_i::GetMEDVersion
2946 * Get MED version of the file by its name
2948 //================================================================================
2949 CORBA::Boolean SMESH_Gen_i::GetMEDVersion(const char* theFileName,
2950 SMESH::MED_VERSION& theVersion)
2952 theVersion = SMESH::MED_V2_1;
2953 MED::EVersion aVersion = MED::GetVersionId( theFileName );
2954 switch( aVersion ) {
2955 case MED::eV2_1 : theVersion = SMESH::MED_V2_1; return true;
2956 case MED::eV2_2 : theVersion = SMESH::MED_V2_2; return true;
2957 case MED::eLATEST : theVersion = SMESH::MED_LATEST; return true;
2958 case MED::eMINOR_0 : theVersion = SMESH::MED_MINOR_0; return true;
2959 case MED::eMINOR_1 : theVersion = SMESH::MED_MINOR_1; return true;
2960 case MED::eMINOR_2 : theVersion = SMESH::MED_MINOR_2; return true;
2961 case MED::eMINOR_3 : theVersion = SMESH::MED_MINOR_3; return true;
2962 case MED::eMINOR_4 : theVersion = SMESH::MED_MINOR_4; return true;
2963 case MED::eMINOR_5 : theVersion = SMESH::MED_MINOR_5; return true;
2964 case MED::eMINOR_6 : theVersion = SMESH::MED_MINOR_6; return true;
2965 case MED::eMINOR_7 : theVersion = SMESH::MED_MINOR_7; return true;
2966 case MED::eMINOR_8 : theVersion = SMESH::MED_MINOR_8; return true;
2967 case MED::eMINOR_9 : theVersion = SMESH::MED_MINOR_9; return true;
2968 case MED::eVUnknown : return false;
2973 //================================================================================
2975 * SMESH_Gen_i::GetMeshNames
2977 * Get names of meshes defined in file with the specified name
2979 //================================================================================
2980 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
2982 SMESH::string_array_var aResult = new SMESH::string_array();
2983 MED::PWrapper aMed = MED::CrWrapper( theFileName );
2985 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
2987 aResult->length( aNbMeshes );
2988 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
2989 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
2990 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
2993 return aResult._retn();
2996 //=============================================================================
3000 * Save SMESH module's data
3002 //=============================================================================
3003 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
3007 // ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
3008 // san -- in case <myCurrentStudy> differs from theComponent's study,
3009 // use that of the component
3010 if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
3011 SetCurrentStudy( theComponent->GetStudy() );
3013 // Store study contents as a set of python commands
3014 SavePython(myCurrentStudy);
3016 StudyContext* myStudyContext = GetCurrentStudyContext();
3018 // Declare a byte stream
3019 SALOMEDS::TMPFile_var aStreamFile;
3021 // Obtain a temporary dir
3022 TCollection_AsciiString tmpDir =
3023 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
3025 // Create a sequence of files processed
3026 SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
3027 aFileSeq->length( NUM_TMP_FILES );
3029 TCollection_AsciiString aStudyName( "" );
3031 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
3033 // Set names of temporary files
3034 TCollection_AsciiString filename =
3035 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
3036 TCollection_AsciiString meshfile =
3037 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
3038 aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
3039 aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
3040 filename = tmpDir + filename;
3041 meshfile = tmpDir + meshfile;
3044 HDFdataset* aDataset;
3045 HDFgroup* aTopGroup;
3047 HDFgroup* aSubGroup;
3048 HDFgroup* aSubSubGroup;
3049 hdf_size aSize[ 1 ];
3052 //Remove the files if they exist: BugID: 11225
3053 #ifndef WIN32 /* unix functionality */
3054 TCollection_AsciiString cmd("rm -f \"");
3056 TCollection_AsciiString cmd("del /F \"");
3063 system(cmd.ToCString());
3065 // MED writer to be used by storage process
3066 DriverMED_W_SMESHDS_Mesh myWriter;
3067 myWriter.SetFile( meshfile.ToCString() );
3070 // SetStoreName() to groups before storing hypotheses to let them refer to
3071 // groups using "store name", which is "Group <group_persistent_id>"
3073 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
3074 for ( ; itBig->More(); itBig->Next() ) {
3075 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3076 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3077 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3078 if ( !CORBA::is_nil( anObject ) ) {
3079 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3080 if ( !myMesh->_is_nil() ) {
3081 myMesh->Load(); // load from study file if not yet done
3082 TPythonDump pd; // not to dump GetGroups()
3083 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
3084 pd << ""; // to avoid optimizing pd out
3085 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
3087 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
3090 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
3091 int anId = myStudyContext->findId( string( objStr.in() ) );
3093 sprintf( grpName, "Group %d", anId );
3094 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
3095 aGrpBaseDS->SetStoreName( grpName );
3105 // ---> create HDF file
3106 aFile = new HDFfile( (char*) filename.ToCString() );
3107 aFile->CreateOnDisk();
3109 // --> iterator for top-level objects
3110 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
3111 for ( ; itBig->More(); itBig->Next() ) {
3112 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3114 // --> hypotheses root branch (only one for the study)
3115 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
3116 // create hypotheses root HDF group
3117 aTopGroup = new HDFgroup( "Hypotheses", aFile );
3118 aTopGroup->CreateOnDisk();
3120 // iterator for all hypotheses
3121 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
3122 for ( ; it->More(); it->Next() ) {
3123 SALOMEDS::SObject_wrap mySObject = it->Value();
3124 CORBA::Object_var anObject = SObjectToObject( mySObject );
3125 if ( !CORBA::is_nil( anObject ) ) {
3126 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3127 if ( !myHyp->_is_nil() ) {
3128 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3130 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
3131 std::string hypname = hn.in();
3132 std::string libname = ln.in();
3134 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3135 // WIN32 and ".so" for X-system) must be deleted
3136 int libname_len = libname.length();
3138 if( libname_len > 4 )
3139 libname.resize( libname_len - 4 );
3141 // PAL17753 (Regression: missing hypothesis in restored study)
3142 // "lib" also should be removed from the beginning
3143 //if( libname_len > 3 )
3144 //libname.resize( libname_len - 3 );
3145 if( libname_len > 6 )
3146 libname = libname.substr( 3, libname_len - 3 - 3 );
3148 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3149 CORBA::String_var hypdata = myImpl->SaveTo();
3150 int id = myStudyContext->findId( string( objStr.in() ));
3152 // for each hypothesis create HDF group basing on its id
3153 char hypGrpName[30];
3154 sprintf( hypGrpName, "Hypothesis %d", id );
3155 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3156 aGroup->CreateOnDisk();
3157 // --> type name of hypothesis
3158 aSize[ 0 ] = hypname.length() + 1;
3159 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3160 aDataset->CreateOnDisk();
3161 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3162 aDataset->CloseOnDisk();
3163 // --> server plugin library name of hypothesis
3164 aSize[ 0 ] = libname.length() + 1;
3165 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3166 aDataset->CreateOnDisk();
3167 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3168 aDataset->CloseOnDisk();
3169 // --> persistent data of hypothesis
3170 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
3171 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3172 aDataset->CreateOnDisk();
3173 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
3174 aDataset->CloseOnDisk();
3175 // close hypothesis HDF group
3176 aGroup->CloseOnDisk();
3181 // close hypotheses root HDF group
3182 aTopGroup->CloseOnDisk();
3184 // --> algorithms root branch (only one for the study)
3185 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
3186 // create algorithms root HDF group
3187 aTopGroup = new HDFgroup( "Algorithms", aFile );
3188 aTopGroup->CreateOnDisk();
3190 // iterator for all algorithms
3191 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
3192 for ( ; it->More(); it->Next() ) {
3193 SALOMEDS::SObject_wrap mySObject = it->Value();
3194 CORBA::Object_var anObject = SObjectToObject( mySObject );
3195 if ( !CORBA::is_nil( anObject ) ) {
3196 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3197 if ( !myHyp->_is_nil() ) {
3198 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3200 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
3201 std::string hypname = hn.in();
3202 std::string libname = ln.in();
3204 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3205 // WIN32 and ".so" for X-system) must be deleted
3206 int libname_len = libname.length();
3208 if( libname_len > 4 )
3209 libname.resize( libname_len - 4 );
3211 // PAL17753 (Regression: missing hypothesis in restored study)
3212 // "lib" also should be removed from the beginning
3213 //if( libname_len > 3 )
3214 //libname.resize( libname_len - 3 );
3215 if( libname_len > 6 )
3216 libname = libname.substr( 3, libname_len - 3 - 3 );
3218 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3219 CORBA::String_var hypdata = myImpl->SaveTo();
3220 int id = myStudyContext->findId( string( objStr.in() ) );
3222 // for each algorithm create HDF group basing on its id
3223 char hypGrpName[30];
3224 sprintf( hypGrpName, "Algorithm %d", id );
3225 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3226 aGroup->CreateOnDisk();
3227 // --> type name of algorithm
3228 aSize[0] = hypname.length() + 1;
3229 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3230 aDataset->CreateOnDisk();
3231 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3232 aDataset->CloseOnDisk();
3233 // --> server plugin library name of hypothesis
3234 aSize[0] = libname.length() + 1;
3235 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3236 aDataset->CreateOnDisk();
3237 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3238 aDataset->CloseOnDisk();
3239 // --> persistent data of algorithm
3240 aSize[0] = strlen( hypdata.in() ) + 1;
3241 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3242 aDataset->CreateOnDisk();
3243 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
3244 aDataset->CloseOnDisk();
3245 // close algorithm HDF group
3246 aGroup->CloseOnDisk();
3251 // close algorithms root HDF group
3252 aTopGroup->CloseOnDisk();
3254 // --> mesh objects roots branches
3255 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3256 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3257 if ( !CORBA::is_nil( anObject ) ) {
3258 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3259 if ( !myMesh->_is_nil() ) {
3260 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
3262 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3263 int id = myStudyContext->findId( string( objStr.in() ) );
3264 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
3265 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
3266 bool hasShape = myLocMesh.HasShapeToMesh();
3268 // for each mesh open the HDF group basing on its id
3269 char meshGrpName[ 30 ];
3270 sprintf( meshGrpName, "Mesh %d", id );
3271 aTopGroup = new HDFgroup( meshGrpName, aFile );
3272 aTopGroup->CreateOnDisk();
3274 // --> put dataset to hdf file which is a flag that mesh has data
3275 string strHasData = "0";
3276 // check if the mesh is not empty
3277 if ( mySMESHDSMesh->NbNodes() > 0 ) {
3278 // write mesh data to med file
3279 myWriter.SetMesh( mySMESHDSMesh );
3280 myWriter.SetMeshId( id );
3283 aSize[ 0 ] = strHasData.length() + 1;
3284 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
3285 aDataset->CreateOnDisk();
3286 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
3287 aDataset->CloseOnDisk();
3290 // for each mesh open the HDF group basing on its auto color parameter
3291 char meshAutoColorName[ 30 ];
3292 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
3294 anAutoColor[0] = myImpl->GetAutoColor();
3296 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
3297 aDataset->CreateOnDisk();
3298 aDataset->WriteOnDisk( anAutoColor );
3299 aDataset->CloseOnDisk();
3301 // issue 0020693. Store _isModified flag
3302 int isModified = myLocMesh.GetIsModified();
3304 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
3305 aDataset->CreateOnDisk();
3306 aDataset->WriteOnDisk( &isModified );
3307 aDataset->CloseOnDisk();
3309 // issue 20918. Store Persistent Id of SMESHDS_Mesh
3310 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
3312 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
3313 aDataset->CreateOnDisk();
3314 aDataset->WriteOnDisk( &meshPersistentId );
3315 aDataset->CloseOnDisk();
3317 // write reference on a shape if exists
3318 SALOMEDS::SObject_wrap myRef;
3319 bool shapeRefFound = false;
3320 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
3322 SALOMEDS::SObject_wrap myShape;
3323 bool ok = myRef->ReferencedObject( myShape.inout() );
3325 CORBA::Object_var shapeObj = myShape->GetObject();
3326 shapeRefFound = (! CORBA::is_nil( shapeObj ));
3327 CORBA::String_var myRefOnObject = myShape->GetID();
3328 if ( shapeRefFound && myRefOnObject.in()[0] ) {
3329 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
3330 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
3331 aDataset->CreateOnDisk();
3332 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
3333 aDataset->CloseOnDisk();
3338 // write applied hypotheses if exist
3339 SALOMEDS::SObject_wrap myHypBranch;
3340 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
3341 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
3342 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
3344 if ( found && (shapeRefFound || !hasShape) ) {
3345 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
3346 aGroup->CreateOnDisk();
3348 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myHypBranch );
3350 for ( ; it->More(); it->Next() ) {
3351 SALOMEDS::SObject_wrap mySObject = it->Value();
3352 SALOMEDS::SObject_wrap myRefOnHyp;
3353 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
3355 // san - it is impossible to recover applied hypotheses
3356 // using their entries within Load() method,
3357 // for there are no AttributeIORs in the study when Load() is working.
3358 // Hence, it is better to store persistent IDs of hypotheses as references to them
3360 //string myRefOnObject = myRefOnHyp->GetID();
3361 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3362 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3363 int id = myStudyContext->findId( string( objStr.in() ) );
3364 //if ( myRefOnObject.length() > 0 ) {
3365 //aSize[ 0 ] = myRefOnObject.length() + 1;
3366 char hypName[ 30 ], hypId[ 30 ];
3367 sprintf( hypName, "Hyp %d", ++hypNb );
3368 sprintf( hypId, "%d", id );
3369 aSize[ 0 ] = strlen( hypId ) + 1;
3370 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
3371 aDataset->CreateOnDisk();
3372 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3373 aDataset->WriteOnDisk( hypId );
3374 aDataset->CloseOnDisk();
3378 aGroup->CloseOnDisk();
3381 // write applied algorithms if exist
3382 SALOMEDS::SObject_wrap myAlgoBranch;
3383 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3384 myAlgoBranch.inout() );
3385 if ( found && !shapeRefFound && hasShape) { // remove applied algos
3386 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
3388 if ( found && (shapeRefFound || !hasShape)) {
3389 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3390 aGroup->CreateOnDisk();
3392 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myAlgoBranch );
3394 for ( ; it->More(); it->Next() ) {
3395 SALOMEDS::SObject_wrap mySObject = it->Value();
3396 SALOMEDS::SObject_wrap myRefOnAlgo;
3397 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
3399 // san - it is impossible to recover applied algorithms
3400 // using their entries within Load() method,
3401 // for there are no AttributeIORs in the study when Load() is working.
3402 // Hence, it is better to store persistent IDs of algorithms as references to them
3404 //string myRefOnObject = myRefOnAlgo->GetID();
3405 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3406 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3407 int id = myStudyContext->findId( string( objStr.in() ) );
3408 //if ( myRefOnObject.length() > 0 ) {
3409 //aSize[ 0 ] = myRefOnObject.length() + 1;
3410 char algoName[ 30 ], algoId[ 30 ];
3411 sprintf( algoName, "Algo %d", ++algoNb );
3412 sprintf( algoId, "%d", id );
3413 aSize[ 0 ] = strlen( algoId ) + 1;
3414 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
3415 aDataset->CreateOnDisk();
3416 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3417 aDataset->WriteOnDisk( algoId );
3418 aDataset->CloseOnDisk();
3422 aGroup->CloseOnDisk();
3425 // --> submesh objects sub-branches
3427 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
3428 SALOMEDS::SObject_wrap mySubmeshBranch;
3429 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
3431 if ( found ) // check if there is shape reference in submeshes
3433 bool hasShapeRef = false;
3434 SALOMEDS::ChildIterator_wrap itSM =
3435 myCurrentStudy->NewChildIterator( mySubmeshBranch );
3436 for ( ; itSM->More(); itSM->Next() ) {
3437 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
3438 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3439 mySubRef->ReferencedObject( myShape.inout() );
3440 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
3443 { // remove one submesh
3444 if ( shapeRefFound )
3445 { // unassign hypothesis
3446 SMESH::SMESH_subMesh_var mySubMesh =
3447 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
3448 if ( !mySubMesh->_is_nil() ) {
3449 int shapeID = mySubMesh->GetId();
3450 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
3451 const list<const SMESHDS_Hypothesis*>& hypList =
3452 mySMESHDSMesh->GetHypothesis( S );
3453 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
3454 while ( hyp != hypList.end() ) {
3455 int hypID = (*hyp++)->GetID(); // goto next hyp here because
3456 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
3460 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
3462 } // loop on submeshes of a type
3463 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
3464 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
3467 } // end check if there is shape reference in submeshes
3469 char name_meshgroup[ 30 ];
3470 if ( i == GetSubMeshOnVertexTag() )
3471 strcpy( name_meshgroup, "SubMeshes On Vertex" );
3472 else if ( i == GetSubMeshOnEdgeTag() )
3473 strcpy( name_meshgroup, "SubMeshes On Edge" );
3474 else if ( i == GetSubMeshOnWireTag() )
3475 strcpy( name_meshgroup, "SubMeshes On Wire" );
3476 else if ( i == GetSubMeshOnFaceTag() )
3477 strcpy( name_meshgroup, "SubMeshes On Face" );
3478 else if ( i == GetSubMeshOnShellTag() )
3479 strcpy( name_meshgroup, "SubMeshes On Shell" );
3480 else if ( i == GetSubMeshOnSolidTag() )
3481 strcpy( name_meshgroup, "SubMeshes On Solid" );
3482 else if ( i == GetSubMeshOnCompoundTag() )
3483 strcpy( name_meshgroup, "SubMeshes On Compound" );
3485 // for each type of submeshes create container HDF group
3486 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
3487 aGroup->CreateOnDisk();
3489 // iterator for all submeshes of given type
3490 SALOMEDS::ChildIterator_wrap itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
3491 for ( ; itSM->More(); itSM->Next() ) {
3492 SALOMEDS::SObject_wrap mySObject = itSM->Value();
3493 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
3494 if ( !CORBA::is_nil( anSubObject ))
3496 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
3497 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
3498 int subid = myStudyContext->findId( string( objStr.in() ) );
3500 // for each mesh open the HDF group basing on its id
3501 char submeshGrpName[ 30 ];
3502 sprintf( submeshGrpName, "SubMesh %d", subid );
3503 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
3504 aSubGroup->CreateOnDisk();
3506 // write reference on a shape, already checked if it exists
3507 SALOMEDS::SObject_wrap mySubRef, myShape;
3508 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3509 mySubRef->ReferencedObject( myShape.inout() );
3510 string myRefOnObject = myShape->GetID();
3511 if ( myRefOnObject.length() > 0 ) {
3512 aSize[ 0 ] = myRefOnObject.length() + 1;
3513 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
3514 aDataset->CreateOnDisk();
3515 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3516 aDataset->CloseOnDisk();
3519 // write applied hypotheses if exist
3520 SALOMEDS::SObject_wrap mySubHypBranch;
3521 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
3522 mySubHypBranch.inout() );
3524 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
3525 aSubSubGroup->CreateOnDisk();
3527 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( mySubHypBranch );
3529 for ( ; it->More(); it->Next() ) {
3530 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3531 SALOMEDS::SObject_wrap myRefOnHyp;
3532 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
3534 //string myRefOnObject = myRefOnHyp->GetID();
3535 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3536 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3537 int id = myStudyContext->findId( string( objStr.in() ) );
3538 //if ( myRefOnObject.length() > 0 ) {
3539 //aSize[ 0 ] = myRefOnObject.length() + 1;
3540 char hypName[ 30 ], hypId[ 30 ];
3541 sprintf( hypName, "Hyp %d", ++hypNb );
3542 sprintf( hypId, "%d", id );
3543 aSize[ 0 ] = strlen( hypId ) + 1;
3544 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
3545 aDataset->CreateOnDisk();
3546 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3547 aDataset->WriteOnDisk( hypId );
3548 aDataset->CloseOnDisk();
3552 aSubSubGroup->CloseOnDisk();
3555 // write applied algorithms if exist
3556 SALOMEDS::SObject_wrap mySubAlgoBranch;
3557 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3558 mySubAlgoBranch.inout() );
3560 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3561 aSubSubGroup->CreateOnDisk();
3563 SALOMEDS::ChildIterator_wrap it =
3564 myCurrentStudy->NewChildIterator( mySubAlgoBranch );
3566 for ( ; it->More(); it->Next() ) {
3567 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3568 SALOMEDS::SObject_wrap myRefOnAlgo;
3569 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
3571 //string myRefOnObject = myRefOnAlgo->GetID();
3572 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3573 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3574 int id = myStudyContext->findId( string( objStr.in() ) );
3575 //if ( myRefOnObject.length() > 0 ) {
3576 //aSize[ 0 ] = myRefOnObject.length() + 1;
3577 char algoName[ 30 ], algoId[ 30 ];
3578 sprintf( algoName, "Algo %d", ++algoNb );
3579 sprintf( algoId, "%d", id );
3580 aSize[ 0 ] = strlen( algoId ) + 1;
3581 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
3582 aDataset->CreateOnDisk();
3583 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3584 aDataset->WriteOnDisk( algoId );
3585 aDataset->CloseOnDisk();
3589 aSubSubGroup->CloseOnDisk();
3591 // close submesh HDF group
3592 aSubGroup->CloseOnDisk();
3595 // close container of submeshes by type HDF group
3596 aGroup->CloseOnDisk();
3599 // All sub-meshes will be stored in MED file
3600 // .. will NOT (PAL 12992)
3601 //if ( shapeRefFound )
3602 //myWriter.AddAllSubMeshes();
3604 // store submesh order if any
3605 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
3606 if ( theOrderIds.size() ) {
3607 char order_list[ 30 ];
3608 strcpy( order_list, "Mesh Order" );
3609 // count number of submesh ids
3611 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
3612 for ( ; idIt != theOrderIds.end(); idIt++ )
3613 nbIDs += (*idIt).size();
3614 // number of values = number of IDs +
3615 // number of lists (for separators) - 1
3616 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
3617 idIt = theOrderIds.begin();
3618 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
3619 const TListOfInt& idList = *idIt;
3620 if (idIt != theOrderIds.begin()) // not first list
3621 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
3622 // dump submesh ids from current list
3623 TListOfInt::const_iterator id_smId = idList.begin();
3624 for( ; id_smId != idList.end(); id_smId++ )
3625 smIDs[ i++ ] = *id_smId;
3628 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
3630 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
3631 aDataset->CreateOnDisk();
3632 aDataset->WriteOnDisk( smIDs );
3633 aDataset->CloseOnDisk();
3638 // groups root sub-branch
3639 SALOMEDS::SObject_wrap myGroupsBranch;
3640 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
3641 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
3643 char name_group[ 30 ];
3644 if ( i == GetNodeGroupsTag() )
3645 strcpy( name_group, "Groups of Nodes" );
3646 else if ( i == GetEdgeGroupsTag() )
3647 strcpy( name_group, "Groups of Edges" );
3648 else if ( i == GetFaceGroupsTag() )
3649 strcpy( name_group, "Groups of Faces" );
3650 else if ( i == GetVolumeGroupsTag() )
3651 strcpy( name_group, "Groups of Volumes" );
3652 else if ( i == Get0DElementsGroupsTag() )
3653 strcpy( name_group, "Groups of 0D Elements" );
3654 else if ( i == GetBallElementsGroupsTag() )
3655 strcpy( name_group, "Groups of Balls" );
3657 aGroup = new HDFgroup( name_group, aTopGroup );
3658 aGroup->CreateOnDisk();
3660 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myGroupsBranch );
3661 for ( ; it->More(); it->Next() ) {
3662 SALOMEDS::SObject_wrap mySObject = it->Value();
3663 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
3664 if ( !CORBA::is_nil( aSubObject ) ) {
3665 SMESH_GroupBase_i* myGroupImpl =
3666 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
3669 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
3673 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
3674 int anId = myStudyContext->findId( string( objStr.in() ) );
3676 // For each group, create a dataset named "Group <group_persistent_id>"
3677 // and store the group's user name into it
3678 const char* grpName = aGrpBaseDS->GetStoreName();
3679 CORBA::String_var aUserName = myGroupImpl->GetName();
3680 aSize[ 0 ] = strlen( aUserName ) + 1;
3682 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
3683 aDataset->CreateOnDisk();
3684 aDataset->WriteOnDisk( aUserName );
3685 aDataset->CloseOnDisk();
3688 // For each group, create a dataset named "Group <group_persistent_id> Color"
3689 // and store the group's color into it
3690 char grpColorName[ 30 ];
3691 sprintf( grpColorName, "ColorGroup %d", anId );
3692 SALOMEDS::Color aColor = myGroupImpl->GetColor();
3694 anRGB[ 0 ] = aColor.R;
3695 anRGB[ 1 ] = aColor.G;
3696 anRGB[ 2 ] = aColor.B;
3698 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
3699 aDataset->CreateOnDisk();
3700 aDataset->WriteOnDisk( anRGB );
3701 aDataset->CloseOnDisk();
3703 // Pass SMESHDS_Group to MED writer
3704 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
3706 myWriter.AddGroup( aGrpDS );
3708 // write reference on a shape if exists
3709 SMESHDS_GroupOnGeom* aGeomGrp =
3710 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
3712 SALOMEDS::SObject_wrap mySubRef, myShape;
3713 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
3714 mySubRef->ReferencedObject( myShape.inout() ) &&
3715 !CORBA::is_nil( myShape->GetObject() ))
3717 CORBA::String_var myRefOnObject = myShape->GetID();
3718 if ( myRefOnObject.in()[0] ) {
3719 char aRefName[ 30 ];
3720 sprintf( aRefName, "Ref on shape %d", anId);
3721 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
3722 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
3723 aDataset->CreateOnDisk();
3724 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
3725 aDataset->CloseOnDisk();
3728 else // shape ref is invalid:
3730 // save a group on geometry as ordinary group
3731 myWriter.AddGroup( aGeomGrp );
3734 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
3735 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
3737 std::string str = aFilterGrp_i->FilterToString();
3738 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
3739 aSize[ 0 ] = str.length() + 1;
3740 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
3741 aDataset->CreateOnDisk();
3742 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
3743 aDataset->CloseOnDisk();
3747 aGroup->CloseOnDisk();
3751 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
3753 // Flush current mesh information into MED file
3756 // save info on nb of elements
3757 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
3759 // maybe a shape was deleted in the study
3760 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
3761 TopoDS_Shape nullShape;
3762 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
3765 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
3770 aGroup = new HDFgroup( "Submeshes", aTopGroup );
3771 aGroup->CreateOnDisk();
3773 // each element belongs to one or none submesh,
3774 // so for each node/element, we store a submesh ID
3776 // Store submesh IDs
3777 for ( int isNode = 0; isNode < 2; ++isNode )
3779 SMDS_ElemIteratorPtr eIt =
3780 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
3781 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
3784 std::vector<int> smIDs; smIDs.reserve( nbElems );
3785 while ( eIt->more() )
3786 if ( const SMDS_MeshElement* e = eIt->next())
3787 smIDs.push_back( e->getshapeId() );
3789 aSize[ 0 ] = nbElems;
3790 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3791 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3792 aDataset->CreateOnDisk();
3793 aDataset->WriteOnDisk( & smIDs[0] );
3794 aDataset->CloseOnDisk();
3797 aGroup->CloseOnDisk();
3799 // Store node positions on sub-shapes (SMDS_Position):
3800 // ----------------------------------------------------
3802 aGroup = new HDFgroup( "Node Positions", aTopGroup );
3803 aGroup->CreateOnDisk();
3805 // in aGroup, create 5 datasets to contain:
3806 // "Nodes on Edges" - ID of node on edge
3807 // "Edge positions" - U parameter on node on edge
3808 // "Nodes on Faces" - ID of node on face
3809 // "Face U positions" - U parameter of node on face
3810 // "Face V positions" - V parameter of node on face
3812 // Find out nb of nodes on edges and faces
3813 // Collect corresponding sub-meshes
3814 int nbEdgeNodes = 0, nbFaceNodes = 0;
3815 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
3816 // loop on SMESHDS_SubMesh'es
3817 while ( smIt->more() )
3819 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
3820 if ( aSubMesh->IsComplexSubmesh() )
3821 continue; // submesh containing other submeshs
3822 int nbNodes = aSubMesh->NbNodes();
3823 if ( nbNodes == 0 ) continue;
3825 int aShapeID = aSubMesh->GetID();
3826 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
3828 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
3829 // write only SMDS_FacePosition and SMDS_EdgePosition
3830 switch ( aShapeType ) {
3832 nbFaceNodes += nbNodes;
3833 aFaceSM.push_back( aSubMesh );
3836 nbEdgeNodes += nbNodes;
3837 aEdgeSM.push_back( aSubMesh );
3843 // Treat positions on edges or faces
3844 for ( int onFace = 0; onFace < 2; onFace++ )
3846 // Create arrays to store in datasets
3847 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
3848 if (!nbNodes) continue;
3849 int* aNodeIDs = new int [ nbNodes ];
3850 double* aUPos = new double [ nbNodes ];
3851 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
3854 // loop on sub-meshes
3855 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
3856 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
3857 for ( ; itSM != pListSM->end(); itSM++ )
3859 SMESHDS_SubMesh* aSubMesh = (*itSM);
3861 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
3862 // loop on nodes in aSubMesh
3863 while ( itNode->more() )
3866 const SMDS_MeshNode* node = itNode->next();
3867 aNodeIDs [ iNode ] = node->GetID();
3870 const SMDS_PositionPtr pos = node->GetPosition();
3871 if ( onFace ) { // on FACE
3872 SMDS_FacePositionPtr fPos = pos;
3874 aUPos[ iNode ] = fPos->GetUParameter();
3875 aVPos[ iNode ] = fPos->GetVParameter();
3882 SMDS_EdgePositionPtr ePos = pos;
3884 aUPos[ iNode ] = ePos->GetUParameter();
3890 } // loop on nodes in aSubMesh
3891 } // loop on sub-meshes
3896 aSize[ 0 ] = nbNodes;
3898 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
3899 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3900 aDataset->CreateOnDisk();
3901 aDataset->WriteOnDisk( aNodeIDs );
3902 aDataset->CloseOnDisk();
3905 aDSName = ( onFace ? "Face U positions" : "Edge positions");
3906 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
3907 aDataset->CreateOnDisk();
3908 aDataset->WriteOnDisk( aUPos );
3909 aDataset->CloseOnDisk();
3912 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
3913 aDataset->CreateOnDisk();
3914 aDataset->WriteOnDisk( aVPos );
3915 aDataset->CloseOnDisk();
3920 if ( aVPos ) delete [] aVPos;
3922 } // treat positions on edges or faces
3924 // close "Node Positions" group
3925 aGroup->CloseOnDisk();
3927 } // if ( there are submeshes in SMESHDS_Mesh )
3930 // close mesh HDF group
3931 aTopGroup->CloseOnDisk();
3939 aFile->CloseOnDisk();
3942 // Convert temporary files to stream
3943 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
3945 // Remove temporary files and directory
3947 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
3949 return aStreamFile._retn();
3952 //=============================================================================
3954 * SMESH_Gen_i::SaveASCII
3956 * Save SMESH module's data in ASCII format
3958 //=============================================================================
3960 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
3962 bool isMultiFile ) {
3963 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
3964 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
3965 return aStreamFile._retn();
3967 //after usual saving needs to encipher binary to text string
3968 //Any binary symbol will be represent as "|xx" () hexadecimal format number
3969 int size = aStreamFile.in().length();
3970 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
3971 for ( int i = 0; i < size; i++ )
3972 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
3974 buffer[size * 3] = '\0';
3976 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
3978 return anAsciiStreamFile._retn();
3981 //=============================================================================
3983 * SMESH_Gen_i::loadGeomData
3985 * Load GEOM module data
3987 //=============================================================================
3989 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
3991 if ( theCompRoot->_is_nil() )
3994 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
3995 if ( aStudy->_is_nil() )
3998 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
3999 aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
4002 //=============================================================================
4006 * Load SMESH module's data
4008 //=============================================================================
4010 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
4011 const SALOMEDS::TMPFile& theStream,
4015 if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
4016 SetCurrentStudy( theComponent->GetStudy() );
4018 /* if( !theComponent->_is_nil() )
4020 //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
4021 if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
4022 loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
4025 StudyContext* myStudyContext = GetCurrentStudyContext();
4027 // Get temporary files location
4028 TCollection_AsciiString tmpDir =
4029 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
4031 // Convert the stream into sequence of files to process
4032 SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
4035 TCollection_AsciiString aStudyName( "" );
4036 if ( isMultiFile ) {
4037 CORBA::String_var url = myCurrentStudy->URL();
4038 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( url.in() ).c_str();
4040 // Set names of temporary files
4041 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
4042 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
4046 HDFdataset* aDataset;
4047 HDFgroup* aTopGroup;
4049 HDFgroup* aSubGroup;
4050 HDFgroup* aSubSubGroup;
4053 // ---> open HDF file
4054 aFile = new HDFfile( (char*) filename.ToCString() );
4056 aFile->OpenOnDisk( HDF_RDONLY );
4058 catch ( HDFexception ) {
4059 INFOS( "Load(): " << filename << " not found!" );
4063 TPythonDump pd; // prevent dump during loading
4065 // DriverMED_R_SMESHDS_Mesh myReader;
4066 // myReader.SetFile( meshfile.ToCString() );
4068 // For PAL13473 ("Repetitive mesh") implementation.
4069 // New dependencies between SMESH objects are established:
4070 // now hypotheses can refer to meshes, shapes and other hypotheses.
4071 // To keep data consistent, the following order of data restoration
4073 // 1. Create hypotheses
4074 // 2. Create all meshes
4075 // 3. Load hypotheses' data
4078 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
4079 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
4080 list< SMESH::Filter_var > filters;
4082 // get total number of top-level groups
4083 int aNbGroups = aFile->nInternalObjects();
4084 if ( aNbGroups > 0 ) {
4085 // --> in first turn we should read&create hypotheses
4086 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
4087 // open hypotheses root HDF group
4088 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4089 aTopGroup->OpenOnDisk();
4091 // get number of hypotheses
4092 int aNbObjects = aTopGroup->nInternalObjects();
4093 for ( int j = 0; j < aNbObjects; j++ ) {
4094 // try to identify hypothesis
4095 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4096 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4098 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
4099 // open hypothesis group
4100 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4101 aGroup->OpenOnDisk();
4103 // --> get hypothesis id
4104 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
4109 // get number of datasets
4110 int aNbSubObjects = aGroup->nInternalObjects();
4111 for ( int k = 0; k < aNbSubObjects; k++ ) {
4113 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4114 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4115 // --> get hypothesis name
4116 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4117 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4118 aDataset->OpenOnDisk();
4119 size = aDataset->GetSize();
4120 char* hypname_str = new char[ size ];
4121 aDataset->ReadFromDisk( hypname_str );
4122 hypname = string( hypname_str );
4123 delete [] hypname_str;
4124 aDataset->CloseOnDisk();
4126 // --> get hypothesis plugin library name
4127 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4128 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4129 aDataset->OpenOnDisk();
4130 size = aDataset->GetSize();
4131 char* libname_str = new char[ size ];
4132 aDataset->ReadFromDisk( libname_str );
4133 if(MYDEBUG) SCRUTE( libname_str );
4134 libname = string( libname_str );
4135 delete [] libname_str;
4136 aDataset->CloseOnDisk();
4138 // --> get hypothesis data
4139 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4140 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4141 aDataset->OpenOnDisk();
4142 size = aDataset->GetSize();
4143 char* hypdata_str = new char[ size ];
4144 aDataset->ReadFromDisk( hypdata_str );
4145 hypdata = string( hypdata_str );
4146 delete [] hypdata_str;
4147 aDataset->CloseOnDisk();
4150 // close hypothesis HDF group
4151 aGroup->CloseOnDisk();
4153 // --> restore hypothesis from data
4154 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4155 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
4156 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4157 SMESH::SMESH_Hypothesis_var myHyp;
4159 try { // protect persistence mechanism against exceptions
4160 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4163 INFOS( "Exception during hypothesis creation" );
4166 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4168 // myImpl->LoadFrom( hypdata.c_str() );
4169 hypDataList.push_back( make_pair( myImpl, hypdata ));
4170 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4171 int newId = myStudyContext->findId( iorString.in() );
4172 myStudyContext->mapOldToNew( id, newId );
4175 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4179 // close hypotheses root HDF group
4180 aTopGroup->CloseOnDisk();
4184 // --> then we should read&create algorithms
4185 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
4186 // open algorithms root HDF group
4187 aTopGroup = new HDFgroup( "Algorithms", aFile );
4188 aTopGroup->OpenOnDisk();
4190 // get number of algorithms
4191 int aNbObjects = aTopGroup->nInternalObjects();
4192 for ( int j = 0; j < aNbObjects; j++ ) {
4193 // try to identify algorithm
4194 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4195 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4197 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
4198 // open algorithm group
4199 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4200 aGroup->OpenOnDisk();
4202 // --> get algorithm id
4203 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
4208 // get number of datasets
4209 int aNbSubObjects = aGroup->nInternalObjects();
4210 for ( int k = 0; k < aNbSubObjects; k++ ) {
4212 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4213 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4214 // --> get algorithm name
4215 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4216 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4217 aDataset->OpenOnDisk();
4218 size = aDataset->GetSize();
4219 char* hypname_str = new char[ size ];
4220 aDataset->ReadFromDisk( hypname_str );
4221 hypname = string( hypname_str );
4222 delete [] hypname_str;
4223 aDataset->CloseOnDisk();
4225 // --> get algorithm plugin library name
4226 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4227 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4228 aDataset->OpenOnDisk();
4229 size = aDataset->GetSize();
4230 char* libname_str = new char[ size ];
4231 aDataset->ReadFromDisk( libname_str );
4232 if(MYDEBUG) SCRUTE( libname_str );
4233 libname = string( libname_str );
4234 delete [] libname_str;
4235 aDataset->CloseOnDisk();
4237 // --> get algorithm data
4238 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4239 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4240 aDataset->OpenOnDisk();
4241 size = aDataset->GetSize();
4242 char* hypdata_str = new char[ size ];
4243 aDataset->ReadFromDisk( hypdata_str );
4244 if(MYDEBUG) SCRUTE( hypdata_str );
4245 hypdata = string( hypdata_str );
4246 delete [] hypdata_str;
4247 aDataset->CloseOnDisk();
4250 // close algorithm HDF group
4251 aGroup->CloseOnDisk();
4253 // --> restore algorithm from data
4254 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4255 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
4256 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4257 SMESH::SMESH_Hypothesis_var myHyp;
4259 try { // protect persistence mechanism against exceptions
4260 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4263 INFOS( "Exception during hypothesis creation" );
4266 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4268 //myImpl->LoadFrom( hypdata.c_str() );
4269 hypDataList.push_back( make_pair( myImpl, hypdata ));
4270 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4271 int newId = myStudyContext->findId( iorString.in() );
4272 myStudyContext->mapOldToNew( id, newId );
4275 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4279 // close algorithms root HDF group
4280 aTopGroup->CloseOnDisk();
4284 // --> the rest groups should be meshes
4285 for ( int i = 0; i < aNbGroups; i++ ) {
4286 // identify next group
4287 char meshName[ HDF_NAME_MAX_LEN+1 ];
4288 aFile->InternalObjectIndentify( i, meshName );
4290 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
4292 int id = atoi( string( meshName ).substr( 4 ).c_str() );
4296 // open mesh HDF group
4297 aTopGroup = new HDFgroup( meshName, aFile );
4298 aTopGroup->OpenOnDisk();
4300 // get number of child HDF objects
4301 int aNbObjects = aTopGroup->nInternalObjects();
4302 if ( aNbObjects > 0 ) {
4304 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
4305 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
4306 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
4307 if ( !myNewMeshImpl )
4309 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
4311 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
4312 int newId = myStudyContext->findId( iorString.in() );
4313 myStudyContext->mapOldToNew( id, newId );
4316 // try to read and set auto color flag
4317 char aMeshAutoColorName[ 30 ];
4318 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
4319 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
4321 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
4322 aDataset->OpenOnDisk();
4323 size = aDataset->GetSize();
4324 int* anAutoColor = new int[ size ];
4325 aDataset->ReadFromDisk( anAutoColor );
4326 aDataset->CloseOnDisk();
4327 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
4328 delete [] anAutoColor;
4331 // try to read and set reference to shape
4332 GEOM::GEOM_Object_var aShapeObject;
4333 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
4334 // load mesh "Ref on shape" - it's an entry to SObject
4335 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
4336 aDataset->OpenOnDisk();
4337 size = aDataset->GetSize();
4338 char* refFromFile = new char[ size ];
4339 aDataset->ReadFromDisk( refFromFile );
4340 aDataset->CloseOnDisk();
4341 if ( strlen( refFromFile ) > 0 ) {
4342 SALOMEDS::SObject_wrap shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4344 // Make sure GEOM data are loaded first
4345 //loadGeomData( shapeSO->GetFatherComponent() );
4347 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4348 if ( !CORBA::is_nil( shapeObject ) ) {
4349 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4350 if ( !aShapeObject->_is_nil() )
4351 myNewMeshImpl->SetShape( aShapeObject );
4354 delete [] refFromFile;
4357 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
4358 if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
4360 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
4361 aDataset->OpenOnDisk();
4362 size = aDataset->GetSize();
4363 int* meshPersistentId = new int[ size ];
4364 aDataset->ReadFromDisk( meshPersistentId );
4365 aDataset->CloseOnDisk();
4366 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
4367 delete [] meshPersistentId;
4373 // As all object that can be referred by hypothesis are created,
4374 // we can restore hypothesis data
4376 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
4377 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4379 SMESH_Hypothesis_i* hyp = hyp_data->first;
4380 string & data = hyp_data->second;
4381 hyp->LoadFrom( data.c_str() );
4384 // Restore the rest mesh data
4386 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
4387 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4389 aTopGroup = meshi_group->second;
4390 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4391 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4392 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4394 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
4395 bool hasData = false;
4398 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
4399 int newId = myStudyContext->findId( iorString.in() );
4400 int id = myStudyContext->getOldId( newId );
4402 // try to find mesh data dataset
4403 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
4404 // load mesh "has data" flag
4405 aDataset = new HDFdataset( "Has data", aTopGroup );
4406 aDataset->OpenOnDisk();
4407 size = aDataset->GetSize();
4408 char* strHasData = new char[ size ];
4409 aDataset->ReadFromDisk( strHasData );
4410 aDataset->CloseOnDisk();
4411 if ( strcmp( strHasData, "1") == 0 ) {
4412 // read mesh data from MED file
4413 // myReader.SetMesh( mySMESHDSMesh );
4414 // myReader.SetMeshId( id );
4415 // myReader.Perform();
4418 delete [] strHasData;
4421 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
4422 // nodes and elements are not yet put into sub-meshes)
4423 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4424 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4425 aGroup->OpenOnDisk();
4426 // get number of applied algorithms
4427 int aNbSubObjects = aGroup->nInternalObjects();
4428 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
4429 for ( int j = 0; j < aNbSubObjects; j++ ) {
4430 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4431 aGroup->InternalObjectIndentify( j, name_dataset );
4432 // check if it is an algorithm
4433 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
4434 aDataset = new HDFdataset( name_dataset, aGroup );
4435 aDataset->OpenOnDisk();
4436 size = aDataset->GetSize();
4437 char* refFromFile = new char[ size ];
4438 aDataset->ReadFromDisk( refFromFile );
4439 aDataset->CloseOnDisk();
4440 // san - it is impossible to recover applied algorithms using their entries within Load() method
4441 //SALOMEDS::SObject_wrap hypSO = myCurrentStudy->FindObjectID( refFromFile );
4442 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4443 int id = atoi( refFromFile );
4444 delete [] refFromFile;
4445 string anIOR = myStudyContext->getIORbyOldId( id );
4446 if ( !anIOR.empty() ) {
4447 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4448 if ( !CORBA::is_nil( hypObject ) ) {
4449 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4450 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4451 || !myNewMeshImpl->HasShapeToMesh()) )
4452 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4457 aGroup->CloseOnDisk();
4460 // try to get applied hypotheses
4461 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4462 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4463 aGroup->OpenOnDisk();
4464 // get number of applied hypotheses
4465 int aNbSubObjects = aGroup->nInternalObjects();
4466 for ( int j = 0; j < aNbSubObjects; j++ ) {
4467 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4468 aGroup->InternalObjectIndentify( j, name_dataset );
4469 // check if it is a hypothesis
4470 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4471 aDataset = new HDFdataset( name_dataset, aGroup );
4472 aDataset->OpenOnDisk();
4473 size = aDataset->GetSize();
4474 char* refFromFile = new char[ size ];
4475 aDataset->ReadFromDisk( refFromFile );
4476 aDataset->CloseOnDisk();
4477 // san - it is impossible to recover applied hypotheses using their entries within Load() method
4478 //SALOMEDS::SObject_wrap hypSO = myCurrentStudy->FindObjectID( refFromFile );
4479 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4480 int id = atoi( refFromFile );
4481 delete [] refFromFile;
4482 string anIOR = myStudyContext->getIORbyOldId( id );
4483 if ( !anIOR.empty() ) {
4484 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4485 if ( !CORBA::is_nil( hypObject ) ) {
4486 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4487 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4488 || !myNewMeshImpl->HasShapeToMesh()) )
4489 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4494 aGroup->CloseOnDisk();
4497 // --> try to find SUB-MESHES containers for each type of submesh
4498 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
4499 const char* name_meshgroup = 0;
4500 if ( j == GetSubMeshOnVertexTag() )
4501 name_meshgroup = "SubMeshes On Vertex";
4502 else if ( j == GetSubMeshOnEdgeTag() )
4503 name_meshgroup = "SubMeshes On Edge";
4504 else if ( j == GetSubMeshOnWireTag() )
4505 name_meshgroup = "SubMeshes On Wire";
4506 else if ( j == GetSubMeshOnFaceTag() )
4507 name_meshgroup = "SubMeshes On Face";
4508 else if ( j == GetSubMeshOnShellTag() )
4509 name_meshgroup = "SubMeshes On Shell";
4510 else if ( j == GetSubMeshOnSolidTag() )
4511 name_meshgroup = "SubMeshes On Solid";
4512 else if ( j == GetSubMeshOnCompoundTag() )
4513 name_meshgroup = "SubMeshes On Compound";
4515 // try to get submeshes container HDF group
4516 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
4517 // open submeshes containers HDF group
4518 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4519 aGroup->OpenOnDisk();
4521 // get number of submeshes
4522 int aNbSubMeshes = aGroup->nInternalObjects();
4523 for ( int k = 0; k < aNbSubMeshes; k++ ) {
4525 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
4526 aGroup->InternalObjectIndentify( k, name_submeshgroup );
4527 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
4528 // --> get submesh id
4529 int subid = atoi( name_submeshgroup + 7 );
4532 // open submesh HDF group
4533 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
4534 aSubGroup->OpenOnDisk();
4536 // try to read and set reference to subshape
4537 GEOM::GEOM_Object_var aSubShapeObject;
4538 SMESH::SMESH_subMesh_var aSubMesh;
4540 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
4541 // load submesh "Ref on shape" - it's an entry to SObject
4542 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
4543 aDataset->OpenOnDisk();
4544 size = aDataset->GetSize();
4545 char* refFromFile = new char[ size ];
4546 aDataset->ReadFromDisk( refFromFile );
4547 aDataset->CloseOnDisk();
4548 if ( strlen( refFromFile ) > 0 ) {
4549 SALOMEDS::SObject_wrap subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
4550 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
4551 if ( !CORBA::is_nil( subShapeObject ) ) {
4552 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
4553 if ( !aSubShapeObject->_is_nil() )
4554 aSubMesh = SMESH::SMESH_subMesh::_duplicate
4555 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
4556 if ( aSubMesh->_is_nil() )
4558 string iorSubString = GetORB()->object_to_string( aSubMesh );
4559 int newSubId = myStudyContext->findId( iorSubString );
4560 myStudyContext->mapOldToNew( subid, newSubId );
4563 delete [] refFromFile;
4566 if ( aSubMesh->_is_nil() )
4569 // try to get applied algorithms
4570 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4571 // open "applied algorithms" HDF group
4572 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4573 aSubSubGroup->OpenOnDisk();
4574 // get number of applied algorithms
4575 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4576 for ( int l = 0; l < aNbSubObjects; l++ ) {
4577 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4578 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4579 // check if it is an algorithm
4580 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
4581 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4582 aDataset->OpenOnDisk();
4583 size = aDataset->GetSize();
4584 char* refFromFile = new char[ size ];
4585 aDataset->ReadFromDisk( refFromFile );
4586 aDataset->CloseOnDisk();
4588 int id = atoi( refFromFile );
4589 string anIOR = myStudyContext->getIORbyOldId( id );
4590 if ( !anIOR.empty() ) {
4591 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4592 if ( !CORBA::is_nil( hypObject ) ) {
4593 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4594 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4595 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4598 delete [] refFromFile;
4601 // close "applied algorithms" HDF group
4602 aSubSubGroup->CloseOnDisk();
4605 // try to get applied hypotheses
4606 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4607 // open "applied hypotheses" HDF group
4608 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4609 aSubSubGroup->OpenOnDisk();
4610 // get number of applied hypotheses
4611 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4612 for ( int l = 0; l < aNbSubObjects; l++ ) {
4613 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4614 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4615 // check if it is a hypothesis
4616 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4617 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4618 aDataset->OpenOnDisk();
4619 size = aDataset->GetSize();
4620 char* refFromFile = new char[ size ];
4621 aDataset->ReadFromDisk( refFromFile );
4622 aDataset->CloseOnDisk();
4624 int id = atoi( refFromFile );
4625 string anIOR = myStudyContext->getIORbyOldId( id );
4626 if ( !anIOR.empty() ) {
4627 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4628 if ( !CORBA::is_nil( hypObject ) ) {
4629 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4630 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4631 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4634 delete [] refFromFile;
4637 // close "APPLIED HYPOTHESES" hdf group
4638 aSubSubGroup->CloseOnDisk();
4641 // close SUB-MESH hdf group
4642 aSubGroup->CloseOnDisk();
4645 // close SUB-MESHES containers hdf group
4646 aGroup->CloseOnDisk();
4650 // try to get GROUPS
4651 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
4652 char name_group[ 30 ];
4653 if ( ii == GetNodeGroupsTag() )
4654 strcpy( name_group, "Groups of Nodes" );
4655 else if ( ii == GetEdgeGroupsTag() )
4656 strcpy( name_group, "Groups of Edges" );
4657 else if ( ii == GetFaceGroupsTag() )
4658 strcpy( name_group, "Groups of Faces" );
4659 else if ( ii == GetVolumeGroupsTag() )
4660 strcpy( name_group, "Groups of Volumes" );
4661 else if ( ii == Get0DElementsGroupsTag() )
4662 strcpy( name_group, "Groups of 0D Elements" );
4663 else if ( ii == GetBallElementsGroupsTag() )
4664 strcpy( name_group, "Groups of Balls" );
4666 if ( aTopGroup->ExistInternalObject( name_group ) ) {
4667 aGroup = new HDFgroup( name_group, aTopGroup );
4668 aGroup->OpenOnDisk();
4669 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
4670 // within aGroup->ExistInternalObject( name )
4671 std::vector< std::string > subNames;
4672 TColStd_MapOfAsciiString mapOfNames;
4673 aGroup->GetAllObjects( subNames );
4674 for ( size_t iN = 0; iN < subNames.size(); ++iN )
4675 mapOfNames.Add( subNames[ iN ].c_str() );
4677 for ( size_t j = 0; j < subNames.size(); j++ ) {
4678 const std::string& name_dataset = subNames[ j ];
4679 // check if it is a group
4680 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
4682 int subid = atoi( name_dataset.substr( 5 ).c_str() );
4685 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
4686 aDataset->OpenOnDisk();
4688 // Retrieve actual group name
4689 size = aDataset->GetSize();
4690 char* nameFromFile = new char[ size ];
4691 aDataset->ReadFromDisk( nameFromFile );
4692 aDataset->CloseOnDisk();
4694 // Try to find a shape reference
4695 TopoDS_Shape aShape;
4696 char aRefName[ 30 ];
4697 sprintf( aRefName, "Ref on shape %d", subid);
4698 if ( mapOfNames.Contains( aRefName ))
4700 // load mesh "Ref on shape" - it's an entry to SObject
4701 aDataset = new HDFdataset( aRefName, aGroup );
4702 aDataset->OpenOnDisk();
4703 size = aDataset->GetSize();
4704 char* refFromFile = new char[ size ];
4705 aDataset->ReadFromDisk( refFromFile );
4706 aDataset->CloseOnDisk();
4707 if ( strlen( refFromFile ) > 0 ) {
4708 SALOMEDS::SObject_wrap shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4709 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4710 if ( !CORBA::is_nil( shapeObject ) ) {
4711 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4712 if ( !aShapeObject->_is_nil() )
4713 aShape = GeomObjectToShape( aShapeObject );
4716 delete [] refFromFile;
4718 // Try to read a filter of SMESH_GroupOnFilter
4719 SMESH::Filter_var filter;
4720 SMESH_PredicatePtr predicate;
4721 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
4722 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
4724 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
4725 aDataset->OpenOnDisk();
4726 size = aDataset->GetSize();
4727 char* persistStr = new char[ size ];
4728 aDataset->ReadFromDisk( persistStr );
4729 aDataset->CloseOnDisk();
4730 if ( strlen( persistStr ) > 0 ) {
4731 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
4732 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
4733 filters.push_back( filter );
4735 delete [] persistStr;
4738 // Create group servant
4739 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
4740 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
4741 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape, predicate ) );
4742 delete [] nameFromFile;
4743 // Obtain a SMESHDS_Group object
4744 if ( aNewGroup->_is_nil() )
4747 string iorSubString = GetORB()->object_to_string( aNewGroup );
4748 int newSubId = myStudyContext->findId( iorSubString );
4749 myStudyContext->mapOldToNew( subid, newSubId );
4751 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
4755 if ( SMESH_GroupOnFilter_i* aFilterGroup =
4756 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
4758 aFilterGroup->SetFilter( filter );
4759 filter->UnRegister();
4761 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
4762 if ( !aGroupBaseDS )
4765 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
4768 // Read color of the group
4769 char aGroupColorName[ 30 ];
4770 sprintf( aGroupColorName, "ColorGroup %d", subid);
4771 if ( mapOfNames.Contains( aGroupColorName ))
4773 aDataset = new HDFdataset( aGroupColorName, aGroup );
4774 aDataset->OpenOnDisk();
4775 size = aDataset->GetSize();
4776 double* anRGB = new double[ size ];
4777 aDataset->ReadFromDisk( anRGB );
4778 aDataset->CloseOnDisk();
4779 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
4780 aGroupBaseDS->SetColor( aColor );
4785 aGroup->CloseOnDisk();
4789 // instead of reading mesh data, we read only brief information of all
4790 // objects: mesh, groups, sub-meshes (issue 0021208 )
4793 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, id,
4794 meshfile.ToCString(), filename.ToCString(),
4798 // read Sub-Mesh ORDER if any
4799 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
4800 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
4801 aDataset->OpenOnDisk();
4802 size = aDataset->GetSize();
4803 int* smIDs = new int[ size ];
4804 aDataset->ReadFromDisk( smIDs );
4805 aDataset->CloseOnDisk();
4806 TListOfListOfInt anOrderIds;
4807 anOrderIds.push_back( TListOfInt() );
4808 for ( int i = 0; i < size; i++ )
4809 if ( smIDs[ i ] < 0 ) // is separator
4810 anOrderIds.push_back( TListOfInt() );
4812 anOrderIds.back().push_back(smIDs[ i ]);
4814 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
4819 // update hyps needing full mesh data restored (issue 20918)
4820 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4822 SMESH_Hypothesis_i* hyp = hyp_data->first;
4823 hyp->UpdateAsMeshesRestored();
4826 // notify algos on completed restoration to set sub-mesh event listeners
4827 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4829 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4830 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4832 TopoDS_Shape myLocShape;
4833 if(myLocMesh.HasShapeToMesh())
4834 myLocShape = myLocMesh.GetShapeToMesh();
4836 myLocShape = SMESH_Mesh::PseudoShape();
4838 myLocMesh.GetSubMesh(myLocShape)->
4839 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
4842 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
4843 list< SMESH::Filter_var >::iterator f = filters.begin();
4844 for ( ; f != filters.end(); ++f )
4845 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
4846 fi->FindBaseObjects();
4851 aTopGroup->CloseOnDisk();
4854 aFile->CloseOnDisk();
4857 // Remove temporary files created from the stream
4860 SMESH_File meshFile( meshfile.ToCString() );
4861 if ( !meshFile ) // no meshfile exists
4863 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
4867 Engines::Container_var container = GetContainerRef();
4868 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
4870 container_i->registerTemporaryFile( filename.ToCString() );
4871 container_i->registerTemporaryFile( meshfile.ToCString() );
4872 container_i->registerTemporaryFile( tmpDir.ToCString() );
4876 pd << ""; // prevent optimizing pd out
4878 // creation of tree nodes for all data objects in the study
4879 // to support tree representation customization and drag-n-drop:
4880 SALOMEDS::Study_var study = theComponent->GetStudy();
4881 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = study->GetUseCaseBuilder();
4882 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
4883 useCaseBuilder->SetRootCurrent();
4884 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
4885 SALOMEDS::ChildIterator_wrap it = study->NewChildIterator( theComponent );
4886 for (it->InitEx(true); it->More(); it->Next()) {
4887 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
4894 //=============================================================================
4896 * SMESH_Gen_i::LoadASCII
4898 * Load SMESH module's data in ASCII format
4900 //=============================================================================
4902 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
4903 const SALOMEDS::TMPFile& theStream,
4905 bool isMultiFile ) {
4906 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
4907 return Load( theComponent, theStream, theURL, isMultiFile );
4909 //before call main ::Load method it's need for decipher text format to
4910 //binary ( "|xx" => x' )
4911 int size = theStream.length();
4912 if ( int((size / 3 )*3) != size ) //error size of buffer
4915 int real_size = int(size / 3);
4917 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
4920 unsigned int c = -1;
4921 for ( int i = 0; i < real_size; i++ )
4923 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
4924 sscanf( tmp, "%x", &c );
4925 sprintf( (char*)&(buffer[i]), "%c", (char)c );
4928 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
4930 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
4933 //=============================================================================
4935 * SMESH_Gen_i::Close
4937 * Clears study-connected data when it is closed
4939 //=============================================================================
4941 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
4943 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
4945 // set correct current study
4946 SALOMEDS::Study_var study = theComponent->GetStudy();
4947 if ( study->StudyId() != GetCurrentStudyID())
4948 setCurrentStudy( study, /*IsBeingClosed=*/true );
4950 // Clear study contexts data
4951 int studyId = GetCurrentStudyID();
4952 if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
4953 delete myStudyContextMap[ studyId ];
4954 myStudyContextMap.erase( studyId );
4957 // remove the tmp files meshes are loaded from
4958 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
4960 myCurrentStudy = SALOMEDS::Study::_nil();
4964 //=============================================================================
4966 * SMESH_Gen_i::ComponentDataType
4968 * Get component data type
4970 //=============================================================================
4972 char* SMESH_Gen_i::ComponentDataType()
4974 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
4975 return CORBA::string_dup( "SMESH" );
4979 //=============================================================================
4981 * SMESH_Gen_i::IORToLocalPersistentID
4983 * Transform data from transient form to persistent
4985 //=============================================================================
4987 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
4988 const char* IORString,
4989 CORBA::Boolean /*isMultiFile*/,
4990 CORBA::Boolean /*isASCII*/ )
4992 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
4993 StudyContext* myStudyContext = GetCurrentStudyContext();
4995 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
4996 int anId = myStudyContext->findId( IORString );
4998 if(MYDEBUG) MESSAGE( "VSR " << anId )
5000 sprintf( strId, "%d", anId );
5001 return CORBA::string_dup( strId );
5004 return CORBA::string_dup( "" );
5007 //=============================================================================
5009 * SMESH_Gen_i::LocalPersistentIDToIOR
5011 * Transform data from persistent form to transient
5013 //=============================================================================
5015 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
5016 const char* aLocalPersistentID,
5017 CORBA::Boolean /*isMultiFile*/,
5018 CORBA::Boolean /*isASCII*/ )
5020 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
5021 StudyContext* myStudyContext = GetCurrentStudyContext();
5023 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
5024 int anId = atoi( aLocalPersistentID );
5025 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
5027 return CORBA::string_dup( "" );
5030 //=======================================================================
5031 //function : RegisterObject
5033 //=======================================================================
5035 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
5037 StudyContext* myStudyContext = GetCurrentStudyContext();
5038 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5039 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
5040 return myStudyContext->addObject( string( iorString.in() ) );
5045 //================================================================================
5047 * \brief Return id of registered object
5048 * \param theObject - the Object
5049 * \retval int - Object id
5051 //================================================================================
5053 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
5055 StudyContext* myStudyContext = GetCurrentStudyContext();
5056 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5057 string iorString = GetORB()->object_to_string( theObject );
5058 return myStudyContext->findId( iorString );
5063 //=============================================================================
5065 * SMESH_Gen_i::SetName
5067 * Set a new object name
5069 //=============================================================================
5070 void SMESH_Gen_i::SetName(const char* theIOR,
5071 const char* theName)
5073 if ( theIOR && strcmp( theIOR, "" ) ) {
5074 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
5075 SALOMEDS::SObject_wrap aSO = ObjectToSObject( myCurrentStudy, anObject );
5076 if ( !aSO->_is_nil() ) {
5077 SetName( aSO, theName );
5082 int SMESH_Gen_i::GetCurrentStudyID()
5084 return myCurrentStudy->_is_nil() || myCurrentStudy->_non_existent() ? -1 : myCurrentStudy->StudyId();
5087 // Version information
5088 char* SMESH_Gen_i::getVersion()
5090 #if SMESH_DEVELOPMENT
5091 return CORBA::string_dup(SMESH_VERSION_STR"dev");
5093 return CORBA::string_dup(SMESH_VERSION_STR);
5097 //=================================================================================
5098 // function : Move()
5099 // purpose : Moves objects to the specified position.
5100 // Is used in the drag-n-drop functionality.
5101 //=================================================================================
5102 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
5103 SALOMEDS::SObject_ptr where,
5106 if ( CORBA::is_nil( where ) ) return;
5108 SALOMEDS::Study_var study = where->GetStudy();
5109 SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder();
5110 SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder();
5111 SALOMEDS::SComponent_var father = where->GetFatherComponent();
5112 std::string dataType = father->ComponentDataType();
5113 if ( dataType != "SMESH" ) return; // not a SMESH component
5115 SALOMEDS::SObject_var objAfter;
5116 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
5117 // insert at given row -> find insertion position
5118 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
5120 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
5121 if ( i == row && useCaseIt->More() ) {
5122 objAfter = useCaseIt->Value();
5126 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
5127 SALOMEDS::SObject_var sobj = what[i];
5128 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
5129 // insert the object to the use case tree
5130 if ( !CORBA::is_nil( objAfter ) )
5131 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
5133 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
5136 //================================================================================
5138 * \brief Returns true if algorithm can be used to mesh a given geometry
5139 * \param [in] theAlgoType - the algorithm type
5140 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
5141 * \param [in] theGeomObject - the geometry to mesh
5142 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
5143 * else, returns \c True if at least one shape is meshable
5144 * \return CORBA::Boolean - can or can't
5146 //================================================================================
5148 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
5149 const char* theLibName,
5150 GEOM::GEOM_Object_ptr theGeomObject,
5151 CORBA::Boolean toCheckAll)
5155 std::string aPlatformLibName;
5156 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
5157 GenericHypothesisCreator_i* aCreator =
5158 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
5161 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
5162 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll );
5169 SMESH_CATCH( SMESH::doNothing );
5172 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
5177 //=================================================================================
5178 // function : GetInsideSphere
5179 // purpose : Collect indices of elements, which are located inside the sphere
5180 //=================================================================================
5181 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
5182 SMESH::ElementType theElemType,
5188 SMESH::long_array_var aResult = new SMESH::long_array();
5189 if ( meshPart->_is_nil() )
5190 return aResult._retn();
5192 // 1. Create geometrical object
5193 gp_Pnt aP( theX, theY, theZ );
5194 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
5196 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5198 if ( lst.size() > 0 ) {
5199 aResult->length( lst.size() );
5200 for ( size_t i = 0; i < lst.size(); i++ ) {
5201 aResult[i] = lst[i];
5204 return aResult._retn();
5207 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
5208 SMESH::ElementType theElemType,
5209 CORBA::Double theX1,
5210 CORBA::Double theY1,
5211 CORBA::Double theZ1,
5212 CORBA::Double theX2,
5213 CORBA::Double theY2,
5214 CORBA::Double theZ2) {
5215 SMESH::long_array_var aResult = new SMESH::long_array();
5216 if( meshPart->_is_nil() )
5217 return aResult._retn();
5219 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
5221 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5223 if( lst.size() > 0 ) {
5224 aResult->length( lst.size() );
5225 for ( size_t i = 0; i < lst.size(); i++ ) {
5226 aResult[i] = lst[i];
5229 return aResult._retn();
5232 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
5233 SMESH::ElementType theElemType,
5237 CORBA::Double theDX,
5238 CORBA::Double theDY,
5239 CORBA::Double theDZ,
5241 CORBA::Double theR ){
5242 SMESH::long_array_var aResult = new SMESH::long_array();
5243 if( meshPart->_is_nil() )
5244 return aResult._retn();
5246 gp_Pnt aP( theX, theY, theZ );
5247 gp_Vec aV( theDX, theDY, theDZ );
5248 gp_Ax2 anAxes (aP, aV);
5250 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
5252 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5254 if( lst.size() > 0 ) {
5255 aResult->length( lst.size() );
5256 for ( size_t i = 0; i < lst.size(); i++ ) {
5257 aResult[i] = lst[i];
5260 return aResult._retn();
5263 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5264 SMESH::ElementType theElemType,
5265 GEOM::GEOM_Object_ptr theGeom,
5266 CORBA::Double theTolerance ) {
5267 SMESH::long_array_var aResult = new SMESH::long_array();
5268 if( meshPart->_is_nil() || theGeom->_is_nil() )
5269 return aResult._retn();
5271 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
5273 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
5275 if( lst.size() > 0 ) {
5276 aResult->length( lst.size() );
5277 for ( size_t i = 0; i < lst.size(); i++ ) {
5278 aResult[i] = lst[i];
5281 return aResult._retn();
5286 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5287 SMESH::ElementType theElemType,
5288 TopoDS_Shape& aShape,
5289 double* theTolerance) {
5291 std::vector<long> res;
5292 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
5294 if ( mesh->_is_nil() )
5297 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
5301 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
5306 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
5307 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
5308 anElementsOnShape->SetAllNodes( true );
5309 anElementsOnShape->SetMesh( meshDS );
5310 anElementsOnShape->SetShape( aShape, aType );
5313 anElementsOnShape->SetTolerance(*theTolerance);
5315 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
5316 if ( !msource->_is_nil() ) { // Mesh case
5317 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
5319 while ( elemIt->more() ) {
5320 const SMDS_MeshElement* anElem = elemIt->next();
5321 long anId = anElem->GetID();
5322 if ( anElementsOnShape->IsSatisfy( anId ) )
5323 res.push_back( anId );
5327 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
5328 if ( !gsource->_is_nil() ) {
5329 if(theElemType == SMESH::NODE) {
5330 SMESH::long_array_var nodes = gsource->GetNodeIDs();
5331 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
5332 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
5333 long anId = node->GetID();
5334 if ( anElementsOnShape->IsSatisfy( anId ) )
5335 res.push_back( anId );
5338 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
5339 SMESH::long_array_var elems = gsource->GetListOfID();
5340 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
5341 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
5342 long anId = elem->GetID();
5343 if ( anElementsOnShape->IsSatisfy( anId ) )
5344 res.push_back( anId );
5349 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
5350 if ( !smsource->_is_nil() ) {
5351 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
5352 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
5353 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
5355 long anId = elem->GetID();
5356 if ( anElementsOnShape->IsSatisfy( anId ) )
5357 res.push_back( anId );
5365 //=============================================================================
5367 * SMESHEngine_factory
5369 * C factory, accessible with dlsym, after dlopen
5371 //=============================================================================
5375 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
5376 PortableServer::POA_ptr poa,
5377 PortableServer::ObjectId* contId,
5378 const char* instanceName,
5379 const char* interfaceName )
5381 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
5382 if(MYDEBUG) SCRUTE(interfaceName);
5383 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
5384 return aSMESHGen->getId() ;