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
27 #include <TopExp_Explorer.hxx>
29 #include <TopoDS_Iterator.hxx>
30 #include <TopoDS_Compound.hxx>
31 #include <TopoDS_CompSolid.hxx>
32 #include <TopoDS_Solid.hxx>
33 #include <TopoDS_Shell.hxx>
34 #include <TopoDS_Face.hxx>
35 #include <TopoDS_Wire.hxx>
36 #include <TopoDS_Edge.hxx>
37 #include <TopoDS_Vertex.hxx>
38 #include <TopoDS_Shape.hxx>
39 #include <TopTools_MapOfShape.hxx>
40 #include <TopTools_IndexedMapOfShape.hxx>
41 #include <TopTools_ListOfShape.hxx>
42 #include <TopTools_ListIteratorOfListOfShape.hxx>
44 #include <BRep_Tool.hxx>
45 #include <TCollection_AsciiString.hxx>
47 #include <BRepPrimAPI_MakeSphere.hxx>
48 #include <BRepPrimAPI_MakeCylinder.hxx>
49 #include <BRepPrimAPI_MakeBox.hxx>
57 #include <libgen.h> // for basename function
61 #define LibHandle HMODULE
62 #define LoadLib( name ) LoadLibrary( name )
63 #define GetProc GetProcAddress
64 #define UnLoadLib( handle ) FreeLibrary( handle );
66 #define LibHandle void*
67 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
69 #define UnLoadLib( handle ) dlclose( handle );
72 #include "SMESH_Gen_i.hxx"
73 #include "SMESH_version.h"
75 #include "DriverMED_W_SMESHDS_Mesh.h"
76 #include "DriverMED_R_SMESHDS_Mesh.h"
78 #include "DriverCGNS_Read.hxx"
80 #include "MED_Factory.hxx"
81 #include "SMDS_EdgePosition.hxx"
82 #include "SMDS_FacePosition.hxx"
83 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
84 #include "SMDS_SetIterator.hxx"
85 #include "SMDS_SpacePosition.hxx"
86 #include "SMDS_VertexPosition.hxx"
87 #include "SMESHDS_Document.hxx"
88 #include "SMESHDS_Group.hxx"
89 #include "SMESHDS_GroupOnGeom.hxx"
90 #include "SMESH_Algo_i.hxx"
91 #include "SMESH_File.hxx"
92 #include "SMESH_Group.hxx"
93 #include "SMESH_Group_i.hxx"
94 #include "SMESH_Hypothesis.hxx"
95 #include "SMESH_Hypothesis_i.hxx"
96 #include "SMESH_Mesh.hxx"
97 #include "SMESH_MeshEditor.hxx"
98 #include "SMESH_Mesh_i.hxx"
99 #include "SMESH_PreMeshInfo.hxx"
100 #include "SMESH_PythonDump.hxx"
101 #include "SMESH_ControlsDef.hxx"
102 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
104 #include CORBA_SERVER_HEADER(SMESH_Group)
105 #include CORBA_SERVER_HEADER(SMESH_Filter)
106 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
109 #include <GEOM_Client.hxx>
111 #include <Basics_Utils.hxx>
112 #include <Basics_DirUtils.hxx>
114 #include <OpUtil.hxx>
115 #include <SALOMEDS_Tool.hxx>
116 #include <SALOME_Container_i.hxx>
117 #include <SALOME_LifeCycleCORBA.hxx>
118 #include <SALOME_NamingService.hxx>
119 #include <Utils_CorbaException.hxx>
120 #include <Utils_ExceptHandlers.hxx>
121 #include <Utils_SINGLETON.hxx>
122 #include <utilities.h>
124 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
125 #include CORBA_CLIENT_HEADER(SALOME_Session)
127 // helpers about SALOME::GenericObj
128 #include <SALOMEDS_wrap.hxx>
129 #include <SALOMEDS_Attributes_wrap.hxx>
130 #include <GEOM_wrap.hxx>
138 using SMESH::TPythonDump;
141 #define NUM_TMP_FILES 2
144 static int MYDEBUG = 0;
146 static int MYDEBUG = 0;
149 // Static variables definition
150 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
151 CORBA::ORB_var SMESH_Gen_i::myOrb;
152 PortableServer::POA_var SMESH_Gen_i::myPoa;
153 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
154 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
155 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
158 const int nbElemPerDiagonal = 10;
160 //=============================================================================
162 * GetServant [ static ]
164 * Get servant of the CORBA object
166 //=============================================================================
168 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
170 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
173 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
177 INFOS( "GetServant - Unknown exception was caught!!!" );
182 //=============================================================================
184 * SObjectToObject [ static ]
186 * Get CORBA object corresponding to the SALOMEDS::SObject
188 //=============================================================================
190 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
192 SALOMEDS::GenericAttribute_wrap anAttr;
193 CORBA::Object_var anObj;
194 if ( !theSObject->_is_nil() ) {
196 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
197 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
198 CORBA::String_var aValue = anIOR->Value();
199 if( strcmp( aValue, "" ) != 0 )
200 anObj = GetORB()->string_to_object( aValue );
204 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
210 //=============================================================================
214 * Get SALOME_NamingService object
216 //=============================================================================
218 SALOME_NamingService* SMESH_Gen_i::GetNS()
220 if ( myNS == NULL ) {
221 myNS = SINGLETON_<SALOME_NamingService>::Instance();
222 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
223 myNS->init_orb( GetORB() );
228 //=============================================================================
232 * Get SALOME_LifeCycleCORBA object
234 //=============================================================================
235 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC() {
236 if ( myLCC == NULL ) {
237 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
243 //=============================================================================
245 * GetGeomEngine [ static ]
247 * Get GEOM::GEOM_Gen reference
249 //=============================================================================
250 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine() {
251 //CCRT GEOM::GEOM_Gen_var aGeomEngine =
252 //CCRT GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
253 //CCRT return aGeomEngine._retn();
254 if(CORBA::is_nil(myGeomGen))
256 Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
257 myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
262 //=============================================================================
264 * SMESH_Gen_i::SMESH_Gen_i
266 * Default constructor: not for use
268 //=============================================================================
270 SMESH_Gen_i::SMESH_Gen_i()
274 //=============================================================================
276 * SMESH_Gen_i::SMESH_Gen_i
278 * Standard constructor, used with Container
280 //=============================================================================
282 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
283 PortableServer::POA_ptr poa,
284 PortableServer::ObjectId* contId,
285 const char* instanceName,
286 const char* interfaceName )
287 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
290 myOrb = CORBA::ORB::_duplicate(orb);
291 myPoa = PortableServer::POA::_duplicate(poa);
294 _id = myPoa->activate_object( _thisObj );
296 myStudyContext = new StudyContext;
298 myIsEmbeddedMode = false;
299 myIsEnablePublish = true;
300 myShapeReader = NULL; // shape reader
302 myIsHistoricalPythonDump = true;
303 myToForgetMeshDataOnHypModif = false;
305 // set it in standalone mode only
306 //OSD::SetSignal( true );
308 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
309 // find out mode (embedded or standalone) here else
310 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
311 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
312 if ( SALOME_NamingService* ns = GetNS() )
314 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
315 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
316 if ( !session->_is_nil() )
318 CORBA::String_var str_host = session->getHostname();
319 CORBA::Long s_pid = session->getPID();
320 string my_host = Kernel_Utils::GetHostname();
322 long my_pid = (long)_getpid();
324 long my_pid = (long) getpid();
326 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
331 //=============================================================================
333 * SMESH_Gen_i::~SMESH_Gen_i
337 //=============================================================================
339 SMESH_Gen_i::~SMESH_Gen_i()
341 // delete hypothesis creators
342 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
343 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
345 // same creator can be mapped under different names
346 GenericHypothesisCreator_i* creator = (*itHyp).second;
350 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
351 if ( creator == (*itHyp2).second )
352 (*itHyp2).second = 0;
354 myHypCreatorMap.clear();
356 // Clear study contexts data
357 delete myStudyContext;
359 // delete shape reader
361 delete myShapeReader;
363 //=============================================================================
365 * SMESH_Gen_i::getHypothesisCreator
367 * Get hypothesis creator
369 //=============================================================================
370 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
371 const char* theLibName,
372 std::string& thePlatformLibName)
373 throw (SALOME::SALOME_Exception)
375 std::string aPlatformLibName;
376 /* It's Need to tranlate lib name for WIN32 or X platform */
377 if ( theLibName && theLibName[0] != '\0' )
379 int libNameLen = strlen(theLibName);
380 //check for old format "libXXXXXXX.so"
381 if (libNameLen > 7 &&
382 !strncmp( theLibName, "lib", 3 ) &&
383 !strcmp( theLibName+libNameLen-3, ".so" ))
387 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
388 #elif defined(__APPLE__)
389 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
391 aPlatformLibName = theLibName;
396 //try to use new format
398 aPlatformLibName = theLibName;
399 aPlatformLibName += ".dll";
400 #elif defined(__APPLE__)
401 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
403 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
407 thePlatformLibName = aPlatformLibName;
409 Unexpect aCatch(SALOME_SalomeException);
410 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
412 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
413 GenericHypothesisCreator_i* aCreator;
416 // check, if creator for this hypothesis type already exists
417 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
419 // load plugin library
420 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
421 LibHandle libHandle = LoadLib( aPlatformLibName.c_str() );
424 // report any error, if occurred
426 const char* anError = dlerror();
427 throw(SALOME_Exception(anError));
429 throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
433 // get method, returning hypothesis creator
434 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
435 GetHypothesisCreator procHandle =
436 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
439 throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
440 UnLoadLib(libHandle);
443 // get hypothesis creator
444 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
445 aCreator = procHandle(theHypName);
448 throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
450 // map hypothesis creator to a hypothesis name
451 myHypCreatorMap[string(theHypName)] = aCreator;
456 return myHypCreatorMap[string(theHypName)];
459 catch (SALOME_Exception& S_ex)
461 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
466 //=============================================================================
468 * SMESH_Gen_i::createHypothesis
470 * Create hypothesis of given type
472 //=============================================================================
473 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
474 const char* theLibName)
476 SMESH_Hypothesis_i* myHypothesis_i = 0;
477 SMESH::SMESH_Hypothesis_var hypothesis_i;
478 std::string aPlatformLibName;
479 GenericHypothesisCreator_i* aCreator =
480 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
482 // create a new hypothesis object, store its ref. in studyContext
483 myHypothesis_i = aCreator->Create(myPoa, &myGen);
486 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
487 CORBA::String_var hypName = myHypothesis_i->GetName();
488 myHypCreatorMap[ hypName.in() ] = aCreator;
490 // activate the CORBA servant of hypothesis
491 hypothesis_i = myHypothesis_i->_this();
492 int nextId = RegisterObject( hypothesis_i );
493 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
494 else { nextId = 0; } // avoid "unused variable" warning in release mode
496 return hypothesis_i._retn();
499 //=============================================================================
501 * SMESH_Gen_i::createMesh
503 * Create empty mesh on shape
505 //=============================================================================
506 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
507 throw ( SALOME::SALOME_Exception )
509 Unexpect aCatch(SALOME_SalomeException);
510 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
512 // Get or create the GEOM_Client instance
514 // create a new mesh object servant, store it in a map in study context
515 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
516 // create a new mesh object
517 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
518 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
520 // activate the CORBA servant of Mesh
521 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
522 int nextId = RegisterObject( mesh );
523 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
524 else { nextId = 0; } // avoid "unused variable" warning in release mode
527 catch (SALOME_Exception& S_ex) {
528 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
530 return SMESH::SMESH_Mesh::_nil();
533 //=============================================================================
535 * SMESH_Gen_i::GetShapeReader
539 //=============================================================================
540 GEOM_Client* SMESH_Gen_i::GetShapeReader()
542 // create shape reader if necessary
543 if ( !myShapeReader )
544 myShapeReader = new GEOM_Client(GetContainerRef());
545 ASSERT( myShapeReader );
546 return myShapeReader;
549 //=============================================================================
551 * SMESH_Gen_i::SetGeomEngine
553 * Set GEOM::GEOM_Gen reference
555 //=============================================================================
556 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
557 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
559 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
560 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
561 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
565 //=============================================================================
567 * SMESH_Gen_i::SetEmbeddedMode
571 //=============================================================================
573 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
575 myIsEmbeddedMode = theMode;
577 if ( !myIsEmbeddedMode ) {
578 //PAL10867: disable signals catching with "noexcepthandler" option
579 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
580 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
585 char* envDisableFPE = getenv("DISABLE_FPE");
586 if (envDisableFPE && atoi(envDisableFPE))
591 OSD::SetSignal( raiseFPE );
593 // else OSD::SetSignal() is called in GUI
597 //=============================================================================
599 * SMESH_Gen_i::IsEmbeddedMode
603 //=============================================================================
605 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
607 return myIsEmbeddedMode;
610 //=============================================================================
612 * SMESH_Gen_i::SetEnablePublish
614 * Set enable publishing in the study
616 //=============================================================================
617 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
619 myIsEnablePublish = theIsEnablePublish;
622 //=============================================================================
624 * SMESH_Gen_i::IsEnablePublish
626 * Check enable publishing
628 //=============================================================================
630 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
632 return myIsEnablePublish;
635 //=============================================================================
637 * SMESH_Gen_i::UpdateStudy
639 * Update study (needed at switching GEOM->SMESH)
641 //=============================================================================
643 void SMESH_Gen_i::UpdateStudy()
645 if ( !myStudyContext )
646 myStudyContext = new StudyContext;
648 SALOMEDS::Study_var aStudy = getStudyServant();
649 if ( !CORBA::is_nil( aStudy ) ) {
650 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
651 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
652 if( !GEOM_var->_is_nil() )
653 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
654 // NPAL16168, issue 0020210
655 // Let meshes update their data depending on GEOM groups that could change
656 CORBA::String_var compDataType = ComponentDataType();
657 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
658 if ( !me->_is_nil() ) {
659 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
660 for ( ; anIter->More(); anIter->Next() ) {
661 SALOMEDS::SObject_wrap so = anIter->Value();
662 CORBA::Object_var ior = SObjectToObject( so );
663 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
664 mesh->CheckGeomModif();
670 //=============================================================================
672 * SMESH_Gen_i::GetStudyContext
676 //=============================================================================
677 StudyContext* SMESH_Gen_i::GetStudyContext()
679 return myStudyContext;
682 //=============================================================================
684 * SMESH_Gen_i::CreateHypothesis
686 * Create hypothesis/algorothm of given type and publish it in the study
688 //=============================================================================
690 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
691 const char* theLibName )
692 throw ( SALOME::SALOME_Exception )
694 Unexpect aCatch(SALOME_SalomeException);
695 // Create hypothesis/algorithm
696 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
698 // Publish hypothesis/algorithm in the study
699 if ( CanPublishInStudy( hyp ) ) {
700 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
701 if ( !aSO->_is_nil() ) {
702 // Update Python script
703 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
704 << theHypName << "', '" << theLibName << "')";
711 //================================================================================
713 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
714 * existing on the given geometry or to size of the geometry.
715 * \param theHypType - hypothesis type name
716 * \param theLibName - plugin library name
717 * \param theMesh - The mesh of interest
718 * \param theGeom - The shape to get parameter values from
719 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
720 * in a study and used to compute the mesh, or a temporary one created just to pass
723 //================================================================================
725 SMESH::SMESH_Hypothesis_ptr
726 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
727 const char* theLibName,
728 SMESH::SMESH_Mesh_ptr theMesh,
729 GEOM::GEOM_Object_ptr theGeom,
730 CORBA::Boolean byMesh)
731 throw ( SALOME::SALOME_Exception )
733 Unexpect aCatch(SALOME_SalomeException);
734 if ( byMesh && CORBA::is_nil( theMesh ) )
735 return SMESH::SMESH_Hypothesis::_nil();
736 if ( byMesh && CORBA::is_nil( theGeom ) )
737 return SMESH::SMESH_Hypothesis::_nil();
739 // -----------------------------------------------
740 // find hypothesis used to mesh theGeom
741 // -----------------------------------------------
743 // get mesh and shape
744 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
745 TopoDS_Shape shape = GeomObjectToShape( theGeom );
746 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
747 return SMESH::SMESH_Hypothesis::_nil();
748 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
750 // create a temporary hypothesis to know its dimension
751 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
752 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
754 return SMESH::SMESH_Hypothesis::_nil();
755 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
758 // look for a hypothesis of theHypType used to mesh the shape
759 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
762 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
763 int nbLocalHyps = aHypList->length();
764 for ( int i = 0; i < nbLocalHyps; i++ ) {
765 CORBA::String_var hypName = aHypList[i]->GetName();
766 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
767 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
769 // check super shapes
770 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
771 while ( nbLocalHyps == 0 && itShape.More() ) {
772 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
773 if ( ! CORBA::is_nil( geomObj )) {
774 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
775 nbLocalHyps = aHypList->length();
776 for ( int i = 0; i < nbLocalHyps; i++ )
777 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
778 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
784 // let the temporary hypothesis find out somehow parameter values by mesh
785 if ( hyp->SetParametersByMesh( mesh, shape ))
786 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
791 diagonal = mesh->GetShapeDiagonalSize();
793 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
794 ::SMESH_Hypothesis::TDefaults dflts;
795 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
796 dflts._nbSegments = myGen.GetDefaultNbSegments();
797 dflts._shape = &shape;
798 // let the temporary hypothesis initialize it's values
799 if ( hyp->SetParametersByDefaults( dflts, mesh ))
800 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
803 return SMESH::SMESH_Hypothesis::_nil();
806 //=============================================================================
808 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
809 * \param [in] theHyp - the hypothesis of interest
810 * \param [out] theMesh - the sole mesh using \a theHyp
811 * \param [out] theShape - the sole geometry \a theHyp is assigned to
812 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
814 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
815 * considered as SAME sub-mesh => result is \c true.
816 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
817 * a shape to which an hyp being edited is assigned.
819 //=============================================================================
821 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
822 SMESH::SMESH_Mesh_out theMesh,
823 GEOM::GEOM_Object_out theShape)
825 if ( CORBA::is_nil( theHyp ))
828 // get Mesh component SO
829 CORBA::String_var compDataType = ComponentDataType();
830 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
831 if ( CORBA::is_nil( comp ))
834 // look for child SO of meshes
835 SMESH::SMESH_Mesh_var foundMesh;
836 TopoDS_Shape foundShape;
838 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
839 for ( ; meshIter->More() && isSole; meshIter->Next() )
841 SALOMEDS::SObject_wrap curSO = meshIter->Value();
842 CORBA::Object_var obj = SObjectToObject( curSO );
843 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
847 // look for a sole shape where theHyp is assigned
848 bool isHypFound = false;
849 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
850 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
851 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
853 const THypList& hyps = s2hypsIt.Value();
854 THypList::const_iterator h = hyps.begin();
855 for ( ; h != hyps.end(); ++h )
856 if ( (*h)->GetID() == theHyp->GetId() )
858 if ( h != hyps.end()) // theHyp found
861 if ( ! foundShape.IsNull() &&
862 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
864 foundShape.Nullify();
868 foundShape = s2hypsIt.Key();
870 } // loop on assigned hyps
872 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
874 if ( !foundMesh->_is_nil() ) // not a sole mesh
876 if ( !foundMesh->HasShapeToMesh() ||
877 !mesh_i ->HasShapeToMesh() )
879 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
883 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
884 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
885 isSole = s1->IsSame( s2 );
888 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
894 ! foundMesh->_is_nil() &&
895 ! foundShape.IsNull() )
897 theMesh = foundMesh._retn();
898 theShape = ShapeToGeomObject( foundShape );
899 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
904 //=============================================================================
906 * Sets number of segments per diagonal of boundary box of geometry by which
907 * default segment length of appropriate 1D hypotheses is defined
909 //=============================================================================
911 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
912 throw ( SALOME::SALOME_Exception )
914 if ( theNbSegments > 0 )
915 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
917 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
919 //=============================================================================
921 * \brief Sets default number of segments per edge
923 //=============================================================================
924 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
925 throw ( SALOME::SALOME_Exception )
927 if ( theNbSegments > 0 )
928 myGen.SetDefaultNbSegments( int(theNbSegments) );
930 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
933 //=============================================================================
937 //=============================================================================
939 void SMESH_Gen_i::SetOption(const char* name, const char* value)
941 if ( name && value && strlen( value ) > 0 )
944 if ( strcmp(name, "historical_python_dump") == 0 )
946 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
947 msgToGUI = "preferences/SMESH/historical_python_dump/";
948 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
950 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
952 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
953 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
954 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
956 else if ( strcmp(name, "default_grp_color") == 0 )
960 // color must be presented as a string of following form:
961 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
963 for ( size_t i = 0; i < str.length()/2; i++ )
964 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
965 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
967 else if ( value ) { // rgb color ("255,170,0", for example)
968 string tempValue( value );
969 char* colorValue = strtok( &tempValue[0], "," );
970 while ( colorValue != NULL ) {
971 int c_value = atoi( colorValue );
972 if ( c_value >= 0 && c_value <= 255 )
973 color.push_back( c_value );
974 colorValue = strtok( NULL, "," );
977 if ( color.size() == 3 ) { // color must have three valid component
978 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
979 myDefaultGroupColor = value;
980 msgToGUI = "preferences/SMESH/default_grp_color/";
985 // update preferences in case if SetOption() is invoked from python console
986 if ( !msgToGUI.empty() )
988 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
989 SALOME::Session_var session = SALOME::Session::_narrow( obj );
990 if ( !CORBA::is_nil( session ) )
991 session->emitMessageOneWay(msgToGUI.c_str());
996 //=============================================================================
998 Return an option value
1000 //=============================================================================
1002 char* SMESH_Gen_i::GetOption(const char* name)
1006 if ( strcmp(name, "historical_python_dump") == 0 )
1008 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1010 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1012 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1014 if ( strcmp(name, "default_grp_color") == 0 )
1016 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1019 return CORBA::string_dup( "" );
1022 //=============================================================================
1024 * SMESH_Gen_i::CreateMesh
1026 * Create empty mesh on a shape and publish it in the study
1028 //=============================================================================
1030 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1031 throw ( SALOME::SALOME_Exception )
1033 Unexpect aCatch(SALOME_SalomeException);
1034 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1036 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1038 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1039 ASSERT( meshServant );
1040 meshServant->SetShape( theShapeObject );
1042 // publish mesh in the study
1043 if ( CanPublishInStudy( mesh ) ) {
1044 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1045 aStudyBuilder->NewCommand(); // There is a transaction
1046 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1047 aStudyBuilder->CommitCommand();
1048 if ( !aSO->_is_nil() ) {
1049 // Update Python script
1050 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1054 return mesh._retn();
1057 //=============================================================================
1059 * SMESH_Gen_i::CreateEmptyMesh
1063 //=============================================================================
1065 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1066 throw ( SALOME::SALOME_Exception )
1068 Unexpect aCatch(SALOME_SalomeException);
1069 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1071 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1073 // publish mesh in the study
1074 if ( CanPublishInStudy( mesh ) ) {
1075 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1076 aStudyBuilder->NewCommand(); // There is a transaction
1077 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1078 aStudyBuilder->CommitCommand();
1079 if ( !aSO->_is_nil() ) {
1080 // Update Python script
1081 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1085 return mesh._retn();
1090 //================================================================================
1092 * \brief Throws an exception in case if the file can't be read
1094 //================================================================================
1096 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1098 SMESH_File f ( theFileName );
1101 if ( !f.error().empty() )
1102 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1104 THROW_SALOME_CORBA_EXCEPTION
1105 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1106 SALOME::BAD_PARAM );
1111 //=============================================================================
1113 * SMESH_Gen_i::CreateMeshFromUNV
1115 * Create mesh and import data from UNV file
1117 //=============================================================================
1119 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1120 throw ( SALOME::SALOME_Exception )
1122 Unexpect aCatch(SALOME_SalomeException);
1124 checkFileReadable( theFileName );
1126 SMESH::SMESH_Mesh_var aMesh = createMesh();
1128 // publish mesh in the study
1129 if ( CanPublishInStudy( aMesh ) ) {
1130 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1131 aStudyBuilder->NewCommand(); // There is a transaction
1132 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1133 aStudyBuilder->CommitCommand();
1134 if ( !aSO->_is_nil() ) {
1135 // Update Python script
1136 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1140 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1142 aServant->ImportUNVFile( theFileName );
1144 // Dump creation of groups
1145 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1147 aServant->GetImpl().GetMeshDS()->Modified();
1148 return aMesh._retn();
1151 //=============================================================================
1153 * SMESH_Gen_i::CreateMeshFromMED
1155 * Create mesh and import data from MED file
1157 //=============================================================================
1159 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1160 SMESH::DriverMED_ReadStatus& theStatus,
1161 const char* theCommandNameForPython,
1162 const char* theFileNameForPython)
1165 char bname[ _MAX_FNAME ];
1166 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1167 string aFileName = bname;
1169 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1171 // Retrieve mesh names from the file
1172 DriverMED_R_SMESHDS_Mesh myReader;
1173 myReader.SetFile( theFileName );
1174 myReader.SetMeshId( -1 );
1175 Driver_Mesh::Status aStatus;
1176 list<string> aNames = myReader.GetMeshNames(aStatus);
1177 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1178 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1180 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1183 TPythonDump aPythonDump;
1184 aPythonDump << "([";
1186 if (theStatus == SMESH::DRS_OK) {
1187 SALOMEDS::StudyBuilder_var aStudyBuilder;
1188 aStudyBuilder = getStudyServant()->NewBuilder();
1189 aStudyBuilder->NewCommand(); // There is a transaction
1191 aResult->length( aNames.size() );
1194 // Iterate through all meshes and create mesh objects
1195 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1198 if (i > 0) aPythonDump << ", ";
1201 SMESH::SMESH_Mesh_var mesh = createMesh();
1203 // publish mesh in the study
1204 SALOMEDS::SObject_wrap aSO;
1205 if ( CanPublishInStudy( mesh ) )
1206 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1207 // - as names of meshes are stored in MED file, we use them for data publishing
1208 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1209 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1212 if ( !aSO->_is_nil() ) {
1215 aPythonDump << "mesh_" << i;
1218 // Read mesh data (groups are published automatically by ImportMEDFile())
1219 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1220 ASSERT( meshServant );
1221 SMESH::DriverMED_ReadStatus status1 =
1222 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1223 if (status1 > theStatus)
1224 theStatus = status1;
1226 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1227 meshServant->GetImpl().GetMeshDS()->Modified();
1229 if ( !aStudyBuilder->_is_nil() )
1230 aStudyBuilder->CommitCommand();
1233 // Update Python script
1234 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1236 // Dump creation of groups
1237 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1238 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1240 return aResult._retn();
1243 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1244 SMESH::DriverMED_ReadStatus& theStatus)
1245 throw ( SALOME::SALOME_Exception )
1247 Unexpect aCatch(SALOME_SalomeException);
1248 checkFileReadable( theFileName );
1250 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1254 //=============================================================================
1256 * SMESH_Gen_i::CreateMeshFromSAUV
1258 * Create mesh and import data from SAUV file
1260 //=============================================================================
1262 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1263 SMESH::DriverMED_ReadStatus& theStatus)
1264 throw ( SALOME::SALOME_Exception )
1266 Unexpect aCatch(SALOME_SalomeException);
1267 checkFileReadable( theFileName );
1269 std::string sauvfilename(theFileName);
1270 std::string medfilename(theFileName);
1271 medfilename += ".med";
1274 cmd = "%PYTHONBIN% ";
1279 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1281 system(cmd.c_str());
1282 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1284 cmd = "%PYTHONBIN% ";
1289 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1291 system(cmd.c_str());
1295 //=============================================================================
1297 * SMESH_Gen_i::CreateMeshFromSTL
1299 * Create mesh and import data from STL file
1301 //=============================================================================
1303 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1304 throw ( SALOME::SALOME_Exception )
1306 Unexpect aCatch(SALOME_SalomeException);
1307 checkFileReadable( theFileName );
1309 SMESH::SMESH_Mesh_var aMesh = createMesh();
1312 char bname[ _MAX_FNAME ];
1313 _splitpath( theFileName, NULL, NULL, bname, NULL );
1314 string aFileName = bname;
1316 string aFileName = basename( const_cast<char *>(theFileName) );
1318 // publish mesh in the study
1319 if ( CanPublishInStudy( aMesh ) ) {
1320 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1321 aStudyBuilder->NewCommand(); // There is a transaction
1322 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1323 aStudyBuilder->CommitCommand();
1324 if ( !aSO->_is_nil() ) {
1325 // Update Python script
1326 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1330 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1332 aServant->ImportSTLFile( theFileName );
1333 aServant->GetImpl().GetMeshDS()->Modified();
1334 return aMesh._retn();
1337 //================================================================================
1339 * \brief Create meshes and import data from the CGSN file
1341 //================================================================================
1343 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1344 SMESH::DriverMED_ReadStatus& theStatus)
1345 throw ( SALOME::SALOME_Exception )
1347 Unexpect aCatch(SALOME_SalomeException);
1348 checkFileReadable( theFileName );
1350 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1353 // Retrieve nb meshes from the file
1354 DriverCGNS_Read myReader;
1355 myReader.SetFile( theFileName );
1356 Driver_Mesh::Status aStatus;
1357 int nbMeshes = myReader.GetNbMeshes(aStatus);
1358 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1360 aResult->length( nbMeshes );
1362 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1365 TPythonDump aPythonDump;
1366 aPythonDump << "([";
1368 if (theStatus == SMESH::DRS_OK)
1370 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1371 aStudyBuilder->NewCommand(); // There is a transaction
1375 // Iterate through all meshes and create mesh objects
1376 for ( ; i < nbMeshes; ++i )
1379 if (i > 0) aPythonDump << ", ";
1382 SMESH::SMESH_Mesh_var mesh = createMesh();
1383 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1385 // Read mesh data (groups are published automatically by ImportMEDFile())
1386 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1387 ASSERT( meshServant );
1389 SMESH::DriverMED_ReadStatus status1 =
1390 meshServant->ImportCGNSFile( theFileName, i, meshName );
1391 if (status1 > theStatus)
1392 theStatus = status1;
1394 meshServant->GetImpl().GetMeshDS()->Modified();
1395 // publish mesh in the study
1396 SALOMEDS::SObject_wrap aSO;
1397 if ( CanPublishInStudy( mesh ) )
1398 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1401 if ( !aSO->_is_nil() ) {
1405 aPythonDump << "mesh_" << i;
1408 aStudyBuilder->CommitCommand();
1411 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1413 // Dump creation of groups
1414 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1415 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1417 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1420 return aResult._retn();
1423 //================================================================================
1425 * \brief Create a mesh and import data from a GMF file
1427 //================================================================================
1429 SMESH::SMESH_Mesh_ptr
1430 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1431 CORBA::Boolean theMakeRequiredGroups,
1432 SMESH::ComputeError_out theError)
1433 throw ( SALOME::SALOME_Exception )
1435 Unexpect aCatch(SALOME_SalomeException);
1436 checkFileReadable( theFileName );
1438 SMESH::SMESH_Mesh_var aMesh = createMesh();
1440 char bname[ _MAX_FNAME ];
1441 _splitpath( theFileName, NULL, NULL, bname, NULL );
1442 string aFileName = bname;
1444 string aFileName = basename( const_cast<char *>(theFileName) );
1446 // publish mesh in the study
1447 if ( CanPublishInStudy( aMesh ) ) {
1448 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1449 aStudyBuilder->NewCommand(); // There is a transaction
1450 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1451 aStudyBuilder->CommitCommand();
1452 if ( !aSO->_is_nil() ) {
1453 // Update Python script
1454 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1455 << theFileName << "', "
1456 << theMakeRequiredGroups << " )";
1459 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1461 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1462 aServant->GetImpl().GetMeshDS()->Modified();
1463 return aMesh._retn();
1467 //=============================================================================
1469 * SMESH_Gen_i::IsReadyToCompute
1471 * Returns true if mesh contains enough data to be computed
1473 //=============================================================================
1475 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1476 GEOM::GEOM_Object_ptr theShapeObject )
1477 throw ( SALOME::SALOME_Exception )
1479 Unexpect aCatch(SALOME_SalomeException);
1480 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1482 if ( CORBA::is_nil( theShapeObject ) )
1483 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1484 SALOME::BAD_PARAM );
1486 if ( CORBA::is_nil( theMesh ) )
1487 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1488 SALOME::BAD_PARAM );
1492 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1493 ASSERT( meshServant );
1494 if ( meshServant ) {
1495 // get local TopoDS_Shape
1496 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1497 // call implementation
1498 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1499 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1502 catch ( SALOME_Exception& S_ex ) {
1503 INFOS( "catch exception "<< S_ex.what() );
1508 //================================================================================
1510 * \brief Find SObject for an algo
1512 //================================================================================
1514 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1517 SALOMEDS::Study_var aStudy = getStudyServant();
1518 if ( !aStudy->_is_nil() ) {
1519 // find algo in the study
1520 CORBA::String_var compDataType = ComponentDataType();
1521 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1522 if ( !father->_is_nil() ) {
1523 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1524 for ( ; itBig->More(); itBig->Next() ) {
1525 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1526 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1527 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1528 for ( ; algoIt->More(); algoIt->Next() ) {
1529 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1530 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1531 if ( !CORBA::is_nil( algoIOR )) {
1532 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1533 if ( impl && impl->GetImpl() == algo )
1534 return algoSO._retn();
1536 } // loop on algo SO's
1539 } // SMESH component iterator
1543 return SALOMEDS::SObject::_nil();
1546 //================================================================================
1548 * \brief Return errors of mesh computation
1550 //================================================================================
1552 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1553 GEOM::GEOM_Object_ptr theSubObject )
1554 throw ( SALOME::SALOME_Exception )
1556 Unexpect aCatch(SALOME_SalomeException);
1557 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1559 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1560 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1562 if ( CORBA::is_nil( theMesh ) )
1563 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1565 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1567 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1570 if(theMesh->HasShapeToMesh())
1571 shape = GeomObjectToShape( theSubObject );
1573 shape = SMESH_Mesh::PseudoShape();
1575 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1577 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1580 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1581 const bool includeSelf = true, complexShapeFirst = true;
1582 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1584 while ( smIt->more() )
1587 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1589 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1590 if ( error && !error->IsOK() )
1592 if ( !( error->myAlgo ) &&
1593 !( error->myAlgo = sm->GetAlgo() ))
1595 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1596 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1597 errStruct.comment = error->myComment.c_str();
1598 errStruct.subShapeID = sm->GetId();
1599 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1600 if ( !algoSO->_is_nil() ) {
1601 CORBA::String_var algoName = algoSO->GetName();
1602 errStruct.algoName = algoName;
1605 errStruct.algoName = error->myAlgo->GetName();
1607 errStruct.hasBadMesh = !error->myBadElements.empty();
1610 error_array->length( nbErr );
1613 catch ( SALOME_Exception& S_ex ) {
1614 INFOS( "catch exception "<< S_ex.what() );
1617 return error_array._retn();
1620 //================================================================================
1622 * \brief Return mesh elements preventing computation of a subshape
1624 //================================================================================
1626 SMESH::MeshPreviewStruct*
1627 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1628 CORBA::Short theSubShapeID )
1629 throw ( SALOME::SALOME_Exception )
1631 Unexpect aCatch(SALOME_SalomeException);
1632 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1634 if ( CORBA::is_nil( theMesh ) )
1635 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1637 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1640 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1642 // mesh implementation
1643 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1644 // submesh by subshape id
1645 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1648 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1649 if ( error && !error->myBadElements.empty())
1651 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1652 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1654 // get nodes of elements and count elements
1655 TNode2LocalIDMap mapNode2LocalID;
1656 list< TNodeLocalID > connectivity;
1657 int i, nbElements = 0, nbConnNodes = 0;
1659 list<const SMDS_MeshElement*>::iterator elemIt = error->myBadElements.begin();
1660 list<const SMDS_MeshElement*>::iterator elemEnd = error->myBadElements.end();
1661 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1663 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1664 while ( nIt->more() )
1665 connectivity.push_back
1666 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1668 // fill node coords and assign local ids to the nodes
1669 int nbNodes = mapNode2LocalID.size();
1670 result->nodesXYZ.length( nbNodes );
1671 TNodeLocalID node2ID = mapNode2LocalID.begin();
1672 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1673 node2ID->second = i;
1674 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1675 result->nodesXYZ[i].x = node->X();
1676 result->nodesXYZ[i].y = node->Y();
1677 result->nodesXYZ[i].z = node->Z();
1679 // fill connectivity
1680 result->elementConnectivities.length( nbConnNodes );
1681 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1682 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1683 result->elementConnectivities[i] = (*connIt)->second;
1685 // fill element types
1686 result->elementTypes.length( nbElements );
1687 for ( i = 0, elemIt = error->myBadElements.begin(); i <nbElements; ++i, ++elemIt )
1689 const SMDS_MeshElement* elem = *elemIt;
1690 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1691 result->elementTypes[i].isPoly = elem->IsPoly();
1692 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1698 catch ( SALOME_Exception& S_ex ) {
1699 INFOS( "catch exception "<< S_ex.what() );
1702 return result._retn();
1705 //================================================================================
1707 * \brief Create a group of elements preventing computation of a sub-shape
1709 //================================================================================
1711 SMESH::ListOfGroups*
1712 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1713 CORBA::Short theSubShapeID,
1714 const char* theGroupName )
1715 throw ( SALOME::SALOME_Exception )
1717 Unexpect aCatch(SALOME_SalomeException);
1719 SMESH::ListOfGroups_var groups;
1721 if ( CORBA::is_nil( theMesh ) )
1722 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1725 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1727 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1728 TPythonDump() << groups << " = " << this
1729 << ".MakeGroupsOfBadInputElements( "
1730 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1733 catch ( SALOME_Exception& S_ex ) {
1734 INFOS( "catch exception "<< S_ex.what() );
1736 return groups._retn();
1739 //================================================================================
1741 * \brief Returns errors of hypotheses definintion
1742 * \param theMesh - the mesh
1743 * \param theSubObject - the main or sub- shape
1744 * \retval SMESH::algo_error_array* - sequence of errors
1746 //================================================================================
1748 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1749 GEOM::GEOM_Object_ptr theSubObject )
1750 throw ( SALOME::SALOME_Exception )
1752 Unexpect aCatch(SALOME_SalomeException);
1753 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1755 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1756 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1758 if ( CORBA::is_nil( theMesh ) )
1759 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1761 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1763 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1764 ASSERT( meshServant );
1765 if ( meshServant ) {
1766 TopoDS_Shape myLocShape;
1767 if(theMesh->HasShapeToMesh())
1768 myLocShape = GeomObjectToShape( theSubObject );
1770 myLocShape = SMESH_Mesh::PseudoShape();
1772 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1773 list< ::SMESH_Gen::TAlgoStateError > error_list;
1774 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1775 // call ::SMESH_Gen::GetAlgoState()
1776 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1777 error_array->length( error_list.size() );
1779 for ( error = error_list.begin(); error != error_list.end(); ++error )
1781 // fill AlgoStateError structure
1782 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1783 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1784 errStruct.algoDim = error->_algoDim;
1785 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1786 errStruct.algoName = "";
1787 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1788 if ( !algoSO->_is_nil() ) {
1789 CORBA::String_var algoName = algoSO->GetName();
1790 errStruct.algoName = algoName.in();
1795 catch ( SALOME_Exception& S_ex ) {
1796 INFOS( "catch exception "<< S_ex.what() );
1798 return error_array._retn();
1801 //=============================================================================
1803 * SMESH_Gen_i::GetSubShapesId
1805 * Get sub-shapes unique ID's list
1807 //=============================================================================
1810 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1811 const SMESH::object_array& theListOfSubShapeObject )
1812 throw ( SALOME::SALOME_Exception )
1814 Unexpect aCatch(SALOME_SalomeException);
1815 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1817 SMESH::long_array_var shapesId = new SMESH::long_array;
1820 if ( CORBA::is_nil( theMainShapeObject ) )
1821 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1825 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1826 TopTools_IndexedMapOfShape myIndexToShape;
1827 TopExp::MapShapes(myMainShape,myIndexToShape);
1829 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1831 GEOM::GEOM_Object_var aShapeObject
1832 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1833 if ( CORBA::is_nil( aShapeObject ) )
1834 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1835 SALOME::BAD_PARAM );
1837 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1838 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1840 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1841 setId.insert(myIndexToShape.FindIndex(F));
1842 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1844 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1846 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1847 setId.insert(myIndexToShape.FindIndex(E));
1848 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1850 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1852 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1853 setId.insert(myIndexToShape.FindIndex(V));
1854 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1857 shapesId->length(setId.size());
1858 set<int>::iterator iind;
1860 for (iind = setId.begin(); iind != setId.end(); iind++)
1862 if(MYDEBUG) SCRUTE((*iind));
1863 shapesId[i] = (*iind);
1864 if(MYDEBUG) SCRUTE(shapesId[i]);
1868 catch (SALOME_Exception& S_ex)
1870 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1873 return shapesId._retn();
1876 //=============================================================================
1878 * SMESH_Gen_i::Compute
1880 * Compute mesh on a shape
1882 //=============================================================================
1884 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1885 GEOM::GEOM_Object_ptr theShapeObject )
1886 throw ( SALOME::SALOME_Exception )
1889 Unexpect aCatch(SALOME_SalomeException);
1890 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1892 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1893 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1894 SALOME::BAD_PARAM );
1896 if ( CORBA::is_nil( theMesh ) )
1897 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1898 SALOME::BAD_PARAM );
1900 // Update Python script
1901 TPythonDump() << "isDone = " << this << ".Compute( "
1902 << theMesh << ", " << theShapeObject << ")";
1906 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1907 ASSERT( meshServant );
1908 if ( meshServant ) {
1909 meshServant->Load();
1910 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1911 meshServant->CheckGeomModif();
1912 // get local TopoDS_Shape
1913 TopoDS_Shape myLocShape;
1914 if(theMesh->HasShapeToMesh())
1915 myLocShape = GeomObjectToShape( theShapeObject );
1917 myLocShape = SMESH_Mesh::PseudoShape();
1918 // call implementation compute
1919 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1920 myGen.PrepareCompute( myLocMesh, myLocShape );
1921 int how = ::SMESH_Gen::COMPACT_MESH;
1922 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
1923 how |= ::SMESH_Gen::SHAPE_ONLY;
1924 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
1925 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1926 myLocMesh.GetMeshDS()->Modified();
1930 catch ( std::bad_alloc ) {
1931 INFOS( "Compute(): lack of memory" );
1933 catch ( SALOME_Exception& S_ex ) {
1934 INFOS( "Compute(): catch exception "<< S_ex.what() );
1937 INFOS( "Compute(): unknown exception " );
1942 //=============================================================================
1944 * SMESH_Gen_i::CancelCompute
1946 * Cancel Compute mesh on a shape
1948 //=============================================================================
1950 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
1951 GEOM::GEOM_Object_ptr theShapeObject )
1953 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1954 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1955 TopoDS_Shape myLocShape;
1956 if(theMesh->HasShapeToMesh())
1957 myLocShape = GeomObjectToShape( theShapeObject );
1959 myLocShape = SMESH_Mesh::PseudoShape();
1960 myGen.CancelCompute( myLocMesh, myLocShape);
1963 //=============================================================================
1965 * SMESH_Gen_i::Precompute
1967 * Compute mesh as preview till indicated dimension on shape
1969 //=============================================================================
1971 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
1972 GEOM::GEOM_Object_ptr theShapeObject,
1973 SMESH::Dimension theDimension,
1974 SMESH::long_array& theShapesId)
1975 throw ( SALOME::SALOME_Exception )
1977 Unexpect aCatch(SALOME_SalomeException);
1978 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
1980 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1981 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1982 SALOME::BAD_PARAM );
1984 if ( CORBA::is_nil( theMesh ) )
1985 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1986 SALOME::BAD_PARAM );
1988 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1991 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1992 meshServant->Load();
1993 ASSERT( meshServant );
1994 if ( meshServant ) {
1995 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1996 meshServant->CheckGeomModif();
1997 // get local TopoDS_Shape
1998 TopoDS_Shape myLocShape;
1999 if(theMesh->HasShapeToMesh())
2000 myLocShape = GeomObjectToShape( theShapeObject );
2002 return result._retn();;
2004 // call implementation compute
2005 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2007 ::MeshDimension aDim = (MeshDimension)theDimension;
2008 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2010 int nbShapeId = shapeIds.size();
2011 theShapesId.length( nbShapeId );
2012 // iterates on shapes and collect mesh entities into mesh preview
2013 TSetOfInt::const_iterator idIt = shapeIds.begin();
2014 TSetOfInt::const_iterator idEnd = shapeIds.end();
2015 std::map< int, int > mapOfShIdNb;
2016 std::set< SMESH_TLink > setOfEdge;
2017 std::list< SMDSAbs_ElementType > listOfElemType;
2018 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2019 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2020 TNode2LocalIDMap mapNode2LocalID;
2021 list< TNodeLocalID > connectivity;
2022 int i, nbConnNodes = 0;
2023 std::set< const SMESH_subMesh* > setOfVSubMesh;
2024 // iterates on shapes
2025 for ( ; idIt != idEnd; idIt++ )
2027 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2029 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2030 if ( !sm || !sm->IsMeshComputed() )
2033 const TopoDS_Shape& aSh = sm->GetSubShape();
2034 const int shDim = myGen.GetShapeDim( aSh );
2035 if ( shDim < 1 || shDim > theDimension )
2038 mapOfShIdNb[ *idIt ] = 0;
2039 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2041 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2042 if ( !smDS ) continue;
2044 if ( theDimension == SMESH::DIM_2D )
2046 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2047 while ( faceIt->more() )
2049 const SMDS_MeshElement* face = faceIt->next();
2050 int aNbNode = face->NbNodes();
2052 aNbNode /= 2; // do not take into account additional middle nodes
2054 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2055 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2057 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2058 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2060 listOfElemType.push_back( SMDSAbs_Edge );
2061 connectivity.push_back
2062 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2063 connectivity.push_back
2064 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2070 else if ( theDimension == SMESH::DIM_1D )
2072 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2073 while ( nodeIt->more() )
2075 listOfElemType.push_back( SMDSAbs_Node );
2076 connectivity.push_back
2077 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2079 // add corner nodes by first vertex from edge
2080 SMESH_subMeshIteratorPtr edgeSmIt =
2081 sm->getDependsOnIterator(/*includeSelf*/false,
2082 /*complexShapeFirst*/false);
2083 while ( edgeSmIt->more() )
2085 SMESH_subMesh* vertexSM = edgeSmIt->next();
2086 // check that vertex is not already treated
2087 if ( !setOfVSubMesh.insert( vertexSM ).second )
2089 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2092 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2093 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2094 while ( nodeIt->more() )
2096 listOfElemType.push_back( SMDSAbs_Node );
2097 connectivity.push_back
2098 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2104 // fill node coords and assign local ids to the nodes
2105 int nbNodes = mapNode2LocalID.size();
2106 result->nodesXYZ.length( nbNodes );
2107 TNodeLocalID node2ID = mapNode2LocalID.begin();
2108 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2109 node2ID->second = i;
2110 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2111 result->nodesXYZ[i].x = node->X();
2112 result->nodesXYZ[i].y = node->Y();
2113 result->nodesXYZ[i].z = node->Z();
2115 // fill connectivity
2116 result->elementConnectivities.length( nbConnNodes );
2117 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2118 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2119 result->elementConnectivities[i] = (*connIt)->second;
2122 // fill element types
2123 result->elementTypes.length( listOfElemType.size() );
2124 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2125 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2126 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2128 SMDSAbs_ElementType elemType = *typeIt;
2129 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2130 result->elementTypes[i].isPoly = false;
2131 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2134 // correct number of shapes
2135 theShapesId.length( mapOfShIdNb.size() );
2139 catch ( std::bad_alloc ) {
2140 INFOS( "Precompute(): lack of memory" );
2142 catch ( SALOME_Exception& S_ex ) {
2143 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2146 INFOS( "Precompute(): unknown exception " );
2148 return result._retn();
2152 //=============================================================================
2154 * SMESH_Gen_i::Evaluate
2156 * Evaluate mesh on a shape
2158 //=============================================================================
2160 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2161 GEOM::GEOM_Object_ptr theShapeObject)
2162 // SMESH::long_array& theNbElems)
2163 throw ( SALOME::SALOME_Exception )
2165 Unexpect aCatch(SALOME_SalomeException);
2166 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2168 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2169 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2170 SALOME::BAD_PARAM );
2172 if ( CORBA::is_nil( theMesh ) )
2173 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2174 SALOME::BAD_PARAM );
2176 SMESH::long_array_var nbels = new SMESH::long_array;
2177 nbels->length(SMESH::Entity_Last);
2178 int i = SMESH::Entity_Node;
2179 for (; i < SMESH::Entity_Last; i++)
2182 // Update Python script
2183 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2184 << theMesh << ", " << theShapeObject << ")";
2188 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2189 ASSERT( meshServant );
2190 if ( meshServant ) {
2191 meshServant->Load();
2192 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
2193 meshServant->CheckGeomModif();
2194 // get local TopoDS_Shape
2195 TopoDS_Shape myLocShape;
2196 if(theMesh->HasShapeToMesh())
2197 myLocShape = GeomObjectToShape( theShapeObject );
2199 myLocShape = SMESH_Mesh::PseudoShape();
2200 // call implementation compute
2201 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2202 MapShapeNbElems aResMap;
2203 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2204 MapShapeNbElemsItr anIt = aResMap.begin();
2205 for(; anIt!=aResMap.end(); anIt++) {
2206 const vector<int>& aVec = (*anIt).second;
2207 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2208 int nbElem = aVec[i];
2209 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2211 SMESH_subMesh* sm = anIt->first;
2212 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2213 const SMESH_Algo* algo = sm->GetAlgo();
2214 if ( (algo && !error.get()) || error->IsOK() )
2215 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2219 nbels[i] += aVec[i];
2223 return nbels._retn();
2226 catch ( std::bad_alloc ) {
2227 INFOS( "Evaluate(): lack of memory" );
2229 catch ( SALOME_Exception& S_ex ) {
2230 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2233 INFOS( "Evaluate(): unknown exception " );
2236 return nbels._retn();
2239 //================================================================================
2241 * \brief Return geometrical object the given element is built on
2242 * \param theMesh - the mesh the element is in
2243 * \param theElementID - the element ID
2244 * \param theGeomName - the name of the result geom object if it is not yet published
2245 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2247 //================================================================================
2249 GEOM::GEOM_Object_ptr
2250 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2251 CORBA::Long theElementID,
2252 const char* theGeomName)
2253 throw ( SALOME::SALOME_Exception )
2255 Unexpect aCatch(SALOME_SalomeException);
2257 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2258 if ( !geom->_is_nil() ) {
2259 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2260 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2262 // try to find the corresponding SObject
2263 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2264 if ( SObj->_is_nil() ) // submesh can be not found even if published
2266 // try to find published submesh
2267 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2268 if ( !geom->IsMainShape() && list->length() == 1 ) {
2269 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2270 SALOMEDS::ChildIterator_wrap it;
2271 if ( !mainSO->_is_nil() ) {
2272 it = getStudyServant()->NewChildIterator( mainSO );
2274 if ( !it->_is_nil() ) {
2275 for ( it->InitEx(true); it->More(); it->Next() ) {
2276 SALOMEDS::SObject_wrap so = it->Value();
2277 CORBA::Object_var obj = SObjectToObject( so );
2278 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2279 if ( !subGeom->_is_nil() ) {
2280 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2281 if ( subList->length() == 1 && list[0] == subList[0] ) {
2291 if ( SObj->_is_nil() ) // publish a new subshape
2292 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2294 // return only published geometry
2295 if ( !SObj->_is_nil() ) {
2296 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2297 CORBA::Object_var obj = SObjectToObject( SObj );
2298 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2302 return GEOM::GEOM_Object::_nil();
2305 //================================================================================
2307 * \brief Return geometrical object the given element is built on.
2308 * \param theMesh - the mesh the element is in
2309 * \param theElementID - the element ID
2310 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2312 //================================================================================
2314 GEOM::GEOM_Object_ptr
2315 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2316 CORBA::Long theElementID)
2317 throw ( SALOME::SALOME_Exception )
2319 Unexpect aCatch(SALOME_SalomeException);
2320 if ( CORBA::is_nil( theMesh ) )
2321 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2323 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2324 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2326 // get a core mesh DS
2327 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2328 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2330 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2331 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2332 // find the element in mesh
2333 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2334 // find a shape id by the element
2335 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2336 // get a geom object by the shape id
2337 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2338 if ( geom->_is_nil() ) {
2339 // try to find a published sub-shape
2340 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2341 SALOMEDS::ChildIterator_wrap it;
2342 if ( !mainSO->_is_nil() ) {
2343 it = getStudyServant()->NewChildIterator( mainSO );
2345 if ( !it->_is_nil() ) {
2346 for ( it->InitEx(true); it->More(); it->Next() ) {
2347 SALOMEDS::SObject_wrap so = it->Value();
2348 CORBA::Object_var obj = SObjectToObject( so );
2349 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2350 if ( !subGeom->_is_nil() ) {
2351 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2352 if ( subList->length() == 1 && shapeID == subList[0] ) {
2360 if ( geom->_is_nil() ) {
2362 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2363 if ( !op->_is_nil() )
2364 geom = op->GetSubShape( mainShape, shapeID );
2369 if ( !geom->_is_nil() ) {
2370 GeomObjectToShape( geom ); // let geom client remember the found shape
2371 return geom._retn();
2376 return GEOM::GEOM_Object::_nil();
2379 //================================================================================
2381 * SMESH_Gen_i::Concatenate
2383 * Concatenate the given meshes into one mesh
2385 //================================================================================
2387 SMESH::SMESH_Mesh_ptr
2388 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2389 CORBA::Boolean theUniteIdenticalGroups,
2390 CORBA::Boolean theMergeNodesAndElements,
2391 CORBA::Double theMergeTolerance)
2392 throw ( SALOME::SALOME_Exception )
2394 return ConcatenateCommon(theMeshesArray,
2395 theUniteIdenticalGroups,
2396 theMergeNodesAndElements,
2401 //================================================================================
2403 * SMESH_Gen_i::ConcatenateWithGroups
2405 * Concatenate the given meshes into one mesh
2406 * Create the groups of all elements from initial meshes
2408 //================================================================================
2410 SMESH::SMESH_Mesh_ptr
2411 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2412 CORBA::Boolean theUniteIdenticalGroups,
2413 CORBA::Boolean theMergeNodesAndElements,
2414 CORBA::Double theMergeTolerance)
2415 throw ( SALOME::SALOME_Exception )
2417 return ConcatenateCommon(theMeshesArray,
2418 theUniteIdenticalGroups,
2419 theMergeNodesAndElements,
2424 //================================================================================
2426 * SMESH_Gen_i::ConcatenateCommon
2428 * Concatenate the given meshes into one mesh
2430 //================================================================================
2432 SMESH::SMESH_Mesh_ptr
2433 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2434 CORBA::Boolean theUniteIdenticalGroups,
2435 CORBA::Boolean theMergeNodesAndElements,
2436 CORBA::Double theMergeTolerance,
2437 CORBA::Boolean theCommonGroups)
2438 throw ( SALOME::SALOME_Exception )
2440 typedef list<SMESH::SMESH_Group_var> TListOfNewGroups;
2441 typedef map< pair<string, SMESH::ElementType>, TListOfNewGroups > TGroupsMap;
2443 TPythonDump* pPythonDump = new TPythonDump;
2444 TPythonDump& aPythonDump = *pPythonDump; // prevent dump of called methods
2447 SMESH::SMESH_Mesh_var aNewMesh = CreateEmptyMesh();
2449 if ( aNewMesh->_is_nil() )
2450 return aNewMesh._retn();
2452 SMESH_Mesh_i* aNewImpl = SMESH::DownCast<SMESH_Mesh_i*>( aNewMesh );
2454 return aNewMesh._retn();
2456 ::SMESH_Mesh& aLocMesh = aNewImpl->GetImpl();
2457 SMESHDS_Mesh* aNewMeshDS = aLocMesh.GetMeshDS();
2459 TGroupsMap aGroupsMap;
2460 TListOfNewGroups aListOfNewGroups;
2461 ::SMESH_MeshEditor aNewEditor(&aLocMesh);
2462 SMESH::ListOfGroups_var aListOfGroups;
2464 ::SMESH_MeshEditor::ElemFeatures elemType;
2465 std::vector<const SMDS_MeshNode*> aNodesArray;
2467 // loop on sub-meshes
2468 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++)
2470 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2471 SMESH::SMESH_Mesh_var anInitMesh = theMeshesArray[i]->GetMesh();
2472 if ( anInitMesh->_is_nil() ) continue;
2473 SMESH_Mesh_i* anInitImpl = SMESH::DownCast<SMESH_Mesh_i*>( anInitMesh );
2474 if ( !anInitImpl ) continue;
2477 //::SMESH_Mesh& aInitLocMesh = anInitImpl->GetImpl();
2478 //SMESHDS_Mesh* anInitMeshDS = aInitLocMesh.GetMeshDS();
2480 // remember nb of elements before filling in
2481 SMESH::long_array_var prevState = aNewMesh->GetNbElementsByType();
2483 typedef std::map<const SMDS_MeshElement*, const SMDS_MeshElement*, TIDCompare > TEEMap;
2484 TEEMap elemsMap, nodesMap;
2486 // loop on elements of a sub-mesh
2487 SMDS_ElemIteratorPtr itElems = anInitImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2488 const SMDS_MeshElement* anElem;
2489 const SMDS_MeshElement* aNewElem;
2490 const SMDS_MeshNode* aNode;
2491 const SMDS_MeshNode* aNewNode;
2494 while ( itElems->more() )
2496 anElem = itElems->next();
2497 anElemNbNodes = anElem->NbNodes();
2498 aNodesArray.resize( anElemNbNodes );
2500 // loop on nodes of an element
2501 SMDS_ElemIteratorPtr itNodes = anElem->nodesIterator();
2502 for ( int k = 0; itNodes->more(); k++)
2504 aNode = static_cast<const SMDS_MeshNode*>( itNodes->next() );
2505 TEEMap::iterator n2nnIt = nodesMap.find( aNode );
2506 if ( n2nnIt == nodesMap.end() )
2508 aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2509 nodesMap.insert( make_pair( aNode, aNewNode ));
2513 aNewNode = static_cast<const SMDS_MeshNode*>( n2nnIt->second );
2515 aNodesArray[k] = aNewNode;
2518 // creates a corresponding element on existent nodes in new mesh
2519 if ( anElem->GetType() == SMDSAbs_Node )
2523 aNewEditor.AddElement( aNodesArray, elemType.Init( anElem, /*basicOnly=*/false ));
2526 elemsMap.insert( make_pair( anElem, aNewElem ));
2530 aNewEditor.ClearLastCreated(); // forget the history
2533 // create groups of just added elements
2534 SMESH::SMESH_Group_var aNewGroup;
2535 SMESH::ElementType aGroupType;
2536 if ( theCommonGroups )
2538 SMESH::long_array_var curState = aNewMesh->GetNbElementsByType();
2540 for( aGroupType = SMESH::NODE;
2541 aGroupType < SMESH::NB_ELEMENT_TYPES;
2542 aGroupType = (SMESH::ElementType)( aGroupType + 1 ))
2544 if ( curState[ aGroupType ] <= prevState[ aGroupType ])
2547 // make a group name
2548 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2549 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2550 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2551 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2553 string groupName = "Gr";
2554 SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( theMeshesArray[i] );
2556 CORBA::String_var name = aMeshSObj->GetName();
2560 groupName += typeNames[ aGroupType ];
2562 // make and fill a group
2563 TEEMap & e2neMap = ( aGroupType == SMESH::NODE ) ? nodesMap : elemsMap;
2564 aNewGroup = aNewImpl->CreateGroup( aGroupType, groupName.c_str() );
2565 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( aNewGroup ))
2567 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2569 TEEMap::iterator e2neIt = e2neMap.begin();
2570 for ( ; e2neIt != e2neMap.end(); ++e2neIt )
2572 aNewElem = e2neIt->second;
2573 if ( aNewElem->GetType() == grpDS->GetType() )
2575 grpDS->Add( aNewElem );
2577 if ( prevState[ aGroupType ]++ >= curState[ aGroupType ] )
2583 aListOfNewGroups.clear();
2584 aListOfNewGroups.push_back(aNewGroup);
2585 aGroupsMap.insert(make_pair( make_pair(groupName, aGroupType), aListOfNewGroups ));
2589 if ( SMESH_Mesh_i* anSrcImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2591 // copy orphan nodes
2592 if ( anSrcImpl->NbNodes() > (int)nodesMap.size() )
2594 SMDS_ElemIteratorPtr itNodes = anInitImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2595 while ( itNodes->more() )
2597 const SMDS_MeshNode* aNode = static_cast< const SMDS_MeshNode* >( itNodes->next() );
2598 if ( aNode->NbInverseElements() == 0 )
2600 aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2601 nodesMap.insert( make_pair( aNode, aNewNode ));
2608 SMESH::SMESH_GroupBase_ptr aGroup;
2609 CORBA::String_var aGroupName;
2610 SMESH::long_array_var anNewIDs = new SMESH::long_array();
2612 // loop on groups of a source mesh
2613 aListOfGroups = anSrcImpl->GetGroups();
2614 for ( CORBA::ULong iG = 0; iG < aListOfGroups->length(); iG++ )
2616 aGroup = aListOfGroups[iG];
2617 aGroupType = aGroup->GetType();
2618 aGroupName = aGroup->GetName();
2619 string aName = aGroupName.in();
2621 // convert a list of IDs
2622 anNewIDs->length( aGroup->Size() );
2623 TEEMap & e2neMap = ( aGroupType == SMESH::NODE ) ? nodesMap : elemsMap;
2624 SMDS_ElemIteratorPtr itGrElems = anSrcImpl->GetElements( aGroup, SMESH::ALL );
2626 while ( itGrElems->more() )
2628 anElem = itGrElems->next();
2629 TEEMap::iterator e2neIt = e2neMap.find( anElem );
2630 if ( e2neIt != e2neMap.end() )
2631 anNewIDs[ iElem++ ] = e2neIt->second->GetID();
2633 anNewIDs->length( iElem );
2635 // check a current group name and type don't have identical ones in final mesh
2636 aListOfNewGroups.clear();
2637 TGroupsMap::iterator anIter = aGroupsMap.find( make_pair( aName, aGroupType ));
2638 if ( anIter == aGroupsMap.end() ) {
2639 // add a new group in the mesh
2640 aNewGroup = aNewImpl->CreateGroup( aGroupType, aGroupName.in() );
2641 // add elements into new group
2642 aNewGroup->Add( anNewIDs );
2644 aListOfNewGroups.push_back(aNewGroup);
2645 aGroupsMap.insert(make_pair( make_pair(aName, aGroupType), aListOfNewGroups ));
2648 else if ( theUniteIdenticalGroups ) {
2649 // unite identical groups
2650 TListOfNewGroups& aNewGroups = anIter->second;
2651 aNewGroups.front()->Add( anNewIDs );
2655 // rename identical groups
2656 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName.in());
2657 aNewGroup->Add( anNewIDs );
2659 TListOfNewGroups& aNewGroups = anIter->second;
2660 string aNewGroupName;
2661 if (aNewGroups.size() == 1) {
2662 aNewGroupName = aName + "_1";
2663 aNewGroups.front()->SetName(aNewGroupName.c_str());
2665 char aGroupNum[128];
2666 sprintf(aGroupNum, "%u", (unsigned int)aNewGroups.size()+1);
2667 aNewGroupName = aName + "_" + string(aGroupNum);
2668 aNewGroup->SetName(aNewGroupName.c_str());
2669 aNewGroups.push_back(aNewGroup);
2672 } // if an IDSource is a mesh
2675 if (theMergeNodesAndElements) // merge nodes
2677 TIDSortedNodeSet aMeshNodes; // no input nodes
2678 SMESH_MeshEditor::TListOfListOfNodes aGroupsOfNodes;
2679 aNewEditor.FindCoincidentNodes( aMeshNodes, theMergeTolerance, aGroupsOfNodes,
2680 /*SeparateCornersAndMedium=*/ false );
2681 aNewEditor.MergeNodes( aGroupsOfNodes );
2683 aNewEditor.MergeEqualElements();
2686 // Update Python script
2687 aPythonDump << aNewMesh << " = " << this << "."
2688 << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" )
2690 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++) {
2691 if (i > 0) aPythonDump << ", ";
2692 aPythonDump << theMeshesArray[i];
2694 aPythonDump << "], ";
2695 aPythonDump << theUniteIdenticalGroups << ", "
2696 << theMergeNodesAndElements << ", "
2697 << TVar( theMergeTolerance ) << ")";
2699 delete pPythonDump; // enable python dump from GetGroups()
2701 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2702 if ( !aNewMesh->_is_nil() )
2704 SMESH::ListOfGroups_var groups = aNewMesh->GetGroups();
2707 // IPAL21468 Change icon of compound because it need not be computed.
2708 SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( aNewMesh );
2709 SetPixMap( aMeshSObj, "ICON_SMESH_TREE_MESH" );
2712 aNewMeshDS->Modified();
2714 return aNewMesh._retn();
2717 //================================================================================
2719 * \brief Create a mesh by copying a part of another mesh
2720 * \param meshPart - a part of mesh to copy
2721 * \param toCopyGroups - to create in the new mesh groups
2722 * the copied elements belongs to
2723 * \param toKeepIDs - to preserve IDs of the copied elements or not
2724 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2726 //================================================================================
2728 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2729 const char* meshName,
2730 CORBA::Boolean toCopyGroups,
2731 CORBA::Boolean toKeepIDs)
2733 Unexpect aCatch(SALOME_SalomeException);
2735 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2737 // 1. Get source mesh
2739 if ( CORBA::is_nil( meshPart ))
2740 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2742 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2743 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2745 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2747 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2749 // 2. Make a new mesh
2751 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2752 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2754 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2755 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2756 if ( !meshSO->_is_nil() )
2758 SetName( meshSO, meshName, "Mesh" );
2759 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2761 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2762 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2763 ::SMESH_MeshEditor::ElemFeatures elemType;
2765 // 3. Get elements to copy
2767 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2768 TIDSortedElemSet srcElems;
2769 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2770 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2773 srcElemIt = srcMeshDS->elementsIterator();
2774 srcNodeIt = srcMeshDS->nodesIterator();
2778 SMESH::long_array_var ids = meshPart->GetIDs();
2779 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2781 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2782 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2783 srcElems.insert( elem );
2787 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2788 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2789 srcElems.insert( elem );
2791 if ( srcElems.empty() )
2792 return newMesh._retn();
2794 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2795 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2800 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2801 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2802 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2804 const SMDS_MeshNode *nSrc, *nTgt;
2805 vector< const SMDS_MeshNode* > nodes;
2806 while ( srcElemIt->more() )
2808 const SMDS_MeshElement * elem = srcElemIt->next();
2810 nodes.resize( elem->NbNodes());
2811 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2813 for ( iN = 0; nIt->more(); ++iN )
2815 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2816 nTgt = newMeshDS->FindNode( nSrc->GetID());
2818 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2823 for ( iN = 0; nIt->more(); ++iN )
2825 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2826 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2828 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2829 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2833 if ( elem->GetType() != SMDSAbs_Node )
2835 elemType.Init( elem, /*basicOnly=*/false );
2836 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2838 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2839 if ( toCopyGroups && !toKeepIDs )
2840 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2842 } // while ( srcElemIt->more() )
2844 // 4(b). Copy free nodes
2846 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2848 while ( srcNodeIt->more() )
2850 nSrc = srcNodeIt->next();
2851 if ( nSrc->NbInverseElements() == 0 )
2854 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2856 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2863 int nbNewGroups = 0;
2866 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2867 while ( gIt->more() )
2869 SMESH_Group* group = gIt->next();
2870 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2872 // Check group type. We copy nodal groups containing nodes of copied element
2873 SMDSAbs_ElementType groupType = groupDS->GetType();
2874 if ( groupType != SMDSAbs_Node &&
2875 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2876 continue; // group type differs from types of meshPart
2878 // Find copied elements in the group
2879 vector< const SMDS_MeshElement* > groupElems;
2880 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2883 const SMDS_MeshElement* foundElem;
2884 if ( groupType == SMDSAbs_Node )
2886 while ( eIt->more() )
2887 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2888 groupElems.push_back( foundElem );
2892 while ( eIt->more() )
2893 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2894 groupElems.push_back( foundElem );
2899 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2900 if ( e2eMap.empty() ) continue;
2901 int minID = e2eMap.begin()->first->GetID();
2902 int maxID = e2eMap.rbegin()->first->GetID();
2903 TE2EMap::iterator e2e;
2904 while ( eIt->more() && groupElems.size() < e2eMap.size())
2906 const SMDS_MeshElement* e = eIt->next();
2907 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2908 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2909 groupElems.push_back( e2e->second );
2913 if ( !groupElems.empty() )
2915 SMESH::SMESH_Group_var newGroupObj =
2916 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2917 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2919 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2920 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2921 for ( unsigned i = 0; i < groupElems.size(); ++i )
2922 smdsGroup.Add( groupElems[i] );
2930 newMeshDS->Modified();
2932 *pyDump << newMesh << " = " << this
2933 << ".CopyMesh( " << meshPart << ", "
2934 << "'" << meshName << "', "
2935 << toCopyGroups << ", "
2936 << toKeepIDs << ")";
2938 delete pyDump; pyDump = 0; // allow dump in GetGroups()
2940 if ( nbNewGroups > 0 ) // dump created groups
2941 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2943 return newMesh._retn();
2946 //================================================================================
2948 * SMESH_Gen_i::GetMEDVersion
2950 * Get MED version of the file by its name
2952 //================================================================================
2953 CORBA::Boolean SMESH_Gen_i::GetMEDVersion(const char* theFileName,
2954 SMESH::MED_VERSION& theVersion)
2956 theVersion = SMESH::MED_V2_1;
2957 MED::EVersion aVersion = MED::GetVersionId( theFileName );
2958 switch( aVersion ) {
2959 case MED::eV2_1 : theVersion = SMESH::MED_V2_1; return true;
2960 case MED::eV2_2 : theVersion = SMESH::MED_V2_2; return true;
2961 case MED::eVUnknown : return false;
2966 //================================================================================
2968 * SMESH_Gen_i::GetMeshNames
2970 * Get names of meshes defined in file with the specified name
2972 //================================================================================
2973 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
2975 SMESH::string_array_var aResult = new SMESH::string_array();
2976 MED::PWrapper aMed = MED::CrWrapper( theFileName );
2978 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
2980 aResult->length( aNbMeshes );
2981 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
2982 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
2983 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
2986 return aResult._retn();
2989 //=============================================================================
2993 * Save SMESH module's data
2995 //=============================================================================
2996 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
3000 if (!myStudyContext)
3003 // Store study contents as a set of python commands
3006 SALOMEDS::Study_var aStudy = getStudyServant();
3008 // Declare a byte stream
3009 SALOMEDS::TMPFile_var aStreamFile;
3011 // Obtain a temporary dir
3012 TCollection_AsciiString tmpDir =
3013 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
3015 // Create a sequence of files processed
3016 SALOMEDS_Tool::ListOfFiles aFileSeq;
3017 aFileSeq.reserve( NUM_TMP_FILES );
3019 TCollection_AsciiString aStudyName( "" );
3021 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( aStudy->URL() ).c_str() );
3023 // Set names of temporary files
3024 TCollection_AsciiString filename =
3025 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
3026 TCollection_AsciiString meshfile =
3027 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
3028 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
3029 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
3030 filename = tmpDir + filename;
3031 meshfile = tmpDir + meshfile;
3034 HDFdataset* aDataset;
3035 HDFgroup* aTopGroup;
3037 HDFgroup* aSubGroup;
3038 HDFgroup* aSubSubGroup;
3039 hdf_size aSize[ 1 ];
3042 //Remove the files if they exist: BugID: 11225
3043 #ifndef WIN32 /* unix functionality */
3044 TCollection_AsciiString cmd("rm -f \"");
3046 TCollection_AsciiString cmd("del /F \"");
3053 system(cmd.ToCString());
3055 // MED writer to be used by storage process
3056 DriverMED_W_SMESHDS_Mesh myWriter;
3057 myWriter.SetFile( meshfile.ToCString() );
3060 // SetStoreName() to groups before storing hypotheses to let them refer to
3061 // groups using "store name", which is "Group <group_persistent_id>"
3063 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
3064 for ( ; itBig->More(); itBig->Next() ) {
3065 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3066 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3067 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3068 if ( !CORBA::is_nil( anObject ) ) {
3069 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3070 if ( !myMesh->_is_nil() ) {
3071 myMesh->Load(); // load from study file if not yet done
3072 TPythonDump pd; // not to dump GetGroups()
3073 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
3074 pd << ""; // to avoid optimizing pd out
3075 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
3077 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
3080 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
3081 int anId = myStudyContext->findId( string( objStr.in() ) );
3083 sprintf( grpName, "Group %d", anId );
3084 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
3085 aGrpBaseDS->SetStoreName( grpName );
3095 // ---> create HDF file
3096 aFile = new HDFfile( (char*) filename.ToCString() );
3097 aFile->CreateOnDisk();
3099 // --> iterator for top-level objects
3100 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
3101 for ( ; itBig->More(); itBig->Next() ) {
3102 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3104 // --> hypotheses root branch (only one for the study)
3105 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
3106 // create hypotheses root HDF group
3107 aTopGroup = new HDFgroup( "Hypotheses", aFile );
3108 aTopGroup->CreateOnDisk();
3110 // iterator for all hypotheses
3111 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
3112 for ( ; it->More(); it->Next() ) {
3113 SALOMEDS::SObject_wrap mySObject = it->Value();
3114 CORBA::Object_var anObject = SObjectToObject( mySObject );
3115 if ( !CORBA::is_nil( anObject ) ) {
3116 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3117 if ( !myHyp->_is_nil() ) {
3118 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3120 string hypname = string( myHyp->GetName() );
3121 string libname = string( myHyp->GetLibName() );
3123 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3124 // WIN32 and ".so" for X-system) must be deleted
3125 int libname_len = libname.length();
3127 if( libname_len > 4 )
3128 libname.resize( libname_len - 4 );
3130 // PAL17753 (Regression: missing hypothesis in restored study)
3131 // "lib" also should be removed from the beginning
3132 //if( libname_len > 3 )
3133 //libname.resize( libname_len - 3 );
3134 if( libname_len > 6 )
3135 libname = libname.substr( 3, libname_len - 3 - 3 );
3137 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3138 int id = myStudyContext->findId( string( objStr.in() ) );
3139 string hypdata = string( myImpl->SaveTo() );
3141 // for each hypothesis create HDF group basing on its id
3142 char hypGrpName[30];
3143 sprintf( hypGrpName, "Hypothesis %d", id );
3144 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3145 aGroup->CreateOnDisk();
3146 // --> type name of hypothesis
3147 aSize[ 0 ] = hypname.length() + 1;
3148 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3149 aDataset->CreateOnDisk();
3150 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3151 aDataset->CloseOnDisk();
3152 // --> server plugin library name of hypothesis
3153 aSize[ 0 ] = libname.length() + 1;
3154 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3155 aDataset->CreateOnDisk();
3156 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3157 aDataset->CloseOnDisk();
3158 // --> persistent data of hypothesis
3159 aSize[ 0 ] = hypdata.length() + 1;
3160 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3161 aDataset->CreateOnDisk();
3162 aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
3163 aDataset->CloseOnDisk();
3164 // close hypothesis HDF group
3165 aGroup->CloseOnDisk();
3170 // close hypotheses root HDF group
3171 aTopGroup->CloseOnDisk();
3173 // --> algorithms root branch (only one for the study)
3174 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
3175 // create algorithms root HDF group
3176 aTopGroup = new HDFgroup( "Algorithms", aFile );
3177 aTopGroup->CreateOnDisk();
3179 // iterator for all algorithms
3180 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
3181 for ( ; it->More(); it->Next() ) {
3182 SALOMEDS::SObject_wrap mySObject = it->Value();
3183 CORBA::Object_var anObject = SObjectToObject( mySObject );
3184 if ( !CORBA::is_nil( anObject ) ) {
3185 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3186 if ( !myHyp->_is_nil() ) {
3187 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3189 string hypname = string( myHyp->GetName() );
3190 string libname = string( myHyp->GetLibName() );
3192 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3193 // WIN32 and ".so" for X-system) must be deleted
3194 int libname_len = libname.length();
3196 if( libname_len > 4 )
3197 libname.resize( libname_len - 4 );
3199 // PAL17753 (Regression: missing hypothesis in restored study)
3200 // "lib" also should be removed from the beginning
3201 //if( libname_len > 3 )
3202 //libname.resize( libname_len - 3 );
3203 if( libname_len > 6 )
3204 libname = libname.substr( 3, libname_len - 3 - 3 );
3206 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3207 int id = myStudyContext->findId( string( objStr.in() ) );
3208 string hypdata = string( myImpl->SaveTo() );
3210 // for each algorithm create HDF group basing on its id
3211 char hypGrpName[30];
3212 sprintf( hypGrpName, "Algorithm %d", id );
3213 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3214 aGroup->CreateOnDisk();
3215 // --> type name of algorithm
3216 aSize[0] = hypname.length() + 1;
3217 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3218 aDataset->CreateOnDisk();
3219 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3220 aDataset->CloseOnDisk();
3221 // --> server plugin library name of hypothesis
3222 aSize[0] = libname.length() + 1;
3223 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3224 aDataset->CreateOnDisk();
3225 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3226 aDataset->CloseOnDisk();
3227 // --> persistent data of algorithm
3228 aSize[0] = hypdata.length() + 1;
3229 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3230 aDataset->CreateOnDisk();
3231 aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
3232 aDataset->CloseOnDisk();
3233 // close algorithm HDF group
3234 aGroup->CloseOnDisk();
3239 // close algorithms root HDF group
3240 aTopGroup->CloseOnDisk();
3242 // --> mesh objects roots branches
3243 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3244 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3245 if ( !CORBA::is_nil( anObject ) ) {
3246 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3247 if ( !myMesh->_is_nil() ) {
3248 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
3250 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3251 int id = myStudyContext->findId( string( objStr.in() ) );
3252 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
3253 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
3254 bool hasShape = myLocMesh.HasShapeToMesh();
3256 // for each mesh open the HDF group basing on its id
3257 char meshGrpName[ 30 ];
3258 sprintf( meshGrpName, "Mesh %d", id );
3259 aTopGroup = new HDFgroup( meshGrpName, aFile );
3260 aTopGroup->CreateOnDisk();
3262 // --> put dataset to hdf file which is a flag that mesh has data
3263 string strHasData = "0";
3264 // check if the mesh is not empty
3265 if ( mySMESHDSMesh->NbNodes() > 0 ) {
3266 // write mesh data to med file
3267 myWriter.SetMesh( mySMESHDSMesh );
3268 myWriter.SetMeshId( id );
3271 aSize[ 0 ] = strHasData.length() + 1;
3272 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
3273 aDataset->CreateOnDisk();
3274 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
3275 aDataset->CloseOnDisk();
3278 // for each mesh open the HDF group basing on its auto color parameter
3279 char meshAutoColorName[ 30 ];
3280 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
3282 anAutoColor[0] = myImpl->GetAutoColor();
3284 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
3285 aDataset->CreateOnDisk();
3286 aDataset->WriteOnDisk( anAutoColor );
3287 aDataset->CloseOnDisk();
3289 // issue 0020693. Store _isModified flag
3290 int isModified = myLocMesh.GetIsModified();
3292 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
3293 aDataset->CreateOnDisk();
3294 aDataset->WriteOnDisk( &isModified );
3295 aDataset->CloseOnDisk();
3297 // issue 20918. Store Persistent Id of SMESHDS_Mesh
3298 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
3300 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
3301 aDataset->CreateOnDisk();
3302 aDataset->WriteOnDisk( &meshPersistentId );
3303 aDataset->CloseOnDisk();
3305 // write reference on a shape if exists
3306 SALOMEDS::SObject_wrap myRef;
3307 bool shapeRefFound = false;
3308 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
3310 SALOMEDS::SObject_wrap myShape;
3311 bool ok = myRef->ReferencedObject( myShape.inout() );
3313 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
3314 string myRefOnObject = myShape->GetID();
3315 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
3316 aSize[ 0 ] = myRefOnObject.length() + 1;
3317 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
3318 aDataset->CreateOnDisk();
3319 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3320 aDataset->CloseOnDisk();
3325 // write applied hypotheses if exist
3326 SALOMEDS::SObject_wrap myHypBranch;
3327 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
3328 if ( found && !shapeRefFound && hasShape) { // remove applied hyps
3329 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
3331 if ( found && (shapeRefFound || !hasShape) ) {
3332 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
3333 aGroup->CreateOnDisk();
3335 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
3337 for ( ; it->More(); it->Next() ) {
3338 SALOMEDS::SObject_wrap mySObject = it->Value();
3339 SALOMEDS::SObject_wrap myRefOnHyp;
3340 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
3342 // san - it is impossible to recover applied hypotheses
3343 // using their entries within Load() method,
3344 // for there are no AttributeIORs in the study when Load() is working.
3345 // Hence, it is better to store persistent IDs of hypotheses as references to them
3347 //string myRefOnObject = myRefOnHyp->GetID();
3348 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3349 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3350 int id = myStudyContext->findId( string( objStr.in() ) );
3351 //if ( myRefOnObject.length() > 0 ) {
3352 //aSize[ 0 ] = myRefOnObject.length() + 1;
3353 char hypName[ 30 ], hypId[ 30 ];
3354 sprintf( hypName, "Hyp %d", ++hypNb );
3355 sprintf( hypId, "%d", id );
3356 aSize[ 0 ] = strlen( hypId ) + 1;
3357 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
3358 aDataset->CreateOnDisk();
3359 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3360 aDataset->WriteOnDisk( hypId );
3361 aDataset->CloseOnDisk();
3365 aGroup->CloseOnDisk();
3368 // write applied algorithms if exist
3369 SALOMEDS::SObject_wrap myAlgoBranch;
3370 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3371 myAlgoBranch.inout() );
3372 if ( found && !shapeRefFound && hasShape) { // remove applied algos
3373 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
3375 if ( found && (shapeRefFound || !hasShape)) {
3376 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3377 aGroup->CreateOnDisk();
3379 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
3381 for ( ; it->More(); it->Next() ) {
3382 SALOMEDS::SObject_wrap mySObject = it->Value();
3383 SALOMEDS::SObject_wrap myRefOnAlgo;
3384 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
3386 // san - it is impossible to recover applied algorithms
3387 // using their entries within Load() method,
3388 // for there are no AttributeIORs in the study when Load() is working.
3389 // Hence, it is better to store persistent IDs of algorithms as references to them
3391 //string myRefOnObject = myRefOnAlgo->GetID();
3392 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3393 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3394 int id = myStudyContext->findId( string( objStr.in() ) );
3395 //if ( myRefOnObject.length() > 0 ) {
3396 //aSize[ 0 ] = myRefOnObject.length() + 1;
3397 char algoName[ 30 ], algoId[ 30 ];
3398 sprintf( algoName, "Algo %d", ++algoNb );
3399 sprintf( algoId, "%d", id );
3400 aSize[ 0 ] = strlen( algoId ) + 1;
3401 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
3402 aDataset->CreateOnDisk();
3403 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3404 aDataset->WriteOnDisk( algoId );
3405 aDataset->CloseOnDisk();
3409 aGroup->CloseOnDisk();
3412 // --> submesh objects sub-branches
3414 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
3415 SALOMEDS::SObject_wrap mySubmeshBranch;
3416 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
3418 if ( found ) // check if there is shape reference in submeshes
3420 bool hasShapeRef = false;
3421 SALOMEDS::ChildIterator_wrap itSM =
3422 aStudy->NewChildIterator( mySubmeshBranch );
3423 for ( ; itSM->More(); itSM->Next() ) {
3424 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
3425 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3426 mySubRef->ReferencedObject( myShape.inout() );
3427 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
3430 { // remove one submesh
3431 if ( shapeRefFound )
3432 { // unassign hypothesis
3433 SMESH::SMESH_subMesh_var mySubMesh =
3434 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
3435 if ( !mySubMesh->_is_nil() ) {
3436 int shapeID = mySubMesh->GetId();
3437 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
3438 const list<const SMESHDS_Hypothesis*>& hypList =
3439 mySMESHDSMesh->GetHypothesis( S );
3440 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
3441 while ( hyp != hypList.end() ) {
3442 int hypID = (*hyp++)->GetID(); // goto next hyp here because
3443 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
3447 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
3449 } // loop on submeshes of a type
3450 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
3451 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
3454 } // end check if there is shape reference in submeshes
3456 char name_meshgroup[ 30 ];
3457 if ( i == GetSubMeshOnVertexTag() )
3458 strcpy( name_meshgroup, "SubMeshes On Vertex" );
3459 else if ( i == GetSubMeshOnEdgeTag() )
3460 strcpy( name_meshgroup, "SubMeshes On Edge" );
3461 else if ( i == GetSubMeshOnWireTag() )
3462 strcpy( name_meshgroup, "SubMeshes On Wire" );
3463 else if ( i == GetSubMeshOnFaceTag() )
3464 strcpy( name_meshgroup, "SubMeshes On Face" );
3465 else if ( i == GetSubMeshOnShellTag() )
3466 strcpy( name_meshgroup, "SubMeshes On Shell" );
3467 else if ( i == GetSubMeshOnSolidTag() )
3468 strcpy( name_meshgroup, "SubMeshes On Solid" );
3469 else if ( i == GetSubMeshOnCompoundTag() )
3470 strcpy( name_meshgroup, "SubMeshes On Compound" );
3472 // for each type of submeshes create container HDF group
3473 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
3474 aGroup->CreateOnDisk();
3476 // iterator for all submeshes of given type
3477 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
3478 for ( ; itSM->More(); itSM->Next() ) {
3479 SALOMEDS::SObject_wrap mySObject = itSM->Value();
3480 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
3481 if ( !CORBA::is_nil( anSubObject ))
3483 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
3484 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
3485 int subid = myStudyContext->findId( string( objStr.in() ) );
3487 // for each mesh open the HDF group basing on its id
3488 char submeshGrpName[ 30 ];
3489 sprintf( submeshGrpName, "SubMesh %d", subid );
3490 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
3491 aSubGroup->CreateOnDisk();
3493 // write reference on a shape, already checked if it exists
3494 SALOMEDS::SObject_wrap mySubRef, myShape;
3495 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3496 mySubRef->ReferencedObject( myShape.inout() );
3497 string myRefOnObject = myShape->GetID();
3498 if ( myRefOnObject.length() > 0 ) {
3499 aSize[ 0 ] = myRefOnObject.length() + 1;
3500 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
3501 aDataset->CreateOnDisk();
3502 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3503 aDataset->CloseOnDisk();
3506 // write applied hypotheses if exist
3507 SALOMEDS::SObject_wrap mySubHypBranch;
3508 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
3509 mySubHypBranch.inout() );
3511 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
3512 aSubSubGroup->CreateOnDisk();
3514 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
3516 for ( ; it->More(); it->Next() ) {
3517 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3518 SALOMEDS::SObject_wrap myRefOnHyp;
3519 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
3521 //string myRefOnObject = myRefOnHyp->GetID();
3522 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3523 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3524 int id = myStudyContext->findId( string( objStr.in() ) );
3525 //if ( myRefOnObject.length() > 0 ) {
3526 //aSize[ 0 ] = myRefOnObject.length() + 1;
3527 char hypName[ 30 ], hypId[ 30 ];
3528 sprintf( hypName, "Hyp %d", ++hypNb );
3529 sprintf( hypId, "%d", id );
3530 aSize[ 0 ] = strlen( hypId ) + 1;
3531 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
3532 aDataset->CreateOnDisk();
3533 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3534 aDataset->WriteOnDisk( hypId );
3535 aDataset->CloseOnDisk();
3539 aSubSubGroup->CloseOnDisk();
3542 // write applied algorithms if exist
3543 SALOMEDS::SObject_wrap mySubAlgoBranch;
3544 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3545 mySubAlgoBranch.inout() );
3547 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3548 aSubSubGroup->CreateOnDisk();
3550 SALOMEDS::ChildIterator_wrap it =
3551 aStudy->NewChildIterator( mySubAlgoBranch );
3553 for ( ; it->More(); it->Next() ) {
3554 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3555 SALOMEDS::SObject_wrap myRefOnAlgo;
3556 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
3558 //string myRefOnObject = myRefOnAlgo->GetID();
3559 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3560 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3561 int id = myStudyContext->findId( string( objStr.in() ) );
3562 //if ( myRefOnObject.length() > 0 ) {
3563 //aSize[ 0 ] = myRefOnObject.length() + 1;
3564 char algoName[ 30 ], algoId[ 30 ];
3565 sprintf( algoName, "Algo %d", ++algoNb );
3566 sprintf( algoId, "%d", id );
3567 aSize[ 0 ] = strlen( algoId ) + 1;
3568 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
3569 aDataset->CreateOnDisk();
3570 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3571 aDataset->WriteOnDisk( algoId );
3572 aDataset->CloseOnDisk();
3576 aSubSubGroup->CloseOnDisk();
3578 // close submesh HDF group
3579 aSubGroup->CloseOnDisk();
3582 // close container of submeshes by type HDF group
3583 aGroup->CloseOnDisk();
3586 // All sub-meshes will be stored in MED file
3587 // .. will NOT (PAL 12992)
3588 //if ( shapeRefFound )
3589 //myWriter.AddAllSubMeshes();
3591 // store submesh order if any
3592 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
3593 if ( theOrderIds.size() ) {
3594 char order_list[ 30 ];
3595 strcpy( order_list, "Mesh Order" );
3596 // count number of submesh ids
3598 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
3599 for ( ; idIt != theOrderIds.end(); idIt++ )
3600 nbIDs += (*idIt).size();
3601 // number of values = number of IDs +
3602 // number of lists (for separators) - 1
3603 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
3604 idIt = theOrderIds.begin();
3605 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
3606 const TListOfInt& idList = *idIt;
3607 if (idIt != theOrderIds.begin()) // not first list
3608 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
3609 // dump submesh ids from current list
3610 TListOfInt::const_iterator id_smId = idList.begin();
3611 for( ; id_smId != idList.end(); id_smId++ )
3612 smIDs[ i++ ] = *id_smId;
3615 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
3617 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
3618 aDataset->CreateOnDisk();
3619 aDataset->WriteOnDisk( smIDs );
3620 aDataset->CloseOnDisk();
3625 // groups root sub-branch
3626 SALOMEDS::SObject_wrap myGroupsBranch;
3627 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
3628 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
3630 char name_group[ 30 ];
3631 if ( i == GetNodeGroupsTag() )
3632 strcpy( name_group, "Groups of Nodes" );
3633 else if ( i == GetEdgeGroupsTag() )
3634 strcpy( name_group, "Groups of Edges" );
3635 else if ( i == GetFaceGroupsTag() )
3636 strcpy( name_group, "Groups of Faces" );
3637 else if ( i == GetVolumeGroupsTag() )
3638 strcpy( name_group, "Groups of Volumes" );
3639 else if ( i == Get0DElementsGroupsTag() )
3640 strcpy( name_group, "Groups of 0D Elements" );
3641 else if ( i == GetBallElementsGroupsTag() )
3642 strcpy( name_group, "Groups of Balls" );
3644 aGroup = new HDFgroup( name_group, aTopGroup );
3645 aGroup->CreateOnDisk();
3647 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
3648 for ( ; it->More(); it->Next() ) {
3649 SALOMEDS::SObject_wrap mySObject = it->Value();
3650 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
3651 if ( !CORBA::is_nil( aSubObject ) ) {
3652 SMESH_GroupBase_i* myGroupImpl =
3653 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
3656 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
3660 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
3661 int anId = myStudyContext->findId( string( objStr.in() ) );
3663 // For each group, create a dataset named "Group <group_persistent_id>"
3664 // and store the group's user name into it
3665 const char* grpName = aGrpBaseDS->GetStoreName();
3666 char* aUserName = myGroupImpl->GetName();
3667 aSize[ 0 ] = strlen( aUserName ) + 1;
3669 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
3670 aDataset->CreateOnDisk();
3671 aDataset->WriteOnDisk( aUserName );
3672 aDataset->CloseOnDisk();
3675 // For each group, create a dataset named "Group <group_persistent_id> Color"
3676 // and store the group's color into it
3677 char grpColorName[ 30 ];
3678 sprintf( grpColorName, "ColorGroup %d", anId );
3679 SALOMEDS::Color aColor = myGroupImpl->GetColor();
3681 anRGB[ 0 ] = aColor.R;
3682 anRGB[ 1 ] = aColor.G;
3683 anRGB[ 2 ] = aColor.B;
3685 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
3686 aDataset->CreateOnDisk();
3687 aDataset->WriteOnDisk( anRGB );
3688 aDataset->CloseOnDisk();
3690 // Pass SMESHDS_Group to MED writer
3691 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
3693 myWriter.AddGroup( aGrpDS );
3695 // write reference on a shape if exists
3696 SMESHDS_GroupOnGeom* aGeomGrp =
3697 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
3699 SALOMEDS::SObject_wrap mySubRef, myShape;
3700 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
3701 mySubRef->ReferencedObject( myShape.inout() ) &&
3702 !CORBA::is_nil( myShape->GetObject() ))
3704 string myRefOnObject = myShape->GetID();
3705 if ( myRefOnObject.length() > 0 ) {
3706 char aRefName[ 30 ];
3707 sprintf( aRefName, "Ref on shape %d", anId);
3708 aSize[ 0 ] = myRefOnObject.length() + 1;
3709 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
3710 aDataset->CreateOnDisk();
3711 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3712 aDataset->CloseOnDisk();
3715 else // shape ref is invalid:
3717 // save a group on geometry as ordinary group
3718 myWriter.AddGroup( aGeomGrp );
3721 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
3722 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
3724 std::string str = aFilterGrp_i->FilterToString();
3725 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
3726 aSize[ 0 ] = str.length() + 1;
3727 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
3728 aDataset->CreateOnDisk();
3729 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
3730 aDataset->CloseOnDisk();
3734 aGroup->CloseOnDisk();
3738 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
3740 // Flush current mesh information into MED file
3743 // save info on nb of elements
3744 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
3746 // maybe a shape was deleted in the study
3747 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
3748 TopoDS_Shape nullShape;
3749 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
3752 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
3757 aGroup = new HDFgroup( "Submeshes", aTopGroup );
3758 aGroup->CreateOnDisk();
3760 // each element belongs to one or none submesh,
3761 // so for each node/element, we store a submesh ID
3763 // Store submesh IDs
3764 for ( int isNode = 0; isNode < 2; ++isNode )
3766 SMDS_ElemIteratorPtr eIt =
3767 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
3768 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
3771 std::vector<int> smIDs; smIDs.reserve( nbElems );
3772 while ( eIt->more() )
3773 if ( const SMDS_MeshElement* e = eIt->next())
3774 smIDs.push_back( e->getshapeId() );
3776 aSize[ 0 ] = nbElems;
3777 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3778 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3779 aDataset->CreateOnDisk();
3780 aDataset->WriteOnDisk( & smIDs[0] );
3781 aDataset->CloseOnDisk();
3784 aGroup->CloseOnDisk();
3786 // Store node positions on sub-shapes (SMDS_Position):
3787 // ----------------------------------------------------
3789 aGroup = new HDFgroup( "Node Positions", aTopGroup );
3790 aGroup->CreateOnDisk();
3792 // in aGroup, create 5 datasets to contain:
3793 // "Nodes on Edges" - ID of node on edge
3794 // "Edge positions" - U parameter on node on edge
3795 // "Nodes on Faces" - ID of node on face
3796 // "Face U positions" - U parameter of node on face
3797 // "Face V positions" - V parameter of node on face
3799 // Find out nb of nodes on edges and faces
3800 // Collect corresponing sub-meshes
3801 int nbEdgeNodes = 0, nbFaceNodes = 0;
3802 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
3803 // loop on SMESHDS_SubMesh'es
3804 while ( smIt->more() )
3806 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
3807 if ( aSubMesh->IsComplexSubmesh() )
3808 continue; // submesh containing other submeshs
3809 int nbNodes = aSubMesh->NbNodes();
3810 if ( nbNodes == 0 ) continue;
3812 int aShapeID = aSubMesh->GetID();
3813 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
3815 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
3816 // write only SMDS_FacePosition and SMDS_EdgePosition
3817 switch ( aShapeType ) {
3819 nbFaceNodes += nbNodes;
3820 aFaceSM.push_back( aSubMesh );
3823 nbEdgeNodes += nbNodes;
3824 aEdgeSM.push_back( aSubMesh );
3830 // Treat positions on edges or faces
3831 for ( int onFace = 0; onFace < 2; onFace++ )
3833 // Create arrays to store in datasets
3834 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
3835 if (!nbNodes) continue;
3836 int* aNodeIDs = new int [ nbNodes ];
3837 double* aUPos = new double [ nbNodes ];
3838 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
3841 // loop on sub-meshes
3842 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
3843 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
3844 for ( ; itSM != pListSM->end(); itSM++ )
3846 SMESHDS_SubMesh* aSubMesh = (*itSM);
3848 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
3849 // loop on nodes in aSubMesh
3850 while ( itNode->more() )
3853 const SMDS_MeshNode* node = itNode->next();
3854 aNodeIDs [ iNode ] = node->GetID();
3857 const SMDS_PositionPtr pos = node->GetPosition();
3858 if ( onFace ) { // on FACE
3859 const SMDS_FacePosition* fPos =
3860 dynamic_cast<const SMDS_FacePosition*>( pos );
3862 aUPos[ iNode ] = fPos->GetUParameter();
3863 aVPos[ iNode ] = fPos->GetVParameter();
3870 const SMDS_EdgePosition* ePos =
3871 dynamic_cast<const SMDS_EdgePosition*>( pos );
3873 aUPos[ iNode ] = ePos->GetUParameter();
3879 } // loop on nodes in aSubMesh
3880 } // loop on sub-meshes
3885 aSize[ 0 ] = nbNodes;
3887 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
3888 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3889 aDataset->CreateOnDisk();
3890 aDataset->WriteOnDisk( aNodeIDs );
3891 aDataset->CloseOnDisk();
3894 aDSName = ( onFace ? "Face U positions" : "Edge positions");
3895 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
3896 aDataset->CreateOnDisk();
3897 aDataset->WriteOnDisk( aUPos );
3898 aDataset->CloseOnDisk();
3901 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
3902 aDataset->CreateOnDisk();
3903 aDataset->WriteOnDisk( aVPos );
3904 aDataset->CloseOnDisk();
3909 if ( aVPos ) delete [] aVPos;
3911 } // treat positions on edges or faces
3913 // close "Node Positions" group
3914 aGroup->CloseOnDisk();
3916 } // if ( there are submeshes in SMESHDS_Mesh )
3919 // close mesh HDF group
3920 aTopGroup->CloseOnDisk();
3928 aFile->CloseOnDisk();
3931 // Convert temporary files to stream
3932 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
3934 // Remove temporary files and directory
3936 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
3938 return aStreamFile._retn();
3941 //=============================================================================
3943 * SMESH_Gen_i::SaveASCII
3945 * Save SMESH module's data in ASCII format
3947 //=============================================================================
3949 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
3951 bool isMultiFile ) {
3952 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
3953 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
3954 return aStreamFile._retn();
3956 //after usual saving needs to encipher binary to text string
3957 //Any binary symbol will be represent as "|xx" () hexadecimal format number
3958 int size = aStreamFile.in().length();
3959 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
3960 for ( int i = 0; i < size; i++ )
3961 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
3963 buffer[size * 3] = '\0';
3965 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
3967 return anAsciiStreamFile._retn();
3970 //=============================================================================
3972 * SMESH_Gen_i::loadGeomData
3974 * Load GEOM module data
3976 //=============================================================================
3978 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
3980 if ( theCompRoot->_is_nil() )
3983 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
3984 aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
3987 //=============================================================================
3991 * Load SMESH module's data
3993 //=============================================================================
3995 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
3996 const SALOMEDS::TMPFile& theStream,
4000 if (!myStudyContext)
4002 SALOMEDS::Study_var aStudy = getStudyServant();
4003 /* if( !theComponent->_is_nil() )
4005 if( !aStudy->FindComponent( "GEOM" )->_is_nil() )
4006 loadGeomData( aStudy->FindComponent( "GEOM" ) );
4009 // Get temporary files location
4010 TCollection_AsciiString tmpDir =
4011 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
4013 // Convert the stream into sequence of files to process
4014 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
4017 TCollection_AsciiString aStudyName( "" );
4018 if ( isMultiFile ) {
4019 CORBA::String_var url = aStudy->URL();
4020 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( url.in() ).c_str();
4022 // Set names of temporary files
4023 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
4024 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
4028 HDFdataset* aDataset;
4029 HDFgroup* aTopGroup;
4031 HDFgroup* aSubGroup;
4032 HDFgroup* aSubSubGroup;
4035 // ---> open HDF file
4036 aFile = new HDFfile( (char*) filename.ToCString() );
4038 aFile->OpenOnDisk( HDF_RDONLY );
4040 catch ( HDFexception ) {
4041 INFOS( "Load(): " << filename << " not found!" );
4045 TPythonDump pd; // prevent dump during loading
4047 // DriverMED_R_SMESHDS_Mesh myReader;
4048 // myReader.SetFile( meshfile.ToCString() );
4050 // For PAL13473 ("Repetitive mesh") implementation.
4051 // New dependencies between SMESH objects are established:
4052 // now hypotheses can refer to meshes, shapes and other hypotheses.
4053 // To keep data consistent, the following order of data restoration
4055 // 1. Create hypotheses
4056 // 2. Create all meshes
4057 // 3. Load hypotheses' data
4060 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
4061 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
4062 list< SMESH::Filter_var > filters;
4064 // get total number of top-level groups
4065 int aNbGroups = aFile->nInternalObjects();
4066 if ( aNbGroups > 0 ) {
4067 // --> in first turn we should read&create hypotheses
4068 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
4069 // open hypotheses root HDF group
4070 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4071 aTopGroup->OpenOnDisk();
4073 // get number of hypotheses
4074 int aNbObjects = aTopGroup->nInternalObjects();
4075 for ( int j = 0; j < aNbObjects; j++ ) {
4076 // try to identify hypothesis
4077 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4078 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4080 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
4081 // open hypothesis group
4082 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4083 aGroup->OpenOnDisk();
4085 // --> get hypothesis id
4086 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
4091 // get number of datasets
4092 int aNbSubObjects = aGroup->nInternalObjects();
4093 for ( int k = 0; k < aNbSubObjects; k++ ) {
4095 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4096 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4097 // --> get hypothesis name
4098 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4099 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4100 aDataset->OpenOnDisk();
4101 size = aDataset->GetSize();
4102 char* hypname_str = new char[ size ];
4103 aDataset->ReadFromDisk( hypname_str );
4104 hypname = string( hypname_str );
4105 delete [] hypname_str;
4106 aDataset->CloseOnDisk();
4108 // --> get hypothesis plugin library name
4109 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4110 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4111 aDataset->OpenOnDisk();
4112 size = aDataset->GetSize();
4113 char* libname_str = new char[ size ];
4114 aDataset->ReadFromDisk( libname_str );
4115 if(MYDEBUG) SCRUTE( libname_str );
4116 libname = string( libname_str );
4117 delete [] libname_str;
4118 aDataset->CloseOnDisk();
4120 // --> get hypothesis data
4121 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4122 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4123 aDataset->OpenOnDisk();
4124 size = aDataset->GetSize();
4125 char* hypdata_str = new char[ size ];
4126 aDataset->ReadFromDisk( hypdata_str );
4127 hypdata = string( hypdata_str );
4128 delete [] hypdata_str;
4129 aDataset->CloseOnDisk();
4132 // close hypothesis HDF group
4133 aGroup->CloseOnDisk();
4135 // --> restore hypothesis from data
4136 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4137 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
4138 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4139 SMESH::SMESH_Hypothesis_var myHyp;
4141 try { // protect persistence mechanism against exceptions
4142 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4145 INFOS( "Exception during hypothesis creation" );
4148 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4150 // myImpl->LoadFrom( hypdata.c_str() );
4151 hypDataList.push_back( make_pair( myImpl, hypdata ));
4152 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4153 int newId = myStudyContext->findId( iorString.in() );
4154 myStudyContext->mapOldToNew( id, newId );
4157 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4161 // close hypotheses root HDF group
4162 aTopGroup->CloseOnDisk();
4166 // --> then we should read&create algorithms
4167 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
4168 // open algorithms root HDF group
4169 aTopGroup = new HDFgroup( "Algorithms", aFile );
4170 aTopGroup->OpenOnDisk();
4172 // get number of algorithms
4173 int aNbObjects = aTopGroup->nInternalObjects();
4174 for ( int j = 0; j < aNbObjects; j++ ) {
4175 // try to identify algorithm
4176 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4177 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4179 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
4180 // open algorithm group
4181 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4182 aGroup->OpenOnDisk();
4184 // --> get algorithm id
4185 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
4190 // get number of datasets
4191 int aNbSubObjects = aGroup->nInternalObjects();
4192 for ( int k = 0; k < aNbSubObjects; k++ ) {
4194 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4195 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4196 // --> get algorithm name
4197 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4198 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4199 aDataset->OpenOnDisk();
4200 size = aDataset->GetSize();
4201 char* hypname_str = new char[ size ];
4202 aDataset->ReadFromDisk( hypname_str );
4203 hypname = string( hypname_str );
4204 delete [] hypname_str;
4205 aDataset->CloseOnDisk();
4207 // --> get algorithm plugin library name
4208 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4209 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4210 aDataset->OpenOnDisk();
4211 size = aDataset->GetSize();
4212 char* libname_str = new char[ size ];
4213 aDataset->ReadFromDisk( libname_str );
4214 if(MYDEBUG) SCRUTE( libname_str );
4215 libname = string( libname_str );
4216 delete [] libname_str;
4217 aDataset->CloseOnDisk();
4219 // --> get algorithm data
4220 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4221 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4222 aDataset->OpenOnDisk();
4223 size = aDataset->GetSize();
4224 char* hypdata_str = new char[ size ];
4225 aDataset->ReadFromDisk( hypdata_str );
4226 if(MYDEBUG) SCRUTE( hypdata_str );
4227 hypdata = string( hypdata_str );
4228 delete [] hypdata_str;
4229 aDataset->CloseOnDisk();
4232 // close algorithm HDF group
4233 aGroup->CloseOnDisk();
4235 // --> restore algorithm from data
4236 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4237 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
4238 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4239 SMESH::SMESH_Hypothesis_var myHyp;
4241 try { // protect persistence mechanism against exceptions
4242 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4245 INFOS( "Exception during hypothesis creation" );
4248 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4250 //myImpl->LoadFrom( hypdata.c_str() );
4251 hypDataList.push_back( make_pair( myImpl, hypdata ));
4252 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4253 int newId = myStudyContext->findId( iorString.in() );
4254 myStudyContext->mapOldToNew( id, newId );
4257 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4261 // close algorithms root HDF group
4262 aTopGroup->CloseOnDisk();
4266 // --> the rest groups should be meshes
4267 for ( int i = 0; i < aNbGroups; i++ ) {
4268 // identify next group
4269 char meshName[ HDF_NAME_MAX_LEN+1 ];
4270 aFile->InternalObjectIndentify( i, meshName );
4272 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
4274 int id = atoi( string( meshName ).substr( 4 ).c_str() );
4278 // open mesh HDF group
4279 aTopGroup = new HDFgroup( meshName, aFile );
4280 aTopGroup->OpenOnDisk();
4282 // get number of child HDF objects
4283 int aNbObjects = aTopGroup->nInternalObjects();
4284 if ( aNbObjects > 0 ) {
4286 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
4287 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
4288 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
4289 if ( !myNewMeshImpl )
4291 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
4293 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
4294 int newId = myStudyContext->findId( iorString.in() );
4295 myStudyContext->mapOldToNew( id, newId );
4298 // try to read and set auto color flag
4299 char aMeshAutoColorName[ 30 ];
4300 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
4301 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
4303 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
4304 aDataset->OpenOnDisk();
4305 size = aDataset->GetSize();
4306 int* anAutoColor = new int[ size ];
4307 aDataset->ReadFromDisk( anAutoColor );
4308 aDataset->CloseOnDisk();
4309 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
4310 delete [] anAutoColor;
4313 // try to read and set reference to shape
4314 GEOM::GEOM_Object_var aShapeObject;
4315 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
4316 // load mesh "Ref on shape" - it's an entry to SObject
4317 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
4318 aDataset->OpenOnDisk();
4319 size = aDataset->GetSize();
4320 char* refFromFile = new char[ size ];
4321 aDataset->ReadFromDisk( refFromFile );
4322 aDataset->CloseOnDisk();
4323 if ( strlen( refFromFile ) > 0 ) {
4324 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
4326 // Make sure GEOM data are loaded first
4327 //loadGeomData( shapeSO->GetFatherComponent() );
4329 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4330 if ( !CORBA::is_nil( shapeObject ) ) {
4331 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4332 if ( !aShapeObject->_is_nil() )
4333 myNewMeshImpl->SetShape( aShapeObject );
4336 delete [] refFromFile;
4339 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
4340 if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
4342 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
4343 aDataset->OpenOnDisk();
4344 size = aDataset->GetSize();
4345 int* meshPersistentId = new int[ size ];
4346 aDataset->ReadFromDisk( meshPersistentId );
4347 aDataset->CloseOnDisk();
4348 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
4349 delete [] meshPersistentId;
4355 // As all object that can be referred by hypothesis are created,
4356 // we can restore hypothesis data
4358 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
4359 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4361 SMESH_Hypothesis_i* hyp = hyp_data->first;
4362 string & data = hyp_data->second;
4363 hyp->LoadFrom( data.c_str() );
4366 // Restore the rest mesh data
4368 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
4369 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4371 aTopGroup = meshi_group->second;
4372 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4373 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4374 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4376 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
4377 bool hasData = false;
4380 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
4381 int newId = myStudyContext->findId( iorString.in() );
4382 int id = myStudyContext->getOldId( newId );
4384 // try to find mesh data dataset
4385 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
4386 // load mesh "has data" flag
4387 aDataset = new HDFdataset( "Has data", aTopGroup );
4388 aDataset->OpenOnDisk();
4389 size = aDataset->GetSize();
4390 char* strHasData = new char[ size ];
4391 aDataset->ReadFromDisk( strHasData );
4392 aDataset->CloseOnDisk();
4393 if ( strcmp( strHasData, "1") == 0 ) {
4394 // read mesh data from MED file
4395 // myReader.SetMesh( mySMESHDSMesh );
4396 // myReader.SetMeshId( id );
4397 // myReader.Perform();
4400 delete [] strHasData;
4403 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
4404 // nodes and elements are not yet put into sub-meshes)
4405 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4406 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4407 aGroup->OpenOnDisk();
4408 // get number of applied algorithms
4409 int aNbSubObjects = aGroup->nInternalObjects();
4410 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
4411 for ( int j = 0; j < aNbSubObjects; j++ ) {
4412 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4413 aGroup->InternalObjectIndentify( j, name_dataset );
4414 // check if it is an algorithm
4415 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
4416 aDataset = new HDFdataset( name_dataset, aGroup );
4417 aDataset->OpenOnDisk();
4418 size = aDataset->GetSize();
4419 char* refFromFile = new char[ size ];
4420 aDataset->ReadFromDisk( refFromFile );
4421 aDataset->CloseOnDisk();
4422 // san - it is impossible to recover applied algorithms using their entries within Load() method
4423 //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
4424 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4425 int id = atoi( refFromFile );
4426 delete [] refFromFile;
4427 string anIOR = myStudyContext->getIORbyOldId( id );
4428 if ( !anIOR.empty() ) {
4429 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4430 if ( !CORBA::is_nil( hypObject ) ) {
4431 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4432 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4433 || !myNewMeshImpl->HasShapeToMesh()) )
4434 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4439 aGroup->CloseOnDisk();
4442 // try to get applied hypotheses
4443 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4444 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4445 aGroup->OpenOnDisk();
4446 // get number of applied hypotheses
4447 int aNbSubObjects = aGroup->nInternalObjects();
4448 for ( int j = 0; j < aNbSubObjects; j++ ) {
4449 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4450 aGroup->InternalObjectIndentify( j, name_dataset );
4451 // check if it is a hypothesis
4452 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4453 aDataset = new HDFdataset( name_dataset, aGroup );
4454 aDataset->OpenOnDisk();
4455 size = aDataset->GetSize();
4456 char* refFromFile = new char[ size ];
4457 aDataset->ReadFromDisk( refFromFile );
4458 aDataset->CloseOnDisk();
4459 // san - it is impossible to recover applied hypotheses using their entries within Load() method
4460 //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
4461 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4462 int id = atoi( refFromFile );
4463 delete [] refFromFile;
4464 string anIOR = myStudyContext->getIORbyOldId( id );
4465 if ( !anIOR.empty() ) {
4466 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4467 if ( !CORBA::is_nil( hypObject ) ) {
4468 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4469 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4470 || !myNewMeshImpl->HasShapeToMesh()) )
4471 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4476 aGroup->CloseOnDisk();
4479 // --> try to find SUB-MESHES containers for each type of submesh
4480 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
4481 const char* name_meshgroup = 0;
4482 if ( j == GetSubMeshOnVertexTag() )
4483 name_meshgroup = "SubMeshes On Vertex";
4484 else if ( j == GetSubMeshOnEdgeTag() )
4485 name_meshgroup = "SubMeshes On Edge";
4486 else if ( j == GetSubMeshOnWireTag() )
4487 name_meshgroup = "SubMeshes On Wire";
4488 else if ( j == GetSubMeshOnFaceTag() )
4489 name_meshgroup = "SubMeshes On Face";
4490 else if ( j == GetSubMeshOnShellTag() )
4491 name_meshgroup = "SubMeshes On Shell";
4492 else if ( j == GetSubMeshOnSolidTag() )
4493 name_meshgroup = "SubMeshes On Solid";
4494 else if ( j == GetSubMeshOnCompoundTag() )
4495 name_meshgroup = "SubMeshes On Compound";
4497 // try to get submeshes container HDF group
4498 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
4499 // open submeshes containers HDF group
4500 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4501 aGroup->OpenOnDisk();
4503 // get number of submeshes
4504 int aNbSubMeshes = aGroup->nInternalObjects();
4505 for ( int k = 0; k < aNbSubMeshes; k++ ) {
4507 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
4508 aGroup->InternalObjectIndentify( k, name_submeshgroup );
4509 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
4510 // --> get submesh id
4511 int subid = atoi( name_submeshgroup + 7 );
4514 // open submesh HDF group
4515 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
4516 aSubGroup->OpenOnDisk();
4518 // try to read and set reference to subshape
4519 GEOM::GEOM_Object_var aSubShapeObject;
4520 SMESH::SMESH_subMesh_var aSubMesh;
4522 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
4523 // load submesh "Ref on shape" - it's an entry to SObject
4524 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
4525 aDataset->OpenOnDisk();
4526 size = aDataset->GetSize();
4527 char* refFromFile = new char[ size ];
4528 aDataset->ReadFromDisk( refFromFile );
4529 aDataset->CloseOnDisk();
4530 if ( strlen( refFromFile ) > 0 ) {
4531 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
4532 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
4533 if ( !CORBA::is_nil( subShapeObject ) ) {
4534 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
4535 if ( !aSubShapeObject->_is_nil() )
4536 aSubMesh = SMESH::SMESH_subMesh::_duplicate
4537 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
4538 if ( aSubMesh->_is_nil() )
4540 string iorSubString = GetORB()->object_to_string( aSubMesh );
4541 int newSubId = myStudyContext->findId( iorSubString );
4542 myStudyContext->mapOldToNew( subid, newSubId );
4547 if ( aSubMesh->_is_nil() )
4550 // try to get applied algorithms
4551 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4552 // open "applied algorithms" HDF group
4553 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4554 aSubSubGroup->OpenOnDisk();
4555 // get number of applied algorithms
4556 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4557 for ( int l = 0; l < aNbSubObjects; l++ ) {
4558 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4559 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4560 // check if it is an algorithm
4561 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
4562 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4563 aDataset->OpenOnDisk();
4564 size = aDataset->GetSize();
4565 char* refFromFile = new char[ size ];
4566 aDataset->ReadFromDisk( refFromFile );
4567 aDataset->CloseOnDisk();
4569 int id = atoi( refFromFile );
4570 string anIOR = myStudyContext->getIORbyOldId( id );
4571 if ( !anIOR.empty() ) {
4572 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4573 if ( !CORBA::is_nil( hypObject ) ) {
4574 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4575 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4576 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4581 // close "applied algorithms" HDF group
4582 aSubSubGroup->CloseOnDisk();
4585 // try to get applied hypotheses
4586 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4587 // open "applied hypotheses" HDF group
4588 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4589 aSubSubGroup->OpenOnDisk();
4590 // get number of applied hypotheses
4591 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4592 for ( int l = 0; l < aNbSubObjects; l++ ) {
4593 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4594 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4595 // check if it is a hypothesis
4596 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4597 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4598 aDataset->OpenOnDisk();
4599 size = aDataset->GetSize();
4600 char* refFromFile = new char[ size ];
4601 aDataset->ReadFromDisk( refFromFile );
4602 aDataset->CloseOnDisk();
4604 int id = atoi( refFromFile );
4605 string anIOR = myStudyContext->getIORbyOldId( id );
4606 if ( !anIOR.empty() ) {
4607 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4608 if ( !CORBA::is_nil( hypObject ) ) {
4609 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4610 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4611 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4616 // close "APPLIED HYPOTHESES" hdf group
4617 aSubSubGroup->CloseOnDisk();
4620 // close SUB-MESH hdf group
4621 aSubGroup->CloseOnDisk();
4624 // close SUB-MESHES containers hdf group
4625 aGroup->CloseOnDisk();
4629 // try to get GROUPS
4630 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
4631 char name_group[ 30 ];
4632 if ( ii == GetNodeGroupsTag() )
4633 strcpy( name_group, "Groups of Nodes" );
4634 else if ( ii == GetEdgeGroupsTag() )
4635 strcpy( name_group, "Groups of Edges" );
4636 else if ( ii == GetFaceGroupsTag() )
4637 strcpy( name_group, "Groups of Faces" );
4638 else if ( ii == GetVolumeGroupsTag() )
4639 strcpy( name_group, "Groups of Volumes" );
4640 else if ( ii == Get0DElementsGroupsTag() )
4641 strcpy( name_group, "Groups of 0D Elements" );
4642 else if ( ii == GetBallElementsGroupsTag() )
4643 strcpy( name_group, "Groups of Balls" );
4645 if ( aTopGroup->ExistInternalObject( name_group ) ) {
4646 aGroup = new HDFgroup( name_group, aTopGroup );
4647 aGroup->OpenOnDisk();
4648 // get number of groups
4649 int aNbSubObjects = aGroup->nInternalObjects();
4650 for ( int j = 0; j < aNbSubObjects; j++ ) {
4651 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4652 aGroup->InternalObjectIndentify( j, name_dataset );
4653 // check if it is an group
4654 if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
4656 int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
4659 aDataset = new HDFdataset( name_dataset, aGroup );
4660 aDataset->OpenOnDisk();
4662 // Retrieve actual group name
4663 size = aDataset->GetSize();
4664 char* nameFromFile = new char[ size ];
4665 aDataset->ReadFromDisk( nameFromFile );
4666 aDataset->CloseOnDisk();
4668 // Try to find a shape reference
4669 TopoDS_Shape aShape;
4670 char aRefName[ 30 ];
4671 sprintf( aRefName, "Ref on shape %d", subid);
4672 if ( aGroup->ExistInternalObject( aRefName ) ) {
4673 // load mesh "Ref on shape" - it's an entry to SObject
4674 aDataset = new HDFdataset( aRefName, aGroup );
4675 aDataset->OpenOnDisk();
4676 size = aDataset->GetSize();
4677 char* refFromFile = new char[ size ];
4678 aDataset->ReadFromDisk( refFromFile );
4679 aDataset->CloseOnDisk();
4680 if ( strlen( refFromFile ) > 0 ) {
4681 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
4682 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4683 if ( !CORBA::is_nil( shapeObject ) ) {
4684 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4685 if ( !aShapeObject->_is_nil() )
4686 aShape = GeomObjectToShape( aShapeObject );
4690 // Try to read a filter of SMESH_GroupOnFilter
4691 SMESH::Filter_var filter;
4692 SMESH_PredicatePtr predicate;
4693 std::string hdfGrpName = "Filter " + SMESH_Comment(subid);
4694 if ( aGroup->ExistInternalObject( hdfGrpName.c_str() ))
4696 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
4697 aDataset->OpenOnDisk();
4698 size = aDataset->GetSize();
4699 char* persistStr = new char[ size ];
4700 aDataset->ReadFromDisk( persistStr );
4701 aDataset->CloseOnDisk();
4702 if ( strlen( persistStr ) > 0 ) {
4703 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
4704 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
4705 filters.push_back( filter );
4709 // Create group servant
4710 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
4711 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
4712 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape, predicate ) );
4713 // Obtain a SMESHDS_Group object
4714 if ( aNewGroup->_is_nil() )
4717 string iorSubString = GetORB()->object_to_string( aNewGroup );
4718 int newSubId = myStudyContext->findId( iorSubString );
4719 myStudyContext->mapOldToNew( subid, newSubId );
4721 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
4725 if ( SMESH_GroupOnFilter_i* aFilterGroup =
4726 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
4728 aFilterGroup->SetFilter( filter );
4729 filter->UnRegister();
4731 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
4732 if ( !aGroupBaseDS )
4735 aGroupBaseDS->SetStoreName( name_dataset );
4738 // Read color of the group
4739 char aGroupColorName[ 30 ];
4740 sprintf( aGroupColorName, "ColorGroup %d", subid);
4741 if ( aGroup->ExistInternalObject( aGroupColorName ) )
4743 aDataset = new HDFdataset( aGroupColorName, aGroup );
4744 aDataset->OpenOnDisk();
4745 size = aDataset->GetSize();
4746 double* anRGB = new double[ size ];
4747 aDataset->ReadFromDisk( anRGB );
4748 aDataset->CloseOnDisk();
4749 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
4750 aGroupBaseDS->SetColor( aColor );
4754 aGroup->CloseOnDisk();
4758 // instead of reading mesh data, we read only brief information of all
4759 // objects: mesh, groups, sub-meshes (issue 0021208 )
4762 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, id,
4763 meshfile.ToCString(), filename.ToCString(),
4767 // read Sub-Mesh ORDER if any
4768 if( aTopGroup->ExistInternalObject( "Mesh Order" ) ) {
4769 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
4770 aDataset->OpenOnDisk();
4771 size = aDataset->GetSize();
4772 int* smIDs = new int[ size ];
4773 aDataset->ReadFromDisk( smIDs );
4774 aDataset->CloseOnDisk();
4775 TListOfListOfInt anOrderIds;
4776 anOrderIds.push_back( TListOfInt() );
4777 for ( int i = 0; i < size; i++ )
4778 if ( smIDs[ i ] < 0 ) // is separator
4779 anOrderIds.push_back( TListOfInt() );
4781 anOrderIds.back().push_back(smIDs[ i ]);
4783 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
4787 // update hyps needing full mesh data restored (issue 20918)
4788 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4790 SMESH_Hypothesis_i* hyp = hyp_data->first;
4791 hyp->UpdateAsMeshesRestored();
4794 // notify algos on completed restoration to set sub-mesh event listeners
4795 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4797 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4798 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4800 TopoDS_Shape myLocShape;
4801 if(myLocMesh.HasShapeToMesh())
4802 myLocShape = myLocMesh.GetShapeToMesh();
4804 myLocShape = SMESH_Mesh::PseudoShape();
4806 myLocMesh.GetSubMesh(myLocShape)->
4807 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
4810 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
4811 list< SMESH::Filter_var >::iterator f = filters.begin();
4812 for ( ; f != filters.end(); ++f )
4813 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
4814 fi->FindBaseObjects();
4819 aTopGroup->CloseOnDisk();
4822 aFile->CloseOnDisk();
4825 // Remove temporary files created from the stream
4828 SMESH_File meshFile( meshfile.ToCString() );
4829 if ( !meshFile ) // no meshfile exists
4831 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
4835 Engines::Container_var container = GetContainerRef();
4836 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
4838 container_i->registerTemporaryFile( filename.ToCString() );
4839 container_i->registerTemporaryFile( meshfile.ToCString() );
4840 container_i->registerTemporaryFile( tmpDir.ToCString() );
4844 pd << ""; // prevent optimizing pd out
4846 // creation of tree nodes for all data objects in the study
4847 // to support tree representation customization and drag-n-drop:
4848 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
4849 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
4850 useCaseBuilder->SetRootCurrent();
4851 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
4852 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
4853 for (it->InitEx(true); it->More(); it->Next()) {
4854 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
4861 //=============================================================================
4863 * SMESH_Gen_i::LoadASCII
4865 * Load SMESH module's data in ASCII format
4867 //=============================================================================
4869 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
4870 const SALOMEDS::TMPFile& theStream,
4872 bool isMultiFile ) {
4873 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
4874 return Load( theComponent, theStream, theURL, isMultiFile );
4876 //before call main ::Load method it's need for decipher text format to
4877 //binary ( "|xx" => x' )
4878 int size = theStream.length();
4879 if ( int((size / 3 )*3) != size ) //error size of buffer
4882 int real_size = int(size / 3);
4884 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
4887 unsigned int c = -1;
4888 for ( int i = 0; i < real_size; i++ )
4890 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
4891 sscanf( tmp, "%x", &c );
4892 sprintf( (char*)&(buffer[i]), "%c", (char)c );
4895 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
4897 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
4900 //=============================================================================
4902 * SMESH_Gen_i::Close
4904 * Clears study-connected data when it is closed
4906 //=============================================================================
4908 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
4910 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
4912 // Clear study contexts data
4913 delete myStudyContext;
4916 // remove the tmp files meshes are loaded from
4917 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
4922 //=============================================================================
4924 * SMESH_Gen_i::ComponentDataType
4926 * Get component data type
4928 //=============================================================================
4930 char* SMESH_Gen_i::ComponentDataType()
4932 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
4933 return CORBA::string_dup( "SMESH" );
4937 //=============================================================================
4939 * SMESH_Gen_i::IORToLocalPersistentID
4941 * Transform data from transient form to persistent
4943 //=============================================================================
4945 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
4946 const char* IORString,
4947 CORBA::Boolean /*isMultiFile*/,
4948 CORBA::Boolean /*isASCII*/ )
4950 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
4952 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
4953 int anId = myStudyContext->findId( IORString );
4955 if(MYDEBUG) MESSAGE( "VSR " << anId )
4957 sprintf( strId, "%d", anId );
4958 return CORBA::string_dup( strId );
4961 return CORBA::string_dup( "" );
4964 //=============================================================================
4966 * SMESH_Gen_i::LocalPersistentIDToIOR
4968 * Transform data from persistent form to transient
4970 //=============================================================================
4972 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
4973 const char* aLocalPersistentID,
4974 CORBA::Boolean /*isMultiFile*/,
4975 CORBA::Boolean /*isASCII*/ )
4977 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
4979 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
4980 int anId = atoi( aLocalPersistentID );
4981 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
4983 return CORBA::string_dup( "" );
4986 //=======================================================================
4987 //function : RegisterObject
4989 //=======================================================================
4991 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
4993 if ( myStudyContext && !CORBA::is_nil( theObject )) {
4994 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
4995 return myStudyContext->addObject( string( iorString.in() ) );
5000 //================================================================================
5002 * \brief Return id of registered object
5003 * \param theObject - the Object
5004 * \retval int - Object id
5006 //================================================================================
5008 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
5010 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5011 string iorString = GetORB()->object_to_string( theObject );
5012 return myStudyContext->findId( iorString );
5017 //=============================================================================
5019 * SMESH_Gen_i::SetName
5021 * Set a new object name
5023 //=============================================================================
5024 void SMESH_Gen_i::SetName(const char* theIOR,
5025 const char* theName)
5027 if ( theIOR && strcmp( theIOR, "" ) ) {
5028 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
5029 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
5030 if ( !aSO->_is_nil() ) {
5031 SetName( aSO, theName );
5036 // Version information
5037 char* SMESH_Gen_i::getVersion()
5039 #if SMESH_DEVELOPMENT
5040 return CORBA::string_dup(SMESH_VERSION_STR"dev");
5042 return CORBA::string_dup(SMESH_VERSION_STR);
5046 //=================================================================================
5047 // function : Move()
5048 // purpose : Moves objects to the specified position.
5049 // Is used in the drag-n-drop functionality.
5050 //=================================================================================
5051 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
5052 SALOMEDS::SObject_ptr where,
5055 if ( CORBA::is_nil( where ) ) return;
5057 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
5058 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
5059 SALOMEDS::SComponent_var father = where->GetFatherComponent();
5060 std::string dataType = father->ComponentDataType();
5061 if ( dataType != "SMESH" ) return; // not a SMESH component
5063 SALOMEDS::SObject_var objAfter;
5064 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
5065 // insert at given row -> find insertion position
5066 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
5068 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
5069 if ( i == row && useCaseIt->More() ) {
5070 objAfter = useCaseIt->Value();
5074 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
5075 SALOMEDS::SObject_var sobj = what[i];
5076 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
5077 // insert the object to the use case tree
5078 if ( !CORBA::is_nil( objAfter ) )
5079 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
5081 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
5084 //================================================================================
5086 * \brief Returns true if algorithm can be used to mesh a given geometry
5087 * \param [in] theAlgoType - the algorithm type
5088 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
5089 * \param [in] theGeomObject - the geometry to mesh
5090 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
5091 * else, returns \c True if at least one shape is meshable
5092 * \return CORBA::Boolean - can or can't
5094 //================================================================================
5096 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
5097 const char* theLibName,
5098 GEOM::GEOM_Object_ptr theGeomObject,
5099 CORBA::Boolean toCheckAll)
5103 std::string aPlatformLibName;
5104 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
5105 GenericHypothesisCreator_i* aCreator =
5106 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
5109 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
5110 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll );
5117 SMESH_CATCH( SMESH::doNothing );
5120 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
5125 //=================================================================================
5126 // function : GetInsideSphere
5127 // purpose : Collect indices of elements, which are located inside the sphere
5128 //=================================================================================
5129 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
5130 SMESH::ElementType theElemType,
5136 SMESH::long_array_var aResult = new SMESH::long_array();
5137 if ( meshPart->_is_nil() )
5138 return aResult._retn();
5140 // 1. Create geometrical object
5141 gp_Pnt aP( theX, theY, theZ );
5142 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
5144 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5146 if ( lst.size() > 0 ) {
5147 aResult->length( lst.size() );
5148 for ( size_t i = 0; i < lst.size(); i++ ) {
5149 aResult[i] = lst[i];
5152 return aResult._retn();
5155 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
5156 SMESH::ElementType theElemType,
5157 CORBA::Double theX1,
5158 CORBA::Double theY1,
5159 CORBA::Double theZ1,
5160 CORBA::Double theX2,
5161 CORBA::Double theY2,
5162 CORBA::Double theZ2) {
5163 SMESH::long_array_var aResult = new SMESH::long_array();
5164 if( meshPart->_is_nil() )
5165 return aResult._retn();
5167 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
5169 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5171 if( lst.size() > 0 ) {
5172 aResult->length( lst.size() );
5173 for ( size_t i = 0; i < lst.size(); i++ ) {
5174 aResult[i] = lst[i];
5177 return aResult._retn();
5180 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
5181 SMESH::ElementType theElemType,
5185 CORBA::Double theDX,
5186 CORBA::Double theDY,
5187 CORBA::Double theDZ,
5189 CORBA::Double theR ){
5190 SMESH::long_array_var aResult = new SMESH::long_array();
5191 if( meshPart->_is_nil() )
5192 return aResult._retn();
5194 gp_Pnt aP( theX, theY, theZ );
5195 gp_Vec aV( theDX, theDY, theDZ );
5196 gp_Ax2 anAxes (aP, aV);
5198 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
5200 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5202 if( lst.size() > 0 ) {
5203 aResult->length( lst.size() );
5204 for ( size_t i = 0; i < lst.size(); i++ ) {
5205 aResult[i] = lst[i];
5208 return aResult._retn();
5211 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5212 SMESH::ElementType theElemType,
5213 GEOM::GEOM_Object_ptr theGeom,
5214 CORBA::Double theTolerance ) {
5215 SMESH::long_array_var aResult = new SMESH::long_array();
5216 if( meshPart->_is_nil() || theGeom->_is_nil() )
5217 return aResult._retn();
5219 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
5221 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
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();
5234 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5235 SMESH::ElementType theElemType,
5236 TopoDS_Shape& aShape,
5237 double* theTolerance) {
5239 std::vector<long> res;
5240 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
5242 if ( mesh->_is_nil() )
5245 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
5249 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
5254 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
5255 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
5256 anElementsOnShape->SetAllNodes( true );
5257 anElementsOnShape->SetMesh( meshDS );
5258 anElementsOnShape->SetShape( aShape, aType );
5261 anElementsOnShape->SetTolerance(*theTolerance);
5263 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
5264 if ( !msource->_is_nil() ) { // Mesh case
5265 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
5267 while ( elemIt->more() ) {
5268 const SMDS_MeshElement* anElem = elemIt->next();
5269 long anId = anElem->GetID();
5270 if ( anElementsOnShape->IsSatisfy( anId ) )
5271 res.push_back( anId );
5275 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
5276 if ( !gsource->_is_nil() ) {
5277 if(theElemType == SMESH::NODE) {
5278 SMESH::long_array_var nodes = gsource->GetNodeIDs();
5279 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
5280 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
5281 long anId = node->GetID();
5282 if ( anElementsOnShape->IsSatisfy( anId ) )
5283 res.push_back( anId );
5286 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
5287 SMESH::long_array_var elems = gsource->GetListOfID();
5288 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
5289 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
5290 long anId = elem->GetID();
5291 if ( anElementsOnShape->IsSatisfy( anId ) )
5292 res.push_back( anId );
5297 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
5298 if ( !smsource->_is_nil() ) {
5299 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
5300 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
5301 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
5303 long anId = elem->GetID();
5304 if ( anElementsOnShape->IsSatisfy( anId ) )
5305 res.push_back( anId );
5313 //=============================================================================
5315 * SMESHEngine_factory
5317 * C factory, accessible with dlsym, after dlopen
5319 //=============================================================================
5323 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
5324 PortableServer::POA_ptr poa,
5325 PortableServer::ObjectId* contId,
5326 const char* instanceName,
5327 const char* interfaceName )
5329 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
5330 if(MYDEBUG) SCRUTE(interfaceName);
5331 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
5332 return aSMESHGen->getId() ;